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