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() &&
1060  !New->getType()->isDependentType()) {
1061  LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1062  TemplateSpecResult.addAllDecls(Old);
1063  if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1064  /*QualifiedFriend*/true)) {
1065  New->setInvalidDecl();
1066  return Ovl_Overload;
1067  }
1068 
1069  Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1070  return Ovl_Match;
1071  }
1072 
1073  return Ovl_Overload;
1074 }
1075 
1077  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1078  // C++ [basic.start.main]p2: This function shall not be overloaded.
1079  if (New->isMain())
1080  return false;
1081 
1082  // MSVCRT user defined entry points cannot be overloaded.
1083  if (New->isMSVCRTEntryPoint())
1084  return false;
1085 
1086  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1087  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1088 
1089  // C++ [temp.fct]p2:
1090  // A function template can be overloaded with other function templates
1091  // and with normal (non-template) functions.
1092  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1093  return true;
1094 
1095  // Is the function New an overload of the function Old?
1096  QualType OldQType = Context.getCanonicalType(Old->getType());
1097  QualType NewQType = Context.getCanonicalType(New->getType());
1098 
1099  // Compare the signatures (C++ 1.3.10) of the two functions to
1100  // determine whether they are overloads. If we find any mismatch
1101  // in the signature, they are overloads.
1102 
1103  // If either of these functions is a K&R-style function (no
1104  // prototype), then we consider them to have matching signatures.
1105  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1106  isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1107  return false;
1108 
1109  const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1110  const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1111 
1112  // The signature of a function includes the types of its
1113  // parameters (C++ 1.3.10), which includes the presence or absence
1114  // of the ellipsis; see C++ DR 357).
1115  if (OldQType != NewQType &&
1116  (OldType->getNumParams() != NewType->getNumParams() ||
1117  OldType->isVariadic() != NewType->isVariadic() ||
1118  !FunctionParamTypesAreEqual(OldType, NewType)))
1119  return true;
1120 
1121  // C++ [temp.over.link]p4:
1122  // The signature of a function template consists of its function
1123  // signature, its return type and its template parameter list. The names
1124  // of the template parameters are significant only for establishing the
1125  // relationship between the template parameters and the rest of the
1126  // signature.
1127  //
1128  // We check the return type and template parameter lists for function
1129  // templates first; the remaining checks follow.
1130  //
1131  // However, we don't consider either of these when deciding whether
1132  // a member introduced by a shadow declaration is hidden.
1133  if (!UseMemberUsingDeclRules && NewTemplate &&
1134  (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1135  OldTemplate->getTemplateParameters(),
1136  false, TPL_TemplateMatch) ||
1137  !Context.hasSameType(Old->getDeclaredReturnType(),
1138  New->getDeclaredReturnType())))
1139  return true;
1140 
1141  // If the function is a class member, its signature includes the
1142  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1143  //
1144  // As part of this, also check whether one of the member functions
1145  // is static, in which case they are not overloads (C++
1146  // 13.1p2). While not part of the definition of the signature,
1147  // this check is important to determine whether these functions
1148  // can be overloaded.
1149  CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1150  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1151  if (OldMethod && NewMethod &&
1152  !OldMethod->isStatic() && !NewMethod->isStatic()) {
1153  if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1154  if (!UseMemberUsingDeclRules &&
1155  (OldMethod->getRefQualifier() == RQ_None ||
1156  NewMethod->getRefQualifier() == RQ_None)) {
1157  // C++0x [over.load]p2:
1158  // - Member function declarations with the same name and the same
1159  // parameter-type-list as well as member function template
1160  // declarations with the same name, the same parameter-type-list, and
1161  // the same template parameter lists cannot be overloaded if any of
1162  // them, but not all, have a ref-qualifier (8.3.5).
1163  Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1164  << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1165  Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1166  }
1167  return true;
1168  }
1169 
1170  // We may not have applied the implicit const for a constexpr member
1171  // function yet (because we haven't yet resolved whether this is a static
1172  // or non-static member function). Add it now, on the assumption that this
1173  // is a redeclaration of OldMethod.
1174  auto OldQuals = OldMethod->getMethodQualifiers();
1175  auto NewQuals = NewMethod->getMethodQualifiers();
1176  if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1177  !isa<CXXConstructorDecl>(NewMethod))
1178  NewQuals.addConst();
1179  // We do not allow overloading based off of '__restrict'.
1180  OldQuals.removeRestrict();
1181  NewQuals.removeRestrict();
1182  if (OldQuals != NewQuals)
1183  return true;
1184  }
1185 
1186  // Though pass_object_size is placed on parameters and takes an argument, we
1187  // consider it to be a function-level modifier for the sake of function
1188  // identity. Either the function has one or more parameters with
1189  // pass_object_size or it doesn't.
1192  return true;
1193 
1194  // enable_if attributes are an order-sensitive part of the signature.
1196  NewI = New->specific_attr_begin<EnableIfAttr>(),
1197  NewE = New->specific_attr_end<EnableIfAttr>(),
1198  OldI = Old->specific_attr_begin<EnableIfAttr>(),
1199  OldE = Old->specific_attr_end<EnableIfAttr>();
1200  NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1201  if (NewI == NewE || OldI == OldE)
1202  return true;
1203  llvm::FoldingSetNodeID NewID, OldID;
1204  NewI->getCond()->Profile(NewID, Context, true);
1205  OldI->getCond()->Profile(OldID, Context, true);
1206  if (NewID != OldID)
1207  return true;
1208  }
1209 
1210  if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1211  // Don't allow overloading of destructors. (In theory we could, but it
1212  // would be a giant change to clang.)
1213  if (isa<CXXDestructorDecl>(New))
1214  return false;
1215 
1216  CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1217  OldTarget = IdentifyCUDATarget(Old);
1218  if (NewTarget == CFT_InvalidTarget)
1219  return false;
1220 
1221  assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1222 
1223  // Allow overloading of functions with same signature and different CUDA
1224  // target attributes.
1225  return NewTarget != OldTarget;
1226  }
1227 
1228  // The signatures match; this is not an overload.
1229  return false;
1230 }
1231 
1232 /// Checks availability of the function depending on the current
1233 /// function context. Inside an unavailable function, unavailability is ignored.
1234 ///
1235 /// \returns true if \arg FD is unavailable and current context is inside
1236 /// an available function, false otherwise.
1238  if (!FD->isUnavailable())
1239  return false;
1240 
1241  // Walk up the context of the caller.
1242  Decl *C = cast<Decl>(CurContext);
1243  do {
1244  if (C->isUnavailable())
1245  return false;
1246  } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1247  return true;
1248 }
1249 
1250 /// Tries a user-defined conversion from From to ToType.
1251 ///
1252 /// Produces an implicit conversion sequence for when a standard conversion
1253 /// is not an option. See TryImplicitConversion for more information.
1256  bool SuppressUserConversions,
1257  bool AllowExplicit,
1258  bool InOverloadResolution,
1259  bool CStyle,
1260  bool AllowObjCWritebackConversion,
1261  bool AllowObjCConversionOnExplicit) {
1263 
1264  if (SuppressUserConversions) {
1265  // We're not in the case above, so there is no conversion that
1266  // we can perform.
1267  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1268  return ICS;
1269  }
1270 
1271  // Attempt user-defined conversion.
1272  OverloadCandidateSet Conversions(From->getExprLoc(),
1274  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1275  Conversions, AllowExplicit,
1276  AllowObjCConversionOnExplicit)) {
1277  case OR_Success:
1278  case OR_Deleted:
1279  ICS.setUserDefined();
1280  // C++ [over.ics.user]p4:
1281  // A conversion of an expression of class type to the same class
1282  // type is given Exact Match rank, and a conversion of an
1283  // expression of class type to a base class of that type is
1284  // given Conversion rank, in spite of the fact that a copy
1285  // constructor (i.e., a user-defined conversion function) is
1286  // called for those cases.
1287  if (CXXConstructorDecl *Constructor
1288  = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1289  QualType FromCanon
1291  QualType ToCanon
1293  if (Constructor->isCopyConstructor() &&
1294  (FromCanon == ToCanon ||
1295  S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1296  // Turn this into a "standard" conversion sequence, so that it
1297  // gets ranked with standard conversion sequences.
1299  ICS.setStandard();
1301  ICS.Standard.setFromType(From->getType());
1302  ICS.Standard.setAllToTypes(ToType);
1303  ICS.Standard.CopyConstructor = Constructor;
1304  ICS.Standard.FoundCopyConstructor = Found;
1305  if (ToCanon != FromCanon)
1307  }
1308  }
1309  break;
1310 
1311  case OR_Ambiguous:
1312  ICS.setAmbiguous();
1313  ICS.Ambiguous.setFromType(From->getType());
1314  ICS.Ambiguous.setToType(ToType);
1315  for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1316  Cand != Conversions.end(); ++Cand)
1317  if (Cand->Viable)
1318  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1319  break;
1320 
1321  // Fall through.
1322  case OR_No_Viable_Function:
1323  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1324  break;
1325  }
1326 
1327  return ICS;
1328 }
1329 
1330 /// TryImplicitConversion - Attempt to perform an implicit conversion
1331 /// from the given expression (Expr) to the given type (ToType). This
1332 /// function returns an implicit conversion sequence that can be used
1333 /// to perform the initialization. Given
1334 ///
1335 /// void f(float f);
1336 /// void g(int i) { f(i); }
1337 ///
1338 /// this routine would produce an implicit conversion sequence to
1339 /// describe the initialization of f from i, which will be a standard
1340 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1341 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1342 //
1343 /// Note that this routine only determines how the conversion can be
1344 /// performed; it does not actually perform the conversion. As such,
1345 /// it will not produce any diagnostics if no conversion is available,
1346 /// but will instead return an implicit conversion sequence of kind
1347 /// "BadConversion".
1348 ///
1349 /// If @p SuppressUserConversions, then user-defined conversions are
1350 /// not permitted.
1351 /// If @p AllowExplicit, then explicit user-defined conversions are
1352 /// permitted.
1353 ///
1354 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1355 /// writeback conversion, which allows __autoreleasing id* parameters to
1356 /// be initialized with __strong id* or __weak id* arguments.
1359  bool SuppressUserConversions,
1360  bool AllowExplicit,
1361  bool InOverloadResolution,
1362  bool CStyle,
1363  bool AllowObjCWritebackConversion,
1364  bool AllowObjCConversionOnExplicit) {
1366  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1367  ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1368  ICS.setStandard();
1369  return ICS;
1370  }
1371 
1372  if (!S.getLangOpts().CPlusPlus) {
1373  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1374  return ICS;
1375  }
1376 
1377  // C++ [over.ics.user]p4:
1378  // A conversion of an expression of class type to the same class
1379  // type is given Exact Match rank, and a conversion of an
1380  // expression of class type to a base class of that type is
1381  // given Conversion rank, in spite of the fact that a copy/move
1382  // constructor (i.e., a user-defined conversion function) is
1383  // called for those cases.
1384  QualType FromType = From->getType();
1385  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1386  (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1387  S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1388  ICS.setStandard();
1390  ICS.Standard.setFromType(FromType);
1391  ICS.Standard.setAllToTypes(ToType);
1392 
1393  // We don't actually check at this point whether there is a valid
1394  // copy/move constructor, since overloading just assumes that it
1395  // exists. When we actually perform initialization, we'll find the
1396  // appropriate constructor to copy the returned object, if needed.
1397  ICS.Standard.CopyConstructor = nullptr;
1398 
1399  // Determine whether this is considered a derived-to-base conversion.
1400  if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1402 
1403  return ICS;
1404  }
1405 
1406  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1407  AllowExplicit, InOverloadResolution, CStyle,
1408  AllowObjCWritebackConversion,
1409  AllowObjCConversionOnExplicit);
1410 }
1411 
1414  bool SuppressUserConversions,
1415  bool AllowExplicit,
1416  bool InOverloadResolution,
1417  bool CStyle,
1418  bool AllowObjCWritebackConversion) {
1419  return ::TryImplicitConversion(*this, From, ToType,
1420  SuppressUserConversions, AllowExplicit,
1421  InOverloadResolution, CStyle,
1422  AllowObjCWritebackConversion,
1423  /*AllowObjCConversionOnExplicit=*/false);
1424 }
1425 
1426 /// PerformImplicitConversion - Perform an implicit conversion of the
1427 /// expression From to the type ToType. Returns the
1428 /// converted expression. Flavor is the kind of conversion we're
1429 /// performing, used in the error message. If @p AllowExplicit,
1430 /// explicit user-defined conversions are permitted.
1431 ExprResult
1433  AssignmentAction Action, bool AllowExplicit) {
1435  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1436 }
1437 
1438 ExprResult
1440  AssignmentAction Action, bool AllowExplicit,
1442  if (checkPlaceholderForOverload(*this, From))
1443  return ExprError();
1444 
1445  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1446  bool AllowObjCWritebackConversion
1447  = getLangOpts().ObjCAutoRefCount &&
1448  (Action == AA_Passing || Action == AA_Sending);
1449  if (getLangOpts().ObjC)
1450  CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1451  From->getType(), From);
1452  ICS = ::TryImplicitConversion(*this, From, ToType,
1453  /*SuppressUserConversions=*/false,
1454  AllowExplicit,
1455  /*InOverloadResolution=*/false,
1456  /*CStyle=*/false,
1457  AllowObjCWritebackConversion,
1458  /*AllowObjCConversionOnExplicit=*/false);
1459  return PerformImplicitConversion(From, ToType, ICS, Action);
1460 }
1461 
1462 /// Determine whether the conversion from FromType to ToType is a valid
1463 /// conversion that strips "noexcept" or "noreturn" off the nested function
1464 /// type.
1466  QualType &ResultTy) {
1467  if (Context.hasSameUnqualifiedType(FromType, ToType))
1468  return false;
1469 
1470  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1471  // or F(t noexcept) -> F(t)
1472  // where F adds one of the following at most once:
1473  // - a pointer
1474  // - a member pointer
1475  // - a block pointer
1476  // Changes here need matching changes in FindCompositePointerType.
1477  CanQualType CanTo = Context.getCanonicalType(ToType);
1478  CanQualType CanFrom = Context.getCanonicalType(FromType);
1479  Type::TypeClass TyClass = CanTo->getTypeClass();
1480  if (TyClass != CanFrom->getTypeClass()) return false;
1481  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1482  if (TyClass == Type::Pointer) {
1483  CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1484  CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1485  } else if (TyClass == Type::BlockPointer) {
1486  CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1487  CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1488  } else if (TyClass == Type::MemberPointer) {
1489  auto ToMPT = CanTo.getAs<MemberPointerType>();
1490  auto FromMPT = CanFrom.getAs<MemberPointerType>();
1491  // A function pointer conversion cannot change the class of the function.
1492  if (ToMPT->getClass() != FromMPT->getClass())
1493  return false;
1494  CanTo = ToMPT->getPointeeType();
1495  CanFrom = FromMPT->getPointeeType();
1496  } else {
1497  return false;
1498  }
1499 
1500  TyClass = CanTo->getTypeClass();
1501  if (TyClass != CanFrom->getTypeClass()) return false;
1502  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1503  return false;
1504  }
1505 
1506  const auto *FromFn = cast<FunctionType>(CanFrom);
1507  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1508 
1509  const auto *ToFn = cast<FunctionType>(CanTo);
1510  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1511 
1512  bool Changed = false;
1513 
1514  // Drop 'noreturn' if not present in target type.
1515  if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1516  FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1517  Changed = true;
1518  }
1519 
1520  // Drop 'noexcept' if not present in target type.
1521  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1522  const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1523  if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1524  FromFn = cast<FunctionType>(
1525  Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1526  EST_None)
1527  .getTypePtr());
1528  Changed = true;
1529  }
1530 
1531  // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1532  // only if the ExtParameterInfo lists of the two function prototypes can be
1533  // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1535  bool CanUseToFPT, CanUseFromFPT;
1536  if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1537  CanUseFromFPT, NewParamInfos) &&
1538  CanUseToFPT && !CanUseFromFPT) {
1539  FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1540  ExtInfo.ExtParameterInfos =
1541  NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1542  QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1543  FromFPT->getParamTypes(), ExtInfo);
1544  FromFn = QT->getAs<FunctionType>();
1545  Changed = true;
1546  }
1547  }
1548 
1549  if (!Changed)
1550  return false;
1551 
1552  assert(QualType(FromFn, 0).isCanonical());
1553  if (QualType(FromFn, 0) != CanTo) return false;
1554 
1555  ResultTy = ToType;
1556  return true;
1557 }
1558 
1559 /// Determine whether the conversion from FromType to ToType is a valid
1560 /// vector conversion.
1561 ///
1562 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1563 /// conversion.
1564 static bool IsVectorConversion(Sema &S, QualType FromType,
1565  QualType ToType, ImplicitConversionKind &ICK) {
1566  // We need at least one of these types to be a vector type to have a vector
1567  // conversion.
1568  if (!ToType->isVectorType() && !FromType->isVectorType())
1569  return false;
1570 
1571  // Identical types require no conversions.
1572  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1573  return false;
1574 
1575  // There are no conversions between extended vector types, only identity.
1576  if (ToType->isExtVectorType()) {
1577  // There are no conversions between extended vector types other than the
1578  // identity conversion.
1579  if (FromType->isExtVectorType())
1580  return false;
1581 
1582  // Vector splat from any arithmetic type to a vector.
1583  if (FromType->isArithmeticType()) {
1584  ICK = ICK_Vector_Splat;
1585  return true;
1586  }
1587  }
1588 
1589  // We can perform the conversion between vector types in the following cases:
1590  // 1)vector types are equivalent AltiVec and GCC vector types
1591  // 2)lax vector conversions are permitted and the vector types are of the
1592  // same size
1593  if (ToType->isVectorType() && FromType->isVectorType()) {
1594  if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1595  S.isLaxVectorConversion(FromType, ToType)) {
1596  ICK = ICK_Vector_Conversion;
1597  return true;
1598  }
1599  }
1600 
1601  return false;
1602 }
1603 
1604 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1605  bool InOverloadResolution,
1607  bool CStyle);
1608 
1609 /// IsStandardConversion - Determines whether there is a standard
1610 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1611 /// expression From to the type ToType. Standard conversion sequences
1612 /// only consider non-class types; for conversions that involve class
1613 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1614 /// contain the standard conversion sequence required to perform this
1615 /// conversion and this routine will return true. Otherwise, this
1616 /// routine will return false and the value of SCS is unspecified.
1617 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1618  bool InOverloadResolution,
1620  bool CStyle,
1621  bool AllowObjCWritebackConversion) {
1622  QualType FromType = From->getType();
1623 
1624  // Standard conversions (C++ [conv])
1626  SCS.IncompatibleObjC = false;
1627  SCS.setFromType(FromType);
1628  SCS.CopyConstructor = nullptr;
1629 
1630  // There are no standard conversions for class types in C++, so
1631  // abort early. When overloading in C, however, we do permit them.
1632  if (S.getLangOpts().CPlusPlus &&
1633  (FromType->isRecordType() || ToType->isRecordType()))
1634  return false;
1635 
1636  // The first conversion can be an lvalue-to-rvalue conversion,
1637  // array-to-pointer conversion, or function-to-pointer conversion
1638  // (C++ 4p1).
1639 
1640  if (FromType == S.Context.OverloadTy) {
1641  DeclAccessPair AccessPair;
1642  if (FunctionDecl *Fn
1643  = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1644  AccessPair)) {
1645  // We were able to resolve the address of the overloaded function,
1646  // so we can convert to the type of that function.
1647  FromType = Fn->getType();
1648  SCS.setFromType(FromType);
1649 
1650  // we can sometimes resolve &foo<int> regardless of ToType, so check
1651  // if the type matches (identity) or we are converting to bool
1653  S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1654  QualType resultTy;
1655  // if the function type matches except for [[noreturn]], it's ok
1656  if (!S.IsFunctionConversion(FromType,
1657  S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1658  // otherwise, only a boolean conversion is standard
1659  if (!ToType->isBooleanType())
1660  return false;
1661  }
1662 
1663  // Check if the "from" expression is taking the address of an overloaded
1664  // function and recompute the FromType accordingly. Take advantage of the
1665  // fact that non-static member functions *must* have such an address-of
1666  // expression.
1667  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1668  if (Method && !Method->isStatic()) {
1669  assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1670  "Non-unary operator on non-static member address");
1671  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1672  == UO_AddrOf &&
1673  "Non-address-of operator on non-static member address");
1674  const Type *ClassType
1675  = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1676  FromType = S.Context.getMemberPointerType(FromType, ClassType);
1677  } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1678  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1679  UO_AddrOf &&
1680  "Non-address-of operator for overloaded function expression");
1681  FromType = S.Context.getPointerType(FromType);
1682  }
1683 
1684  // Check that we've computed the proper type after overload resolution.
1685  // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1686  // be calling it from within an NDEBUG block.
1687  assert(S.Context.hasSameType(
1688  FromType,
1689  S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1690  } else {
1691  return false;
1692  }
1693  }
1694  // Lvalue-to-rvalue conversion (C++11 4.1):
1695  // A glvalue (3.10) of a non-function, non-array type T can
1696  // be converted to a prvalue.
1697  bool argIsLValue = From->isGLValue();
1698  if (argIsLValue &&
1699  !FromType->isFunctionType() && !FromType->isArrayType() &&
1700  S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1702 
1703  // C11 6.3.2.1p2:
1704  // ... if the lvalue has atomic type, the value has the non-atomic version
1705  // of the type of the lvalue ...
1706  if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1707  FromType = Atomic->getValueType();
1708 
1709  // If T is a non-class type, the type of the rvalue is the
1710  // cv-unqualified version of T. Otherwise, the type of the rvalue
1711  // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1712  // just strip the qualifiers because they don't matter.
1713  FromType = FromType.getUnqualifiedType();
1714  } else if (FromType->isArrayType()) {
1715  // Array-to-pointer conversion (C++ 4.2)
1717 
1718  // An lvalue or rvalue of type "array of N T" or "array of unknown
1719  // bound of T" can be converted to an rvalue of type "pointer to
1720  // T" (C++ 4.2p1).
1721  FromType = S.Context.getArrayDecayedType(FromType);
1722 
1723  if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1724  // This conversion is deprecated in C++03 (D.4)
1726 
1727  // For the purpose of ranking in overload resolution
1728  // (13.3.3.1.1), this conversion is considered an
1729  // array-to-pointer conversion followed by a qualification
1730  // conversion (4.4). (C++ 4.2p2)
1731  SCS.Second = ICK_Identity;
1732  SCS.Third = ICK_Qualification;
1734  SCS.setAllToTypes(FromType);
1735  return true;
1736  }
1737  } else if (FromType->isFunctionType() && argIsLValue) {
1738  // Function-to-pointer conversion (C++ 4.3).
1740 
1741  if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1742  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1744  return false;
1745 
1746  // An lvalue of function type T can be converted to an rvalue of
1747  // type "pointer to T." The result is a pointer to the
1748  // function. (C++ 4.3p1).
1749  FromType = S.Context.getPointerType(FromType);
1750  } else {
1751  // We don't require any conversions for the first step.
1752  SCS.First = ICK_Identity;
1753  }
1754  SCS.setToType(0, FromType);
1755 
1756  // The second conversion can be an integral promotion, floating
1757  // point promotion, integral conversion, floating point conversion,
1758  // floating-integral conversion, pointer conversion,
1759  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1760  // For overloading in C, this can also be a "compatible-type"
1761  // conversion.
1762  bool IncompatibleObjC = false;
1764  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1765  // The unqualified versions of the types are the same: there's no
1766  // conversion to do.
1767  SCS.Second = ICK_Identity;
1768  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1769  // Integral promotion (C++ 4.5).
1771  FromType = ToType.getUnqualifiedType();
1772  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1773  // Floating point promotion (C++ 4.6).
1775  FromType = ToType.getUnqualifiedType();
1776  } else if (S.IsComplexPromotion(FromType, ToType)) {
1777  // Complex promotion (Clang extension)
1779  FromType = ToType.getUnqualifiedType();
1780  } else if (ToType->isBooleanType() &&
1781  (FromType->isArithmeticType() ||
1782  FromType->isAnyPointerType() ||
1783  FromType->isBlockPointerType() ||
1784  FromType->isMemberPointerType() ||
1785  FromType->isNullPtrType())) {
1786  // Boolean conversions (C++ 4.12).
1788  FromType = S.Context.BoolTy;
1789  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1790  ToType->isIntegralType(S.Context)) {
1791  // Integral conversions (C++ 4.7).
1793  FromType = ToType.getUnqualifiedType();
1794  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1795  // Complex conversions (C99 6.3.1.6)
1797  FromType = ToType.getUnqualifiedType();
1798  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1799  (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1800  // Complex-real conversions (C99 6.3.1.7)
1801  SCS.Second = ICK_Complex_Real;
1802  FromType = ToType.getUnqualifiedType();
1803  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1804  // FIXME: disable conversions between long double and __float128 if
1805  // their representation is different until there is back end support
1806  // We of course allow this conversion if long double is really double.
1807  if (&S.Context.getFloatTypeSemantics(FromType) !=
1808  &S.Context.getFloatTypeSemantics(ToType)) {
1809  bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1810  ToType == S.Context.LongDoubleTy) ||
1811  (FromType == S.Context.LongDoubleTy &&
1812  ToType == S.Context.Float128Ty));
1813  if (Float128AndLongDouble &&
1815  &llvm::APFloat::PPCDoubleDouble()))
1816  return false;
1817  }
1818  // Floating point conversions (C++ 4.8).
1820  FromType = ToType.getUnqualifiedType();
1821  } else if ((FromType->isRealFloatingType() &&
1822  ToType->isIntegralType(S.Context)) ||
1823  (FromType->isIntegralOrUnscopedEnumerationType() &&
1824  ToType->isRealFloatingType())) {
1825  // Floating-integral conversions (C++ 4.9).
1827  FromType = ToType.getUnqualifiedType();
1828  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1830  } else if (AllowObjCWritebackConversion &&
1831  S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1833  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1834  FromType, IncompatibleObjC)) {
1835  // Pointer conversions (C++ 4.10).
1837  SCS.IncompatibleObjC = IncompatibleObjC;
1838  FromType = FromType.getUnqualifiedType();
1839  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1840  InOverloadResolution, FromType)) {
1841  // Pointer to member conversions (4.11).
1842  SCS.Second = ICK_Pointer_Member;
1843  } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1844  SCS.Second = SecondICK;
1845  FromType = ToType.getUnqualifiedType();
1846  } else if (!S.getLangOpts().CPlusPlus &&
1847  S.Context.typesAreCompatible(ToType, FromType)) {
1848  // Compatible conversions (Clang extension for C function overloading)
1850  FromType = ToType.getUnqualifiedType();
1851  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1852  InOverloadResolution,
1853  SCS, CStyle)) {
1855  FromType = ToType;
1856  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1857  CStyle)) {
1858  // tryAtomicConversion has updated the standard conversion sequence
1859  // appropriately.
1860  return true;
1861  } else if (ToType->isEventT() &&
1862  From->isIntegerConstantExpr(S.getASTContext()) &&
1863  From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1865  FromType = ToType;
1866  } else if (ToType->isQueueT() &&
1867  From->isIntegerConstantExpr(S.getASTContext()) &&
1868  (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1870  FromType = ToType;
1871  } else {
1872  // No second conversion required.
1873  SCS.Second = ICK_Identity;
1874  }
1875  SCS.setToType(1, FromType);
1876 
1877  // The third conversion can be a function pointer conversion or a
1878  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1879  bool ObjCLifetimeConversion;
1880  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1881  // Function pointer conversions (removing 'noexcept') including removal of
1882  // 'noreturn' (Clang extension).
1884  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1885  ObjCLifetimeConversion)) {
1886  SCS.Third = ICK_Qualification;
1887  SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1888  FromType = ToType;
1889  } else {
1890  // No conversion required
1891  SCS.Third = ICK_Identity;
1892  }
1893 
1894  // C++ [over.best.ics]p6:
1895  // [...] Any difference in top-level cv-qualification is
1896  // subsumed by the initialization itself and does not constitute
1897  // a conversion. [...]
1898  QualType CanonFrom = S.Context.getCanonicalType(FromType);
1899  QualType CanonTo = S.Context.getCanonicalType(ToType);
1900  if (CanonFrom.getLocalUnqualifiedType()
1901  == CanonTo.getLocalUnqualifiedType() &&
1902  CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1903  FromType = ToType;
1904  CanonFrom = CanonTo;
1905  }
1906 
1907  SCS.setToType(2, FromType);
1908 
1909  if (CanonFrom == CanonTo)
1910  return true;
1911 
1912  // If we have not converted the argument type to the parameter type,
1913  // this is a bad conversion sequence, unless we're resolving an overload in C.
1914  if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1915  return false;
1916 
1917  ExprResult ER = ExprResult{From};
1919  S.CheckSingleAssignmentConstraints(ToType, ER,
1920  /*Diagnose=*/false,
1921  /*DiagnoseCFAudited=*/false,
1922  /*ConvertRHS=*/false);
1923  ImplicitConversionKind SecondConv;
1924  switch (Conv) {
1925  case Sema::Compatible:
1926  SecondConv = ICK_C_Only_Conversion;
1927  break;
1928  // For our purposes, discarding qualifiers is just as bad as using an
1929  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1930  // qualifiers, as well.
1935  break;
1936  default:
1937  return false;
1938  }
1939 
1940  // First can only be an lvalue conversion, so we pretend that this was the
1941  // second conversion. First should already be valid from earlier in the
1942  // function.
1943  SCS.Second = SecondConv;
1944  SCS.setToType(1, ToType);
1945 
1946  // Third is Identity, because Second should rank us worse than any other
1947  // conversion. This could also be ICK_Qualification, but it's simpler to just
1948  // lump everything in with the second conversion, and we don't gain anything
1949  // from making this ICK_Qualification.
1950  SCS.Third = ICK_Identity;
1951  SCS.setToType(2, ToType);
1952  return true;
1953 }
1954 
1955 static bool
1957  QualType &ToType,
1958  bool InOverloadResolution,
1960  bool CStyle) {
1961 
1962  const RecordType *UT = ToType->getAsUnionType();
1963  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1964  return false;
1965  // The field to initialize within the transparent union.
1966  RecordDecl *UD = UT->getDecl();
1967  // It's compatible if the expression matches any of the fields.
1968  for (const auto *it : UD->fields()) {
1969  if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1970  CStyle, /*ObjCWritebackConversion=*/false)) {
1971  ToType = it->getType();
1972  return true;
1973  }
1974  }
1975  return false;
1976 }
1977 
1978 /// IsIntegralPromotion - Determines whether the conversion from the
1979 /// expression From (whose potentially-adjusted type is FromType) to
1980 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1981 /// sets PromotedType to the promoted type.
1982 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1983  const BuiltinType *To = ToType->getAs<BuiltinType>();
1984  // All integers are built-in.
1985  if (!To) {
1986  return false;
1987  }
1988 
1989  // An rvalue of type char, signed char, unsigned char, short int, or
1990  // unsigned short int can be converted to an rvalue of type int if
1991  // int can represent all the values of the source type; otherwise,
1992  // the source rvalue can be converted to an rvalue of type unsigned
1993  // int (C++ 4.5p1).
1994  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1995  !FromType->isEnumeralType()) {
1996  if (// We can promote any signed, promotable integer type to an int
1997  (FromType->isSignedIntegerType() ||
1998  // We can promote any unsigned integer type whose size is
1999  // less than int to an int.
2000  Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2001  return To->getKind() == BuiltinType::Int;
2002  }
2003 
2004  return To->getKind() == BuiltinType::UInt;
2005  }
2006 
2007  // C++11 [conv.prom]p3:
2008  // A prvalue of an unscoped enumeration type whose underlying type is not
2009  // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2010  // following types that can represent all the values of the enumeration
2011  // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2012  // unsigned int, long int, unsigned long int, long long int, or unsigned
2013  // long long int. If none of the types in that list can represent all the
2014  // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2015  // type can be converted to an rvalue a prvalue of the extended integer type
2016  // with lowest integer conversion rank (4.13) greater than the rank of long
2017  // long in which all the values of the enumeration can be represented. If
2018  // there are two such extended types, the signed one is chosen.
2019  // C++11 [conv.prom]p4:
2020  // A prvalue of an unscoped enumeration type whose underlying type is fixed
2021  // can be converted to a prvalue of its underlying type. Moreover, if
2022  // integral promotion can be applied to its underlying type, a prvalue of an
2023  // unscoped enumeration type whose underlying type is fixed can also be
2024  // converted to a prvalue of the promoted underlying type.
2025  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2026  // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2027  // provided for a scoped enumeration.
2028  if (FromEnumType->getDecl()->isScoped())
2029  return false;
2030 
2031  // We can perform an integral promotion to the underlying type of the enum,
2032  // even if that's not the promoted type. Note that the check for promoting
2033  // the underlying type is based on the type alone, and does not consider
2034  // the bitfield-ness of the actual source expression.
2035  if (FromEnumType->getDecl()->isFixed()) {
2036  QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2037  return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2038  IsIntegralPromotion(nullptr, Underlying, ToType);
2039  }
2040 
2041  // We have already pre-calculated the promotion type, so this is trivial.
2042  if (ToType->isIntegerType() &&
2043  isCompleteType(From->getBeginLoc(), FromType))
2044  return Context.hasSameUnqualifiedType(
2045  ToType, FromEnumType->getDecl()->getPromotionType());
2046 
2047  // C++ [conv.prom]p5:
2048  // If the bit-field has an enumerated type, it is treated as any other
2049  // value of that type for promotion purposes.
2050  //
2051  // ... so do not fall through into the bit-field checks below in C++.
2052  if (getLangOpts().CPlusPlus)
2053  return false;
2054  }
2055 
2056  // C++0x [conv.prom]p2:
2057  // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2058  // to an rvalue a prvalue of the first of the following types that can
2059  // represent all the values of its underlying type: int, unsigned int,
2060  // long int, unsigned long int, long long int, or unsigned long long int.
2061  // If none of the types in that list can represent all the values of its
2062  // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2063  // or wchar_t can be converted to an rvalue a prvalue of its underlying
2064  // type.
2065  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2066  ToType->isIntegerType()) {
2067  // Determine whether the type we're converting from is signed or
2068  // unsigned.
2069  bool FromIsSigned = FromType->isSignedIntegerType();
2070  uint64_t FromSize = Context.getTypeSize(FromType);
2071 
2072  // The types we'll try to promote to, in the appropriate
2073  // order. Try each of these types.
2074  QualType PromoteTypes[6] = {
2075  Context.IntTy, Context.UnsignedIntTy,
2076  Context.LongTy, Context.UnsignedLongTy ,
2077  Context.LongLongTy, Context.UnsignedLongLongTy
2078  };
2079  for (int Idx = 0; Idx < 6; ++Idx) {
2080  uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2081  if (FromSize < ToSize ||
2082  (FromSize == ToSize &&
2083  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2084  // We found the type that we can promote to. If this is the
2085  // type we wanted, we have a promotion. Otherwise, no
2086  // promotion.
2087  return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2088  }
2089  }
2090  }
2091 
2092  // An rvalue for an integral bit-field (9.6) can be converted to an
2093  // rvalue of type int if int can represent all the values of the
2094  // bit-field; otherwise, it can be converted to unsigned int if
2095  // unsigned int can represent all the values of the bit-field. If
2096  // the bit-field is larger yet, no integral promotion applies to
2097  // it. If the bit-field has an enumerated type, it is treated as any
2098  // other value of that type for promotion purposes (C++ 4.5p3).
2099  // FIXME: We should delay checking of bit-fields until we actually perform the
2100  // conversion.
2101  //
2102  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2103  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2104  // bit-fields and those whose underlying type is larger than int) for GCC
2105  // compatibility.
2106  if (From) {
2107  if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2108  llvm::APSInt BitWidth;
2109  if (FromType->isIntegralType(Context) &&
2110  MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2111  llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2112  ToSize = Context.getTypeSize(ToType);
2113 
2114  // Are we promoting to an int from a bitfield that fits in an int?
2115  if (BitWidth < ToSize ||
2116  (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2117  return To->getKind() == BuiltinType::Int;
2118  }
2119 
2120  // Are we promoting to an unsigned int from an unsigned bitfield
2121  // that fits into an unsigned int?
2122  if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2123  return To->getKind() == BuiltinType::UInt;
2124  }
2125 
2126  return false;
2127  }
2128  }
2129  }
2130 
2131  // An rvalue of type bool can be converted to an rvalue of type int,
2132  // with false becoming zero and true becoming one (C++ 4.5p4).
2133  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2134  return true;
2135  }
2136 
2137  return false;
2138 }
2139 
2140 /// IsFloatingPointPromotion - Determines whether the conversion from
2141 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2142 /// returns true and sets PromotedType to the promoted type.
2144  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2145  if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2146  /// An rvalue of type float can be converted to an rvalue of type
2147  /// double. (C++ 4.6p1).
2148  if (FromBuiltin->getKind() == BuiltinType::Float &&
2149  ToBuiltin->getKind() == BuiltinType::Double)
2150  return true;
2151 
2152  // C99 6.3.1.5p1:
2153  // When a float is promoted to double or long double, or a
2154  // double is promoted to long double [...].
2155  if (!getLangOpts().CPlusPlus &&
2156  (FromBuiltin->getKind() == BuiltinType::Float ||
2157  FromBuiltin->getKind() == BuiltinType::Double) &&
2158  (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2159  ToBuiltin->getKind() == BuiltinType::Float128))
2160  return true;
2161 
2162  // Half can be promoted to float.
2163  if (!getLangOpts().NativeHalfType &&
2164  FromBuiltin->getKind() == BuiltinType::Half &&
2165  ToBuiltin->getKind() == BuiltinType::Float)
2166  return true;
2167  }
2168 
2169  return false;
2170 }
2171 
2172 /// Determine if a conversion is a complex promotion.
2173 ///
2174 /// A complex promotion is defined as a complex -> complex conversion
2175 /// where the conversion between the underlying real types is a
2176 /// floating-point or integral promotion.
2178  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2179  if (!FromComplex)
2180  return false;
2181 
2182  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2183  if (!ToComplex)
2184  return false;
2185 
2186  return IsFloatingPointPromotion(FromComplex->getElementType(),
2187  ToComplex->getElementType()) ||
2188  IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2189  ToComplex->getElementType());
2190 }
2191 
2192 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2193 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2194 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2195 /// if non-empty, will be a pointer to ToType that may or may not have
2196 /// the right set of qualifiers on its pointee.
2197 ///
2198 static QualType
2200  QualType ToPointee, QualType ToType,
2201  ASTContext &Context,
2202  bool StripObjCLifetime = false) {
2203  assert((FromPtr->getTypeClass() == Type::Pointer ||
2204  FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2205  "Invalid similarly-qualified pointer type");
2206 
2207  /// Conversions to 'id' subsume cv-qualifier conversions.
2208  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2209  return ToType.getUnqualifiedType();
2210 
2211  QualType CanonFromPointee
2212  = Context.getCanonicalType(FromPtr->getPointeeType());
2213  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2214  Qualifiers Quals = CanonFromPointee.getQualifiers();
2215 
2216  if (StripObjCLifetime)
2217  Quals.removeObjCLifetime();
2218 
2219  // Exact qualifier match -> return the pointer type we're converting to.
2220  if (CanonToPointee.getLocalQualifiers() == Quals) {
2221  // ToType is exactly what we need. Return it.
2222  if (!ToType.isNull())
2223  return ToType.getUnqualifiedType();
2224 
2225  // Build a pointer to ToPointee. It has the right qualifiers
2226  // already.
2227  if (isa<ObjCObjectPointerType>(ToType))
2228  return Context.getObjCObjectPointerType(ToPointee);
2229  return Context.getPointerType(ToPointee);
2230  }
2231 
2232  // Just build a canonical type that has the right qualifiers.
2233  QualType QualifiedCanonToPointee
2234  = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2235 
2236  if (isa<ObjCObjectPointerType>(ToType))
2237  return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2238  return Context.getPointerType(QualifiedCanonToPointee);
2239 }
2240 
2242  bool InOverloadResolution,
2243  ASTContext &Context) {
2244  // Handle value-dependent integral null pointer constants correctly.
2245  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2246  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2247  Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2248  return !InOverloadResolution;
2249 
2250  return Expr->isNullPointerConstant(Context,
2251  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2253 }
2254 
2255 /// IsPointerConversion - Determines whether the conversion of the
2256 /// expression From, which has the (possibly adjusted) type FromType,
2257 /// can be converted to the type ToType via a pointer conversion (C++
2258 /// 4.10). If so, returns true and places the converted type (that
2259 /// might differ from ToType in its cv-qualifiers at some level) into
2260 /// ConvertedType.
2261 ///
2262 /// This routine also supports conversions to and from block pointers
2263 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2264 /// pointers to interfaces. FIXME: Once we've determined the
2265 /// appropriate overloading rules for Objective-C, we may want to
2266 /// split the Objective-C checks into a different routine; however,
2267 /// GCC seems to consider all of these conversions to be pointer
2268 /// conversions, so for now they live here. IncompatibleObjC will be
2269 /// set if the conversion is an allowed Objective-C conversion that
2270 /// should result in a warning.
2271 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2272  bool InOverloadResolution,
2273  QualType& ConvertedType,
2274  bool &IncompatibleObjC) {
2275  IncompatibleObjC = false;
2276  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2277  IncompatibleObjC))
2278  return true;
2279 
2280  // Conversion from a null pointer constant to any Objective-C pointer type.
2281  if (ToType->isObjCObjectPointerType() &&
2282  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2283  ConvertedType = ToType;
2284  return true;
2285  }
2286 
2287  // Blocks: Block pointers can be converted to void*.
2288  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2289  ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2290  ConvertedType = ToType;
2291  return true;
2292  }
2293  // Blocks: A null pointer constant can be converted to a block
2294  // pointer type.
2295  if (ToType->isBlockPointerType() &&
2296  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2297  ConvertedType = ToType;
2298  return true;
2299  }
2300 
2301  // If the left-hand-side is nullptr_t, the right side can be a null
2302  // pointer constant.
2303  if (ToType->isNullPtrType() &&
2304  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2305  ConvertedType = ToType;
2306  return true;
2307  }
2308 
2309  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2310  if (!ToTypePtr)
2311  return false;
2312 
2313  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2314  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2315  ConvertedType = ToType;
2316  return true;
2317  }
2318 
2319  // Beyond this point, both types need to be pointers
2320  // , including objective-c pointers.
2321  QualType ToPointeeType = ToTypePtr->getPointeeType();
2322  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2323  !getLangOpts().ObjCAutoRefCount) {
2324  ConvertedType = BuildSimilarlyQualifiedPointerType(
2325  FromType->getAs<ObjCObjectPointerType>(),
2326  ToPointeeType,
2327  ToType, Context);
2328  return true;
2329  }
2330  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2331  if (!FromTypePtr)
2332  return false;
2333 
2334  QualType FromPointeeType = FromTypePtr->getPointeeType();
2335 
2336  // If the unqualified pointee types are the same, this can't be a
2337  // pointer conversion, so don't do all of the work below.
2338  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2339  return false;
2340 
2341  // An rvalue of type "pointer to cv T," where T is an object type,
2342  // can be converted to an rvalue of type "pointer to cv void" (C++
2343  // 4.10p2).
2344  if (FromPointeeType->isIncompleteOrObjectType() &&
2345  ToPointeeType->isVoidType()) {
2346  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2347  ToPointeeType,
2348  ToType, Context,
2349  /*StripObjCLifetime=*/true);
2350  return true;
2351  }
2352 
2353  // MSVC allows implicit function to void* type conversion.
2354  if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2355  ToPointeeType->isVoidType()) {
2356  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2357  ToPointeeType,
2358  ToType, Context);
2359  return true;
2360  }
2361 
2362  // When we're overloading in C, we allow a special kind of pointer
2363  // conversion for compatible-but-not-identical pointee types.
2364  if (!getLangOpts().CPlusPlus &&
2365  Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2366  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2367  ToPointeeType,
2368  ToType, Context);
2369  return true;
2370  }
2371 
2372  // C++ [conv.ptr]p3:
2373  //
2374  // An rvalue of type "pointer to cv D," where D is a class type,
2375  // can be converted to an rvalue of type "pointer to cv B," where
2376  // B is a base class (clause 10) of D. If B is an inaccessible
2377  // (clause 11) or ambiguous (10.2) base class of D, a program that
2378  // necessitates this conversion is ill-formed. The result of the
2379  // conversion is a pointer to the base class sub-object of the
2380  // derived class object. The null pointer value is converted to
2381  // the null pointer value of the destination type.
2382  //
2383  // Note that we do not check for ambiguity or inaccessibility
2384  // here. That is handled by CheckPointerConversion.
2385  if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2386  ToPointeeType->isRecordType() &&
2387  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2388  IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2389  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2390  ToPointeeType,
2391  ToType, Context);
2392  return true;
2393  }
2394 
2395  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2396  Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2397  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2398  ToPointeeType,
2399  ToType, Context);
2400  return true;
2401  }
2402 
2403  return false;
2404 }
2405 
2406 /// Adopt the given qualifiers for the given type.
2408  Qualifiers TQs = T.getQualifiers();
2409 
2410  // Check whether qualifiers already match.
2411  if (TQs == Qs)
2412  return T;
2413 
2414  if (Qs.compatiblyIncludes(TQs))
2415  return Context.getQualifiedType(T, Qs);
2416 
2417  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2418 }
2419 
2420 /// isObjCPointerConversion - Determines whether this is an
2421 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2422 /// with the same arguments and return values.
2424  QualType& ConvertedType,
2425  bool &IncompatibleObjC) {
2426  if (!getLangOpts().ObjC)
2427  return false;
2428 
2429  // The set of qualifiers on the type we're converting from.
2430  Qualifiers FromQualifiers = FromType.getQualifiers();
2431 
2432  // First, we handle all conversions on ObjC object pointer types.
2433  const ObjCObjectPointerType* ToObjCPtr =
2434  ToType->getAs<ObjCObjectPointerType>();
2435  const ObjCObjectPointerType *FromObjCPtr =
2436  FromType->getAs<ObjCObjectPointerType>();
2437 
2438  if (ToObjCPtr && FromObjCPtr) {
2439  // If the pointee types are the same (ignoring qualifications),
2440  // then this is not a pointer conversion.
2441  if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2442  FromObjCPtr->getPointeeType()))
2443  return false;
2444 
2445  // Conversion between Objective-C pointers.
2446  if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2447  const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2448  const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2449  if (getLangOpts().CPlusPlus && LHS && RHS &&
2450  !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2451  FromObjCPtr->getPointeeType()))
2452  return false;
2453  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2454  ToObjCPtr->getPointeeType(),
2455  ToType, Context);
2456  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2457  return true;
2458  }
2459 
2460  if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2461  // Okay: this is some kind of implicit downcast of Objective-C
2462  // interfaces, which is permitted. However, we're going to
2463  // complain about it.
2464  IncompatibleObjC = true;
2465  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2466  ToObjCPtr->getPointeeType(),
2467  ToType, Context);
2468  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2469  return true;
2470  }
2471  }
2472  // Beyond this point, both types need to be C pointers or block pointers.
2473  QualType ToPointeeType;
2474  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2475  ToPointeeType = ToCPtr->getPointeeType();
2476  else if (const BlockPointerType *ToBlockPtr =
2477  ToType->getAs<BlockPointerType>()) {
2478  // Objective C++: We're able to convert from a pointer to any object
2479  // to a block pointer type.
2480  if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2481  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2482  return true;
2483  }
2484  ToPointeeType = ToBlockPtr->getPointeeType();
2485  }
2486  else if (FromType->getAs<BlockPointerType>() &&
2487  ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2488  // Objective C++: We're able to convert from a block pointer type to a
2489  // pointer to any object.
2490  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2491  return true;
2492  }
2493  else
2494  return false;
2495 
2496  QualType FromPointeeType;
2497  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2498  FromPointeeType = FromCPtr->getPointeeType();
2499  else if (const BlockPointerType *FromBlockPtr =
2500  FromType->getAs<BlockPointerType>())
2501  FromPointeeType = FromBlockPtr->getPointeeType();
2502  else
2503  return false;
2504 
2505  // If we have pointers to pointers, recursively check whether this
2506  // is an Objective-C conversion.
2507  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2508  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2509  IncompatibleObjC)) {
2510  // We always complain about this conversion.
2511  IncompatibleObjC = true;
2512  ConvertedType = Context.getPointerType(ConvertedType);
2513  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2514  return true;
2515  }
2516  // Allow conversion of pointee being objective-c pointer to another one;
2517  // as in I* to id.
2518  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2519  ToPointeeType->getAs<ObjCObjectPointerType>() &&
2520  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2521  IncompatibleObjC)) {
2522 
2523  ConvertedType = Context.getPointerType(ConvertedType);
2524  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2525  return true;
2526  }
2527 
2528  // If we have pointers to functions or blocks, check whether the only
2529  // differences in the argument and result types are in Objective-C
2530  // pointer conversions. If so, we permit the conversion (but
2531  // complain about it).
2532  const FunctionProtoType *FromFunctionType
2533  = FromPointeeType->getAs<FunctionProtoType>();
2534  const FunctionProtoType *ToFunctionType
2535  = ToPointeeType->getAs<FunctionProtoType>();
2536  if (FromFunctionType && ToFunctionType) {
2537  // If the function types are exactly the same, this isn't an
2538  // Objective-C pointer conversion.
2539  if (Context.getCanonicalType(FromPointeeType)
2540  == Context.getCanonicalType(ToPointeeType))
2541  return false;
2542 
2543  // Perform the quick checks that will tell us whether these
2544  // function types are obviously different.
2545  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2546  FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2547  FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2548  return false;
2549 
2550  bool HasObjCConversion = false;
2551  if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2552  Context.getCanonicalType(ToFunctionType->getReturnType())) {
2553  // Okay, the types match exactly. Nothing to do.
2554  } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2555  ToFunctionType->getReturnType(),
2556  ConvertedType, IncompatibleObjC)) {
2557  // Okay, we have an Objective-C pointer conversion.
2558  HasObjCConversion = true;
2559  } else {
2560  // Function types are too different. Abort.
2561  return false;
2562  }
2563 
2564  // Check argument types.
2565  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2566  ArgIdx != NumArgs; ++ArgIdx) {
2567  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2568  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2569  if (Context.getCanonicalType(FromArgType)
2570  == Context.getCanonicalType(ToArgType)) {
2571  // Okay, the types match exactly. Nothing to do.
2572  } else if (isObjCPointerConversion(FromArgType, ToArgType,
2573  ConvertedType, IncompatibleObjC)) {
2574  // Okay, we have an Objective-C pointer conversion.
2575  HasObjCConversion = true;
2576  } else {
2577  // Argument types are too different. Abort.
2578  return false;
2579  }
2580  }
2581 
2582  if (HasObjCConversion) {
2583  // We had an Objective-C conversion. Allow this pointer
2584  // conversion, but complain about it.
2585  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2586  IncompatibleObjC = true;
2587  return true;
2588  }
2589  }
2590 
2591  return false;
2592 }
2593 
2594 /// Determine whether this is an Objective-C writeback conversion,
2595 /// used for parameter passing when performing automatic reference counting.
2596 ///
2597 /// \param FromType The type we're converting form.
2598 ///
2599 /// \param ToType The type we're converting to.
2600 ///
2601 /// \param ConvertedType The type that will be produced after applying
2602 /// this conversion.
2604  QualType &ConvertedType) {
2605  if (!getLangOpts().ObjCAutoRefCount ||
2606  Context.hasSameUnqualifiedType(FromType, ToType))
2607  return false;
2608 
2609  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2610  QualType ToPointee;
2611  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2612  ToPointee = ToPointer->getPointeeType();
2613  else
2614  return false;
2615 
2616  Qualifiers ToQuals = ToPointee.getQualifiers();
2617  if (!ToPointee->isObjCLifetimeType() ||
2619  !ToQuals.withoutObjCLifetime().empty())
2620  return false;
2621 
2622  // Argument must be a pointer to __strong to __weak.
2623  QualType FromPointee;
2624  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2625  FromPointee = FromPointer->getPointeeType();
2626  else
2627  return false;
2628 
2629  Qualifiers FromQuals = FromPointee.getQualifiers();
2630  if (!FromPointee->isObjCLifetimeType() ||
2631  (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2632  FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2633  return false;
2634 
2635  // Make sure that we have compatible qualifiers.
2637  if (!ToQuals.compatiblyIncludes(FromQuals))
2638  return false;
2639 
2640  // Remove qualifiers from the pointee type we're converting from; they
2641  // aren't used in the compatibility check belong, and we'll be adding back
2642  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2643  FromPointee = FromPointee.getUnqualifiedType();
2644 
2645  // The unqualified form of the pointee types must be compatible.
2646  ToPointee = ToPointee.getUnqualifiedType();
2647  bool IncompatibleObjC;
2648  if (Context.typesAreCompatible(FromPointee, ToPointee))
2649  FromPointee = ToPointee;
2650  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2651  IncompatibleObjC))
2652  return false;
2653 
2654  /// Construct the type we're converting to, which is a pointer to
2655  /// __autoreleasing pointee.
2656  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2657  ConvertedType = Context.getPointerType(FromPointee);
2658  return true;
2659 }
2660 
2662  QualType& ConvertedType) {
2663  QualType ToPointeeType;
2664  if (const BlockPointerType *ToBlockPtr =
2665  ToType->getAs<BlockPointerType>())
2666  ToPointeeType = ToBlockPtr->getPointeeType();
2667  else
2668  return false;
2669 
2670  QualType FromPointeeType;
2671  if (const BlockPointerType *FromBlockPtr =
2672  FromType->getAs<BlockPointerType>())
2673  FromPointeeType = FromBlockPtr->getPointeeType();
2674  else
2675  return false;
2676  // We have pointer to blocks, check whether the only
2677  // differences in the argument and result types are in Objective-C
2678  // pointer conversions. If so, we permit the conversion.
2679 
2680  const FunctionProtoType *FromFunctionType
2681  = FromPointeeType->getAs<FunctionProtoType>();
2682  const FunctionProtoType *ToFunctionType
2683  = ToPointeeType->getAs<FunctionProtoType>();
2684 
2685  if (!FromFunctionType || !ToFunctionType)
2686  return false;
2687 
2688  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2689  return true;
2690 
2691  // Perform the quick checks that will tell us whether these
2692  // function types are obviously different.
2693  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2694  FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2695  return false;
2696 
2697  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2698  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2699  if (FromEInfo != ToEInfo)
2700  return false;
2701 
2702  bool IncompatibleObjC = false;
2703  if (Context.hasSameType(FromFunctionType->getReturnType(),
2704  ToFunctionType->getReturnType())) {
2705  // Okay, the types match exactly. Nothing to do.
2706  } else {
2707  QualType RHS = FromFunctionType->getReturnType();
2708  QualType LHS = ToFunctionType->getReturnType();
2709  if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2710  !RHS.hasQualifiers() && LHS.hasQualifiers())
2711  LHS = LHS.getUnqualifiedType();
2712 
2713  if (Context.hasSameType(RHS,LHS)) {
2714  // OK exact match.
2715  } else if (isObjCPointerConversion(RHS, LHS,
2716  ConvertedType, IncompatibleObjC)) {
2717  if (IncompatibleObjC)
2718  return false;
2719  // Okay, we have an Objective-C pointer conversion.
2720  }
2721  else
2722  return false;
2723  }
2724 
2725  // Check argument types.
2726  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2727  ArgIdx != NumArgs; ++ArgIdx) {
2728  IncompatibleObjC = false;
2729  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2730  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2731  if (Context.hasSameType(FromArgType, ToArgType)) {
2732  // Okay, the types match exactly. Nothing to do.
2733  } else if (isObjCPointerConversion(ToArgType, FromArgType,
2734  ConvertedType, IncompatibleObjC)) {
2735  if (IncompatibleObjC)
2736  return false;
2737  // Okay, we have an Objective-C pointer conversion.
2738  } else
2739  // Argument types are too different. Abort.
2740  return false;
2741  }
2742 
2744  bool CanUseToFPT, CanUseFromFPT;
2745  if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2746  CanUseToFPT, CanUseFromFPT,
2747  NewParamInfos))
2748  return false;
2749 
2750  ConvertedType = ToType;
2751  return true;
2752 }
2753 
2754 enum {
2762 };
2763 
2764 /// Attempts to get the FunctionProtoType from a Type. Handles
2765 /// MemberFunctionPointers properly.
2767  if (auto *FPT = FromType->getAs<FunctionProtoType>())
2768  return FPT;
2769 
2770  if (auto *MPT = FromType->getAs<MemberPointerType>())
2771  return MPT->getPointeeType()->getAs<FunctionProtoType>();
2772 
2773  return nullptr;
2774 }
2775 
2776 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2777 /// function types. Catches different number of parameter, mismatch in
2778 /// parameter types, and different return types.
2780  QualType FromType, QualType ToType) {
2781  // If either type is not valid, include no extra info.
2782  if (FromType.isNull() || ToType.isNull()) {
2783  PDiag << ft_default;
2784  return;
2785  }
2786 
2787  // Get the function type from the pointers.
2788  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2789  const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2790  *ToMember = ToType->getAs<MemberPointerType>();
2791  if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2792  PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2793  << QualType(FromMember->getClass(), 0);
2794  return;
2795  }
2796  FromType = FromMember->getPointeeType();
2797  ToType = ToMember->getPointeeType();
2798  }
2799 
2800  if (FromType->isPointerType())
2801  FromType = FromType->getPointeeType();
2802  if (ToType->isPointerType())
2803  ToType = ToType->getPointeeType();
2804 
2805  // Remove references.
2806  FromType = FromType.getNonReferenceType();
2807  ToType = ToType.getNonReferenceType();
2808 
2809  // Don't print extra info for non-specialized template functions.
2810  if (FromType->isInstantiationDependentType() &&
2811  !FromType->getAs<TemplateSpecializationType>()) {
2812  PDiag << ft_default;
2813  return;
2814  }
2815 
2816  // No extra info for same types.
2817  if (Context.hasSameType(FromType, ToType)) {
2818  PDiag << ft_default;
2819  return;
2820  }
2821 
2822  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2823  *ToFunction = tryGetFunctionProtoType(ToType);
2824 
2825  // Both types need to be function types.
2826  if (!FromFunction || !ToFunction) {
2827  PDiag << ft_default;
2828  return;
2829  }
2830 
2831  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2832  PDiag << ft_parameter_arity << ToFunction->getNumParams()
2833  << FromFunction->getNumParams();
2834  return;
2835  }
2836 
2837  // Handle different parameter types.
2838  unsigned ArgPos;
2839  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2840  PDiag << ft_parameter_mismatch << ArgPos + 1
2841  << ToFunction->getParamType(ArgPos)
2842  << FromFunction->getParamType(ArgPos);
2843  return;
2844  }
2845 
2846  // Handle different return type.
2847  if (!Context.hasSameType(FromFunction->getReturnType(),
2848  ToFunction->getReturnType())) {
2849  PDiag << ft_return_type << ToFunction->getReturnType()
2850  << FromFunction->getReturnType();
2851  return;
2852  }
2853 
2854  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2855  PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2856  << FromFunction->getMethodQuals();
2857  return;
2858  }
2859 
2860  // Handle exception specification differences on canonical type (in C++17
2861  // onwards).
2862  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2863  ->isNothrow() !=
2864  cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2865  ->isNothrow()) {
2866  PDiag << ft_noexcept;
2867  return;
2868  }
2869 
2870  // Unable to find a difference, so add no extra info.
2871  PDiag << ft_default;
2872 }
2873 
2874 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2875 /// for equality of their argument types. Caller has already checked that
2876 /// they have same number of arguments. If the parameters are different,
2877 /// ArgPos will have the parameter index of the first different parameter.
2879  const FunctionProtoType *NewType,
2880  unsigned *ArgPos) {
2882  N = NewType->param_type_begin(),
2883  E = OldType->param_type_end();
2884  O && (O != E); ++O, ++N) {
2885  if (!Context.hasSameType(O->getUnqualifiedType(),
2886  N->getUnqualifiedType())) {
2887  if (ArgPos)
2888  *ArgPos = O - OldType->param_type_begin();
2889  return false;
2890  }
2891  }
2892  return true;
2893 }
2894 
2895 /// CheckPointerConversion - Check the pointer conversion from the
2896 /// expression From to the type ToType. This routine checks for
2897 /// ambiguous or inaccessible derived-to-base pointer
2898 /// conversions for which IsPointerConversion has already returned
2899 /// true. It returns true and produces a diagnostic if there was an
2900 /// error, or returns false otherwise.
2902  CastKind &Kind,
2903  CXXCastPath& BasePath,
2904  bool IgnoreBaseAccess,
2905  bool Diagnose) {
2906  QualType FromType = From->getType();
2907  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2908 
2909  Kind = CK_BitCast;
2910 
2911  if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2914  if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2915  DiagRuntimeBehavior(From->getExprLoc(), From,
2916  PDiag(diag::warn_impcast_bool_to_null_pointer)
2917  << ToType << From->getSourceRange());
2918  else if (!isUnevaluatedContext())
2919  Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2920  << ToType << From->getSourceRange();
2921  }
2922  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2923  if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2924  QualType FromPointeeType = FromPtrType->getPointeeType(),
2925  ToPointeeType = ToPtrType->getPointeeType();
2926 
2927  if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2928  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2929  // We must have a derived-to-base conversion. Check an
2930  // ambiguous or inaccessible conversion.
2931  unsigned InaccessibleID = 0;
2932  unsigned AmbigiousID = 0;
2933  if (Diagnose) {
2934  InaccessibleID = diag::err_upcast_to_inaccessible_base;
2935  AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2936  }
2937  if (CheckDerivedToBaseConversion(
2938  FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2939  From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2940  &BasePath, IgnoreBaseAccess))
2941  return true;
2942 
2943  // The conversion was successful.
2944  Kind = CK_DerivedToBase;
2945  }
2946 
2947  if (Diagnose && !IsCStyleOrFunctionalCast &&
2948  FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2949  assert(getLangOpts().MSVCCompat &&
2950  "this should only be possible with MSVCCompat!");
2951  Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2952  << From->getSourceRange();
2953  }
2954  }
2955  } else if (const ObjCObjectPointerType *ToPtrType =
2956  ToType->getAs<ObjCObjectPointerType>()) {
2957  if (const ObjCObjectPointerType *FromPtrType =
2958  FromType->getAs<ObjCObjectPointerType>()) {
2959  // Objective-C++ conversions are always okay.
2960  // FIXME: We should have a different class of conversions for the
2961  // Objective-C++ implicit conversions.
2962  if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2963  return false;
2964  } else if (FromType->isBlockPointerType()) {
2965  Kind = CK_BlockPointerToObjCPointerCast;
2966  } else {
2967  Kind = CK_CPointerToObjCPointerCast;
2968  }
2969  } else if (ToType->isBlockPointerType()) {
2970  if (!FromType->isBlockPointerType())
2971  Kind = CK_AnyPointerToBlockPointerCast;
2972  }
2973 
2974  // We shouldn't fall into this case unless it's valid for other
2975  // reasons.
2977  Kind = CK_NullToPointer;
2978 
2979  return false;
2980 }
2981 
2982 /// IsMemberPointerConversion - Determines whether the conversion of the
2983 /// expression From, which has the (possibly adjusted) type FromType, can be
2984 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2985 /// If so, returns true and places the converted type (that might differ from
2986 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2988  QualType ToType,
2989  bool InOverloadResolution,
2990  QualType &ConvertedType) {
2991  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2992  if (!ToTypePtr)
2993  return false;
2994 
2995  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2996  if (From->isNullPointerConstant(Context,
2997  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2999  ConvertedType = ToType;
3000  return true;
3001  }
3002 
3003  // Otherwise, both types have to be member pointers.
3004  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3005  if (!FromTypePtr)
3006  return false;
3007 
3008  // A pointer to member of B can be converted to a pointer to member of D,
3009  // where D is derived from B (C++ 4.11p2).
3010  QualType FromClass(FromTypePtr->getClass(), 0);
3011  QualType ToClass(ToTypePtr->getClass(), 0);
3012 
3013  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3014  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3015  ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3016  ToClass.getTypePtr());
3017  return true;
3018  }
3019 
3020  return false;
3021 }
3022 
3023 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3024 /// expression From to the type ToType. This routine checks for ambiguous or
3025 /// virtual or inaccessible base-to-derived member pointer conversions
3026 /// for which IsMemberPointerConversion has already returned true. It returns
3027 /// true and produces a diagnostic if there was an error, or returns false
3028 /// otherwise.
3030  CastKind &Kind,
3031  CXXCastPath &BasePath,
3032  bool IgnoreBaseAccess) {
3033  QualType FromType = From->getType();
3034  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3035  if (!FromPtrType) {
3036  // This must be a null pointer to member pointer conversion
3037  assert(From->isNullPointerConstant(Context,
3039  "Expr must be null pointer constant!");
3040  Kind = CK_NullToMemberPointer;
3041  return false;
3042  }
3043 
3044  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3045  assert(ToPtrType && "No member pointer cast has a target type "
3046  "that is not a member pointer.");
3047 
3048  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3049  QualType ToClass = QualType(ToPtrType->getClass(), 0);
3050 
3051  // FIXME: What about dependent types?
3052  assert(FromClass->isRecordType() && "Pointer into non-class.");
3053  assert(ToClass->isRecordType() && "Pointer into non-class.");
3054 
3055  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3056  /*DetectVirtual=*/true);
3057  bool DerivationOkay =
3058  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3059  assert(DerivationOkay &&
3060  "Should not have been called if derivation isn't OK.");
3061  (void)DerivationOkay;
3062 
3063  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3064  getUnqualifiedType())) {
3065  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3066  Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3067  << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3068  return true;
3069  }
3070 
3071  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3072  Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3073  << FromClass << ToClass << QualType(VBase, 0)
3074  << From->getSourceRange();
3075  return true;
3076  }
3077 
3078  if (!IgnoreBaseAccess)
3079  CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3080  Paths.front(),
3081  diag::err_downcast_from_inaccessible_base);
3082 
3083  // Must be a base to derived member conversion.
3084  BuildBasePathArray(Paths, BasePath);
3085  Kind = CK_BaseToDerivedMemberPointer;
3086  return false;
3087 }
3088 
3089 /// Determine whether the lifetime conversion between the two given
3090 /// qualifiers sets is nontrivial.
3092  Qualifiers ToQuals) {
3093  // Converting anything to const __unsafe_unretained is trivial.
3094  if (ToQuals.hasConst() &&
3096  return false;
3097 
3098  return true;
3099 }
3100 
3101 /// IsQualificationConversion - Determines whether the conversion from
3102 /// an rvalue of type FromType to ToType is a qualification conversion
3103 /// (C++ 4.4).
3104 ///
3105 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3106 /// when the qualification conversion involves a change in the Objective-C
3107 /// object lifetime.
3108 bool
3110  bool CStyle, bool &ObjCLifetimeConversion) {
3111  FromType = Context.getCanonicalType(FromType);
3112  ToType = Context.getCanonicalType(ToType);
3113  ObjCLifetimeConversion = false;
3114 
3115  // If FromType and ToType are the same type, this is not a
3116  // qualification conversion.
3117  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3118  return false;
3119 
3120  // (C++ 4.4p4):
3121  // A conversion can add cv-qualifiers at levels other than the first
3122  // in multi-level pointers, subject to the following rules: [...]
3123  bool PreviousToQualsIncludeConst = true;
3124  bool UnwrappedAnyPointer = false;
3125  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3126  // Within each iteration of the loop, we check the qualifiers to
3127  // determine if this still looks like a qualification
3128  // conversion. Then, if all is well, we unwrap one more level of
3129  // pointers or pointers-to-members and do it all again
3130  // until there are no more pointers or pointers-to-members left to
3131  // unwrap.
3132  UnwrappedAnyPointer = true;
3133 
3134  Qualifiers FromQuals = FromType.getQualifiers();
3135  Qualifiers ToQuals = ToType.getQualifiers();
3136 
3137  // Ignore __unaligned qualifier if this type is void.
3138  if (ToType.getUnqualifiedType()->isVoidType())
3139  FromQuals.removeUnaligned();
3140 
3141  // Objective-C ARC:
3142  // Check Objective-C lifetime conversions.
3143  if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3144  UnwrappedAnyPointer) {
3145  if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3146  if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3147  ObjCLifetimeConversion = true;
3148  FromQuals.removeObjCLifetime();
3149  ToQuals.removeObjCLifetime();
3150  } else {
3151  // Qualification conversions cannot cast between different
3152  // Objective-C lifetime qualifiers.
3153  return false;
3154  }
3155  }
3156 
3157  // Allow addition/removal of GC attributes but not changing GC attributes.
3158  if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3159  (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3160  FromQuals.removeObjCGCAttr();
3161  ToQuals.removeObjCGCAttr();
3162  }
3163 
3164  // -- for every j > 0, if const is in cv 1,j then const is in cv
3165  // 2,j, and similarly for volatile.
3166  if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3167  return false;
3168 
3169  // -- if the cv 1,j and cv 2,j are different, then const is in
3170  // every cv for 0 < k < j.
3171  if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3172  && !PreviousToQualsIncludeConst)
3173  return false;
3174 
3175  // Keep track of whether all prior cv-qualifiers in the "to" type
3176  // include const.
3177  PreviousToQualsIncludeConst
3178  = PreviousToQualsIncludeConst && ToQuals.hasConst();
3179  }
3180 
3181  // Allows address space promotion by language rules implemented in
3182  // Type::Qualifiers::isAddressSpaceSupersetOf.
3183  Qualifiers FromQuals = FromType.getQualifiers();
3184  Qualifiers ToQuals = ToType.getQualifiers();
3185  if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3186  !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3187  return false;
3188  }
3189 
3190  // We are left with FromType and ToType being the pointee types
3191  // after unwrapping the original FromType and ToType the same number
3192  // of types. If we unwrapped any pointers, and if FromType and
3193  // ToType have the same unqualified type (since we checked
3194  // qualifiers above), then this is a qualification conversion.
3195  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3196 }
3197 
3198 /// - Determine whether this is a conversion from a scalar type to an
3199 /// atomic type.
3200 ///
3201 /// If successful, updates \c SCS's second and third steps in the conversion
3202 /// sequence to finish the conversion.
3203 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3204  bool InOverloadResolution,
3206  bool CStyle) {
3207  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3208  if (!ToAtomic)
3209  return false;
3210 
3211  StandardConversionSequence InnerSCS;
3212  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3213  InOverloadResolution, InnerSCS,
3214  CStyle, /*AllowObjCWritebackConversion=*/false))
3215  return false;
3216 
3217  SCS.Second = InnerSCS.Second;
3218  SCS.setToType(1, InnerSCS.getToType(1));
3219  SCS.Third = InnerSCS.Third;
3221  = InnerSCS.QualificationIncludesObjCLifetime;
3222  SCS.setToType(2, InnerSCS.getToType(2));
3223  return true;
3224 }
3225 
3227  CXXConstructorDecl *Constructor,
3228  QualType Type) {
3229  const FunctionProtoType *CtorType =
3230  Constructor->getType()->getAs<FunctionProtoType>();
3231  if (CtorType->getNumParams() > 0) {
3232  QualType FirstArg = CtorType->getParamType(0);
3233  if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3234  return true;
3235  }
3236  return false;
3237 }
3238 
3239 static OverloadingResult
3241  CXXRecordDecl *To,
3243  OverloadCandidateSet &CandidateSet,
3244  bool AllowExplicit) {
3246  for (auto *D : S.LookupConstructors(To)) {
3247  auto Info = getConstructorInfo(D);
3248  if (!Info)
3249  continue;
3250 
3251  bool Usable = !Info.Constructor->isInvalidDecl() &&
3252  S.isInitListConstructor(Info.Constructor) &&
3253  (AllowExplicit || !Info.Constructor->isExplicit());
3254  if (Usable) {
3255  // If the first argument is (a reference to) the target type,
3256  // suppress conversions.
3257  bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3258  S.Context, Info.Constructor, ToType);
3259  if (Info.ConstructorTmpl)
3260  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3261  /*ExplicitArgs*/ nullptr, From,
3262  CandidateSet, SuppressUserConversions);
3263  else
3264  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3265  CandidateSet, SuppressUserConversions);
3266  }
3267  }
3268 
3269  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3270 
3272  switch (auto Result =
3273  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3274  case OR_Deleted:
3275  case OR_Success: {
3276  // Record the standard conversion we used and the conversion function.
3277  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3278  QualType ThisType = Constructor->getThisType();
3279  // Initializer lists don't have conversions as such.
3281  User.HadMultipleCandidates = HadMultipleCandidates;
3282  User.ConversionFunction = Constructor;
3283  User.FoundConversionFunction = Best->FoundDecl;
3285  User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3286  User.After.setAllToTypes(ToType);
3287  return Result;
3288  }
3289 
3290  case OR_No_Viable_Function:
3291  return OR_No_Viable_Function;
3292  case OR_Ambiguous:
3293  return OR_Ambiguous;
3294  }
3295 
3296  llvm_unreachable("Invalid OverloadResult!");
3297 }
3298 
3299 /// Determines whether there is a user-defined conversion sequence
3300 /// (C++ [over.ics.user]) that converts expression From to the type
3301 /// ToType. If such a conversion exists, User will contain the
3302 /// user-defined conversion sequence that performs such a conversion
3303 /// and this routine will return true. Otherwise, this routine returns
3304 /// false and User is unspecified.
3305 ///
3306 /// \param AllowExplicit true if the conversion should consider C++0x
3307 /// "explicit" conversion functions as well as non-explicit conversion
3308 /// functions (C++0x [class.conv.fct]p2).
3309 ///
3310 /// \param AllowObjCConversionOnExplicit true if the conversion should
3311 /// allow an extra Objective-C pointer conversion on uses of explicit
3312 /// constructors. Requires \c AllowExplicit to also be set.
3313 static OverloadingResult
3316  OverloadCandidateSet &CandidateSet,
3317  bool AllowExplicit,
3318  bool AllowObjCConversionOnExplicit) {
3319  assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3321 
3322  // Whether we will only visit constructors.
3323  bool ConstructorsOnly = false;
3324 
3325  // If the type we are conversion to is a class type, enumerate its
3326  // constructors.
3327  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3328  // C++ [over.match.ctor]p1:
3329  // When objects of class type are direct-initialized (8.5), or
3330  // copy-initialized from an expression of the same or a
3331  // derived class type (8.5), overload resolution selects the
3332  // constructor. [...] For copy-initialization, the candidate
3333  // functions are all the converting constructors (12.3.1) of
3334  // that class. The argument list is the expression-list within
3335  // the parentheses of the initializer.
3336  if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3337  (From->getType()->getAs<RecordType>() &&
3338  S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3339  ConstructorsOnly = true;
3340 
3341  if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3342  // We're not going to find any constructors.
3343  } else if (CXXRecordDecl *ToRecordDecl
3344  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3345 
3346  Expr **Args = &From;
3347  unsigned NumArgs = 1;
3348  bool ListInitializing = false;
3349  if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3350  // But first, see if there is an init-list-constructor that will work.
3352  S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3353  if (Result != OR_No_Viable_Function)
3354  return Result;
3355  // Never mind.
3356  CandidateSet.clear(
3358 
3359  // If we're list-initializing, we pass the individual elements as
3360  // arguments, not the entire list.
3361  Args = InitList->getInits();
3362  NumArgs = InitList->getNumInits();
3363  ListInitializing = true;
3364  }
3365 
3366  for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3367  auto Info = getConstructorInfo(D);
3368  if (!Info)
3369  continue;
3370 
3371  bool Usable = !Info.Constructor->isInvalidDecl();
3372  if (ListInitializing)
3373  Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3374  else
3375  Usable = Usable &&
3376  Info.Constructor->isConvertingConstructor(AllowExplicit);
3377  if (Usable) {
3378  bool SuppressUserConversions = !ConstructorsOnly;
3379  if (SuppressUserConversions && ListInitializing) {
3380  SuppressUserConversions = false;
3381  if (NumArgs == 1) {
3382  // If the first argument is (a reference to) the target type,
3383  // suppress conversions.
3384  SuppressUserConversions = isFirstArgumentCompatibleWithType(
3385  S.Context, Info.Constructor, ToType);
3386  }
3387  }
3388  if (Info.ConstructorTmpl)
3390  Info.ConstructorTmpl, Info.FoundDecl,
3391  /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3392  CandidateSet, SuppressUserConversions);
3393  else
3394  // Allow one user-defined conversion when user specifies a
3395  // From->ToType conversion via an static cast (c-style, etc).
3396  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3397  llvm::makeArrayRef(Args, NumArgs),
3398  CandidateSet, SuppressUserConversions);
3399  }
3400  }
3401  }
3402  }
3403 
3404  // Enumerate conversion functions, if we're allowed to.
3405  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3406  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3407  // No conversion functions from incomplete types.
3408  } else if (const RecordType *FromRecordType =
3409  From->getType()->getAs<RecordType>()) {
3410  if (CXXRecordDecl *FromRecordDecl
3411  = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3412  // Add all of the conversion functions as candidates.
3413  const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3414  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3415  DeclAccessPair FoundDecl = I.getPair();
3416  NamedDecl *D = FoundDecl.getDecl();
3417  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3418  if (isa<UsingShadowDecl>(D))
3419  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3420 
3421  CXXConversionDecl *Conv;
3422  FunctionTemplateDecl *ConvTemplate;
3423  if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3424  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3425  else
3426  Conv = cast<CXXConversionDecl>(D);
3427 
3428  if (AllowExplicit || !Conv->isExplicit()) {
3429  if (ConvTemplate)
3430  S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3431  ActingContext, From, ToType,
3432  CandidateSet,
3433  AllowObjCConversionOnExplicit);
3434  else
3435  S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3436  From, ToType, CandidateSet,
3437  AllowObjCConversionOnExplicit);
3438  }
3439  }
3440  }
3441  }
3442 
3443  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3444 
3446  switch (auto Result =
3447  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3448  case OR_Success:
3449  case OR_Deleted:
3450  // Record the standard conversion we used and the conversion function.
3451  if (CXXConstructorDecl *Constructor
3452  = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3453  // C++ [over.ics.user]p1:
3454  // If the user-defined conversion is specified by a
3455  // constructor (12.3.1), the initial standard conversion
3456  // sequence converts the source type to the type required by
3457  // the argument of the constructor.
3458  //
3459  QualType ThisType = Constructor->getThisType();
3460  if (isa<InitListExpr>(From)) {
3461  // Initializer lists don't have conversions as such.
3463  } else {
3464  if (Best->Conversions[0].isEllipsis())
3465  User.EllipsisConversion = true;
3466  else {
3467  User.Before = Best->Conversions[0].Standard;
3468  User.EllipsisConversion = false;
3469  }
3470  }
3471  User.HadMultipleCandidates = HadMultipleCandidates;
3472  User.ConversionFunction = Constructor;
3473  User.FoundConversionFunction = Best->FoundDecl;
3475  User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3476  User.After.setAllToTypes(ToType);
3477  return Result;
3478  }
3479  if (CXXConversionDecl *Conversion
3480  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3481  // C++ [over.ics.user]p1:
3482  //
3483  // [...] If the user-defined conversion is specified by a
3484  // conversion function (12.3.2), the initial standard
3485  // conversion sequence converts the source type to the
3486  // implicit object parameter of the conversion function.
3487  User.Before = Best->Conversions[0].Standard;
3488  User.HadMultipleCandidates = HadMultipleCandidates;
3489  User.ConversionFunction = Conversion;
3490  User.FoundConversionFunction = Best->FoundDecl;
3491  User.EllipsisConversion = false;
3492 
3493  // C++ [over.ics.user]p2:
3494  // The second standard conversion sequence converts the
3495  // result of the user-defined conversion to the target type
3496  // for the sequence. Since an implicit conversion sequence
3497  // is an initialization, the special rules for
3498  // initialization by user-defined conversion apply when
3499  // selecting the best user-defined conversion for a
3500  // user-defined conversion sequence (see 13.3.3 and
3501  // 13.3.3.1).
3502  User.After = Best->FinalConversion;
3503  return Result;
3504  }
3505  llvm_unreachable("Not a constructor or conversion function?");
3506 
3507  case OR_No_Viable_Function:
3508  return OR_No_Viable_Function;
3509 
3510  case OR_Ambiguous:
3511  return OR_Ambiguous;
3512  }
3513 
3514  llvm_unreachable("Invalid OverloadResult!");
3515 }
3516 
3517 bool
3520  OverloadCandidateSet CandidateSet(From->getExprLoc(),
3522  OverloadingResult OvResult =
3523  IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3524  CandidateSet, false, false);
3525  if (OvResult == OR_Ambiguous)
3526  Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3527  << From->getType() << ToType << From->getSourceRange();
3528  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3529  if (!RequireCompleteType(From->getBeginLoc(), ToType,
3530  diag::err_typecheck_nonviable_condition_incomplete,
3531  From->getType(), From->getSourceRange()))
3532  Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3533  << false << From->getType() << From->getSourceRange() << ToType;
3534  } else
3535  return false;
3536  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3537  return true;
3538 }
3539 
3540 /// Compare the user-defined conversion functions or constructors
3541 /// of two user-defined conversion sequences to determine whether any ordering
3542 /// is possible.
3545  FunctionDecl *Function2) {
3546  if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3548 
3549  // Objective-C++:
3550  // If both conversion functions are implicitly-declared conversions from
3551  // a lambda closure type to a function pointer and a block pointer,
3552  // respectively, always prefer the conversion to a function pointer,
3553  // because the function pointer is more lightweight and is more likely
3554  // to keep code working.
3555  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3556  if (!Conv1)
3558 
3559  CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3560  if (!Conv2)
3562 
3563  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3564  bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3565  bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3566  if (Block1 != Block2)
3567  return Block1 ? ImplicitConversionSequence::Worse
3569  }
3570 
3572 }
3573 
3575  const ImplicitConversionSequence &ICS) {
3576  return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3577  (ICS.isUserDefined() &&
3579 }
3580 
3581 /// CompareImplicitConversionSequences - Compare two implicit
3582 /// conversion sequences to determine whether one is better than the
3583 /// other or if they are indistinguishable (C++ 13.3.3.2).
3586  const ImplicitConversionSequence& ICS1,
3587  const ImplicitConversionSequence& ICS2)
3588 {
3589  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3590  // conversion sequences (as defined in 13.3.3.1)
3591  // -- a standard conversion sequence (13.3.3.1.1) is a better
3592  // conversion sequence than a user-defined conversion sequence or
3593  // an ellipsis conversion sequence, and
3594  // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3595  // conversion sequence than an ellipsis conversion sequence
3596  // (13.3.3.1.3).
3597  //
3598  // C++0x [over.best.ics]p10:
3599  // For the purpose of ranking implicit conversion sequences as
3600  // described in 13.3.3.2, the ambiguous conversion sequence is
3601  // treated as a user-defined sequence that is indistinguishable
3602  // from any other user-defined conversion sequence.
3603 
3604  // String literal to 'char *' conversion has been deprecated in C++03. It has
3605  // been removed from C++11. We still accept this conversion, if it happens at
3606  // the best viable function. Otherwise, this conversion is considered worse
3607  // than ellipsis conversion. Consider this as an extension; this is not in the
3608  // standard. For example:
3609  //
3610  // int &f(...); // #1
3611  // void f(char*); // #2
3612  // void g() { int &r = f("foo"); }
3613  //
3614  // In C++03, we pick #2 as the best viable function.
3615  // In C++11, we pick #1 as the best viable function, because ellipsis
3616  // conversion is better than string-literal to char* conversion (since there
3617  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3618  // convert arguments, #2 would be the best viable function in C++11.
3619  // If the best viable function has this conversion, a warning will be issued
3620  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3621 
3622  if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3628 
3629  if (ICS1.getKindRank() < ICS2.getKindRank())
3631  if (ICS2.getKindRank() < ICS1.getKindRank())
3633 
3634  // The following checks require both conversion sequences to be of
3635  // the same kind.
3636  if (ICS1.getKind() != ICS2.getKind())
3638 
3641 
3642  // Two implicit conversion sequences of the same form are
3643  // indistinguishable conversion sequences unless one of the
3644  // following rules apply: (C++ 13.3.3.2p3):
3645 
3646  // List-initialization sequence L1 is a better conversion sequence than
3647  // list-initialization sequence L2 if:
3648  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3649  // if not that,
3650  // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3651  // and N1 is smaller than N2.,
3652  // even if one of the other rules in this paragraph would otherwise apply.
3653  if (!ICS1.isBad()) {
3654  if (ICS1.isStdInitializerListElement() &&
3657  if (!ICS1.isStdInitializerListElement() &&
3660  }
3661 
3662  if (ICS1.isStandard())
3663  // Standard conversion sequence S1 is a better conversion sequence than
3664  // standard conversion sequence S2 if [...]
3665  Result = CompareStandardConversionSequences(S, Loc,
3666  ICS1.Standard, ICS2.Standard);
3667  else if (ICS1.isUserDefined()) {
3668  // User-defined conversion sequence U1 is a better conversion
3669  // sequence than another user-defined conversion sequence U2 if
3670  // they contain the same user-defined conversion function or
3671  // constructor and if the second standard conversion sequence of
3672  // U1 is better than the second standard conversion sequence of
3673  // U2 (C++ 13.3.3.2p3).
3674  if (ICS1.UserDefined.ConversionFunction ==
3676  Result = CompareStandardConversionSequences(S, Loc,
3677  ICS1.UserDefined.After,
3678  ICS2.UserDefined.After);
3679  else
3680  Result = compareConversionFunctions(S,
3683  }
3684 
3685  return Result;
3686 }
3687 
3688 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3689 // determine if one is a proper subset of the other.
3692  const StandardConversionSequence& SCS1,
3693  const StandardConversionSequence& SCS2) {
3696 
3697  // the identity conversion sequence is considered to be a subsequence of
3698  // any non-identity conversion sequence
3699  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3701  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3703 
3704  if (SCS1.Second != SCS2.Second) {
3705  if (SCS1.Second == ICK_Identity)
3707  else if (SCS2.Second == ICK_Identity)
3709  else
3711  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3713 
3714  if (SCS1.Third == SCS2.Third) {
3715  return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3717  }
3718 
3719  if (SCS1.Third == ICK_Identity)
3720  return Result == ImplicitConversionSequence::Worse
3723 
3724  if (SCS2.Third == ICK_Identity)
3725  return Result == ImplicitConversionSequence::Better
3728 
3730 }
3731 
3732 /// Determine whether one of the given reference bindings is better
3733 /// than the other based on what kind of bindings they are.
3734 static bool
3736  const StandardConversionSequence &SCS2) {
3737  // C++0x [over.ics.rank]p3b4:
3738  // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3739  // implicit object parameter of a non-static member function declared
3740  // without a ref-qualifier, and *either* S1 binds an rvalue reference
3741  // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3742  // lvalue reference to a function lvalue and S2 binds an rvalue
3743  // reference*.
3744  //
3745  // FIXME: Rvalue references. We're going rogue with the above edits,
3746  // because the semantics in the current C++0x working paper (N3225 at the
3747  // time of this writing) break the standard definition of std::forward
3748  // and std::reference_wrapper when dealing with references to functions.
3749  // Proposed wording changes submitted to CWG for consideration.
3752  return false;
3753 
3754  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3755  SCS2.IsLvalueReference) ||
3756  (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3758 }
3759 
3760 /// CompareStandardConversionSequences - Compare two standard
3761 /// conversion sequences to determine whether one is better than the
3762 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3765  const StandardConversionSequence& SCS1,
3766  const StandardConversionSequence& SCS2)
3767 {
3768  // Standard conversion sequence S1 is a better conversion sequence
3769  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3770 
3771  // -- S1 is a proper subsequence of S2 (comparing the conversion
3772  // sequences in the canonical form defined by 13.3.3.1.1,
3773  // excluding any Lvalue Transformation; the identity conversion
3774  // sequence is considered to be a subsequence of any
3775  // non-identity conversion sequence) or, if not that,
3777  = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3778  return CK;
3779 
3780  // -- the rank of S1 is better than the rank of S2 (by the rules
3781  // defined below), or, if not that,
3782  ImplicitConversionRank Rank1 = SCS1.getRank();
3783  ImplicitConversionRank Rank2 = SCS2.getRank();
3784  if (Rank1 < Rank2)
3786  else if (Rank2 < Rank1)
3788 
3789  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3790  // are indistinguishable unless one of the following rules
3791  // applies:
3792 
3793  // A conversion that is not a conversion of a pointer, or
3794  // pointer to member, to bool is better than another conversion
3795  // that is such a conversion.
3797  return SCS2.isPointerConversionToBool()
3800 
3801  // C++ [over.ics.rank]p4b2:
3802  //
3803  // If class B is derived directly or indirectly from class A,
3804  // conversion of B* to A* is better than conversion of B* to
3805  // void*, and conversion of A* to void* is better than conversion
3806  // of B* to void*.
3807  bool SCS1ConvertsToVoid
3809  bool SCS2ConvertsToVoid
3811  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3812  // Exactly one of the conversion sequences is a conversion to
3813  // a void pointer; it's the worse conversion.
3814  return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3816  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3817  // Neither conversion sequence converts to a void pointer; compare
3818  // their derived-to-base conversions.
3820  = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3821  return DerivedCK;
3822  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3823  !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3824  // Both conversion sequences are conversions to void
3825  // pointers. Compare the source types to determine if there's an
3826  // inheritance relationship in their sources.
3827  QualType FromType1 = SCS1.getFromType();
3828  QualType FromType2 = SCS2.getFromType();
3829 
3830  // Adjust the types we're converting from via the array-to-pointer
3831  // conversion, if we need to.
3832  if (SCS1.First == ICK_Array_To_Pointer)
3833  FromType1 = S.Context.getArrayDecayedType(FromType1);
3834  if (SCS2.First == ICK_Array_To_Pointer)
3835  FromType2 = S.Context.getArrayDecayedType(FromType2);
3836 
3837  QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3838  QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3839 
3840  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3842  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3844 
3845  // Objective-C++: If one interface is more specific than the
3846  // other, it is the better one.
3847  const ObjCObjectPointerType* FromObjCPtr1
3848  = FromType1->getAs<ObjCObjectPointerType>();
3849  const ObjCObjectPointerType* FromObjCPtr2
3850  = FromType2->getAs<ObjCObjectPointerType>();
3851  if (FromObjCPtr1 && FromObjCPtr2) {
3852  bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3853  FromObjCPtr2);
3854  bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3855  FromObjCPtr1);
3856  if (AssignLeft != AssignRight) {
3857  return AssignLeft? ImplicitConversionSequence::Better
3859  }
3860  }
3861  }
3862 
3863  // Compare based on qualification conversions (C++ 13.3.3.2p3,
3864  // bullet 3).
3866  = CompareQualificationConversions(S, SCS1, SCS2))
3867  return QualCK;
3868 
3869  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3870  // Check for a better reference binding based on the kind of bindings.
3871  if (isBetterReferenceBindingKind(SCS1, SCS2))
3873  else if (isBetterReferenceBindingKind(SCS2, SCS1))
3875 
3876  // C++ [over.ics.rank]p3b4:
3877  // -- S1 and S2 are reference bindings (8.5.3), and the types to
3878  // which the references refer are the same type except for
3879  // top-level cv-qualifiers, and the type to which the reference
3880  // initialized by S2 refers is more cv-qualified than the type
3881  // to which the reference initialized by S1 refers.
3882  QualType T1 = SCS1.getToType(2);
3883  QualType T2 = SCS2.getToType(2);
3884  T1 = S.Context.getCanonicalType(T1);
3885  T2 = S.Context.getCanonicalType(T2);
3886  Qualifiers T1Quals, T2Quals;
3887  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3888  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3889  if (UnqualT1 == UnqualT2) {
3890  // Objective-C++ ARC: If the references refer to objects with different
3891  // lifetimes, prefer bindings that don't change lifetime.
3892  if (SCS1.ObjCLifetimeConversionBinding !=
3894  return SCS1.ObjCLifetimeConversionBinding
3897  }
3898 
3899  // If the type is an array type, promote the element qualifiers to the
3900  // type for comparison.
3901  if (isa<ArrayType>(T1) && T1Quals)
3902  T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3903  if (isa<ArrayType>(T2) && T2Quals)
3904  T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3905  if (T2.isMoreQualifiedThan(T1))
3907  else if (T1.isMoreQualifiedThan(T2))
3909  }
3910  }
3911 
3912  // In Microsoft mode, prefer an integral conversion to a
3913  // floating-to-integral conversion if the integral conversion
3914  // is between types of the same size.
3915  // For example:
3916  // void f(float);
3917  // void f(int);
3918  // int main {
3919  // long a;
3920  // f(a);
3921  // }
3922  // Here, MSVC will call f(int) instead of generating a compile error
3923  // as clang will do in standard mode.
3924  if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3925  SCS2.Second == ICK_Floating_Integral &&
3926  S.Context.getTypeSize(SCS1.getFromType()) ==
3927  S.Context.getTypeSize(SCS1.getToType(2)))
3929 
3930  // Prefer a compatible vector conversion over a lax vector conversion
3931  // For example:
3932  //
3933  // typedef float __v4sf __attribute__((__vector_size__(16)));
3934  // void f(vector float);
3935  // void f(vector signed int);
3936  // int main() {
3937  // __v4sf a;
3938  // f(a);
3939  // }
3940  // Here, we'd like to choose f(vector float) and not
3941  // report an ambiguous call error
3942  if (SCS1.Second == ICK_Vector_Conversion &&
3943  SCS2.Second == ICK_Vector_Conversion) {
3944  bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3945  SCS1.getFromType(), SCS1.getToType(2));
3946  bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3947  SCS2.getFromType(), SCS2.getToType(2));
3948 
3949  if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3950  return SCS1IsCompatibleVectorConversion
3953  }
3954 
3956 }
3957 
3958 /// CompareQualificationConversions - Compares two standard conversion
3959 /// sequences to determine whether they can be ranked based on their
3960 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3963  const StandardConversionSequence& SCS1,
3964  const StandardConversionSequence& SCS2) {
3965  // C++ 13.3.3.2p3:
3966  // -- S1 and S2 differ only in their qualification conversion and
3967  // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3968  // cv-qualification signature of type T1 is a proper subset of
3969  // the cv-qualification signature of type T2, and S1 is not the
3970  // deprecated string literal array-to-pointer conversion (4.2).
3971  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3972  SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3974 
3975  // FIXME: the example in the standard doesn't use a qualification
3976  // conversion (!)
3977  QualType T1 = SCS1.getToType(2);
3978  QualType T2 = SCS2.getToType(2);
3979  T1 = S.Context.getCanonicalType(T1);
3980  T2 = S.Context.getCanonicalType(T2);
3981  Qualifiers T1Quals, T2Quals;
3982  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3983  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3984 
3985  // If the types are the same, we won't learn anything by unwrapped
3986  // them.
3987  if (UnqualT1 == UnqualT2)
3989 
3990  // If the type is an array type, promote the element qualifiers to the type
3991  // for comparison.
3992  if (isa<ArrayType>(T1) && T1Quals)
3993  T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3994  if (isa<ArrayType>(T2) && T2Quals)
3995  T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3996 
3999 
4000  // Objective-C++ ARC:
4001  // Prefer qualification conversions not involving a change in lifetime
4002  // to qualification conversions that do not change lifetime.
4005  Result = SCS1.QualificationIncludesObjCLifetime
4008  }
4009 
4010  while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4011  // Within each iteration of the loop, we check the qualifiers to
4012  // determine if this still looks like a qualification
4013  // conversion. Then, if all is well, we unwrap one more level of
4014  // pointers or pointers-to-members and do it all again
4015  // until there are no more pointers or pointers-to-members left
4016  // to unwrap. This essentially mimics what
4017  // IsQualificationConversion does, but here we're checking for a
4018  // strict subset of qualifiers.
4019  if (T1.getQualifiers().withoutObjCLifetime() ==
4021  // The qualifiers are the same, so this doesn't tell us anything
4022  // about how the sequences rank.
4023  // ObjC ownership quals are omitted above as they interfere with
4024  // the ARC overload rule.
4025  ;
4026  else if (T2.isMoreQualifiedThan(T1)) {
4027  // T1 has fewer qualifiers, so it could be the better sequence.
4028  if (Result == ImplicitConversionSequence::Worse)
4029  // Neither has qualifiers that are a subset of the other's
4030  // qualifiers.
4032 
4034  } else if (T1.isMoreQualifiedThan(T2)) {
4035  // T2 has fewer qualifiers, so it could be the better sequence.
4036  if (Result == ImplicitConversionSequence::Better)
4037  // Neither has qualifiers that are a subset of the other's
4038  // qualifiers.
4040 
4042  } else {
4043  // Qualifiers are disjoint.
4045  }
4046 
4047  // If the types after this point are equivalent, we're done.
4048  if (S.Context.hasSameUnqualifiedType(T1, T2))
4049  break;
4050  }
4051 
4052  // Check that the winning standard conversion sequence isn't using
4053  // the deprecated string literal array to pointer conversion.
4054  switch (Result) {
4058  break;
4059 
4061  break;
4062 
4066  break;
4067  }
4068 
4069  return Result;
4070 }
4071 
4072 /// CompareDerivedToBaseConversions - Compares two standard conversion
4073 /// sequences to determine whether they can be ranked based on their
4074 /// various kinds of derived-to-base conversions (C++
4075 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4076 /// conversions between Objective-C interface types.
4079  const StandardConversionSequence& SCS1,
4080  const StandardConversionSequence& SCS2) {
4081  QualType FromType1 = SCS1.getFromType();
4082  QualType ToType1 = SCS1.getToType(1);
4083  QualType FromType2 = SCS2.getFromType();
4084  QualType ToType2 = SCS2.getToType(1);
4085 
4086  // Adjust the types we're converting from via the array-to-pointer
4087  // conversion, if we need to.
4088  if (SCS1.First == ICK_Array_To_Pointer)
4089  FromType1 = S.Context.getArrayDecayedType(FromType1);
4090  if (SCS2.First == ICK_Array_To_Pointer)
4091  FromType2 = S.Context.getArrayDecayedType(FromType2);
4092 
4093  // Canonicalize all of the types.
4094  FromType1 = S.Context.getCanonicalType(FromType1);
4095  ToType1 = S.Context.getCanonicalType(ToType1);
4096  FromType2 = S.Context.getCanonicalType(FromType2);
4097  ToType2 = S.Context.getCanonicalType(ToType2);
4098 
4099  // C++ [over.ics.rank]p4b3:
4100  //
4101  // If class B is derived directly or indirectly from class A and
4102  // class C is derived directly or indirectly from B,
4103  //
4104  // Compare based on pointer conversions.
4105  if (SCS1.Second == ICK_Pointer_Conversion &&
4106  SCS2.Second == ICK_Pointer_Conversion &&
4107  /*FIXME: Remove if Objective-C id conversions get their own rank*/
4108  FromType1->isPointerType() && FromType2->isPointerType() &&
4109  ToType1->isPointerType() && ToType2->isPointerType()) {
4110  QualType FromPointee1
4111  = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4112  QualType ToPointee1
4113  = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4114  QualType FromPointee2
4115  = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4116  QualType ToPointee2
4117  = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4118 
4119  // -- conversion of C* to B* is better than conversion of C* to A*,
4120  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4121  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4123  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4125  }
4126 
4127  // -- conversion of B* to A* is better than conversion of C* to A*,
4128  if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4129  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4131  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4133  }
4134  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4135  SCS2.Second == ICK_Pointer_Conversion) {
4136  const ObjCObjectPointerType *FromPtr1
4137  = FromType1->getAs<ObjCObjectPointerType>();
4138  const ObjCObjectPointerType *FromPtr2
4139  = FromType2->getAs<ObjCObjectPointerType>();
4140  const ObjCObjectPointerType *ToPtr1
4141  = ToType1->getAs<ObjCObjectPointerType>();
4142  const ObjCObjectPointerType *ToPtr2
4143  = ToType2->getAs<ObjCObjectPointerType>();
4144 
4145  if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4146  // Apply the same conversion ranking rules for Objective-C pointer types
4147  // that we do for C++ pointers to class types. However, we employ the
4148  // Objective-C pseudo-subtyping relationship used for assignment of
4149  // Objective-C pointer types.
4150  bool FromAssignLeft
4151  = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4152  bool FromAssignRight
4153  = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4154  bool ToAssignLeft
4155  = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4156  bool ToAssignRight
4157  = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4158 
4159  // A conversion to an a non-id object pointer type or qualified 'id'
4160  // type is better than a conversion to 'id'.
4161  if (ToPtr1->isObjCIdType() &&
4162  (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4164  if (ToPtr2->isObjCIdType() &&
4165  (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4167 
4168  // A conversion to a non-id object pointer type is better than a
4169  // conversion to a qualified 'id' type
4170  if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4172  if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4174 
4175  // A conversion to an a non-Class object pointer type or qualified 'Class'
4176  // type is better than a conversion to 'Class'.
4177  if (ToPtr1->isObjCClassType() &&
4178  (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4180  if (ToPtr2->isObjCClassType() &&
4181  (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4183 
4184  // A conversion to a non-Class object pointer type is better than a
4185  // conversion to a qualified 'Class' type.
4186  if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4188  if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4190 
4191  // -- "conversion of C* to B* is better than conversion of C* to A*,"
4192  if (S.Context.hasSameType(FromType1, FromType2) &&
4193  !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4194  (ToAssignLeft != ToAssignRight)) {
4195  if (FromPtr1->isSpecialized()) {
4196  // "conversion of B<A> * to B * is better than conversion of B * to
4197  // C *.
4198  bool IsFirstSame =
4199  FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4200  bool IsSecondSame =
4201  FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4202  if (IsFirstSame) {
4203  if (!IsSecondSame)
4205  } else if (IsSecondSame)
4207  }
4208  return ToAssignLeft? ImplicitConversionSequence::Worse
4210  }
4211 
4212  // -- "conversion of B* to A* is better than conversion of C* to A*,"
4213  if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4214  (FromAssignLeft != FromAssignRight))
4215  return FromAssignLeft? ImplicitConversionSequence::Better
4217  }
4218  }
4219 
4220  // Ranking of member-pointer types.
4221  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4222  FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4223  ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4224  const MemberPointerType * FromMemPointer1 =
4225  FromType1->getAs<MemberPointerType>();
4226  const MemberPointerType * ToMemPointer1 =
4227  ToType1->getAs<MemberPointerType>();
4228  const MemberPointerType * FromMemPointer2 =
4229  FromType2->getAs<MemberPointerType>();
4230  const MemberPointerType * ToMemPointer2 =
4231  ToType2->getAs<MemberPointerType>();
4232  const Type *FromPointeeType1 = FromMemPointer1->getClass();
4233  const Type *ToPointeeType1 = ToMemPointer1->getClass();
4234  const Type *FromPointeeType2 = FromMemPointer2->getClass();
4235  const Type *ToPointeeType2 = ToMemPointer2->getClass();
4236  QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4237  QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4238  QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4239  QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4240  // conversion of A::* to B::* is better than conversion of A::* to C::*,
4241  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4242  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4244  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4246  }
4247  // conversion of B::* to C::* is better than conversion of A::* to C::*
4248  if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4249  if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4251  else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4253  }
4254  }
4255 
4256  if (SCS1.Second == ICK_Derived_To_Base) {
4257  // -- conversion of C to B is better than conversion of C to A,
4258  // -- binding of an expression of type C to a reference of type
4259  // B& is better than binding an expression of type C to a
4260  // reference of type A&,
4261  if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4262  !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4263  if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4265  else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4267  }
4268 
4269  // -- conversion of B to A is better than conversion of C to A.
4270  // -- binding of an expression of type B to a reference of type
4271  // A& is better than binding an expression of type C to a
4272  // reference of type A&,
4273  if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4274  S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4275  if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4277  else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4279  }
4280  }
4281 
4283 }
4284 
4285 /// Determine whether the given type is valid, e.g., it is not an invalid
4286 /// C++ class.
4287 static bool isTypeValid(QualType T) {
4288  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4289  return !Record->isInvalidDecl();
4290 
4291  return true;
4292 }
4293 
4294 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4295 /// determine whether they are reference-related,
4296 /// reference-compatible, reference-compatible with added
4297 /// qualification, or incompatible, for use in C++ initialization by
4298 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4299 /// type, and the first type (T1) is the pointee type of the reference
4300 /// type being initialized.
4303  QualType OrigT1, QualType OrigT2,
4304  bool &DerivedToBase,
4305  bool &ObjCConversion,
4306  bool &ObjCLifetimeConversion) {
4307  assert(!OrigT1->isReferenceType() &&
4308  "T1 must be the pointee type of the reference type");
4309  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4310 
4311  QualType T1 = Context.getCanonicalType(OrigT1);
4312  QualType T2 = Context.getCanonicalType(OrigT2);
4313  Qualifiers T1Quals, T2Quals;
4314  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4315  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4316 
4317  // C++ [dcl.init.ref]p4:
4318  // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4319  // reference-related to "cv2 T2" if T1 is the same type as T2, or
4320  // T1 is a base class of T2.
4321  DerivedToBase = false;
4322  ObjCConversion = false;
4323  ObjCLifetimeConversion = false;
4324  QualType ConvertedT2;
4325  if (UnqualT1 == UnqualT2) {
4326  // Nothing to do.
4327  } else if (isCompleteType(Loc, OrigT2) &&
4328  isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4329  IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4330  DerivedToBase = true;
4331  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4332  UnqualT2->isObjCObjectOrInterfaceType() &&
4333  Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4334  ObjCConversion = true;
4335  else if (UnqualT2->isFunctionType() &&
4336  IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4337  // C++1z [dcl.init.ref]p4:
4338  // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4339  // function" and T1 is "function"
4340  //
4341  // We extend this to also apply to 'noreturn', so allow any function
4342  // conversion between function types.
4343  return Ref_Compatible;
4344  else
4345  return Ref_Incompatible;
4346 
4347  // At this point, we know that T1 and T2 are reference-related (at
4348  // least).
4349 
4350  // If the type is an array type, promote the element qualifiers to the type
4351  // for comparison.
4352  if (isa<ArrayType>(T1) && T1Quals)
4353  T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4354  if (isa<ArrayType>(T2) && T2Quals)
4355  T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4356 
4357  // C++ [dcl.init.ref]p4:
4358  // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4359  // reference-related to T2 and cv1 is the same cv-qualification
4360  // as, or greater cv-qualification than, cv2. For purposes of
4361  // overload resolution, cases for which cv1 is greater
4362  // cv-qualification than cv2 are identified as
4363  // reference-compatible with added qualification (see 13.3.3.2).
4364  //
4365  // Note that we also require equivalence of Objective-C GC and address-space
4366  // qualifiers when performing these computations, so that e.g., an int in
4367  // address space 1 is not reference-compatible with an int in address
4368  // space 2.
4369  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4370  T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4371  if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4372  ObjCLifetimeConversion = true;
4373 
4374  T1Quals.removeObjCLifetime();
4375  T2Quals.removeObjCLifetime();
4376  }
4377 
4378  // MS compiler ignores __unaligned qualifier for references; do the same.
4379  T1Quals.removeUnaligned();
4380  T2Quals.removeUnaligned();
4381 
4382  if (T1Quals.compatiblyIncludes(T2Quals))
4383  return Ref_Compatible;
4384  else
4385  return Ref_Related;
4386 }
4387 
4388 /// Look for a user-defined conversion to a value reference-compatible
4389 /// with DeclType. Return true if something definite is found.
4390 static bool
4392  QualType DeclType, SourceLocation DeclLoc,
4393  Expr *Init, QualType T2, bool AllowRvalues,
4394  bool AllowExplicit) {
4395  assert(T2->isRecordType() && "Can only find conversions of record types.");
4396  CXXRecordDecl *T2RecordDecl
4397  = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4398 
4399  OverloadCandidateSet CandidateSet(
4401  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4402  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4403  NamedDecl *D = *I;
4404  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4405  if (isa<UsingShadowDecl>(D))
4406  D = cast<UsingShadowDecl>(D)->getTargetDecl();
4407 
4408  FunctionTemplateDecl *ConvTemplate
4409  = dyn_cast<FunctionTemplateDecl>(D);
4410  CXXConversionDecl *Conv;
4411  if (ConvTemplate)
4412  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4413  else
4414  Conv = cast<CXXConversionDecl>(D);
4415 
4416  // If this is an explicit conversion, and we're not allowed to consider
4417  // explicit conversions, skip it.
4418  if (!AllowExplicit && Conv->isExplicit())
4419  continue;
4420 
4421  if (AllowRvalues) {
4422  bool DerivedToBase = false;
4423  bool ObjCConversion = false;
4424  bool ObjCLifetimeConversion = false;
4425 
4426  // If we are initializing an rvalue reference, don't permit conversion
4427  // functions that return lvalues.
4428  if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4429  const ReferenceType *RefType
4430  = Conv->getConversionType()->getAs<LValueReferenceType>();
4431  if (RefType && !RefType->getPointeeType()->isFunctionType())
4432  continue;
4433  }
4434 
4435  if (!ConvTemplate &&
4437  DeclLoc,
4438  Conv->getConversionType().getNonReferenceType()
4439  .getUnqualifiedType(),
4441  DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4443  continue;
4444  } else {
4445  // If the conversion function doesn't return a reference type,
4446  // it can't be considered for this conversion. An rvalue reference
4447  // is only acceptable if its referencee is a function type.
4448 
4449  const ReferenceType *RefType =
4450  Conv->getConversionType()->getAs<ReferenceType>();
4451  if (!RefType ||
4452  (!RefType->isLValueReferenceType() &&
4453  !RefType->getPointeeType()->isFunctionType()))
4454  continue;
4455  }
4456 
4457  if (ConvTemplate)
4458  S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4459  Init, DeclType, CandidateSet,
4460  /*AllowObjCConversionOnExplicit=*/false);
4461  else
4462  S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4463  DeclType, CandidateSet,
4464  /*AllowObjCConversionOnExplicit=*/false);
4465  }
4466 
4467  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4468 
4470  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4471  case OR_Success:
4472  // C++ [over.ics.ref]p1:
4473  //
4474  // [...] If the parameter binds directly to the result of
4475  // applying a conversion function to the argument
4476  // expression, the implicit conversion sequence is a
4477  // user-defined conversion sequence (13.3.3.1.2), with the
4478  // second standard conversion sequence either an identity
4479  // conversion or, if the conversion function returns an
4480  // entity of a type that is a derived class of the parameter
4481  // type, a derived-to-base Conversion.
4482  if (!Best->FinalConversion.DirectBinding)
4483  return false;
4484 
4485  ICS.setUserDefined();
4486  ICS.UserDefined.Before = Best->Conversions[0].Standard;
4487  ICS.UserDefined.After = Best->FinalConversion;
4488  ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4489  ICS.UserDefined.ConversionFunction = Best->Function;
4490  ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4491  ICS.UserDefined.EllipsisConversion = false;
4492  assert(ICS.UserDefined.After.ReferenceBinding &&
4494  "Expected a direct reference binding!");
4495  return true;
4496 
4497  case OR_Ambiguous:
4498  ICS.setAmbiguous();
4499  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4500  Cand != CandidateSet.end(); ++Cand)
4501  if (Cand->Viable)
4502  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4503  return true;
4504 
4505  case OR_No_Viable_Function:
4506  case OR_Deleted:
4507  // There was no suitable conversion, or we found a deleted
4508  // conversion; continue with other checks.
4509  return false;
4510  }
4511 
4512  llvm_unreachable("Invalid OverloadResult!");
4513 }
4514 
4515 /// Compute an implicit conversion sequence for reference
4516 /// initialization.
4518 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4519  SourceLocation DeclLoc,
4520  bool SuppressUserConversions,
4521  bool AllowExplicit) {
4522  assert(DeclType->isReferenceType() && "Reference init needs a reference");
4523 
4524  // Most paths end in a failed conversion.
4526  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4527 
4528  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4529  QualType T2 = Init->getType();
4530 
4531  // If the initializer is the address of an overloaded function, try
4532  // to resolve the overloaded function. If all goes well, T2 is the
4533  // type of the resulting function.
4534  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4535  DeclAccessPair Found;
4536  if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4537  false, Found))
4538  T2 = Fn->getType();
4539  }
4540 
4541  // Compute some basic properties of the types and the initializer.
4542  bool isRValRef = DeclType->isRValueReferenceType();
4543  bool DerivedToBase = false;
4544  bool ObjCConversion = false;
4545  bool ObjCLifetimeConversion = false;
4546  Expr::Classification InitCategory = Init->Classify(S.Context);
4547  Sema::ReferenceCompareResult RefRelationship
4548  = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4549  ObjCConversion, ObjCLifetimeConversion);
4550 
4551 
4552  // C++0x [dcl.init.ref]p5:
4553  // A reference to type "cv1 T1" is initialized by an expression
4554  // of type "cv2 T2" as follows:
4555 
4556  // -- If reference is an lvalue reference and the initializer expression
4557  if (!isRValRef) {
4558  // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4559  // reference-compatible with "cv2 T2," or
4560  //
4561  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4562  if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4563  // C++ [over.ics.ref]p1:
4564  // When a parameter of reference type binds directly (8.5.3)
4565  // to an argument expression, the implicit conversion sequence
4566  // is the identity conversion, unless the argument expression
4567  // has a type that is a derived class of the parameter type,
4568  // in which case the implicit conversion sequence is a
4569  // derived-to-base Conversion (13.3.3.1).
4570  ICS.setStandard();
4571  ICS.Standard.First = ICK_Identity;
4572  ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4573  : ObjCConversion? ICK_Compatible_Conversion
4574  : ICK_Identity;
4575  ICS.Standard.Third = ICK_Identity;
4576  ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4577  ICS.Standard.setToType(0, T2);
4578  ICS.Standard.setToType(1, T1);
4579  ICS.Standard.setToType(2, T1);
4580  ICS.Standard.ReferenceBinding = true;
4581  ICS.Standard.DirectBinding = true;
4582  ICS.Standard.IsLvalueReference = !isRValRef;
4583  ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4584  ICS.Standard.BindsToRvalue = false;
4585  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4586  ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4587  ICS.Standard.CopyConstructor = nullptr;
4588  ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4589 
4590  // Nothing more to do: the inaccessibility/ambiguity check for
4591  // derived-to-base conversions is suppressed when we're
4592  // computing the implicit conversion sequence (C++
4593  // [over.best.ics]p2).
4594  return ICS;
4595  }
4596 
4597  // -- has a class type (i.e., T2 is a class type), where T1 is
4598  // not reference-related to T2, and can be implicitly
4599  // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4600  // is reference-compatible with "cv3 T3" 92) (this
4601  // conversion is selected by enumerating the applicable
4602  // conversion functions (13.3.1.6) and choosing the best
4603  // one through overload resolution (13.3)),
4604  if (!SuppressUserConversions && T2->isRecordType() &&
4605  S.isCompleteType(DeclLoc, T2) &&
4606  RefRelationship == Sema::Ref_Incompatible) {
4607  if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4608  Init, T2, /*AllowRvalues=*/false,
4609  AllowExplicit))
4610  return ICS;
4611  }
4612  }
4613 
4614  // -- Otherwise, the reference shall be an lvalue reference to a
4615  // non-volatile const type (i.e., cv1 shall be const), or the reference
4616  // shall be an rvalue reference.
4617  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4618  return ICS;
4619 
4620  // -- If the initializer expression
4621  //
4622  // -- is an xvalue, class prvalue, array prvalue or function
4623  // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4624  if (RefRelationship == Sema::Ref_Compatible &&
4625  (InitCategory.isXValue() ||
4626  (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4627  (InitCategory.isLValue() && T2->isFunctionType()))) {
4628  ICS.setStandard();
4629  ICS.Standard.First = ICK_Identity;
4630  ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4631  : ObjCConversion? ICK_Compatible_Conversion
4632  : ICK_Identity;
4633  ICS.Standard.Third = ICK_Identity;
4634  ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4635  ICS.Standard.setToType(0, T2);
4636  ICS.Standard.setToType(1, T1);
4637  ICS.Standard.setToType(2, T1);
4638  ICS.Standard.ReferenceBinding = true;
4639  // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4640  // binding unless we're binding to a class prvalue.
4641  // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4642  // allow the use of rvalue references in C++98/03 for the benefit of
4643  // standard library implementors; therefore, we need the xvalue check here.
4644  ICS.Standard.DirectBinding =
4645  S.getLangOpts().CPlusPlus11 ||
4646  !(InitCategory.isPRValue() || T2->isRecordType());
4647  ICS.Standard.IsLvalueReference = !isRValRef;
4648  ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4649  ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4650  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4651  ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4652  ICS.Standard.CopyConstructor = nullptr;
4653  ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4654  return ICS;
4655  }
4656 
4657  // -- has a class type (i.e., T2 is a class type), where T1 is not
4658  // reference-related to T2, and can be implicitly converted to
4659  // an xvalue, class prvalue, or function lvalue of type
4660  // "cv3 T3", where "cv1 T1" is reference-compatible with
4661  // "cv3 T3",
4662  //
4663  // then the reference is bound to the value of the initializer
4664  // expression in the first case and to the result of the conversion
4665  // in the second case (or, in either case, to an appropriate base
4666  // class subobject).
4667  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4668  T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4669  FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4670  Init, T2, /*AllowRvalues=*/true,
4671  AllowExplicit)) {
4672  // In the second case, if the reference is an rvalue reference
4673  // and the second standard conversion sequence of the
4674  // user-defined conversion sequence includes an lvalue-to-rvalue
4675  // conversion, the program is ill-formed.
4676  if (ICS.isUserDefined() && isRValRef &&
4677  ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4678  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4679 
4680  return ICS;
4681  }
4682 
4683  // A temporary of function type cannot be created; don't even try.
4684  if (T1->isFunctionType())
4685  return ICS;
4686 
4687  // -- Otherwise, a temporary of type "cv1 T1" is created and
4688  // initialized from the initializer expression using the
4689  // rules for a non-reference copy initialization (8.5). The
4690  // reference is then bound to the temporary. If T1 is
4691  // reference-related to T2, cv1 must be the same
4692  // cv-qualification as, or greater cv-qualification than,
4693  // cv2; otherwise, the program is ill-formed.
4694  if (RefRelationship == Sema::Ref_Related) {
4695  // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4696  // we would be reference-compatible or reference-compatible with
4697  // added qualification. But that wasn't the case, so the reference
4698  // initialization fails.
4699  //
4700  // Note that we only want to check address spaces and cvr-qualifiers here.
4701  // ObjC GC, lifetime and unaligned qualifiers aren't important.
4702  Qualifiers T1Quals = T1.getQualifiers();
4703  Qualifiers T2Quals = T2.getQualifiers();
4704  T1Quals.removeObjCGCAttr();
4705  T1Quals.removeObjCLifetime();
4706  T2Quals.removeObjCGCAttr();
4707  T2Quals.removeObjCLifetime();
4708  // MS compiler ignores __unaligned qualifier for references; do the same.
4709  T1Quals.removeUnaligned();
4710  T2Quals.removeUnaligned();
4711  if (!T1Quals.compatiblyIncludes(T2Quals))
4712  return ICS;
4713  }
4714 
4715  // If at least one of the types is a class type, the types are not
4716  // related, and we aren't allowed any user conversions, the
4717  // reference binding fails. This case is important for breaking
4718  // recursion, since TryImplicitConversion below will attempt to
4719  // create a temporary through the use of a copy constructor.
4720  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4721  (T1->isRecordType() || T2->isRecordType()))
4722  return ICS;
4723 
4724  // If T1 is reference-related to T2 and the reference is an rvalue
4725  // reference, the initializer expression shall not be an lvalue.
4726  if (RefRelationship >= Sema::Ref_Related &&
4727  isRValRef && Init->Classify(S.Context).isLValue())
4728  return ICS;
4729 
4730  // C++ [over.ics.ref]p2:
4731  // When a parameter of reference type is not bound directly to
4732  // an argument expression, the conversion sequence is the one
4733  // required to convert the argument expression to the
4734  // underlying type of the reference according to
4735  // 13.3.3.1. Conceptually, this conversion sequence corresponds
4736  // to copy-initializing a temporary of the underlying type with
4737  // the argument expression. Any difference in top-level
4738  // cv-qualification is subsumed by the initialization itself
4739  // and does not constitute a conversion.
4740  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4741  /*AllowExplicit=*/false,
4742  /*InOverloadResolution=*/false,
4743  /*CStyle=*/false,
4744  /*AllowObjCWritebackConversion=*/false,
4745  /*AllowObjCConversionOnExplicit=*/false);
4746 
4747  // Of course, that's still a reference binding.
4748  if (ICS.isStandard()) {
4749  ICS.Standard.ReferenceBinding = true;
4750  ICS.Standard.IsLvalueReference = !isRValRef;
4751  ICS.Standard.BindsToFunctionLvalue = false;
4752  ICS.Standard.BindsToRvalue = true;
4753  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4754  ICS.Standard.ObjCLifetimeConversionBinding = false;
4755  } else if (ICS.isUserDefined()) {
4756  const ReferenceType *LValRefType =
4757  ICS.UserDefined.ConversionFunction->getReturnType()
4759 
4760  // C++ [over.ics.ref]p3:
4761  // Except for an implicit object parameter, for which see 13.3.1, a
4762  // standard conversion sequence cannot be formed if it requires [...]
4763  // binding an rvalue reference to an lvalue other than a function
4764  // lvalue.
4765  // Note that the function case is not possible here.
4766  if (DeclType->isRValueReferenceType() && LValRefType) {
4767  // FIXME: This is the wrong BadConversionSequence. The problem is binding
4768  // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4769  // reference to an rvalue!
4770  ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4771  return ICS;
4772  }
4773 
4774  ICS.UserDefined.After.ReferenceBinding = true;
4775  ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4776  ICS.UserDefined.After.BindsToFunctionLvalue = false;
4777  ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4778  ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4779  ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4780  }
4781 
4782  return ICS;
4783 }
4784 
4786 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4787  bool SuppressUserConversions,
4788  bool InOverloadResolution,
4789  bool AllowObjCWritebackConversion,
4790  bool AllowExplicit = false);
4791 
4792 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4793 /// initializer list From.
4796  bool SuppressUserConversions,
4797  bool InOverloadResolution,
4798  bool AllowObjCWritebackConversion) {
4799  // C++11 [over.ics.list]p1:
4800  // When an argument is an initializer list, it is not an expression and
4801  // special rules apply for converting it to a parameter type.
4802 
4804  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4805 
4806  // We need a complete type for what follows. Incomplete types can never be
4807  // initialized from init lists.
4808  if (!S.isCompleteType(From->getBeginLoc(), ToType))
4809  return Result;
4810 
4811  // Per DR1467:
4812  // If the parameter type is a class X and the initializer list has a single
4813  // element of type cv U, where U is X or a class derived from X, the
4814  // implicit conversion sequence is the one required to convert the element
4815  // to the parameter type.
4816  //
4817  // Otherwise, if the parameter type is a character array [... ]
4818  // and the initializer list has a single element that is an
4819  // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4820  // implicit conversion sequence is the identity conversion.
4821  if (From->getNumInits() == 1) {
4822  if (ToType->isRecordType()) {
4823  QualType InitType = From->getInit(0)->getType();
4824  if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4825  S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4826  return TryCopyInitialization(S, From->getInit(0), ToType,
4827  SuppressUserConversions,
4828  InOverloadResolution,
4829  AllowObjCWritebackConversion);
4830  }
4831  // FIXME: Check the other conditions here: array of character type,
4832  // initializer is a string literal.
4833  if (ToType->isArrayType()) {
4834  InitializedEntity Entity =
4836  /*Consumed=*/false);
4837  if (S.CanPerformCopyInitialization(Entity, From)) {
4838  Result.setStandard();
4840  Result.Standard.setFromType(ToType);
4841  Result.Standard.setAllToTypes(ToType);
4842  return Result;
4843  }
4844  }
4845  }
4846 
4847  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4848  // C++11 [over.ics.list]p2:
4849  // If the parameter type is std::initializer_list<X> or "array of X" and
4850  // all the elements can be implicitly converted to X, the implicit
4851  // conversion sequence is the worst conversion necessary to convert an
4852  // element of the list to X.
4853  //
4854  // C++14 [over.ics.list]p3:
4855  // Otherwise, if the parameter type is "array of N X", if the initializer
4856  // list has exactly N elements or if it has fewer than N elements and X is
4857  // default-constructible, and if all the elements of the initializer list
4858  // can be implicitly converted to X, the implicit conversion sequence is
4859  // the worst conversion necessary to convert an element of the list to X.
4860  //
4861  // FIXME: We're missing a lot of these checks.
4862  bool toStdInitializerList = false;
4863  QualType X;
4864  if (ToType->isArrayType())
4865  X = S.Context.getAsArrayType(ToType)->getElementType();
4866  else
4867  toStdInitializerList = S.isStdInitializerList(ToType, &X);
4868  if (!X.isNull()) {
4869  for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4870  Expr *Init = From->getInit(i);
4872  TryCopyInitialization(S, Init, X, SuppressUserConversions,
4873  InOverloadResolution,
4874  AllowObjCWritebackConversion);
4875  // If a single element isn't convertible, fail.
4876  if (ICS.isBad()) {
4877  Result = ICS;
4878  break;
4879  }
4880  // Otherwise, look for the worst conversion.
4881  if (Result.isBad() || CompareImplicitConversionSequences(
4882  S, From->getBeginLoc(), ICS, Result) ==
4884  Result = ICS;
4885  }
4886 
4887  // For an empty list, we won't have computed any conversion sequence.
4888  // Introduce the identity conversion sequence.
4889  if (From->getNumInits() == 0) {
4890  Result.setStandard();
4892  Result.Standard.setFromType(ToType);
4893  Result.Standard.setAllToTypes(ToType);
4894  }
4895 
4896  Result.setStdInitializerListElement(toStdInitializerList);
4897  return Result;
4898  }
4899 
4900  // C++14 [over.ics.list]p4:
4901  // C++11 [over.ics.list]p3:
4902  // Otherwise, if the parameter is a non-aggregate class X and overload
4903  // resolution chooses a single best constructor [...] the implicit
4904  // conversion sequence is a user-defined conversion sequence. If multiple
4905  // constructors are viable but none is better than the others, the
4906  // implicit conversion sequence is a user-defined conversion sequence.
4907  if (ToType->isRecordType() && !ToType->isAggregateType()) {
4908  // This function can deal with initializer lists.
4909  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4910  /*AllowExplicit=*/false,
4911  InOverloadResolution, /*CStyle=*/false,
4912  AllowObjCWritebackConversion,
4913  /*AllowObjCConversionOnExplicit=*/false);
4914  }
4915 
4916  // C++14 [over.ics.list]p5:
4917  // C++11 [over.ics.list]p4:
4918  // Otherwise, if the parameter has an aggregate type which can be
4919  // initialized from the initializer list [...] the implicit conversion
4920  // sequence is a user-defined conversion sequence.
4921  if (ToType->isAggregateType()) {
4922  // Type is an aggregate, argument is an init list. At this point it comes
4923  // down to checking whether the initialization works.
4924  // FIXME: Find out whether this parameter is consumed or not.
4925  // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4926  // need to call into the initialization code here; overload resolution
4927  // should not be doing that.
4928  InitializedEntity Entity =
4930  /*Consumed=*/false);
4931  if (S.CanPerformCopyInitialization(Entity, From)) {
4932  Result.setUserDefined();
4934  // Initializer lists don't have a type.
4937 
4939  Result.UserDefined.After.setFromType(ToType);
4940  Result.UserDefined.After.setAllToTypes(ToType);
4941  Result.UserDefined.ConversionFunction = nullptr;
4942  }
4943  return Result;
4944  }
4945 
4946  // C++14 [over.ics.list]p6:
4947  // C++11 [over.ics.list]p5:
4948  // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4949  if (ToType->isReferenceType()) {
4950  // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4951  // mention initializer lists in any way. So we go by what list-
4952  // initialization would do and try to extrapolate from that.
4953 
4954  QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4955 
4956  // If the initializer list has a single element that is reference-related
4957  // to the parameter type, we initialize the reference from that.
4958  if (From->getNumInits() == 1) {
4959  Expr *Init = From->getInit(0);
4960 
4961  QualType T2 = Init->getType();
4962 
4963  // If the initializer is the address of an overloaded function, try
4964  // to resolve the overloaded function. If all goes well, T2 is the
4965  // type of the resulting function.
4966  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4967  DeclAccessPair Found;
4969  Init, ToType, false, Found))
4970  T2 = Fn->getType();
4971  }
4972 
4973  // Compute some basic properties of the types and the initializer.
4974  bool dummy1 = false;
4975  bool dummy2 = false;
4976  bool dummy3 = false;
4977  Sema::ReferenceCompareResult RefRelationship =
4978  S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4979  dummy2, dummy3);
4980 
4981  if (RefRelationship >= Sema::Ref_Related) {
4982  return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4983  SuppressUserConversions,
4984  /*AllowExplicit=*/false);
4985  }
4986  }
4987 
4988  // Otherwise, we bind the reference to a temporary created from the
4989  // initializer list.
4990  Result = TryListConversion(S, From, T1, SuppressUserConversions,
4991  InOverloadResolution,
4992  AllowObjCWritebackConversion);
4993  if (Result.isFailure())
4994  return Result;
4995  assert(!Result.isEllipsis() &&
4996  "Sub-initialization cannot result in ellipsis conversion.");
4997 
4998  // Can we even bind to a temporary?
4999  if (ToType->isRValueReferenceType() ||
5000  (T1.isConstQualified() && !T1.isVolatileQualified())) {
5001  StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5002  Result.UserDefined.After;
5003  SCS.ReferenceBinding = true;
5004  SCS.IsLvalueReference = ToType->isLValueReferenceType();
5005  SCS.BindsToRvalue = true;
5006  SCS.BindsToFunctionLvalue = false;
5008  SCS.ObjCLifetimeConversionBinding = false;
5009  } else
5011  From, ToType);
5012  return Result;
5013  }
5014 
5015  // C++14 [over.ics.list]p7:
5016  // C++11 [over.ics.list]p6:
5017  // Otherwise, if the parameter type is not a class:
5018  if (!ToType->isRecordType()) {
5019  // - if the initializer list has one element that is not itself an
5020  // initializer list, the implicit conversion sequence is the one
5021  // required to convert the element to the parameter type.
5022  unsigned NumInits = From->getNumInits();
5023  if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5024  Result = TryCopyInitialization(S, From->getInit(0), ToType,
5025  SuppressUserConversions,
5026  InOverloadResolution,
5027  AllowObjCWritebackConversion);
5028  // - if the initializer list has no elements, the implicit conversion
5029  // sequence is the identity conversion.
5030  else if (NumInits == 0) {
5031  Result.setStandard();
5033  Result.Standard.setFromType(ToType);
5034  Result.Standard.setAllToTypes(ToType);
5035  }
5036  return Result;
5037  }
5038 
5039  // C++14 [over.ics.list]p8:
5040  // C++11 [over.ics.list]p7:
5041  // In all cases other than those enumerated above, no conversion is possible
5042  return Result;
5043 }
5044 
5045 /// TryCopyInitialization - Try to copy-initialize a value of type
5046 /// ToType from the expression From. Return the implicit conversion
5047 /// sequence required to pass this argument, which may be a bad
5048 /// conversion sequence (meaning that the argument cannot be passed to
5049 /// a parameter of this type). If @p SuppressUserConversions, then we
5050 /// do not permit any user-defined conversion sequences.
5053  bool SuppressUserConversions,
5054  bool InOverloadResolution,
5055  bool AllowObjCWritebackConversion,
5056  bool AllowExplicit) {
5057  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5058  return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5059  InOverloadResolution,AllowObjCWritebackConversion);
5060 
5061  if (ToType->isReferenceType())
5062  return TryReferenceInit(S, From, ToType,
5063  /*FIXME:*/ From->getBeginLoc(),
5064  SuppressUserConversions, AllowExplicit);
5065 
5066  return TryImplicitConversion(S, From, ToType,
5067  SuppressUserConversions,
5068  /*AllowExplicit=*/false,
5069  InOverloadResolution,
5070  /*CStyle=*/false,
5071  AllowObjCWritebackConversion,
5072  /*AllowObjCConversionOnExplicit=*/false);
5073 }
5074 
5075 static bool TryCopyInitialization(const CanQualType FromQTy,
5076  const CanQualType ToQTy,
5077  Sema &S,
5078  SourceLocation Loc,
5079  ExprValueKind FromVK) {
5080  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5082  TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5083 
5084  return !ICS.isBad();
5085 }
5086 
5087 /// TryObjectArgumentInitialization - Try to initialize the object
5088 /// parameter of the given member function (@c Method) from the
5089 /// expression @p From.
5092  Expr::Classification FromClassification,
5093  CXXMethodDecl *Method,
5094  CXXRecordDecl *ActingContext) {
5095  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5096  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5097  // const volatile object.
5098  Qualifiers Quals;
5099  if (isa<CXXDestructorDecl>(Method)) {
5100  Quals.addConst();
5101  Quals.addVolatile();
5102  } else {
5103  Quals = Method->getMethodQualifiers();
5104  }
5105 
5106  QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5107 
5108  // Set up the conversion sequence as a "bad" conversion, to allow us
5109  // to exit early.
5111 
5112  // We need to have an object of class type.
5113  if (const PointerType *PT = FromType->getAs<PointerType>()) {
5114  FromType = PT->getPointeeType();
5115 
5116  // When we had a pointer, it's implicitly dereferenced, so we
5117  // better have an lvalue.
5118  assert(FromClassification.isLValue());
5119  }
5120 
5121  assert(FromType->isRecordType());
5122 
5123  // C++0x [over.match.funcs]p4:
5124  // For non-static member functions, the type of the implicit object
5125  // parameter is
5126  //
5127  // - "lvalue reference to cv X" for functions declared without a
5128  // ref-qualifier or with the & ref-qualifier
5129  // - "rvalue reference to cv X" for functions declared with the &&
5130  // ref-qualifier
5131  //
5132  // where X is the class of which the function is a member and cv is the
5133  // cv-qualification on the member function declaration.
5134  //
5135  // However, when finding an implicit conversion sequence for the argument, we
5136  // are not allowed to perform user-defined conversions
5137  // (C++ [over.match.funcs]p5). We perform a simplified version of
5138  // reference binding here, that allows class rvalues to bind to
5139  // non-constant references.
5140 
5141  // First check the qualifiers.
5142  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5143  if (ImplicitParamType.getCVRQualifiers()
5144  != FromTypeCanon.getLocalCVRQualifiers() &&
5145  !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5147  FromType, ImplicitParamType);
5148  return ICS;
5149  }
5150 
5151  if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5152  Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5153  Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5154  if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5156  FromType, ImplicitParamType);
5157  return ICS;
5158  }
5159  }
5160 
5161  // Check that we have either the same type or a derived type. It
5162  // affects the conversion rank.
5163  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5164  ImplicitConversionKind SecondKind;
5165  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5166  SecondKind = ICK_Identity;
5167  } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5168  SecondKind = ICK_Derived_To_Base;
5169  else {
5171  FromType, ImplicitParamType);
5172  return ICS;
5173  }
5174 
5175  // Check the ref-qualifier.
5176  switch (Method->getRefQualifier()) {
5177  case RQ_None:
5178  // Do nothing; we don't care about lvalueness or rvalueness.
5179  break;
5180 
5181  case RQ_LValue:
5182  if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5183  // non-const lvalue reference cannot bind to an rvalue
5185  ImplicitParamType);
5186  return ICS;
5187  }
5188  break;
5189 
5190  case RQ_RValue:
5191  if (!FromClassification.isRValue()) {
5192  // rvalue reference cannot bind to an lvalue
5194  ImplicitParamType);
5195  return ICS;
5196  }
5197  break;
5198  }
5199 
5200  // Success. Mark this as a reference binding.
5201  ICS.setStandard();
5203  ICS.Standard.Second = SecondKind;
5204  ICS.Standard.setFromType(FromType);
5205  ICS.Standard.setAllToTypes(ImplicitParamType);
5206  ICS.Standard.ReferenceBinding = true;
5207  ICS.Standard.DirectBinding = true;
5209  ICS.Standard.BindsToFunctionLvalue = false;
5210  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5212  = (Method->getRefQualifier() == RQ_None);
5213  return ICS;
5214 }
5215 
5216 /// PerformObjectArgumentInitialization - Perform initialization of
5217 /// the implicit object parameter for the given Method with the given
5218 /// expression.
5219 ExprResult
5221  NestedNameSpecifier *Qualifier,
5222  NamedDecl *FoundDecl,
5223  CXXMethodDecl *Method) {
5224  QualType FromRecordType, DestType;
5225  QualType ImplicitParamRecordType =
5226  Method->getThisType()->getAs<PointerType>()->getPointeeType();
5227 
5228  Expr::Classification FromClassification;
5229  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5230  FromRecordType = PT->getPointeeType();
5231  DestType = Method->getThisType();
5232  FromClassification = Expr::Classification::makeSimpleLValue();
5233  } else {
5234  FromRecordType = From->getType();
5235  DestType = ImplicitParamRecordType;
5236  FromClassification = From->Classify(Context);
5237 
5238  // When performing member access on an rvalue, materialize a temporary.
5239  if (From->isRValue()) {
5240  From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5241  Method->getRefQualifier() !=
5243  }
5244  }
5245 
5246  // Note that we always use the true parent context when performing
5247  // the actual argument initialization.
5249  *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5250  Method->getParent());
5251  if (ICS.isBad()) {
5252  switch (ICS.Bad.Kind) {
5254  Qualifiers FromQs = FromRecordType.getQualifiers();
5255  Qualifiers ToQs = DestType.getQualifiers();
5256  unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5257  if (CVR) {
5258  Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5259  << Method->getDeclName() << FromRecordType << (CVR - 1)
5260  << From->getSourceRange();
5261  Diag(Method->getLocation(), diag::note_previous_decl)
5262  << Method->getDeclName();
5263  return ExprError();
5264  }
5265  break;
5266  }
5267 
5270  bool IsRValueQualified =
5271  Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5272  Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5273  << Method->getDeclName() << FromClassification.isRValue()
5274  << IsRValueQualified;
5275  Diag(Method->getLocation(), diag::note_previous_decl)
5276  << Method->getDeclName();
5277  return ExprError();
5278  }
5279 
5282  break;
5283  }
5284 
5285  return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5286  << ImplicitParamRecordType << FromRecordType
5287  << From->getSourceRange();
5288  }
5289 
5290  if (ICS.Standard.Second == ICK_Derived_To_Base) {
5291  ExprResult FromRes =
5292  PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5293  if (FromRes.isInvalid())
5294  return ExprError();
5295  From = FromRes.get();
5296  }
5297 
5298  if (!Context.hasSameType(From->getType(), DestType)) {
5299  if (From->getType().getAddressSpace() != DestType.getAddressSpace())
5300  From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion,
5301  From->getValueKind()).get();
5302  else
5303  From = ImpCastExprToType(From, DestType, CK_NoOp,
5304  From->getValueKind()).get();
5305  }
5306  return From;
5307 }
5308 
5309 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5310 /// expression From to bool (C++0x [conv]p3).
5313  return TryImplicitConversion(S, From, S.Context.BoolTy,
5314  /*SuppressUserConversions=*/false,
5315  /*AllowExplicit=*/true,
5316  /*InOverloadResolution=*/false,
5317  /*CStyle=*/false,
5318  /*AllowObjCWritebackConversion=*/false,
5319  /*AllowObjCConversionOnExplicit=*/false);
5320 }
5321 
5322 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5323 /// of the expression From to bool (C++0x [conv]p3).
5325  if (checkPlaceholderForOverload(*this, From))
5326  return ExprError();
5327 
5329  if (!ICS.isBad())
5330  return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5331 
5332  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5333  return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5334  << From->getType() << From->getSourceRange();
5335  return ExprError();
5336 }
5337 
5338 /// Check that the specified conversion is permitted in a converted constant
5339 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5340 /// is acceptable.
5343  // Since we know that the target type is an integral or unscoped enumeration
5344  // type, most conversion kinds are impossible. All possible First and Third
5345  // conversions are fine.
5346  switch (SCS.Second) {
5347  case ICK_Identity:
5350  case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5352  return true;
5353 
5355  // Conversion from an integral or unscoped enumeration type to bool is
5356  // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5357  // conversion, so we allow it in a converted constant expression.
5358  //