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