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