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