clang  19.0.0git
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/AST/ASTContext.h"
14 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeOrdering.h"
25 #include "clang/Basic/Diagnostic.h"
30 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/Overload.h"
35 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaSYCL.h"
38 #include "clang/Sema/SemaObjC.h"
39 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/DenseSet.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/STLForwardCompat.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/Support/Casting.h"
48 #include <algorithm>
49 #include <cstddef>
50 #include <cstdlib>
51 #include <optional>
52 
53 using namespace clang;
54 using namespace sema;
55 
57 
59  return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
60  return P->hasAttr<PassObjectSizeAttr>();
61  });
62 }
63 
64 /// A convenience routine for creating a decayed reference to a function.
66  Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
67  bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
68  const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
69  if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
70  return ExprError();
71  // If FoundDecl is different from Fn (such as if one is a template
72  // and the other a specialization), make sure DiagnoseUseOfDecl is
73  // called on both.
74  // FIXME: This would be more comprehensively addressed by modifying
75  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
76  // being used.
77  if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
78  return ExprError();
79  DeclRefExpr *DRE = new (S.Context)
80  DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
81  if (HadMultipleCandidates)
82  DRE->setHadMultipleCandidates(true);
83 
85  if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
86  if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
87  S.ResolveExceptionSpec(Loc, FPT);
88  DRE->setType(Fn->getType());
89  }
90  }
91  return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
92  CK_FunctionToPointerDecay);
93 }
94 
95 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
96  bool InOverloadResolution,
98  bool CStyle,
99  bool AllowObjCWritebackConversion);
100 
101 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
102  QualType &ToType,
103  bool InOverloadResolution,
105  bool CStyle);
106 static OverloadingResult
107 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
109  OverloadCandidateSet& Conversions,
110  AllowedExplicit AllowExplicit,
111  bool AllowObjCConversionOnExplicit);
112 
115  const StandardConversionSequence& SCS1,
116  const StandardConversionSequence& SCS2);
117 
120  const StandardConversionSequence& SCS1,
121  const StandardConversionSequence& SCS2);
122 
125  const StandardConversionSequence& SCS1,
126  const StandardConversionSequence& SCS2);
127 
128 /// GetConversionRank - Retrieve the implicit conversion rank
129 /// corresponding to the given implicit conversion kind.
131  static const ImplicitConversionRank Rank[] = {
158  ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
159  // it was omitted by the patch that added
160  // ICK_Zero_Event_Conversion
161  ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
162  // it was omitted by the patch that added
163  // ICK_Zero_Queue_Conversion
169  };
170  static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171  return Rank[(int)Kind];
172 }
173 
174 /// GetImplicitConversionName - Return the name of this kind of
175 /// implicit conversion.
177  static const char *const Name[] = {
178  "No conversion",
179  "Lvalue-to-rvalue",
180  "Array-to-pointer",
181  "Function-to-pointer",
182  "Function pointer conversion",
183  "Qualification",
184  "Integral promotion",
185  "Floating point promotion",
186  "Complex promotion",
187  "Integral conversion",
188  "Floating conversion",
189  "Complex conversion",
190  "Floating-integral conversion",
191  "Pointer conversion",
192  "Pointer-to-member conversion",
193  "Boolean conversion",
194  "Compatible-types conversion",
195  "Derived-to-base conversion",
196  "Vector conversion",
197  "SVE Vector conversion",
198  "RVV Vector conversion",
199  "Vector splat",
200  "Complex-real conversion",
201  "Block Pointer conversion",
202  "Transparent Union Conversion",
203  "Writeback conversion",
204  "OpenCL Zero Event Conversion",
205  "OpenCL Zero Queue Conversion",
206  "C specific type conversion",
207  "Incompatible pointer conversion",
208  "Fixed point conversion",
209  "HLSL vector truncation",
210  "Non-decaying array conversion",
211  };
212  static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
213  return Name[Kind];
214 }
215 
216 /// StandardConversionSequence - Set the standard conversion
217 /// sequence to the identity conversion.
220  Second = ICK_Identity;
221  Element = ICK_Identity;
222  Third = ICK_Identity;
223  DeprecatedStringLiteralToCharPtr = false;
224  QualificationIncludesObjCLifetime = false;
225  ReferenceBinding = false;
226  DirectBinding = false;
227  IsLvalueReference = true;
228  BindsToFunctionLvalue = false;
229  BindsToRvalue = false;
230  BindsImplicitObjectArgumentWithoutRefQualifier = false;
231  ObjCLifetimeConversionBinding = false;
232  CopyConstructor = nullptr;
233 }
234 
235 /// getRank - Retrieve the rank of this standard conversion sequence
236 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
237 /// implicit conversions.
240  if (GetConversionRank(First) > Rank)
241  Rank = GetConversionRank(First);
242  if (GetConversionRank(Second) > Rank)
243  Rank = GetConversionRank(Second);
244  if (GetConversionRank(Element) > Rank)
245  Rank = GetConversionRank(Element);
246  if (GetConversionRank(Third) > Rank)
247  Rank = GetConversionRank(Third);
248  return Rank;
249 }
250 
251 /// isPointerConversionToBool - Determines whether this conversion is
252 /// a conversion of a pointer or pointer-to-member to bool. This is
253 /// used as part of the ranking of standard conversion sequences
254 /// (C++ 13.3.3.2p4).
256  // Note that FromType has not necessarily been transformed by the
257  // array-to-pointer or function-to-pointer implicit conversions, so
258  // check for their presence as well as checking whether FromType is
259  // a pointer.
260  if (getToType(1)->isBooleanType() &&
261  (getFromType()->isPointerType() ||
262  getFromType()->isMemberPointerType() ||
263  getFromType()->isObjCObjectPointerType() ||
264  getFromType()->isBlockPointerType() ||
266  return true;
267 
268  return false;
269 }
270 
271 /// isPointerConversionToVoidPointer - Determines whether this
272 /// conversion is a conversion of a pointer to a void pointer. This is
273 /// used as part of the ranking of standard conversion sequences (C++
274 /// 13.3.3.2p4).
275 bool
278  QualType FromType = getFromType();
279  QualType ToType = getToType(1);
280 
281  // Note that FromType has not necessarily been transformed by the
282  // array-to-pointer implicit conversion, so check for its presence
283  // and redo the conversion to get a pointer.
285  FromType = Context.getArrayDecayedType(FromType);
286 
287  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
288  if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
289  return ToPtrType->getPointeeType()->isVoidType();
290 
291  return false;
292 }
293 
294 /// Skip any implicit casts which could be either part of a narrowing conversion
295 /// or after one in an implicit conversion.
297  const Expr *Converted) {
298  // We can have cleanups wrapping the converted expression; these need to be
299  // preserved so that destructors run if necessary.
300  if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
301  Expr *Inner =
302  const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
303  return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
304  EWC->getObjects());
305  }
306 
307  while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
308  switch (ICE->getCastKind()) {
309  case CK_NoOp:
310  case CK_IntegralCast:
311  case CK_IntegralToBoolean:
312  case CK_IntegralToFloating:
313  case CK_BooleanToSignedIntegral:
314  case CK_FloatingToIntegral:
315  case CK_FloatingToBoolean:
316  case CK_FloatingCast:
317  Converted = ICE->getSubExpr();
318  continue;
319 
320  default:
321  return Converted;
322  }
323  }
324 
325  return Converted;
326 }
327 
328 /// Check if this standard conversion sequence represents a narrowing
329 /// conversion, according to C++11 [dcl.init.list]p7.
330 ///
331 /// \param Ctx The AST context.
332 /// \param Converted The result of applying this standard conversion sequence.
333 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
334 /// value of the expression prior to the narrowing conversion.
335 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
336 /// type of the expression prior to the narrowing conversion.
337 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
338 /// from floating point types to integral types should be ignored.
340  ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
341  QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
342  assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
343  "narrowing check outside C++");
344 
345  // C++11 [dcl.init.list]p7:
346  // A narrowing conversion is an implicit conversion ...
347  QualType FromType = getToType(0);
348  QualType ToType = getToType(1);
349 
350  // A conversion to an enumeration type is narrowing if the conversion to
351  // the underlying type is narrowing. This only arises for expressions of
352  // the form 'Enum{init}'.
353  if (auto *ET = ToType->getAs<EnumType>())
354  ToType = ET->getDecl()->getIntegerType();
355 
356  switch (Second) {
357  // 'bool' is an integral type; dispatch to the right place to handle it.
359  if (FromType->isRealFloatingType())
360  goto FloatingIntegralConversion;
361  if (FromType->isIntegralOrUnscopedEnumerationType())
362  goto IntegralConversion;
363  // -- from a pointer type or pointer-to-member type to bool, or
364  return NK_Type_Narrowing;
365 
366  // -- from a floating-point type to an integer type, or
367  //
368  // -- from an integer type or unscoped enumeration type to a floating-point
369  // type, except where the source is a constant expression and the actual
370  // value after conversion will fit into the target type and will produce
371  // the original value when converted back to the original type, or
373  FloatingIntegralConversion:
374  if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
375  return NK_Type_Narrowing;
376  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
377  ToType->isRealFloatingType()) {
378  if (IgnoreFloatToIntegralConversion)
379  return NK_Not_Narrowing;
380  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
381  assert(Initializer && "Unknown conversion expression");
382 
383  // If it's value-dependent, we can't tell whether it's narrowing.
384  if (Initializer->isValueDependent())
385  return NK_Dependent_Narrowing;
386 
387  if (std::optional<llvm::APSInt> IntConstantValue =
388  Initializer->getIntegerConstantExpr(Ctx)) {
389  // Convert the integer to the floating type.
390  llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
391  Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
392  llvm::APFloat::rmNearestTiesToEven);
393  // And back.
394  llvm::APSInt ConvertedValue = *IntConstantValue;
395  bool ignored;
396  Result.convertToInteger(ConvertedValue,
397  llvm::APFloat::rmTowardZero, &ignored);
398  // If the resulting value is different, this was a narrowing conversion.
399  if (*IntConstantValue != ConvertedValue) {
400  ConstantValue = APValue(*IntConstantValue);
401  ConstantType = Initializer->getType();
402  return NK_Constant_Narrowing;
403  }
404  } else {
405  // Variables are always narrowings.
406  return NK_Variable_Narrowing;
407  }
408  }
409  return NK_Not_Narrowing;
410 
411  // -- from long double to double or float, or from double to float, except
412  // where the source is a constant expression and the actual value after
413  // conversion is within the range of values that can be represented (even
414  // if it cannot be represented exactly), or
416  if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
417  Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
418  // FromType is larger than ToType.
419  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
420 
421  // If it's value-dependent, we can't tell whether it's narrowing.
422  if (Initializer->isValueDependent())
423  return NK_Dependent_Narrowing;
424 
426  if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
427  Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
428  // Constant!
429  if (Ctx.getLangOpts().C23)
430  ConstantValue = R.Val;
431  assert(ConstantValue.isFloat());
432  llvm::APFloat FloatVal = ConstantValue.getFloat();
433  // Convert the source value into the target type.
434  bool ignored;
435  llvm::APFloat Converted = FloatVal;
436  llvm::APFloat::opStatus ConvertStatus =
437  Converted.convert(Ctx.getFloatTypeSemantics(ToType),
438  llvm::APFloat::rmNearestTiesToEven, &ignored);
439  Converted.convert(Ctx.getFloatTypeSemantics(FromType),
440  llvm::APFloat::rmNearestTiesToEven, &ignored);
441  if (Ctx.getLangOpts().C23) {
442  if (FloatVal.isNaN() && Converted.isNaN() &&
443  !FloatVal.isSignaling() && !Converted.isSignaling()) {
444  // Quiet NaNs are considered the same value, regardless of
445  // payloads.
446  return NK_Not_Narrowing;
447  }
448  // For normal values, check exact equality.
449  if (!Converted.bitwiseIsEqual(FloatVal)) {
450  ConstantType = Initializer->getType();
451  return NK_Constant_Narrowing;
452  }
453  } else {
454  // If there was no overflow, the source value is within the range of
455  // values that can be represented.
456  if (ConvertStatus & llvm::APFloat::opOverflow) {
457  ConstantType = Initializer->getType();
458  return NK_Constant_Narrowing;
459  }
460  }
461  } else {
462  return NK_Variable_Narrowing;
463  }
464  }
465  return NK_Not_Narrowing;
466 
467  // -- from an integer type or unscoped enumeration type to an integer type
468  // that cannot represent all the values of the original type, except where
469  // the source is a constant expression and the actual value after
470  // conversion will fit into the target type and will produce the original
471  // value when converted back to the original type.
473  IntegralConversion: {
474  assert(FromType->isIntegralOrUnscopedEnumerationType());
475  assert(ToType->isIntegralOrUnscopedEnumerationType());
476  const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
477  const unsigned FromWidth = Ctx.getIntWidth(FromType);
478  const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
479  const unsigned ToWidth = Ctx.getIntWidth(ToType);
480 
481  if (FromWidth > ToWidth ||
482  (FromWidth == ToWidth && FromSigned != ToSigned) ||
483  (FromSigned && !ToSigned)) {
484  // Not all values of FromType can be represented in ToType.
485  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
486 
487  // If it's value-dependent, we can't tell whether it's narrowing.
488  if (Initializer->isValueDependent())
489  return NK_Dependent_Narrowing;
490 
491  std::optional<llvm::APSInt> OptInitializerValue;
492  if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
493  // Such conversions on variables are always narrowing.
494  return NK_Variable_Narrowing;
495  }
496  llvm::APSInt &InitializerValue = *OptInitializerValue;
497  bool Narrowing = false;
498  if (FromWidth < ToWidth) {
499  // Negative -> unsigned is narrowing. Otherwise, more bits is never
500  // narrowing.
501  if (InitializerValue.isSigned() && InitializerValue.isNegative())
502  Narrowing = true;
503  } else {
504  // Add a bit to the InitializerValue so we don't have to worry about
505  // signed vs. unsigned comparisons.
506  InitializerValue = InitializerValue.extend(
507  InitializerValue.getBitWidth() + 1);
508  // Convert the initializer to and from the target width and signed-ness.
509  llvm::APSInt ConvertedValue = InitializerValue;
510  ConvertedValue = ConvertedValue.trunc(ToWidth);
511  ConvertedValue.setIsSigned(ToSigned);
512  ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
513  ConvertedValue.setIsSigned(InitializerValue.isSigned());
514  // If the result is different, this was a narrowing conversion.
515  if (ConvertedValue != InitializerValue)
516  Narrowing = true;
517  }
518  if (Narrowing) {
519  ConstantType = Initializer->getType();
520  ConstantValue = APValue(InitializerValue);
521  return NK_Constant_Narrowing;
522  }
523  }
524  return NK_Not_Narrowing;
525  }
526  case ICK_Complex_Real:
527  if (FromType->isComplexType() && !ToType->isComplexType())
528  return NK_Type_Narrowing;
529  return NK_Not_Narrowing;
530 
532  if (Ctx.getLangOpts().C23) {
533  const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
535  if (Initializer->EvaluateAsRValue(R, Ctx)) {
536  ConstantValue = R.Val;
537  assert(ConstantValue.isFloat());
538  llvm::APFloat FloatVal = ConstantValue.getFloat();
539  // C23 6.7.3p6 If the initializer has real type and a signaling NaN
540  // value, the unqualified versions of the type of the initializer and
541  // the corresponding real type of the object declared shall be
542  // compatible.
543  if (FloatVal.isNaN() && FloatVal.isSignaling()) {
544  ConstantType = Initializer->getType();
545  return NK_Constant_Narrowing;
546  }
547  }
548  }
549  return NK_Not_Narrowing;
550  default:
551  // Other kinds of conversions are not narrowings.
552  return NK_Not_Narrowing;
553  }
554 }
555 
556 /// dump - Print this standard conversion sequence to standard
557 /// error. Useful for debugging overloading issues.
558 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
559  raw_ostream &OS = llvm::errs();
560  bool PrintedSomething = false;
561  if (First != ICK_Identity) {
563  PrintedSomething = true;
564  }
565 
566  if (Second != ICK_Identity) {
567  if (PrintedSomething) {
568  OS << " -> ";
569  }
570  OS << GetImplicitConversionName(Second);
571 
572  if (CopyConstructor) {
573  OS << " (by copy constructor)";
574  } else if (DirectBinding) {
575  OS << " (direct reference binding)";
576  } else if (ReferenceBinding) {
577  OS << " (reference binding)";
578  }
579  PrintedSomething = true;
580  }
581 
582  if (Third != ICK_Identity) {
583  if (PrintedSomething) {
584  OS << " -> ";
585  }
586  OS << GetImplicitConversionName(Third);
587  PrintedSomething = true;
588  }
589 
590  if (!PrintedSomething) {
591  OS << "No conversions required";
592  }
593 }
594 
595 /// dump - Print this user-defined conversion sequence to standard
596 /// error. Useful for debugging overloading issues.
598  raw_ostream &OS = llvm::errs();
599  if (Before.First || Before.Second || Before.Third) {
600  Before.dump();
601  OS << " -> ";
602  }
603  if (ConversionFunction)
604  OS << '\'' << *ConversionFunction << '\'';
605  else
606  OS << "aggregate initialization";
607  if (After.First || After.Second || After.Third) {
608  OS << " -> ";
609  After.dump();
610  }
611 }
612 
613 /// dump - Print this implicit conversion sequence to standard
614 /// error. Useful for debugging overloading issues.
616  raw_ostream &OS = llvm::errs();
617  if (hasInitializerListContainerType())
618  OS << "Worst list element conversion: ";
619  switch (ConversionKind) {
620  case StandardConversion:
621  OS << "Standard conversion: ";
622  Standard.dump();
623  break;
624  case UserDefinedConversion:
625  OS << "User-defined conversion: ";
626  UserDefined.dump();
627  break;
628  case EllipsisConversion:
629  OS << "Ellipsis conversion";
630  break;
631  case AmbiguousConversion:
632  OS << "Ambiguous conversion";
633  break;
634  case BadConversion:
635  OS << "Bad conversion";
636  break;
637  }
638 
639  OS << "\n";
640 }
641 
643  new (&conversions()) ConversionSet();
644 }
645 
647  conversions().~ConversionSet();
648 }
649 
650 void
652  FromTypePtr = O.FromTypePtr;
653  ToTypePtr = O.ToTypePtr;
654  new (&conversions()) ConversionSet(O.conversions());
655 }
656 
657 namespace {
658  // Structure used by DeductionFailureInfo to store
659  // template argument information.
660  struct DFIArguments {
661  TemplateArgument FirstArg;
662  TemplateArgument SecondArg;
663  };
664  // Structure used by DeductionFailureInfo to store
665  // template parameter and template argument information.
666  struct DFIParamWithArguments : DFIArguments {
667  TemplateParameter Param;
668  };
669  // Structure used by DeductionFailureInfo to store template argument
670  // information and the index of the problematic call argument.
671  struct DFIDeducedMismatchArgs : DFIArguments {
672  TemplateArgumentList *TemplateArgs;
673  unsigned CallArgIndex;
674  };
675  // Structure used by DeductionFailureInfo to store information about
676  // unsatisfied constraints.
677  struct CNSInfo {
678  TemplateArgumentList *TemplateArgs;
679  ConstraintSatisfaction Satisfaction;
680  };
681 }
682 
683 /// Convert from Sema's representation of template deduction information
684 /// to the form used in overload-candidate information.
688  TemplateDeductionInfo &Info) {
689  DeductionFailureInfo Result;
690  Result.Result = static_cast<unsigned>(TDK);
691  Result.HasDiagnostic = false;
692  switch (TDK) {
699  Result.Data = nullptr;
700  break;
701 
704  Result.Data = Info.Param.getOpaqueValue();
705  break;
706 
709  // FIXME: Should allocate from normal heap so that we can free this later.
710  auto *Saved = new (Context) DFIDeducedMismatchArgs;
711  Saved->FirstArg = Info.FirstArg;
712  Saved->SecondArg = Info.SecondArg;
713  Saved->TemplateArgs = Info.takeSugared();
714  Saved->CallArgIndex = Info.CallArgIndex;
715  Result.Data = Saved;
716  break;
717  }
718 
720  // FIXME: Should allocate from normal heap so that we can free this later.
721  DFIArguments *Saved = new (Context) DFIArguments;
722  Saved->FirstArg = Info.FirstArg;
723  Saved->SecondArg = Info.SecondArg;
724  Result.Data = Saved;
725  break;
726  }
727 
729  // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
732  // FIXME: Should allocate from normal heap so that we can free this later.
733  DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
734  Saved->Param = Info.Param;
735  Saved->FirstArg = Info.FirstArg;
736  Saved->SecondArg = Info.SecondArg;
737  Result.Data = Saved;
738  break;
739  }
740 
742  Result.Data = Info.takeSugared();
743  if (Info.hasSFINAEDiagnostic()) {
744  PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
746  Info.takeSFINAEDiagnostic(*Diag);
747  Result.HasDiagnostic = true;
748  }
749  break;
750 
752  CNSInfo *Saved = new (Context) CNSInfo;
753  Saved->TemplateArgs = Info.takeSugared();
754  Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
755  Result.Data = Saved;
756  break;
757  }
758 
762  llvm_unreachable("not a deduction failure");
763  }
764 
765  return Result;
766 }
767 
769  switch (static_cast<TemplateDeductionResult>(Result)) {
779  break;
780 
787  // FIXME: Destroy the data?
788  Data = nullptr;
789  break;
790 
792  // FIXME: Destroy the template argument list?
793  Data = nullptr;
794  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
795  Diag->~PartialDiagnosticAt();
796  HasDiagnostic = false;
797  }
798  break;
799 
801  // FIXME: Destroy the template argument list?
802  Data = nullptr;
803  if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
804  Diag->~PartialDiagnosticAt();
805  HasDiagnostic = false;
806  }
807  break;
808 
809  // Unhandled
812  break;
813  }
814 }
815 
817  if (HasDiagnostic)
818  return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
819  return nullptr;
820 }
821 
823  switch (static_cast<TemplateDeductionResult>(Result)) {
836  return TemplateParameter();
837 
840  return TemplateParameter::getFromOpaqueValue(Data);
841 
845  return static_cast<DFIParamWithArguments*>(Data)->Param;
846 
847  // Unhandled
850  break;
851  }
852 
853  return TemplateParameter();
854 }
855 
857  switch (static_cast<TemplateDeductionResult>(Result)) {
871  return nullptr;
872 
875  return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
876 
878  return static_cast<TemplateArgumentList*>(Data);
879 
881  return static_cast<CNSInfo*>(Data)->TemplateArgs;
882 
883  // Unhandled
886  break;
887  }
888 
889  return nullptr;
890 }
891 
893  switch (static_cast<TemplateDeductionResult>(Result)) {
905  return nullptr;
906 
913  return &static_cast<DFIArguments*>(Data)->FirstArg;
914 
915  // Unhandled
918  break;
919  }
920 
921  return nullptr;
922 }
923 
925  switch (static_cast<TemplateDeductionResult>(Result)) {
938  return nullptr;
939 
945  return &static_cast<DFIArguments*>(Data)->SecondArg;
946 
947  // Unhandled
950  break;
951  }
952 
953  return nullptr;
954 }
955 
956 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
957  switch (static_cast<TemplateDeductionResult>(Result)) {
960  return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
961 
962  default:
963  return std::nullopt;
964  }
965 }
966 
967 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
968  const FunctionDecl *Y) {
969  if (!X || !Y)
970  return false;
971  if (X->getNumParams() != Y->getNumParams())
972  return false;
973  // FIXME: when do rewritten comparison operators
974  // with explicit object parameters correspond?
975  // https://cplusplus.github.io/CWG/issues/2797.html
976  for (unsigned I = 0; I < X->getNumParams(); ++I)
977  if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
978  Y->getParamDecl(I)->getType()))
979  return false;
980  if (auto *FTX = X->getDescribedFunctionTemplate()) {
981  auto *FTY = Y->getDescribedFunctionTemplate();
982  if (!FTY)
983  return false;
984  if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
985  FTY->getTemplateParameters()))
986  return false;
987  }
988  return true;
989 }
990 
992  Expr *FirstOperand, FunctionDecl *EqFD) {
993  assert(EqFD->getOverloadedOperator() ==
994  OverloadedOperatorKind::OO_EqualEqual);
995  // C++2a [over.match.oper]p4:
996  // A non-template function or function template F named operator== is a
997  // rewrite target with first operand o unless a search for the name operator!=
998  // in the scope S from the instantiation context of the operator expression
999  // finds a function or function template that would correspond
1000  // ([basic.scope.scope]) to F if its name were operator==, where S is the
1001  // scope of the class type of o if F is a class member, and the namespace
1002  // scope of which F is a member otherwise. A function template specialization
1003  // named operator== is a rewrite target if its function template is a rewrite
1004  // target.
1006  OverloadedOperatorKind::OO_ExclaimEqual);
1007  if (isa<CXXMethodDecl>(EqFD)) {
1008  // If F is a class member, search scope is class type of first operand.
1009  QualType RHS = FirstOperand->getType();
1010  auto *RHSRec = RHS->getAs<RecordType>();
1011  if (!RHSRec)
1012  return true;
1013  LookupResult Members(S, NotEqOp, OpLoc,
1014  Sema::LookupNameKind::LookupMemberName);
1015  S.LookupQualifiedName(Members, RHSRec->getDecl());
1016  Members.suppressAccessDiagnostics();
1017  for (NamedDecl *Op : Members)
1018  if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1019  return false;
1020  return true;
1021  }
1022  // Otherwise the search scope is the namespace scope of which F is a member.
1023  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1024  auto *NotEqFD = Op->getAsFunction();
1025  if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1026  NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1027  if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1029  cast<Decl>(Op->getLexicalDeclContext())))
1030  return false;
1031  }
1032  return true;
1033 }
1034 
1037  if (!AllowRewrittenCandidates)
1038  return false;
1039  return Op == OO_EqualEqual || Op == OO_Spaceship;
1040 }
1041 
1043  Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1044  auto Op = FD->getOverloadedOperator();
1045  if (!allowsReversed(Op))
1046  return false;
1047  if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1048  assert(OriginalArgs.size() == 2);
1049  if (!shouldAddReversedEqEq(
1050  S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1051  return false;
1052  }
1053  // Don't bother adding a reversed candidate that can never be a better
1054  // match than the non-reversed version.
1055  return FD->getNumNonObjectParams() != 2 ||
1057  FD->getParamDecl(1)->getType()) ||
1058  FD->hasAttr<EnableIfAttr>();
1059 }
1060 
1061 void OverloadCandidateSet::destroyCandidates() {
1062  for (iterator i = begin(), e = end(); i != e; ++i) {
1063  for (auto &C : i->Conversions)
1064  C.~ImplicitConversionSequence();
1065  if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1066  i->DeductionFailure.Destroy();
1067  }
1068 }
1069 
1071  destroyCandidates();
1072  SlabAllocator.Reset();
1073  NumInlineBytesUsed = 0;
1074  Candidates.clear();
1075  Functions.clear();
1076  Kind = CSK;
1077 }
1078 
1079 namespace {
1080  class UnbridgedCastsSet {
1081  struct Entry {
1082  Expr **Addr;
1083  Expr *Saved;
1084  };
1085  SmallVector<Entry, 2> Entries;
1086 
1087  public:
1088  void save(Sema &S, Expr *&E) {
1089  assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1090  Entry entry = { &E, E };
1091  Entries.push_back(entry);
1092  E = S.ObjC().stripARCUnbridgedCast(E);
1093  }
1094 
1095  void restore() {
1097  i = Entries.begin(), e = Entries.end(); i != e; ++i)
1098  *i->Addr = i->Saved;
1099  }
1100  };
1101 }
1102 
1103 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1104 /// preprocessing on the given expression.
1105 ///
1106 /// \param unbridgedCasts a collection to which to add unbridged casts;
1107 /// without this, they will be immediately diagnosed as errors
1108 ///
1109 /// Return true on unrecoverable error.
1110 static bool
1112  UnbridgedCastsSet *unbridgedCasts = nullptr) {
1113  if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1114  // We can't handle overloaded expressions here because overload
1115  // resolution might reasonably tweak them.
1116  if (placeholder->getKind() == BuiltinType::Overload) return false;
1117 
1118  // If the context potentially accepts unbridged ARC casts, strip
1119  // the unbridged cast and add it to the collection for later restoration.
1120  if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1121  unbridgedCasts) {
1122  unbridgedCasts->save(S, E);
1123  return false;
1124  }
1125 
1126  // Go ahead and check everything else.
1127  ExprResult result = S.CheckPlaceholderExpr(E);
1128  if (result.isInvalid())
1129  return true;
1130 
1131  E = result.get();
1132  return false;
1133  }
1134 
1135  // Nothing to do.
1136  return false;
1137 }
1138 
1139 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1140 /// placeholders.
1142  UnbridgedCastsSet &unbridged) {
1143  for (unsigned i = 0, e = Args.size(); i != e; ++i)
1144  if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1145  return true;
1146 
1147  return false;
1148 }
1149 
1150 /// Determine whether the given New declaration is an overload of the
1151 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1152 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1153 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1154 /// functions (or function templates) at all. When it does return Ovl_Match or
1155 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1156 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1157 /// declaration.
1158 ///
1159 /// Example: Given the following input:
1160 ///
1161 /// void f(int, float); // #1
1162 /// void f(int, int); // #2
1163 /// int f(int, int); // #3
1164 ///
1165 /// When we process #1, there is no previous declaration of "f", so IsOverload
1166 /// will not be used.
1167 ///
1168 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1169 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1170 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1171 /// unchanged.
1172 ///
1173 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1174 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1175 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1176 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1177 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1178 ///
1179 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1180 /// by a using declaration. The rules for whether to hide shadow declarations
1181 /// ignore some properties which otherwise figure into a function template's
1182 /// signature.
1185  NamedDecl *&Match, bool NewIsUsingDecl) {
1186  for (LookupResult::iterator I = Old.begin(), E = Old.end();
1187  I != E; ++I) {
1188  NamedDecl *OldD = *I;
1189 
1190  bool OldIsUsingDecl = false;
1191  if (isa<UsingShadowDecl>(OldD)) {
1192  OldIsUsingDecl = true;
1193 
1194  // We can always introduce two using declarations into the same
1195  // context, even if they have identical signatures.
1196  if (NewIsUsingDecl) continue;
1197 
1198  OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1199  }
1200 
1201  // A using-declaration does not conflict with another declaration
1202  // if one of them is hidden.
1203  if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1204  continue;
1205 
1206  // If either declaration was introduced by a using declaration,
1207  // we'll need to use slightly different rules for matching.
1208  // Essentially, these rules are the normal rules, except that
1209  // function templates hide function templates with different
1210  // return types or template parameter lists.
1211  bool UseMemberUsingDeclRules =
1212  (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1213  !New->getFriendObjectKind();
1214 
1215  if (FunctionDecl *OldF = OldD->getAsFunction()) {
1216  if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1217  if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1218  HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1219  continue;
1220  }
1221 
1222  if (!isa<FunctionTemplateDecl>(OldD) &&
1223  !shouldLinkPossiblyHiddenDecl(*I, New))
1224  continue;
1225 
1226  Match = *I;
1227  return Ovl_Match;
1228  }
1229 
1230  // Builtins that have custom typechecking or have a reference should
1231  // not be overloadable or redeclarable.
1232  if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1233  Match = *I;
1234  return Ovl_NonFunction;
1235  }
1236  } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1237  // We can overload with these, which can show up when doing
1238  // redeclaration checks for UsingDecls.
1239  assert(Old.getLookupKind() == LookupUsingDeclName);
1240  } else if (isa<TagDecl>(OldD)) {
1241  // We can always overload with tags by hiding them.
1242  } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1243  // Optimistically assume that an unresolved using decl will
1244  // overload; if it doesn't, we'll have to diagnose during
1245  // template instantiation.
1246  //
1247  // Exception: if the scope is dependent and this is not a class
1248  // member, the using declaration can only introduce an enumerator.
1249  if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1250  Match = *I;
1251  return Ovl_NonFunction;
1252  }
1253  } else {
1254  // (C++ 13p1):
1255  // Only function declarations can be overloaded; object and type
1256  // declarations cannot be overloaded.
1257  Match = *I;
1258  return Ovl_NonFunction;
1259  }
1260  }
1261 
1262  // C++ [temp.friend]p1:
1263  // For a friend function declaration that is not a template declaration:
1264  // -- if the name of the friend is a qualified or unqualified template-id,
1265  // [...], otherwise
1266  // -- if the name of the friend is a qualified-id and a matching
1267  // non-template function is found in the specified class or namespace,
1268  // the friend declaration refers to that function, otherwise,
1269  // -- if the name of the friend is a qualified-id and a matching function
1270  // template is found in the specified class or namespace, the friend
1271  // declaration refers to the deduced specialization of that function
1272  // template, otherwise
1273  // -- the name shall be an unqualified-id [...]
1274  // If we get here for a qualified friend declaration, we've just reached the
1275  // third bullet. If the type of the friend is dependent, skip this lookup
1276  // until instantiation.
1277  if (New->getFriendObjectKind() && New->getQualifier() &&
1278  !New->getDescribedFunctionTemplate() &&
1280  !New->getType()->isDependentType()) {
1281  LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1282  TemplateSpecResult.addAllDecls(Old);
1283  if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1284  /*QualifiedFriend*/true)) {
1285  New->setInvalidDecl();
1286  return Ovl_Overload;
1287  }
1288 
1289  Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1290  return Ovl_Match;
1291  }
1292 
1293  return Ovl_Overload;
1294 }
1295 
1296 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1297  FunctionDecl *Old,
1298  bool UseMemberUsingDeclRules,
1299  bool ConsiderCudaAttrs,
1300  bool UseOverrideRules = false) {
1301  // C++ [basic.start.main]p2: This function shall not be overloaded.
1302  if (New->isMain())
1303  return false;
1304 
1305  // MSVCRT user defined entry points cannot be overloaded.
1306  if (New->isMSVCRTEntryPoint())
1307  return false;
1308 
1309  NamedDecl *OldDecl = Old;
1310  NamedDecl *NewDecl = New;
1311  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1312  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1313 
1314  // C++ [temp.fct]p2:
1315  // A function template can be overloaded with other function templates
1316  // and with normal (non-template) functions.
1317  if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1318  return true;
1319 
1320  // Is the function New an overload of the function Old?
1321  QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1322  QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1323 
1324  // Compare the signatures (C++ 1.3.10) of the two functions to
1325  // determine whether they are overloads. If we find any mismatch
1326  // in the signature, they are overloads.
1327 
1328  // If either of these functions is a K&R-style function (no
1329  // prototype), then we consider them to have matching signatures.
1330  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1331  isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1332  return false;
1333 
1334  const auto *OldType = cast<FunctionProtoType>(OldQType);
1335  const auto *NewType = cast<FunctionProtoType>(NewQType);
1336 
1337  // The signature of a function includes the types of its
1338  // parameters (C++ 1.3.10), which includes the presence or absence
1339  // of the ellipsis; see C++ DR 357).
1340  if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1341  return true;
1342 
1343  // For member-like friends, the enclosing class is part of the signature.
1344  if ((New->isMemberLikeConstrainedFriend() ||
1347  return true;
1348 
1349  // Compare the parameter lists.
1350  // This can only be done once we have establish that friend functions
1351  // inhabit the same context, otherwise we might tried to instantiate
1352  // references to non-instantiated entities during constraint substitution.
1353  // GH78101.
1354  if (NewTemplate) {
1355  OldDecl = OldTemplate;
1356  NewDecl = NewTemplate;
1357  // C++ [temp.over.link]p4:
1358  // The signature of a function template consists of its function
1359  // signature, its return type and its template parameter list. The names
1360  // of the template parameters are significant only for establishing the
1361  // relationship between the template parameters and the rest of the
1362  // signature.
1363  //
1364  // We check the return type and template parameter lists for function
1365  // templates first; the remaining checks follow.
1366  bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1367  NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1368  OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1369  bool SameReturnType = SemaRef.Context.hasSameType(
1371  // FIXME(GH58571): Match template parameter list even for non-constrained
1372  // template heads. This currently ensures that the code prior to C++20 is
1373  // not newly broken.
1374  bool ConstraintsInTemplateHead =
1375  NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1377  // C++ [namespace.udecl]p11:
1378  // The set of declarations named by a using-declarator that inhabits a
1379  // class C does not include member functions and member function
1380  // templates of a base class that "correspond" to (and thus would
1381  // conflict with) a declaration of a function or function template in
1382  // C.
1383  // Comparing return types is not required for the "correspond" check to
1384  // decide whether a member introduced by a shadow declaration is hidden.
1385  if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1386  !SameTemplateParameterList)
1387  return true;
1388  if (!UseMemberUsingDeclRules &&
1389  (!SameTemplateParameterList || !SameReturnType))
1390  return true;
1391  }
1392 
1393  const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1394  const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1395 
1396  int OldParamsOffset = 0;
1397  int NewParamsOffset = 0;
1398 
1399  // When determining if a method is an overload from a base class, act as if
1400  // the implicit object parameter are of the same type.
1401 
1402  auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1404  return Q;
1405 
1406  // We do not allow overloading based off of '__restrict'.
1407  Q.removeRestrict();
1408 
1409  // We may not have applied the implicit const for a constexpr member
1410  // function yet (because we haven't yet resolved whether this is a static
1411  // or non-static member function). Add it now, on the assumption that this
1412  // is a redeclaration of OldMethod.
1413  if (!SemaRef.getLangOpts().CPlusPlus14 &&
1414  (M->isConstexpr() || M->isConsteval()) &&
1415  !isa<CXXConstructorDecl>(NewMethod))
1416  Q.addConst();
1417  return Q;
1418  };
1419 
1420  auto CompareType = [&](QualType Base, QualType D) {
1421  auto BS = Base.getNonReferenceType().getCanonicalType().split();
1422  BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1423 
1424  auto DS = D.getNonReferenceType().getCanonicalType().split();
1425  DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1426 
1427  if (BS.Quals != DS.Quals)
1428  return false;
1429 
1430  if (OldMethod->isImplicitObjectMemberFunction() &&
1431  OldMethod->getParent() != NewMethod->getParent()) {
1432  QualType ParentType =
1433  SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1434  .getCanonicalType();
1435  if (ParentType.getTypePtr() != BS.Ty)
1436  return false;
1437  BS.Ty = DS.Ty;
1438  }
1439 
1440  // FIXME: should we ignore some type attributes here?
1441  if (BS.Ty != DS.Ty)
1442  return false;
1443 
1444  if (Base->isLValueReferenceType())
1445  return D->isLValueReferenceType();
1446  return Base->isRValueReferenceType() == D->isRValueReferenceType();
1447  };
1448 
1449  // If the function is a class member, its signature includes the
1450  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1451  auto DiagnoseInconsistentRefQualifiers = [&]() {
1452  if (SemaRef.LangOpts.CPlusPlus23)
1453  return false;
1454  if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1455  return false;
1456  if (OldMethod->isExplicitObjectMemberFunction() ||
1457  NewMethod->isExplicitObjectMemberFunction())
1458  return false;
1459  if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1460  NewMethod->getRefQualifier() == RQ_None)) {
1461  SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1462  << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1463  SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1464  return true;
1465  }
1466  return false;
1467  };
1468 
1469  if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1470  OldParamsOffset++;
1471  if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1472  NewParamsOffset++;
1473 
1474  if (OldType->getNumParams() - OldParamsOffset !=
1475  NewType->getNumParams() - NewParamsOffset ||
1476  !SemaRef.FunctionParamTypesAreEqual(
1477  {OldType->param_type_begin() + OldParamsOffset,
1478  OldType->param_type_end()},
1479  {NewType->param_type_begin() + NewParamsOffset,
1480  NewType->param_type_end()},
1481  nullptr)) {
1482  return true;
1483  }
1484 
1485  if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1486  !NewMethod->isStatic()) {
1487  bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1488  const CXXMethodDecl *New) {
1489  auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1490  auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1491 
1492  auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1493  return F->getRefQualifier() == RQ_None &&
1494  !F->isExplicitObjectMemberFunction();
1495  };
1496 
1497  if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1498  CompareType(OldObjectType.getNonReferenceType(),
1499  NewObjectType.getNonReferenceType()))
1500  return true;
1501  return CompareType(OldObjectType, NewObjectType);
1502  }(OldMethod, NewMethod);
1503 
1504  if (!HaveCorrespondingObjectParameters) {
1505  if (DiagnoseInconsistentRefQualifiers())
1506  return true;
1507  // CWG2554
1508  // and, if at least one is an explicit object member function, ignoring
1509  // object parameters
1510  if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1511  !OldMethod->isExplicitObjectMemberFunction()))
1512  return true;
1513  }
1514  }
1515 
1516  if (!UseOverrideRules &&
1518  Expr *NewRC = New->getTrailingRequiresClause(),
1519  *OldRC = Old->getTrailingRequiresClause();
1520  if ((NewRC != nullptr) != (OldRC != nullptr))
1521  return true;
1522  if (NewRC &&
1523  !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1524  return true;
1525  }
1526 
1527  if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1528  NewMethod->isImplicitObjectMemberFunction()) {
1529  if (DiagnoseInconsistentRefQualifiers())
1530  return true;
1531  }
1532 
1533  // Though pass_object_size is placed on parameters and takes an argument, we
1534  // consider it to be a function-level modifier for the sake of function
1535  // identity. Either the function has one or more parameters with
1536  // pass_object_size or it doesn't.
1539  return true;
1540 
1541  // enable_if attributes are an order-sensitive part of the signature.
1543  NewI = New->specific_attr_begin<EnableIfAttr>(),
1544  NewE = New->specific_attr_end<EnableIfAttr>(),
1545  OldI = Old->specific_attr_begin<EnableIfAttr>(),
1546  OldE = Old->specific_attr_end<EnableIfAttr>();
1547  NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1548  if (NewI == NewE || OldI == OldE)
1549  return true;
1550  llvm::FoldingSetNodeID NewID, OldID;
1551  NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1552  OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1553  if (NewID != OldID)
1554  return true;
1555  }
1556 
1557  if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1558  // Don't allow overloading of destructors. (In theory we could, but it
1559  // would be a giant change to clang.)
1560  if (!isa<CXXDestructorDecl>(New)) {
1561  CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1562  OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1563  if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1564  assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1565  "Unexpected invalid target.");
1566 
1567  // Allow overloading of functions with same signature and different CUDA
1568  // target attributes.
1569  if (NewTarget != OldTarget)
1570  return true;
1571  }
1572  }
1573  }
1574 
1575  // The signatures match; this is not an overload.
1576  return false;
1577 }
1578 
1580  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1581  return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1582  ConsiderCudaAttrs);
1583 }
1584 
1586  bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1587  return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1588  /*UseMemberUsingDeclRules=*/false,
1589  /*ConsiderCudaAttrs=*/true,
1590  /*UseOverrideRules=*/true);
1591 }
1592 
1593 /// Tries a user-defined conversion from From to ToType.
1594 ///
1595 /// Produces an implicit conversion sequence for when a standard conversion
1596 /// is not an option. See TryImplicitConversion for more information.
1599  bool SuppressUserConversions,
1600  AllowedExplicit AllowExplicit,
1601  bool InOverloadResolution,
1602  bool CStyle,
1603  bool AllowObjCWritebackConversion,
1604  bool AllowObjCConversionOnExplicit) {
1606 
1607  if (SuppressUserConversions) {
1608  // We're not in the case above, so there is no conversion that
1609  // we can perform.
1610  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1611  return ICS;
1612  }
1613 
1614  // Attempt user-defined conversion.
1615  OverloadCandidateSet Conversions(From->getExprLoc(),
1617  switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1618  Conversions, AllowExplicit,
1619  AllowObjCConversionOnExplicit)) {
1620  case OR_Success:
1621  case OR_Deleted:
1622  ICS.setUserDefined();
1623  // C++ [over.ics.user]p4:
1624  // A conversion of an expression of class type to the same class
1625  // type is given Exact Match rank, and a conversion of an
1626  // expression of class type to a base class of that type is
1627  // given Conversion rank, in spite of the fact that a copy
1628  // constructor (i.e., a user-defined conversion function) is
1629  // called for those cases.
1630  if (CXXConstructorDecl *Constructor
1631  = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1632  QualType FromCanon
1634  QualType ToCanon
1636  if (Constructor->isCopyConstructor() &&
1637  (FromCanon == ToCanon ||
1638  S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1639  // Turn this into a "standard" conversion sequence, so that it
1640  // gets ranked with standard conversion sequences.
1642  ICS.setStandard();
1644  ICS.Standard.setFromType(From->getType());
1645  ICS.Standard.setAllToTypes(ToType);
1646  ICS.Standard.CopyConstructor = Constructor;
1647  ICS.Standard.FoundCopyConstructor = Found;
1648  if (ToCanon != FromCanon)
1650  }
1651  }
1652  break;
1653 
1654  case OR_Ambiguous:
1655  ICS.setAmbiguous();
1656  ICS.Ambiguous.setFromType(From->getType());
1657  ICS.Ambiguous.setToType(ToType);
1658  for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1659  Cand != Conversions.end(); ++Cand)
1660  if (Cand->Best)
1661  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1662  break;
1663 
1664  // Fall through.
1665  case OR_No_Viable_Function:
1666  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1667  break;
1668  }
1669 
1670  return ICS;
1671 }
1672 
1673 /// TryImplicitConversion - Attempt to perform an implicit conversion
1674 /// from the given expression (Expr) to the given type (ToType). This
1675 /// function returns an implicit conversion sequence that can be used
1676 /// to perform the initialization. Given
1677 ///
1678 /// void f(float f);
1679 /// void g(int i) { f(i); }
1680 ///
1681 /// this routine would produce an implicit conversion sequence to
1682 /// describe the initialization of f from i, which will be a standard
1683 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1684 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1685 //
1686 /// Note that this routine only determines how the conversion can be
1687 /// performed; it does not actually perform the conversion. As such,
1688 /// it will not produce any diagnostics if no conversion is available,
1689 /// but will instead return an implicit conversion sequence of kind
1690 /// "BadConversion".
1691 ///
1692 /// If @p SuppressUserConversions, then user-defined conversions are
1693 /// not permitted.
1694 /// If @p AllowExplicit, then explicit user-defined conversions are
1695 /// permitted.
1696 ///
1697 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1698 /// writeback conversion, which allows __autoreleasing id* parameters to
1699 /// be initialized with __strong id* or __weak id* arguments.
1702  bool SuppressUserConversions,
1703  AllowedExplicit AllowExplicit,
1704  bool InOverloadResolution,
1705  bool CStyle,
1706  bool AllowObjCWritebackConversion,
1707  bool AllowObjCConversionOnExplicit) {
1709  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1710  ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1711  ICS.setStandard();
1712  return ICS;
1713  }
1714 
1715  if (!S.getLangOpts().CPlusPlus) {
1716  ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1717  return ICS;
1718  }
1719 
1720  // C++ [over.ics.user]p4:
1721  // A conversion of an expression of class type to the same class
1722  // type is given Exact Match rank, and a conversion of an
1723  // expression of class type to a base class of that type is
1724  // given Conversion rank, in spite of the fact that a copy/move
1725  // constructor (i.e., a user-defined conversion function) is
1726  // called for those cases.
1727  QualType FromType = From->getType();
1728  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1729  (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1730  S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1731  ICS.setStandard();
1733  ICS.Standard.setFromType(FromType);
1734  ICS.Standard.setAllToTypes(ToType);
1735 
1736  // We don't actually check at this point whether there is a valid
1737  // copy/move constructor, since overloading just assumes that it
1738  // exists. When we actually perform initialization, we'll find the
1739  // appropriate constructor to copy the returned object, if needed.
1740  ICS.Standard.CopyConstructor = nullptr;
1741 
1742  // Determine whether this is considered a derived-to-base conversion.
1743  if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1745 
1746  return ICS;
1747  }
1748 
1749  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1750  AllowExplicit, InOverloadResolution, CStyle,
1751  AllowObjCWritebackConversion,
1752  AllowObjCConversionOnExplicit);
1753 }
1754 
1757  bool SuppressUserConversions,
1758  AllowedExplicit AllowExplicit,
1759  bool InOverloadResolution,
1760  bool CStyle,
1761  bool AllowObjCWritebackConversion) {
1762  return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1763  AllowExplicit, InOverloadResolution, CStyle,
1764  AllowObjCWritebackConversion,
1765  /*AllowObjCConversionOnExplicit=*/false);
1766 }
1767 
1768 /// PerformImplicitConversion - Perform an implicit conversion of the
1769 /// expression From to the type ToType. Returns the
1770 /// converted expression. Flavor is the kind of conversion we're
1771 /// performing, used in the error message. If @p AllowExplicit,
1772 /// explicit user-defined conversions are permitted.
1774  AssignmentAction Action,
1775  bool AllowExplicit) {
1776  if (checkPlaceholderForOverload(*this, From))
1777  return ExprError();
1778 
1779  // Objective-C ARC: Determine whether we will allow the writeback conversion.
1780  bool AllowObjCWritebackConversion
1781  = getLangOpts().ObjCAutoRefCount &&
1782  (Action == AA_Passing || Action == AA_Sending);
1783  if (getLangOpts().ObjC)
1784  ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1785  From->getType(), From);
1787  *this, From, ToType,
1788  /*SuppressUserConversions=*/false,
1789  AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1790  /*InOverloadResolution=*/false,
1791  /*CStyle=*/false, AllowObjCWritebackConversion,
1792  /*AllowObjCConversionOnExplicit=*/false);
1793  return PerformImplicitConversion(From, ToType, ICS, Action);
1794 }
1795 
1796 /// Determine whether the conversion from FromType to ToType is a valid
1797 /// conversion that strips "noexcept" or "noreturn" off the nested function
1798 /// type.
1800  QualType &ResultTy) {
1801  if (Context.hasSameUnqualifiedType(FromType, ToType))
1802  return false;
1803 
1804  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1805  // or F(t noexcept) -> F(t)
1806  // where F adds one of the following at most once:
1807  // - a pointer
1808  // - a member pointer
1809  // - a block pointer
1810  // Changes here need matching changes in FindCompositePointerType.
1811  CanQualType CanTo = Context.getCanonicalType(ToType);
1812  CanQualType CanFrom = Context.getCanonicalType(FromType);
1813  Type::TypeClass TyClass = CanTo->getTypeClass();
1814  if (TyClass != CanFrom->getTypeClass()) return false;
1815  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1816  if (TyClass == Type::Pointer) {
1817  CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1818  CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1819  } else if (TyClass == Type::BlockPointer) {
1820  CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1821  CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1822  } else if (TyClass == Type::MemberPointer) {
1823  auto ToMPT = CanTo.castAs<MemberPointerType>();
1824  auto FromMPT = CanFrom.castAs<MemberPointerType>();
1825  // A function pointer conversion cannot change the class of the function.
1826  if (ToMPT->getClass() != FromMPT->getClass())
1827  return false;
1828  CanTo = ToMPT->getPointeeType();
1829  CanFrom = FromMPT->getPointeeType();
1830  } else {
1831  return false;
1832  }
1833 
1834  TyClass = CanTo->getTypeClass();
1835  if (TyClass != CanFrom->getTypeClass()) return false;
1836  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1837  return false;
1838  }
1839 
1840  const auto *FromFn = cast<FunctionType>(CanFrom);
1841  FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1842 
1843  const auto *ToFn = cast<FunctionType>(CanTo);
1844  FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1845 
1846  bool Changed = false;
1847 
1848  // Drop 'noreturn' if not present in target type.
1849  if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1850  FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1851  Changed = true;
1852  }
1853 
1854  // Drop 'noexcept' if not present in target type.
1855  if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1856  const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1857  if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1858  FromFn = cast<FunctionType>(
1859  Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1860  EST_None)
1861  .getTypePtr());
1862  Changed = true;
1863  }
1864 
1865  // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1866  // only if the ExtParameterInfo lists of the two function prototypes can be
1867  // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1869  bool CanUseToFPT, CanUseFromFPT;
1870  if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1871  CanUseFromFPT, NewParamInfos) &&
1872  CanUseToFPT && !CanUseFromFPT) {
1873  FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1874  ExtInfo.ExtParameterInfos =
1875  NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1876  QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1877  FromFPT->getParamTypes(), ExtInfo);
1878  FromFn = QT->getAs<FunctionType>();
1879  Changed = true;
1880  }
1881  }
1882 
1883  if (!Changed)
1884  return false;
1885 
1886  assert(QualType(FromFn, 0).isCanonical());
1887  if (QualType(FromFn, 0) != CanTo) return false;
1888 
1889  ResultTy = ToType;
1890  return true;
1891 }
1892 
1893 /// Determine whether the conversion from FromType to ToType is a valid
1894 /// floating point conversion.
1895 ///
1896 static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1897  QualType ToType) {
1898  if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1899  return false;
1900  // FIXME: disable conversions between long double, __ibm128 and __float128
1901  // if their representation is different until there is back end support
1902  // We of course allow this conversion if long double is really double.
1903 
1904  // Conversions between bfloat16 and float16 are currently not supported.
1905  if ((FromType->isBFloat16Type() &&
1906  (ToType->isFloat16Type() || ToType->isHalfType())) ||
1907  (ToType->isBFloat16Type() &&
1908  (FromType->isFloat16Type() || FromType->isHalfType())))
1909  return false;
1910 
1911  // Conversions between IEEE-quad and IBM-extended semantics are not
1912  // permitted.
1913  const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1914  const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1915  if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1916  &ToSem == &llvm::APFloat::IEEEquad()) ||
1917  (&FromSem == &llvm::APFloat::IEEEquad() &&
1918  &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1919  return false;
1920  return true;
1921 }
1922 
1923 static bool IsVectorElementConversion(Sema &S, QualType FromType,
1924  QualType ToType,
1925  ImplicitConversionKind &ICK, Expr *From) {
1926  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1927  return true;
1928 
1929  if (S.IsFloatingPointPromotion(FromType, ToType)) {
1930  ICK = ICK_Floating_Promotion;
1931  return true;
1932  }
1933 
1934  if (IsFloatingPointConversion(S, FromType, ToType)) {
1936  return true;
1937  }
1938 
1939  if (ToType->isBooleanType() && FromType->isArithmeticType()) {
1940  ICK = ICK_Boolean_Conversion;
1941  return true;
1942  }
1943 
1944  if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
1945  (FromType->isIntegralOrUnscopedEnumerationType() &&
1946  ToType->isRealFloatingType())) {
1947  ICK = ICK_Floating_Integral;
1948  return true;
1949  }
1950 
1951  if (S.IsIntegralPromotion(From, FromType, ToType)) {
1952  ICK = ICK_Integral_Promotion;
1953  return true;
1954  }
1955 
1956  if (FromType->isIntegralOrUnscopedEnumerationType() &&
1957  ToType->isIntegralType(S.Context)) {
1959  return true;
1960  }
1961 
1962  return false;
1963 }
1964 
1965 /// Determine whether the conversion from FromType to ToType is a valid
1966 /// vector conversion.
1967 ///
1968 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1969 /// conversion.
1970 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1972  ImplicitConversionKind &ElConv, Expr *From,
1973  bool InOverloadResolution, bool CStyle) {
1974  // We need at least one of these types to be a vector type to have a vector
1975  // conversion.
1976  if (!ToType->isVectorType() && !FromType->isVectorType())
1977  return false;
1978 
1979  // Identical types require no conversions.
1980  if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1981  return false;
1982 
1983  // There are no conversions between extended vector types, only identity.
1984  if (ToType->isExtVectorType()) {
1985  if (FromType->isExtVectorType()) {
1986  // HLSL allows implicit truncation of vector types.
1987  if (S.getLangOpts().HLSL) {
1988  unsigned FromElts = FromType->getAs<VectorType>()->getNumElements();
1989  unsigned ToElts = ToType->getAs<VectorType>()->getNumElements();
1990  if (FromElts < ToElts)
1991  return false;
1992  if (FromElts == ToElts)
1993  ICK = ICK_Identity;
1994  else
1996 
1997  QualType FromElTy = FromType->getAs<VectorType>()->getElementType();
1998  QualType ToElTy = ToType->getAs<VectorType>()->getElementType();
1999  if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2000  return true;
2001  return IsVectorElementConversion(S, FromElTy, ToElTy, ElConv, From);
2002  }
2003  // There are no conversions between extended vector types other than the
2004  // identity conversion.
2005  return false;
2006  }
2007 
2008  // Vector splat from any arithmetic type to a vector.
2009  if (FromType->isArithmeticType()) {
2010  ICK = ICK_Vector_Splat;
2011  return true;
2012  }
2013  }
2014 
2015  if (ToType->isSVESizelessBuiltinType() ||
2016  FromType->isSVESizelessBuiltinType())
2017  if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2018  S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2020  return true;
2021  }
2022 
2023  if (ToType->isRVVSizelessBuiltinType() ||
2024  FromType->isRVVSizelessBuiltinType())
2025  if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2026  S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2028  return true;
2029  }
2030 
2031  // We can perform the conversion between vector types in the following cases:
2032  // 1)vector types are equivalent AltiVec and GCC vector types
2033  // 2)lax vector conversions are permitted and the vector types are of the
2034  // same size
2035  // 3)the destination type does not have the ARM MVE strict-polymorphism
2036  // attribute, which inhibits lax vector conversion for overload resolution
2037  // only
2038  if (ToType->isVectorType() && FromType->isVectorType()) {
2039  if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2040  (S.isLaxVectorConversion(FromType, ToType) &&
2041  !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2042  if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2043  S.isLaxVectorConversion(FromType, ToType) &&
2044  S.anyAltivecTypes(FromType, ToType) &&
2045  !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2046  !InOverloadResolution && !CStyle) {
2047  S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2048  << FromType << ToType;
2049  }
2050  ICK = ICK_Vector_Conversion;
2051  return true;
2052  }
2053  }
2054 
2055  return false;
2056 }
2057 
2058 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2059  bool InOverloadResolution,
2061  bool CStyle);
2062 
2063 /// IsStandardConversion - Determines whether there is a standard
2064 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2065 /// expression From to the type ToType. Standard conversion sequences
2066 /// only consider non-class types; for conversions that involve class
2067 /// types, use TryImplicitConversion. If a conversion exists, SCS will
2068 /// contain the standard conversion sequence required to perform this
2069 /// conversion and this routine will return true. Otherwise, this
2070 /// routine will return false and the value of SCS is unspecified.
2071 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2072  bool InOverloadResolution,
2074  bool CStyle,
2075  bool AllowObjCWritebackConversion) {
2076  QualType FromType = From->getType();
2077 
2078  // Standard conversions (C++ [conv])
2080  SCS.IncompatibleObjC = false;
2081  SCS.setFromType(FromType);
2082  SCS.CopyConstructor = nullptr;
2083 
2084  // There are no standard conversions for class types in C++, so
2085  // abort early. When overloading in C, however, we do permit them.
2086  if (S.getLangOpts().CPlusPlus &&
2087  (FromType->isRecordType() || ToType->isRecordType()))
2088  return false;
2089 
2090  // The first conversion can be an lvalue-to-rvalue conversion,
2091  // array-to-pointer conversion, or function-to-pointer conversion
2092  // (C++ 4p1).
2093 
2094  if (FromType == S.Context.OverloadTy) {
2095  DeclAccessPair AccessPair;
2096  if (FunctionDecl *Fn
2097  = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2098  AccessPair)) {
2099  // We were able to resolve the address of the overloaded function,
2100  // so we can convert to the type of that function.
2101  FromType = Fn->getType();
2102  SCS.setFromType(FromType);
2103 
2104  // we can sometimes resolve &foo<int> regardless of ToType, so check
2105  // if the type matches (identity) or we are converting to bool
2107  S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2108  QualType resultTy;
2109  // if the function type matches except for [[noreturn]], it's ok
2110  if (!S.IsFunctionConversion(FromType,
2111  S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2112  // otherwise, only a boolean conversion is standard
2113  if (!ToType->isBooleanType())
2114  return false;
2115  }
2116 
2117  // Check if the "from" expression is taking the address of an overloaded
2118  // function and recompute the FromType accordingly. Take advantage of the
2119  // fact that non-static member functions *must* have such an address-of
2120  // expression.
2121  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2122  if (Method && !Method->isStatic() &&
2123  !Method->isExplicitObjectMemberFunction()) {
2124  assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2125  "Non-unary operator on non-static member address");
2126  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2127  == UO_AddrOf &&
2128  "Non-address-of operator on non-static member address");
2129  const Type *ClassType
2130  = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
2131  FromType = S.Context.getMemberPointerType(FromType, ClassType);
2132  } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2133  assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2134  UO_AddrOf &&
2135  "Non-address-of operator for overloaded function expression");
2136  FromType = S.Context.getPointerType(FromType);
2137  }
2138  } else {
2139  return false;
2140  }
2141  }
2142  // Lvalue-to-rvalue conversion (C++11 4.1):
2143  // A glvalue (3.10) of a non-function, non-array type T can
2144  // be converted to a prvalue.
2145  bool argIsLValue = From->isGLValue();
2146  if (argIsLValue && !FromType->canDecayToPointerType() &&
2147  S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2149 
2150  // C11 6.3.2.1p2:
2151  // ... if the lvalue has atomic type, the value has the non-atomic version
2152  // of the type of the lvalue ...
2153  if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2154  FromType = Atomic->getValueType();
2155 
2156  // If T is a non-class type, the type of the rvalue is the
2157  // cv-unqualified version of T. Otherwise, the type of the rvalue
2158  // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2159  // just strip the qualifiers because they don't matter.
2160  FromType = FromType.getUnqualifiedType();
2161  } else if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2162  ToType->isArrayParameterType()) {
2163  // HLSL constant array parameters do not decay, so if the argument is a
2164  // constant array and the parameter is an ArrayParameterType we have special
2165  // handling here.
2166  FromType = S.Context.getArrayParameterType(FromType);
2167  if (S.Context.getCanonicalType(FromType) !=
2168  S.Context.getCanonicalType(ToType))
2169  return false;
2170 
2172  SCS.setAllToTypes(ToType);
2173  return true;
2174  } else if (FromType->isArrayType()) {
2175  // Array-to-pointer conversion (C++ 4.2)
2177 
2178  // An lvalue or rvalue of type "array of N T" or "array of unknown
2179  // bound of T" can be converted to an rvalue of type "pointer to
2180  // T" (C++ 4.2p1).
2181  FromType = S.Context.getArrayDecayedType(FromType);
2182 
2183  if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2184  // This conversion is deprecated in C++03 (D.4)
2186 
2187  // For the purpose of ranking in overload resolution
2188  // (13.3.3.1.1), this conversion is considered an
2189  // array-to-pointer conversion followed by a qualification
2190  // conversion (4.4). (C++ 4.2p2)
2191  SCS.Second = ICK_Identity;
2192  SCS.Third = ICK_Qualification;
2194  SCS.setAllToTypes(FromType);
2195  return true;
2196  }
2197  } else if (FromType->isFunctionType() && argIsLValue) {
2198  // Function-to-pointer conversion (C++ 4.3).
2200 
2201  if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) {
2202  if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2204  return false;
2205 
2206  // Some parts of clang are not designed for deferred diagnostics.
2207  // One of the examples - initialization. When a new initialization is
2208  // performed - it may end up here checking validity of a conversion.
2209  // If false is returned from here, initialization sequence is marked as
2210  // invalid, then checkAddressOfFunctionIsAvailable is called again
2211  // to understand the reason of invaid initialization and in the end
2212  // it is called with 'Complain' parameter to emit diagnostics.
2213  // We cannot mark an initialization permanently invalid for SYCL device,
2214  // because we may not know yet where the device code is.
2215  // So, just call 'checkAddressOfFunctionIsAvailable' again but with
2216  // 'Complain' parameter to issue a deferred diagnostic.
2217  if (S.getLangOpts().SYCLIsDevice)
2218  (void)S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
2219  DRE->getExprLoc());
2220  }
2221  }
2222 
2223  // An lvalue of function type T can be converted to an rvalue of
2224  // type "pointer to T." The result is a pointer to the
2225  // function. (C++ 4.3p1).
2226  FromType = S.Context.getPointerType(FromType);
2227  } else {
2228  // We don't require any conversions for the first step.
2229  SCS.First = ICK_Identity;
2230  }
2231  SCS.setToType(0, FromType);
2232 
2233  // The second conversion can be an integral promotion, floating
2234  // point promotion, integral conversion, floating point conversion,
2235  // floating-integral conversion, pointer conversion,
2236  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2237  // For overloading in C, this can also be a "compatible-type"
2238  // conversion.
2239  bool IncompatibleObjC = false;
2241  ImplicitConversionKind ElementICK = ICK_Identity;
2242  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2243  // The unqualified versions of the types are the same: there's no
2244  // conversion to do.
2245  SCS.Second = ICK_Identity;
2246  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2247  // Integral promotion (C++ 4.5).
2249  FromType = ToType.getUnqualifiedType();
2250  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2251  // Floating point promotion (C++ 4.6).
2253  FromType = ToType.getUnqualifiedType();
2254  } else if (S.IsComplexPromotion(FromType, ToType)) {
2255  // Complex promotion (Clang extension)
2257  FromType = ToType.getUnqualifiedType();
2258  } else if (ToType->isBooleanType() &&
2259  (FromType->isArithmeticType() ||
2260  FromType->isAnyPointerType() ||
2261  FromType->isBlockPointerType() ||
2262  FromType->isMemberPointerType())) {
2263  // Boolean conversions (C++ 4.12).
2265  FromType = S.Context.BoolTy;
2266  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2267  ToType->isIntegralType(S.Context)) {
2268  // Integral conversions (C++ 4.7).
2270  FromType = ToType.getUnqualifiedType();
2271  } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2272  // Complex conversions (C99 6.3.1.6)
2274  FromType = ToType.getUnqualifiedType();
2275  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2276  (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2277  // Complex-real conversions (C99 6.3.1.7)
2278  SCS.Second = ICK_Complex_Real;
2279  FromType = ToType.getUnqualifiedType();
2280  } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2281  // Floating point conversions (C++ 4.8).
2283  FromType = ToType.getUnqualifiedType();
2284  } else if ((FromType->isRealFloatingType() &&
2285  ToType->isIntegralType(S.Context)) ||
2286  (FromType->isIntegralOrUnscopedEnumerationType() &&
2287  ToType->isRealFloatingType())) {
2288 
2289  // Floating-integral conversions (C++ 4.9).
2291  FromType = ToType.getUnqualifiedType();
2292  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2294  } else if (AllowObjCWritebackConversion &&
2295  S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2297  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2298  FromType, IncompatibleObjC)) {
2299  // Pointer conversions (C++ 4.10).
2301  SCS.IncompatibleObjC = IncompatibleObjC;
2302  FromType = FromType.getUnqualifiedType();
2303  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2304  InOverloadResolution, FromType)) {
2305  // Pointer to member conversions (4.11).
2306  SCS.Second = ICK_Pointer_Member;
2307  } else if (IsVectorConversion(S, FromType, ToType, SecondICK, ElementICK,
2308  From, InOverloadResolution, CStyle)) {
2309  SCS.Second = SecondICK;
2310  SCS.Element = ElementICK;
2311  FromType = ToType.getUnqualifiedType();
2312  } else if (!S.getLangOpts().CPlusPlus &&
2313  S.Context.typesAreCompatible(ToType, FromType)) {
2314  // Compatible conversions (Clang extension for C function overloading)
2316  FromType = ToType.getUnqualifiedType();
2318  S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2320  FromType = ToType;
2321  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2322  CStyle)) {
2323  // tryAtomicConversion has updated the standard conversion sequence
2324  // appropriately.
2325  return true;
2326  } else if (ToType->isEventT() &&
2327  From->isIntegerConstantExpr(S.getASTContext()) &&
2328  From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2330  FromType = ToType;
2331  } else if (ToType->isQueueT() &&
2332  From->isIntegerConstantExpr(S.getASTContext()) &&
2333  (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2335  FromType = ToType;
2336  } else if (ToType->isSamplerT() &&
2337  From->isIntegerConstantExpr(S.getASTContext())) {
2339  FromType = ToType;
2340  } else if ((ToType->isFixedPointType() &&
2341  FromType->isConvertibleToFixedPointType()) ||
2342  (FromType->isFixedPointType() &&
2343  ToType->isConvertibleToFixedPointType())) {
2345  FromType = ToType;
2346  } else {
2347  // No second conversion required.
2348  SCS.Second = ICK_Identity;
2349  }
2350  SCS.setToType(1, FromType);
2351 
2352  // The third conversion can be a function pointer conversion or a
2353  // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2354  bool ObjCLifetimeConversion;
2355  if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2356  // Function pointer conversions (removing 'noexcept') including removal of
2357  // 'noreturn' (Clang extension).
2359  } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2360  ObjCLifetimeConversion)) {
2361  SCS.Third = ICK_Qualification;
2362  SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2363  FromType = ToType;
2364  } else {
2365  // No conversion required
2366  SCS.Third = ICK_Identity;
2367  }
2368 
2369  // C++ [over.best.ics]p6:
2370  // [...] Any difference in top-level cv-qualification is
2371  // subsumed by the initialization itself and does not constitute
2372  // a conversion. [...]
2373  QualType CanonFrom = S.Context.getCanonicalType(FromType);
2374  QualType CanonTo = S.Context.getCanonicalType(ToType);
2375  if (CanonFrom.getLocalUnqualifiedType()
2376  == CanonTo.getLocalUnqualifiedType() &&
2377  CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2378  FromType = ToType;
2379  CanonFrom = CanonTo;
2380  }
2381 
2382  SCS.setToType(2, FromType);
2383 
2384  if (CanonFrom == CanonTo)
2385  return true;
2386 
2387  // If we have not converted the argument type to the parameter type,
2388  // this is a bad conversion sequence, unless we're resolving an overload in C.
2389  if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2390  return false;
2391 
2392  ExprResult ER = ExprResult{From};
2394  S.CheckSingleAssignmentConstraints(ToType, ER,
2395  /*Diagnose=*/false,
2396  /*DiagnoseCFAudited=*/false,
2397  /*ConvertRHS=*/false);
2398  ImplicitConversionKind SecondConv;
2399  switch (Conv) {
2400  case Sema::Compatible:
2401  SecondConv = ICK_C_Only_Conversion;
2402  break;
2403  // For our purposes, discarding qualifiers is just as bad as using an
2404  // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2405  // qualifiers, as well.
2410  break;
2411  default:
2412  return false;
2413  }
2414 
2415  // First can only be an lvalue conversion, so we pretend that this was the
2416  // second conversion. First should already be valid from earlier in the
2417  // function.
2418  SCS.Second = SecondConv;
2419  SCS.setToType(1, ToType);
2420 
2421  // Third is Identity, because Second should rank us worse than any other
2422  // conversion. This could also be ICK_Qualification, but it's simpler to just
2423  // lump everything in with the second conversion, and we don't gain anything
2424  // from making this ICK_Qualification.
2425  SCS.Third = ICK_Identity;
2426  SCS.setToType(2, ToType);
2427  return true;
2428 }
2429 
2430 static bool
2432  QualType &ToType,
2433  bool InOverloadResolution,
2435  bool CStyle) {
2436 
2437  const RecordType *UT = ToType->getAsUnionType();
2438  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2439  return false;
2440  // The field to initialize within the transparent union.
2441  RecordDecl *UD = UT->getDecl();
2442  // It's compatible if the expression matches any of the fields.
2443  for (const auto *it : UD->fields()) {
2444  if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2445  CStyle, /*AllowObjCWritebackConversion=*/false)) {
2446  ToType = it->getType();
2447  return true;
2448  }
2449  }
2450  return false;
2451 }
2452 
2453 /// IsIntegralPromotion - Determines whether the conversion from the
2454 /// expression From (whose potentially-adjusted type is FromType) to
2455 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2456 /// sets PromotedType to the promoted type.
2457 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2458  const BuiltinType *To = ToType->getAs<BuiltinType>();
2459  // All integers are built-in.
2460  if (!To) {
2461  return false;
2462  }
2463 
2464  // An rvalue of type char, signed char, unsigned char, short int, or
2465  // unsigned short int can be converted to an rvalue of type int if
2466  // int can represent all the values of the source type; otherwise,
2467  // the source rvalue can be converted to an rvalue of type unsigned
2468  // int (C++ 4.5p1).
2469  if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2470  !FromType->isEnumeralType()) {
2471  if ( // We can promote any signed, promotable integer type to an int
2472  (FromType->isSignedIntegerType() ||
2473  // We can promote any unsigned integer type whose size is
2474  // less than int to an int.
2475  Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2476  return To->getKind() == BuiltinType::Int;
2477  }
2478 
2479  return To->getKind() == BuiltinType::UInt;
2480  }
2481 
2482  // C++11 [conv.prom]p3:
2483  // A prvalue of an unscoped enumeration type whose underlying type is not
2484  // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2485  // following types that can represent all the values of the enumeration
2486  // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2487  // unsigned int, long int, unsigned long int, long long int, or unsigned
2488  // long long int. If none of the types in that list can represent all the
2489  // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2490  // type can be converted to an rvalue a prvalue of the extended integer type
2491  // with lowest integer conversion rank (4.13) greater than the rank of long
2492  // long in which all the values of the enumeration can be represented. If
2493  // there are two such extended types, the signed one is chosen.
2494  // C++11 [conv.prom]p4:
2495  // A prvalue of an unscoped enumeration type whose underlying type is fixed
2496  // can be converted to a prvalue of its underlying type. Moreover, if
2497  // integral promotion can be applied to its underlying type, a prvalue of an
2498  // unscoped enumeration type whose underlying type is fixed can also be
2499  // converted to a prvalue of the promoted underlying type.
2500  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2501  // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2502  // provided for a scoped enumeration.
2503  if (FromEnumType->getDecl()->isScoped())
2504  return false;
2505 
2506  // We can perform an integral promotion to the underlying type of the enum,
2507  // even if that's not the promoted type. Note that the check for promoting
2508  // the underlying type is based on the type alone, and does not consider
2509  // the bitfield-ness of the actual source expression.
2510  if (FromEnumType->getDecl()->isFixed()) {
2511  QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2512  return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2513  IsIntegralPromotion(nullptr, Underlying, ToType);
2514  }
2515 
2516  // We have already pre-calculated the promotion type, so this is trivial.
2517  if (ToType->isIntegerType() &&
2518  isCompleteType(From->getBeginLoc(), FromType))
2519  return Context.hasSameUnqualifiedType(
2520  ToType, FromEnumType->getDecl()->getPromotionType());
2521 
2522  // C++ [conv.prom]p5:
2523  // If the bit-field has an enumerated type, it is treated as any other
2524  // value of that type for promotion purposes.
2525  //
2526  // ... so do not fall through into the bit-field checks below in C++.
2527  if (getLangOpts().CPlusPlus)
2528  return false;
2529  }
2530 
2531  // C++0x [conv.prom]p2:
2532  // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2533  // to an rvalue a prvalue of the first of the following types that can
2534  // represent all the values of its underlying type: int, unsigned int,
2535  // long int, unsigned long int, long long int, or unsigned long long int.
2536  // If none of the types in that list can represent all the values of its
2537  // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2538  // or wchar_t can be converted to an rvalue a prvalue of its underlying
2539  // type.
2540  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2541  ToType->isIntegerType()) {
2542  // Determine whether the type we're converting from is signed or
2543  // unsigned.
2544  bool FromIsSigned = FromType->isSignedIntegerType();
2545  uint64_t FromSize = Context.getTypeSize(FromType);
2546 
2547  // The types we'll try to promote to, in the appropriate
2548  // order. Try each of these types.
2549  QualType PromoteTypes[6] = {
2550  Context.IntTy, Context.UnsignedIntTy,
2551  Context.LongTy, Context.UnsignedLongTy ,
2552  Context.LongLongTy, Context.UnsignedLongLongTy
2553  };
2554  for (int Idx = 0; Idx < 6; ++Idx) {
2555  uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2556  if (FromSize < ToSize ||
2557  (FromSize == ToSize &&
2558  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2559  // We found the type that we can promote to. If this is the
2560  // type we wanted, we have a promotion. Otherwise, no
2561  // promotion.
2562  return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2563  }
2564  }
2565  }
2566 
2567  // An rvalue for an integral bit-field (9.6) can be converted to an
2568  // rvalue of type int if int can represent all the values of the
2569  // bit-field; otherwise, it can be converted to unsigned int if
2570  // unsigned int can represent all the values of the bit-field. If
2571  // the bit-field is larger yet, no integral promotion applies to
2572  // it. If the bit-field has an enumerated type, it is treated as any
2573  // other value of that type for promotion purposes (C++ 4.5p3).
2574  // FIXME: We should delay checking of bit-fields until we actually perform the
2575  // conversion.
2576  //
2577  // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2578  // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2579  // bit-fields and those whose underlying type is larger than int) for GCC
2580  // compatibility.
2581  if (From) {
2582  if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2583  std::optional<llvm::APSInt> BitWidth;
2584  if (FromType->isIntegralType(Context) &&
2585  (BitWidth =
2586  MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2587  llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2588  ToSize = Context.getTypeSize(ToType);
2589 
2590  // Are we promoting to an int from a bitfield that fits in an int?
2591  if (*BitWidth < ToSize ||
2592  (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2593  return To->getKind() == BuiltinType::Int;
2594  }
2595 
2596  // Are we promoting to an unsigned int from an unsigned bitfield
2597  // that fits into an unsigned int?
2598  if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2599  return To->getKind() == BuiltinType::UInt;
2600  }
2601 
2602  return false;
2603  }
2604  }
2605  }
2606 
2607  // An rvalue of type bool can be converted to an rvalue of type int,
2608  // with false becoming zero and true becoming one (C++ 4.5p4).
2609  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2610  return true;
2611  }
2612 
2613  // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2614  // integral type.
2615  if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2616  ToType->isIntegerType())
2617  return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2618 
2619  return false;
2620 }
2621 
2622 /// IsFloatingPointPromotion - Determines whether the conversion from
2623 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2624 /// returns true and sets PromotedType to the promoted type.
2626  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2627  if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2628  /// An rvalue of type float can be converted to an rvalue of type
2629  /// double. (C++ 4.6p1).
2630  if (FromBuiltin->getKind() == BuiltinType::Float &&
2631  ToBuiltin->getKind() == BuiltinType::Double)
2632  return true;
2633 
2634  // C99 6.3.1.5p1:
2635  // When a float is promoted to double or long double, or a
2636  // double is promoted to long double [...].
2637  if (!getLangOpts().CPlusPlus &&
2638  (FromBuiltin->getKind() == BuiltinType::Float ||
2639  FromBuiltin->getKind() == BuiltinType::Double) &&
2640  (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2641  ToBuiltin->getKind() == BuiltinType::Float128 ||
2642  ToBuiltin->getKind() == BuiltinType::Ibm128))
2643  return true;
2644 
2645  // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2646  // or not native half types are enabled.
2647  if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2648  (ToBuiltin->getKind() == BuiltinType::Float ||
2649  ToBuiltin->getKind() == BuiltinType::Double))
2650  return true;
2651 
2652  // Half can be promoted to float.
2653  if (!getLangOpts().NativeHalfType &&
2654  FromBuiltin->getKind() == BuiltinType::Half &&
2655  ToBuiltin->getKind() == BuiltinType::Float)
2656  return true;
2657  }
2658 
2659  return false;
2660 }
2661 
2662 /// Determine if a conversion is a complex promotion.
2663 ///
2664 /// A complex promotion is defined as a complex -> complex conversion
2665 /// where the conversion between the underlying real types is a
2666 /// floating-point or integral promotion.
2668  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2669  if (!FromComplex)
2670  return false;
2671 
2672  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2673  if (!ToComplex)
2674  return false;
2675 
2676  return IsFloatingPointPromotion(FromComplex->getElementType(),
2677  ToComplex->getElementType()) ||
2678  IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2679  ToComplex->getElementType());
2680 }
2681 
2682 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2683 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2684 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2685 /// if non-empty, will be a pointer to ToType that may or may not have
2686 /// the right set of qualifiers on its pointee.
2687 ///
2688 static QualType
2690  QualType ToPointee, QualType ToType,
2691  ASTContext &Context,
2692  bool StripObjCLifetime = false) {
2693  assert((FromPtr->getTypeClass() == Type::Pointer ||
2694  FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2695  "Invalid similarly-qualified pointer type");
2696 
2697  /// Conversions to 'id' subsume cv-qualifier conversions.
2698  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2699  return ToType.getUnqualifiedType();
2700 
2701  QualType CanonFromPointee
2702  = Context.getCanonicalType(FromPtr->getPointeeType());
2703  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2704  Qualifiers Quals = CanonFromPointee.getQualifiers();
2705 
2706  if (StripObjCLifetime)
2707  Quals.removeObjCLifetime();
2708 
2709  // Exact qualifier match -> return the pointer type we're converting to.
2710  if (CanonToPointee.getLocalQualifiers() == Quals) {
2711  // ToType is exactly what we need. Return it.
2712  if (!ToType.isNull())
2713  return ToType.getUnqualifiedType();
2714 
2715  // Build a pointer to ToPointee. It has the right qualifiers
2716  // already.
2717  if (isa<ObjCObjectPointerType>(ToType))
2718  return Context.getObjCObjectPointerType(ToPointee);
2719  return Context.getPointerType(ToPointee);
2720  }
2721 
2722  // Just build a canonical type that has the right qualifiers.
2723  QualType QualifiedCanonToPointee
2724  = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2725 
2726  if (isa<ObjCObjectPointerType>(ToType))
2727  return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2728  return Context.getPointerType(QualifiedCanonToPointee);
2729 }
2730 
2732  bool InOverloadResolution,
2733  ASTContext &Context) {
2734  // Handle value-dependent integral null pointer constants correctly.
2735  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2736  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2738  return !InOverloadResolution;
2739 
2740  return Expr->isNullPointerConstant(Context,
2741  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2743 }
2744 
2745 /// IsPointerConversion - Determines whether the conversion of the
2746 /// expression From, which has the (possibly adjusted) type FromType,
2747 /// can be converted to the type ToType via a pointer conversion (C++
2748 /// 4.10). If so, returns true and places the converted type (that
2749 /// might differ from ToType in its cv-qualifiers at some level) into
2750 /// ConvertedType.
2751 ///
2752 /// This routine also supports conversions to and from block pointers
2753 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2754 /// pointers to interfaces. FIXME: Once we've determined the
2755 /// appropriate overloading rules for Objective-C, we may want to
2756 /// split the Objective-C checks into a different routine; however,
2757 /// GCC seems to consider all of these conversions to be pointer
2758 /// conversions, so for now they live here. IncompatibleObjC will be
2759 /// set if the conversion is an allowed Objective-C conversion that
2760 /// should result in a warning.
2761 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2762  bool InOverloadResolution,
2763  QualType& ConvertedType,
2764  bool &IncompatibleObjC) {
2765  IncompatibleObjC = false;
2766  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2767  IncompatibleObjC))
2768  return true;
2769 
2770  // Conversion from a null pointer constant to any Objective-C pointer type.
2771  if (ToType->isObjCObjectPointerType() &&
2772  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2773  ConvertedType = ToType;
2774  return true;
2775  }
2776 
2777  // Blocks: Block pointers can be converted to void*.
2778  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2779  ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2780  ConvertedType = ToType;
2781  return true;
2782  }
2783  // Blocks: A null pointer constant can be converted to a block
2784  // pointer type.
2785  if (ToType->isBlockPointerType() &&
2786  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2787  ConvertedType = ToType;
2788  return true;
2789  }
2790 
2791  // If the left-hand-side is nullptr_t, the right side can be a null
2792  // pointer constant.
2793  if (ToType->isNullPtrType() &&
2794  isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2795  ConvertedType = ToType;
2796  return true;
2797  }
2798 
2799  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2800  if (!ToTypePtr)
2801  return false;
2802 
2803  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2804  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2805  ConvertedType = ToType;
2806  return true;
2807  }
2808 
2809  // Beyond this point, both types need to be pointers
2810  // , including objective-c pointers.
2811  QualType ToPointeeType = ToTypePtr->getPointeeType();
2812  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2813  !getLangOpts().ObjCAutoRefCount) {
2814  ConvertedType = BuildSimilarlyQualifiedPointerType(
2815  FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2816  Context);
2817  return true;
2818  }
2819  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2820  if (!FromTypePtr)
2821  return false;
2822 
2823  QualType FromPointeeType = FromTypePtr->getPointeeType();
2824 
2825  // If the unqualified pointee types are the same, this can't be a
2826  // pointer conversion, so don't do all of the work below.
2827  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2828  return false;
2829 
2830  // An rvalue of type "pointer to cv T," where T is an object type,
2831  // can be converted to an rvalue of type "pointer to cv void" (C++
2832  // 4.10p2).
2833  if (FromPointeeType->isIncompleteOrObjectType() &&
2834  ToPointeeType->isVoidType()) {
2835  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2836  ToPointeeType,
2837  ToType, Context,
2838  /*StripObjCLifetime=*/true);
2839  return true;
2840  }
2841 
2842  // MSVC allows implicit function to void* type conversion.
2843  if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2844  ToPointeeType->isVoidType()) {
2845  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2846  ToPointeeType,
2847  ToType, Context);
2848  return true;
2849  }
2850 
2851  // When we're overloading in C, we allow a special kind of pointer
2852  // conversion for compatible-but-not-identical pointee types.
2853  if (!getLangOpts().CPlusPlus &&
2854  Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2855  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2856  ToPointeeType,
2857  ToType, Context);
2858  return true;
2859  }
2860 
2861  // C++ [conv.ptr]p3:
2862  //
2863  // An rvalue of type "pointer to cv D," where D is a class type,
2864  // can be converted to an rvalue of type "pointer to cv B," where
2865  // B is a base class (clause 10) of D. If B is an inaccessible
2866  // (clause 11) or ambiguous (10.2) base class of D, a program that
2867  // necessitates this conversion is ill-formed. The result of the
2868  // conversion is a pointer to the base class sub-object of the
2869  // derived class object. The null pointer value is converted to
2870  // the null pointer value of the destination type.
2871  //
2872  // Note that we do not check for ambiguity or inaccessibility
2873  // here. That is handled by CheckPointerConversion.
2874  if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2875  ToPointeeType->isRecordType() &&
2876  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2877  IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2878  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2879  ToPointeeType,
2880  ToType, Context);
2881  return true;
2882  }
2883 
2884  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2885  Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2886  ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2887  ToPointeeType,
2888  ToType, Context);
2889  return true;
2890  }
2891 
2892  return false;
2893 }
2894 
2895 /// Adopt the given qualifiers for the given type.
2897  Qualifiers TQs = T.getQualifiers();
2898 
2899  // Check whether qualifiers already match.
2900  if (TQs == Qs)
2901  return T;
2902 
2903  if (Qs.compatiblyIncludes(TQs))
2904  return Context.getQualifiedType(T, Qs);
2905 
2906  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2907 }
2908 
2909 /// isObjCPointerConversion - Determines whether this is an
2910 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2911 /// with the same arguments and return values.
2913  QualType& ConvertedType,
2914  bool &IncompatibleObjC) {
2915  if (!getLangOpts().ObjC)
2916  return false;
2917 
2918  // The set of qualifiers on the type we're converting from.
2919  Qualifiers FromQualifiers = FromType.getQualifiers();
2920 
2921  // First, we handle all conversions on ObjC object pointer types.
2922  const ObjCObjectPointerType* ToObjCPtr =
2923  ToType->getAs<ObjCObjectPointerType>();
2924  const ObjCObjectPointerType *FromObjCPtr =
2925  FromType->getAs<ObjCObjectPointerType>();
2926 
2927  if (ToObjCPtr && FromObjCPtr) {
2928  // If the pointee types are the same (ignoring qualifications),
2929  // then this is not a pointer conversion.
2930  if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2931  FromObjCPtr->getPointeeType()))
2932  return false;
2933 
2934  // Conversion between Objective-C pointers.
2935  if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2936  const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2937  const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2938  if (getLangOpts().CPlusPlus && LHS && RHS &&
2939  !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2940  FromObjCPtr->getPointeeType()))
2941  return false;
2942  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2943  ToObjCPtr->getPointeeType(),
2944  ToType, Context);
2945  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2946  return true;
2947  }
2948 
2949  if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2950  // Okay: this is some kind of implicit downcast of Objective-C
2951  // interfaces, which is permitted. However, we're going to
2952  // complain about it.
2953  IncompatibleObjC = true;
2954  ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2955  ToObjCPtr->getPointeeType(),
2956  ToType, Context);
2957  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2958  return true;
2959  }
2960  }
2961  // Beyond this point, both types need to be C pointers or block pointers.
2962  QualType ToPointeeType;
2963  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2964  ToPointeeType = ToCPtr->getPointeeType();
2965  else if (const BlockPointerType *ToBlockPtr =
2966  ToType->getAs<BlockPointerType>()) {
2967  // Objective C++: We're able to convert from a pointer to any object
2968  // to a block pointer type.
2969  if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2970  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2971  return true;
2972  }
2973  ToPointeeType = ToBlockPtr->getPointeeType();
2974  }
2975  else if (FromType->getAs<BlockPointerType>() &&
2976  ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2977  // Objective C++: We're able to convert from a block pointer type to a
2978  // pointer to any object.
2979  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2980  return true;
2981  }
2982  else
2983  return false;
2984 
2985  QualType FromPointeeType;
2986  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2987  FromPointeeType = FromCPtr->getPointeeType();
2988  else if (const BlockPointerType *FromBlockPtr =
2989  FromType->getAs<BlockPointerType>())
2990  FromPointeeType = FromBlockPtr->getPointeeType();
2991  else
2992  return false;
2993 
2994  // If we have pointers to pointers, recursively check whether this
2995  // is an Objective-C conversion.
2996  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2997  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2998  IncompatibleObjC)) {
2999  // We always complain about this conversion.
3000  IncompatibleObjC = true;
3001  ConvertedType = Context.getPointerType(ConvertedType);
3002  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3003  return true;
3004  }
3005  // Allow conversion of pointee being objective-c pointer to another one;
3006  // as in I* to id.
3007  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3008  ToPointeeType->getAs<ObjCObjectPointerType>() &&
3009  isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3010  IncompatibleObjC)) {
3011 
3012  ConvertedType = Context.getPointerType(ConvertedType);
3013  ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3014  return true;
3015  }
3016 
3017  // If we have pointers to functions or blocks, check whether the only
3018  // differences in the argument and result types are in Objective-C
3019  // pointer conversions. If so, we permit the conversion (but
3020  // complain about it).
3021  const FunctionProtoType *FromFunctionType
3022  = FromPointeeType->getAs<FunctionProtoType>();
3023  const FunctionProtoType *ToFunctionType
3024  = ToPointeeType->getAs<FunctionProtoType>();
3025  if (FromFunctionType && ToFunctionType) {
3026  // If the function types are exactly the same, this isn't an
3027  // Objective-C pointer conversion.
3028  if (Context.getCanonicalType(FromPointeeType)
3029  == Context.getCanonicalType(ToPointeeType))
3030  return false;
3031 
3032  // Perform the quick checks that will tell us whether these
3033  // function types are obviously different.
3034  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3035  FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3036  FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3037  return false;
3038 
3039  bool HasObjCConversion = false;
3040  if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3041  Context.getCanonicalType(ToFunctionType->getReturnType())) {
3042  // Okay, the types match exactly. Nothing to do.
3043  } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3044  ToFunctionType->getReturnType(),
3045  ConvertedType, IncompatibleObjC)) {
3046  // Okay, we have an Objective-C pointer conversion.
3047  HasObjCConversion = true;
3048  } else {
3049  // Function types are too different. Abort.
3050  return false;
3051  }
3052 
3053  // Check argument types.
3054  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3055  ArgIdx != NumArgs; ++ArgIdx) {
3056  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3057  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3058  if (Context.getCanonicalType(FromArgType)
3059  == Context.getCanonicalType(ToArgType)) {
3060  // Okay, the types match exactly. Nothing to do.
3061  } else if (isObjCPointerConversion(FromArgType, ToArgType,
3062  ConvertedType, IncompatibleObjC)) {
3063  // Okay, we have an Objective-C pointer conversion.
3064  HasObjCConversion = true;
3065  } else {
3066  // Argument types are too different. Abort.
3067  return false;
3068  }
3069  }
3070 
3071  if (HasObjCConversion) {
3072  // We had an Objective-C conversion. Allow this pointer
3073  // conversion, but complain about it.
3074  ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3075  IncompatibleObjC = true;
3076  return true;
3077  }
3078  }
3079 
3080  return false;
3081 }
3082 
3084  QualType& ConvertedType) {
3085  QualType ToPointeeType;
3086  if (const BlockPointerType *ToBlockPtr =
3087  ToType->getAs<BlockPointerType>())
3088  ToPointeeType = ToBlockPtr->getPointeeType();
3089  else
3090  return false;
3091 
3092  QualType FromPointeeType;
3093  if (const BlockPointerType *FromBlockPtr =
3094  FromType->getAs<BlockPointerType>())
3095  FromPointeeType = FromBlockPtr->getPointeeType();
3096  else
3097  return false;
3098  // We have pointer to blocks, check whether the only
3099  // differences in the argument and result types are in Objective-C
3100  // pointer conversions. If so, we permit the conversion.
3101 
3102  const FunctionProtoType *FromFunctionType
3103  = FromPointeeType->getAs<FunctionProtoType>();
3104  const FunctionProtoType *ToFunctionType
3105  = ToPointeeType->getAs<FunctionProtoType>();
3106 
3107  if (!FromFunctionType || !ToFunctionType)
3108  return false;
3109 
3110  if (Context.hasSameType(FromPointeeType, ToPointeeType))
3111  return true;
3112 
3113  // Perform the quick checks that will tell us whether these
3114  // function types are obviously different.
3115  if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3116  FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3117  return false;
3118 
3119  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3120  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3121  if (FromEInfo != ToEInfo)
3122  return false;
3123 
3124  bool IncompatibleObjC = false;
3125  if (Context.hasSameType(FromFunctionType->getReturnType(),
3126  ToFunctionType->getReturnType())) {
3127  // Okay, the types match exactly. Nothing to do.
3128  } else {
3129  QualType RHS = FromFunctionType->getReturnType();
3130  QualType LHS = ToFunctionType->getReturnType();
3131  if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3132  !RHS.hasQualifiers() && LHS.hasQualifiers())
3133  LHS = LHS.getUnqualifiedType();
3134 
3135  if (Context.hasSameType(RHS,LHS)) {
3136  // OK exact match.
3137  } else if (isObjCPointerConversion(RHS, LHS,
3138  ConvertedType, IncompatibleObjC)) {
3139  if (IncompatibleObjC)
3140  return false;
3141  // Okay, we have an Objective-C pointer conversion.
3142  }
3143  else
3144  return false;
3145  }
3146 
3147  // Check argument types.
3148  for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3149  ArgIdx != NumArgs; ++ArgIdx) {
3150  IncompatibleObjC = false;
3151  QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3152  QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3153  if (Context.hasSameType(FromArgType, ToArgType)) {
3154  // Okay, the types match exactly. Nothing to do.
3155  } else if (isObjCPointerConversion(ToArgType, FromArgType,
3156  ConvertedType, IncompatibleObjC)) {
3157  if (IncompatibleObjC)
3158  return false;
3159  // Okay, we have an Objective-C pointer conversion.
3160  } else
3161  // Argument types are too different. Abort.
3162  return false;
3163  }
3164 
3166  bool CanUseToFPT, CanUseFromFPT;
3167  if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3168  CanUseToFPT, CanUseFromFPT,
3169  NewParamInfos))
3170  return false;
3171 
3172  ConvertedType = ToType;
3173  return true;
3174 }
3175 
3176 enum {
3183  ft_noexcept
3184 };
3185 
3186 /// Attempts to get the FunctionProtoType from a Type. Handles
3187 /// MemberFunctionPointers properly.
3189  if (auto *FPT = FromType->getAs<FunctionProtoType>())
3190  return FPT;
3191 
3192  if (auto *MPT = FromType->getAs<MemberPointerType>())
3193  return MPT->getPointeeType()->getAs<FunctionProtoType>();
3194 
3195  return nullptr;
3196 }
3197 
3198 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3199 /// function types. Catches different number of parameter, mismatch in
3200 /// parameter types, and different return types.
3202  QualType FromType, QualType ToType) {
3203  // If either type is not valid, include no extra info.
3204  if (FromType.isNull() || ToType.isNull()) {
3205  PDiag << ft_default;
3206  return;
3207  }
3208 
3209  // Get the function type from the pointers.
3210  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3211  const auto *FromMember = FromType->castAs<MemberPointerType>(),
3212  *ToMember = ToType->castAs<MemberPointerType>();
3213  if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3214  PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3215  << QualType(FromMember->getClass(), 0);
3216  return;
3217  }
3218  FromType = FromMember->getPointeeType();
3219  ToType = ToMember->getPointeeType();
3220  }
3221 
3222  if (FromType->isPointerType())
3223  FromType = FromType->getPointeeType();
3224  if (ToType->isPointerType())
3225  ToType = ToType->getPointeeType();
3226 
3227  // Remove references.
3228  FromType = FromType.getNonReferenceType();
3229  ToType = ToType.getNonReferenceType();
3230 
3231  // Don't print extra info for non-specialized template functions.
3232  if (FromType->isInstantiationDependentType() &&
3233  !FromType->getAs<TemplateSpecializationType>()) {
3234  PDiag << ft_default;
3235  return;
3236  }
3237 
3238  // No extra info for same types.
3239  if (Context.hasSameType(FromType, ToType)) {
3240  PDiag << ft_default;
3241  return;
3242  }
3243 
3244  const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3245  *ToFunction = tryGetFunctionProtoType(ToType);
3246 
3247  // Both types need to be function types.
3248  if (!FromFunction || !ToFunction) {
3249  PDiag << ft_default;
3250  return;
3251  }
3252 
3253  if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3254  PDiag << ft_parameter_arity << ToFunction->getNumParams()
3255  << FromFunction->getNumParams();
3256  return;
3257  }
3258 
3259  // Handle different parameter types.
3260  unsigned ArgPos;
3261  if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3262  PDiag << ft_parameter_mismatch << ArgPos + 1
3263  << ToFunction->getParamType(ArgPos)
3264  << FromFunction->getParamType(ArgPos);
3265  return;
3266  }
3267 
3268  // Handle different return type.
3269  if (!Context.hasSameType(FromFunction->getReturnType(),
3270  ToFunction->getReturnType())) {
3271  PDiag << ft_return_type << ToFunction->getReturnType()
3272  << FromFunction->getReturnType();
3273  return;
3274  }
3275 
3276  if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3277  PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3278  << FromFunction->getMethodQuals();
3279  return;
3280  }
3281 
3282  // Handle exception specification differences on canonical type (in C++17
3283  // onwards).
3284  if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3285  ->isNothrow() !=
3286  cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3287  ->isNothrow()) {
3288  PDiag << ft_noexcept;
3289  return;
3290  }
3291 
3292  // Unable to find a difference, so add no extra info.
3293  PDiag << ft_default;
3294 }
3295 
3296 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3297 /// for equality of their parameter types. Caller has already checked that
3298 /// they have same number of parameters. If the parameters are different,
3299 /// ArgPos will have the parameter index of the first different parameter.
3300 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3301 /// reverse order. That's useful if one of the functions is being used as a C++20
3302 /// synthesized operator overload with a reversed parameter order.
3304  ArrayRef<QualType> New, unsigned *ArgPos,
3305  bool Reversed) {
3306  assert(llvm::size(Old) == llvm::size(New) &&
3307  "Can't compare parameters of functions with different number of "
3308  "parameters!");
3309 
3310  for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3311  // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3312  size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3313 
3314  // Ignore address spaces in pointee type. This is to disallow overloading
3315  // on __ptr32/__ptr64 address spaces.
3316  QualType OldType =
3317  Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3318  QualType NewType =
3319  Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3320 
3321  if (!Context.hasSameType(OldType, NewType)) {
3322  if (ArgPos)
3323  *ArgPos = Idx;
3324  return false;
3325  }
3326  }
3327  return true;
3328 }
3329 
3331  const FunctionProtoType *NewType,
3332  unsigned *ArgPos, bool Reversed) {
3333  return FunctionParamTypesAreEqual(OldType->param_types(),
3334  NewType->param_types(), ArgPos, Reversed);
3335 }
3336 
3338  const FunctionDecl *NewFunction,
3339  unsigned *ArgPos,
3340  bool Reversed) {
3341 
3342  if (OldFunction->getNumNonObjectParams() !=
3343  NewFunction->getNumNonObjectParams())
3344  return false;
3345 
3346  unsigned OldIgnore =
3348  unsigned NewIgnore =
3350 
3351  auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3352  auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3353 
3354  return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3355  NewPT->param_types().slice(NewIgnore),
3356  ArgPos, Reversed);
3357 }
3358 
3359 /// CheckPointerConversion - Check the pointer conversion from the
3360 /// expression From to the type ToType. This routine checks for
3361 /// ambiguous or inaccessible derived-to-base pointer
3362 /// conversions for which IsPointerConversion has already returned
3363 /// true. It returns true and produces a diagnostic if there was an
3364 /// error, or returns false otherwise.
3366  CastKind &Kind,
3367  CXXCastPath& BasePath,
3368  bool IgnoreBaseAccess,
3369  bool Diagnose) {
3370  QualType FromType = From->getType();
3371  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3372 
3373  Kind = CK_BitCast;
3374 
3375  if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3378  if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3379  DiagRuntimeBehavior(From->getExprLoc(), From,
3380  PDiag(diag::warn_impcast_bool_to_null_pointer)
3381  << ToType << From->getSourceRange());
3382  else if (!isUnevaluatedContext())
3383  Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3384  << ToType << From->getSourceRange();
3385  }
3386  if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3387  if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3388  QualType FromPointeeType = FromPtrType->getPointeeType(),
3389  ToPointeeType = ToPtrType->getPointeeType();
3390 
3391  if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3392  !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3393  // We must have a derived-to-base conversion. Check an
3394  // ambiguous or inaccessible conversion.
3395  unsigned InaccessibleID = 0;
3396  unsigned AmbiguousID = 0;
3397  if (Diagnose) {
3398  InaccessibleID = diag::err_upcast_to_inaccessible_base;
3399  AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3400  }
3401  if (CheckDerivedToBaseConversion(
3402  FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3403  From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3404  &BasePath, IgnoreBaseAccess))
3405  return true;
3406 
3407  // The conversion was successful.
3408  Kind = CK_DerivedToBase;
3409  }
3410 
3411  if (Diagnose && !IsCStyleOrFunctionalCast &&
3412  FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3413  assert(getLangOpts().MSVCCompat &&
3414  "this should only be possible with MSVCCompat!");
3415  Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3416  << From->getSourceRange();
3417  }
3418  }
3419  } else if (const ObjCObjectPointerType *ToPtrType =
3420  ToType->getAs<ObjCObjectPointerType>()) {
3421  if (const ObjCObjectPointerType *FromPtrType =
3422  FromType->getAs<ObjCObjectPointerType>()) {
3423  // Objective-C++ conversions are always okay.
3424  // FIXME: We should have a different class of conversions for the
3425  // Objective-C++ implicit conversions.
3426  if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3427  return false;
3428  } else if (FromType->isBlockPointerType()) {
3429  Kind = CK_BlockPointerToObjCPointerCast;
3430  } else {
3431  Kind = CK_CPointerToObjCPointerCast;
3432  }
3433  } else if (ToType->isBlockPointerType()) {
3434  if (!FromType->isBlockPointerType())
3435  Kind = CK_AnyPointerToBlockPointerCast;
3436  }
3437 
3438  // We shouldn't fall into this case unless it's valid for other
3439  // reasons.
3441  Kind = CK_NullToPointer;
3442 
3443  return false;
3444 }
3445 
3446 /// IsMemberPointerConversion - Determines whether the conversion of the
3447 /// expression From, which has the (possibly adjusted) type FromType, can be
3448 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3449 /// If so, returns true and places the converted type (that might differ from
3450 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3452  QualType ToType,
3453  bool InOverloadResolution,
3454  QualType &ConvertedType) {
3455  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3456  if (!ToTypePtr)
3457  return false;
3458 
3459  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3460  if (From->isNullPointerConstant(Context,
3461  InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3463  ConvertedType = ToType;
3464  return true;
3465  }
3466 
3467  // Otherwise, both types have to be member pointers.
3468  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3469  if (!FromTypePtr)
3470  return false;
3471 
3472  // A pointer to member of B can be converted to a pointer to member of D,
3473  // where D is derived from B (C++ 4.11p2).
3474  QualType FromClass(FromTypePtr->getClass(), 0);
3475  QualType ToClass(ToTypePtr->getClass(), 0);
3476 
3477  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3478  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3479  ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3480  ToClass.getTypePtr());
3481  return true;
3482  }
3483 
3484  return false;
3485 }
3486 
3487 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3488 /// expression From to the type ToType. This routine checks for ambiguous or
3489 /// virtual or inaccessible base-to-derived member pointer conversions
3490 /// for which IsMemberPointerConversion has already returned true. It returns
3491 /// true and produces a diagnostic if there was an error, or returns false
3492 /// otherwise.
3494  CastKind &Kind,
3495  CXXCastPath &BasePath,
3496  bool IgnoreBaseAccess) {
3497  QualType FromType = From->getType();
3498  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3499  if (!FromPtrType) {
3500  // This must be a null pointer to member pointer conversion
3501  assert(From->isNullPointerConstant(Context,
3503  "Expr must be null pointer constant!");
3504  Kind = CK_NullToMemberPointer;
3505  return false;
3506  }
3507 
3508  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3509  assert(ToPtrType && "No member pointer cast has a target type "
3510  "that is not a member pointer.");
3511 
3512  QualType FromClass = QualType(FromPtrType->getClass(), 0);
3513  QualType ToClass = QualType(ToPtrType->getClass(), 0);
3514 
3515  // FIXME: What about dependent types?
3516  assert(FromClass->isRecordType() && "Pointer into non-class.");
3517  assert(ToClass->isRecordType() && "Pointer into non-class.");
3518 
3519  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3520  /*DetectVirtual=*/true);
3521  bool DerivationOkay =
3522  IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3523  assert(DerivationOkay &&
3524  "Should not have been called if derivation isn't OK.");
3525  (void)DerivationOkay;
3526 
3527  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3528  getUnqualifiedType())) {
3529  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3530  Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3531  << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3532  return true;
3533  }
3534 
3535  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3536  Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3537  << FromClass << ToClass << QualType(VBase, 0)
3538  << From->getSourceRange();
3539  return true;
3540  }
3541 
3542  if (!IgnoreBaseAccess)
3543  CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3544  Paths.front(),
3545  diag::err_downcast_from_inaccessible_base);
3546 
3547  // Must be a base to derived member conversion.
3548  BuildBasePathArray(Paths, BasePath);
3549  Kind = CK_BaseToDerivedMemberPointer;
3550  return false;
3551 }
3552 
3553 /// Determine whether the lifetime conversion between the two given
3554 /// qualifiers sets is nontrivial.
3556  Qualifiers ToQuals) {
3557  // Converting anything to const __unsafe_unretained is trivial.
3558  if (ToQuals.hasConst() &&
3560  return false;
3561 
3562  return true;
3563 }
3564 
3565 /// Perform a single iteration of the loop for checking if a qualification
3566 /// conversion is valid.
3567 ///
3568 /// Specifically, check whether any change between the qualifiers of \p
3569 /// FromType and \p ToType is permissible, given knowledge about whether every
3570 /// outer layer is const-qualified.
3571 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3572  bool CStyle, bool IsTopLevel,
3573  bool &PreviousToQualsIncludeConst,
3574  bool &ObjCLifetimeConversion) {
3575  Qualifiers FromQuals = FromType.getQualifiers();
3576  Qualifiers ToQuals = ToType.getQualifiers();
3577 
3578  // Ignore __unaligned qualifier.
3579  FromQuals.removeUnaligned();
3580 
3581  // Objective-C ARC:
3582  // Check Objective-C lifetime conversions.
3583  if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3584  if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3585  if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3586  ObjCLifetimeConversion = true;
3587  FromQuals.removeObjCLifetime();
3588  ToQuals.removeObjCLifetime();
3589  } else {
3590  // Qualification conversions cannot cast between different
3591  // Objective-C lifetime qualifiers.
3592  return false;
3593  }
3594  }
3595 
3596  // Allow addition/removal of GC attributes but not changing GC attributes.
3597  if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3598  (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3599  FromQuals.removeObjCGCAttr();
3600  ToQuals.removeObjCGCAttr();
3601  }
3602 
3603  // -- for every j > 0, if const is in cv 1,j then const is in cv
3604  // 2,j, and similarly for volatile.
3605  if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3606  return false;
3607 
3608  // If address spaces mismatch:
3609  // - in top level it is only valid to convert to addr space that is a
3610  // superset in all cases apart from C-style casts where we allow
3611  // conversions between overlapping address spaces.
3612  // - in non-top levels it is not a valid conversion.
3613  if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3614  (!IsTopLevel ||
3615  !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3616  (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3617  return false;
3618 
3619  // -- if the cv 1,j and cv 2,j are different, then const is in
3620  // every cv for 0 < k < j.
3621  if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3622  !PreviousToQualsIncludeConst)
3623  return false;
3624 
3625  // The following wording is from C++20, where the result of the conversion
3626  // is T3, not T2.
3627  // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3628  // "array of unknown bound of"
3629  if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3630  return false;
3631 
3632  // -- if the resulting P3,i is different from P1,i [...], then const is
3633  // added to every cv 3_k for 0 < k < i.
3634  if (!CStyle && FromType->isConstantArrayType() &&
3635  ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3636  return false;
3637 
3638  // Keep track of whether all prior cv-qualifiers in the "to" type
3639  // include const.
3640  PreviousToQualsIncludeConst =
3641  PreviousToQualsIncludeConst && ToQuals.hasConst();
3642  return true;
3643 }
3644 
3645 /// IsQualificationConversion - Determines whether the conversion from
3646 /// an rvalue of type FromType to ToType is a qualification conversion
3647 /// (C++ 4.4).
3648 ///
3649 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3650 /// when the qualification conversion involves a change in the Objective-C
3651 /// object lifetime.
3652 bool
3654  bool CStyle, bool &ObjCLifetimeConversion) {
3655  FromType = Context.getCanonicalType(FromType);
3656  ToType = Context.getCanonicalType(ToType);
3657  ObjCLifetimeConversion = false;
3658 
3659  // If FromType and ToType are the same type, this is not a
3660  // qualification conversion.
3661  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3662  return false;
3663 
3664  // (C++ 4.4p4):
3665  // A conversion can add cv-qualifiers at levels other than the first
3666  // in multi-level pointers, subject to the following rules: [...]
3667  bool PreviousToQualsIncludeConst = true;
3668  bool UnwrappedAnyPointer = false;
3669  while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3671  FromType, ToType, CStyle, !UnwrappedAnyPointer,
3672  PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3673  return false;
3674  UnwrappedAnyPointer = true;
3675  }
3676 
3677  // We are left with FromType and ToType being the pointee types
3678  // after unwrapping the original FromType and ToType the same number
3679  // of times. If we unwrapped any pointers, and if FromType and
3680  // ToType have the same unqualified type (since we checked
3681  // qualifiers above), then this is a qualification conversion.
3682  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3683 }
3684 
3685 /// - Determine whether this is a conversion from a scalar type to an
3686 /// atomic type.
3687 ///
3688 /// If successful, updates \c SCS's second and third steps in the conversion
3689 /// sequence to finish the conversion.
3690 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3691  bool InOverloadResolution,
3693  bool CStyle) {
3694  const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3695  if (!ToAtomic)
3696  return false;
3697 
3698  StandardConversionSequence InnerSCS;
3699  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3700  InOverloadResolution, InnerSCS,
3701  CStyle, /*AllowObjCWritebackConversion=*/false))
3702  return false;
3703 
3704  SCS.Second = InnerSCS.Second;
3705  SCS.setToType(1, InnerSCS.getToType(1));
3706  SCS.Third = InnerSCS.Third;
3709  SCS.setToType(2, InnerSCS.getToType(2));
3710  return true;
3711 }
3712 
3714  CXXConstructorDecl *Constructor,
3715  QualType Type) {
3716  const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3717  if (CtorType->getNumParams() > 0) {
3718  QualType FirstArg = CtorType->getParamType(0);
3719  if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3720  return true;
3721  }
3722  return false;
3723 }
3724 
3725 static OverloadingResult
3727  CXXRecordDecl *To,
3729  OverloadCandidateSet &CandidateSet,
3730  bool AllowExplicit) {
3732  for (auto *D : S.LookupConstructors(To)) {
3733  auto Info = getConstructorInfo(D);
3734  if (!Info)
3735  continue;
3736 
3737  bool Usable = !Info.Constructor->isInvalidDecl() &&
3738  S.isInitListConstructor(Info.Constructor);
3739  if (Usable) {
3740  bool SuppressUserConversions = false;
3741  if (Info.ConstructorTmpl)
3742  S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3743  /*ExplicitArgs*/ nullptr, From,
3744  CandidateSet, SuppressUserConversions,
3745  /*PartialOverloading*/ false,
3746  AllowExplicit);
3747  else
3748  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3749  CandidateSet, SuppressUserConversions,
3750  /*PartialOverloading*/ false, AllowExplicit);
3751  }
3752  }
3753 
3754  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3755 
3757  switch (auto Result =
3758  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3759  case OR_Deleted:
3760  case OR_Success: {
3761  // Record the standard conversion we used and the conversion function.
3762  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3763  QualType ThisType = Constructor->getFunctionObjectParameterType();
3764  // Initializer lists don't have conversions as such.
3766  User.HadMultipleCandidates = HadMultipleCandidates;
3767  User.ConversionFunction = Constructor;
3768  User.FoundConversionFunction = Best->FoundDecl;
3770  User.After.setFromType(ThisType);
3771  User.After.setAllToTypes(ToType);
3772  return Result;
3773  }
3774 
3775  case OR_No_Viable_Function:
3776  return OR_No_Viable_Function;
3777  case OR_Ambiguous:
3778  return OR_Ambiguous;
3779  }
3780 
3781  llvm_unreachable("Invalid OverloadResult!");
3782 }
3783 
3784 /// Determines whether there is a user-defined conversion sequence
3785 /// (C++ [over.ics.user]) that converts expression From to the type
3786 /// ToType. If such a conversion exists, User will contain the
3787 /// user-defined conversion sequence that performs such a conversion
3788 /// and this routine will return true. Otherwise, this routine returns
3789 /// false and User is unspecified.
3790 ///
3791 /// \param AllowExplicit true if the conversion should consider C++0x
3792 /// "explicit" conversion functions as well as non-explicit conversion
3793 /// functions (C++0x [class.conv.fct]p2).
3794 ///
3795 /// \param AllowObjCConversionOnExplicit true if the conversion should
3796 /// allow an extra Objective-C pointer conversion on uses of explicit
3797 /// constructors. Requires \c AllowExplicit to also be set.
3798 static OverloadingResult
3801  OverloadCandidateSet &CandidateSet,
3802  AllowedExplicit AllowExplicit,
3803  bool AllowObjCConversionOnExplicit) {
3804  assert(AllowExplicit != AllowedExplicit::None ||
3805  !AllowObjCConversionOnExplicit);
3807 
3808  // Whether we will only visit constructors.
3809  bool ConstructorsOnly = false;
3810 
3811  // If the type we are conversion to is a class type, enumerate its
3812  // constructors.
3813  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3814  // C++ [over.match.ctor]p1:
3815  // When objects of class type are direct-initialized (8.5), or
3816  // copy-initialized from an expression of the same or a
3817  // derived class type (8.5), overload resolution selects the
3818  // constructor. [...] For copy-initialization, the candidate
3819  // functions are all the converting constructors (12.3.1) of
3820  // that class. The argument list is the expression-list within
3821  // the parentheses of the initializer.
3822  if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3823  (From->getType()->getAs<RecordType>() &&
3824  S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3825  ConstructorsOnly = true;
3826 
3827  if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3828  // We're not going to find any constructors.
3829  } else if (CXXRecordDecl *ToRecordDecl
3830  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3831 
3832  Expr **Args = &From;
3833  unsigned NumArgs = 1;
3834  bool ListInitializing = false;
3835  if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3836  // But first, see if there is an init-list-constructor that will work.
3838  S, From, ToType, ToRecordDecl, User, CandidateSet,
3839  AllowExplicit == AllowedExplicit::All);
3840  if (Result != OR_No_Viable_Function)
3841  return Result;
3842  // Never mind.
3843  CandidateSet.clear(
3845 
3846  // If we're list-initializing, we pass the individual elements as
3847  // arguments, not the entire list.
3848  Args = InitList->getInits();
3849  NumArgs = InitList->getNumInits();
3850  ListInitializing = true;
3851  }
3852 
3853  for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3854  auto Info = getConstructorInfo(D);
3855  if (!Info)
3856  continue;
3857 
3858  bool Usable = !Info.Constructor->isInvalidDecl();
3859  if (!ListInitializing)
3860  Usable = Usable && Info.Constructor->isConvertingConstructor(
3861  /*AllowExplicit*/ true);
3862  if (Usable) {
3863  bool SuppressUserConversions = !ConstructorsOnly;
3864  // C++20 [over.best.ics.general]/4.5:
3865  // if the target is the first parameter of a constructor [of class
3866  // X] and the constructor [...] is a candidate by [...] the second
3867  // phase of [over.match.list] when the initializer list has exactly
3868  // one element that is itself an initializer list, [...] and the
3869  // conversion is to X or reference to cv X, user-defined conversion
3870  // sequences are not cnosidered.
3871  if (SuppressUserConversions && ListInitializing) {
3872  SuppressUserConversions =
3873  NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3874  isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3875  ToType);
3876  }
3877  if (Info.ConstructorTmpl)
3879  Info.ConstructorTmpl, Info.FoundDecl,
3880  /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3881  CandidateSet, SuppressUserConversions,
3882  /*PartialOverloading*/ false,
3883  AllowExplicit == AllowedExplicit::All);
3884  else
3885  // Allow one user-defined conversion when user specifies a
3886  // From->ToType conversion via an static cast (c-style, etc).
3887  S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3888  llvm::ArrayRef(Args, NumArgs), CandidateSet,
3889  SuppressUserConversions,
3890  /*PartialOverloading*/ false,
3891  AllowExplicit == AllowedExplicit::All);
3892  }
3893  }
3894  }
3895  }
3896 
3897  // Enumerate conversion functions, if we're allowed to.
3898  if (ConstructorsOnly || isa<InitListExpr>(From)) {
3899  } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3900  // No conversion functions from incomplete types.
3901  } else if (const RecordType *FromRecordType =
3902  From->getType()->getAs<RecordType>()) {
3903  if (CXXRecordDecl *FromRecordDecl
3904  = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3905  // Add all of the conversion functions as candidates.
3906  const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3907  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3908  DeclAccessPair FoundDecl = I.getPair();
3909  NamedDecl *D = FoundDecl.getDecl();
3910  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3911  if (isa<UsingShadowDecl>(D))
3912  D = cast<UsingShadowDecl>(D)->getTargetDecl();
3913 
3914  CXXConversionDecl *Conv;
3915  FunctionTemplateDecl *ConvTemplate;
3916  if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3917  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3918  else
3919  Conv = cast<CXXConversionDecl>(D);
3920 
3921  if (ConvTemplate)
3923  ConvTemplate, FoundDecl, ActingContext, From, ToType,
3924  CandidateSet, AllowObjCConversionOnExplicit,
3925  AllowExplicit != AllowedExplicit::None);
3926  else
3927  S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3928  CandidateSet, AllowObjCConversionOnExplicit,
3929  AllowExplicit != AllowedExplicit::None);
3930  }
3931  }
3932  }
3933 
3934  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3935 
3937  switch (auto Result =
3938  CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3939  case OR_Success:
3940  case OR_Deleted:
3941  // Record the standard conversion we used and the conversion function.
3942  if (CXXConstructorDecl *Constructor
3943  = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3944  // C++ [over.ics.user]p1:
3945  // If the user-defined conversion is specified by a
3946  // constructor (12.3.1), the initial standard conversion
3947  // sequence converts the source type to the type required by
3948  // the argument of the constructor.
3949  //
3950  if (isa<InitListExpr>(From)) {
3951  // Initializer lists don't have conversions as such.
3953  } else {
3954  if (Best->Conversions[0].isEllipsis())
3955  User.EllipsisConversion = true;
3956  else {
3957  User.Before = Best->Conversions[0].Standard;
3958  User.EllipsisConversion = false;
3959  }
3960  }
3961  User.HadMultipleCandidates = HadMultipleCandidates;
3962  User.ConversionFunction = Constructor;
3963  User.FoundConversionFunction = Best->FoundDecl;
3965  User.After.setFromType(Constructor->getFunctionObjectParameterType());
3966  User.After.setAllToTypes(ToType);
3967  return Result;
3968  }
3969  if (CXXConversionDecl *Conversion
3970  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3971  // C++ [over.ics.user]p1:
3972  //
3973  // [...] If the user-defined conversion is specified by a
3974  // conversion function (12.3.2), the initial standard
3975  // conversion sequence converts the source type to the
3976  // implicit object parameter of the conversion function.
3977  User.Before = Best->Conversions[0].Standard;
3978  User.HadMultipleCandidates = HadMultipleCandidates;
3979  User.ConversionFunction = Conversion;
3980  User.FoundConversionFunction = Best->FoundDecl;
3981  User.EllipsisConversion = false;
3982 
3983  // C++ [over.ics.user]p2:
3984  // The second standard conversion sequence converts the
3985  // result of the user-defined conversion to the target type
3986  // for the sequence. Since an implicit conversion sequence
3987  // is an initialization, the special rules for
3988  // initialization by user-defined conversion apply when
3989  // selecting the best user-defined conversion for a
3990  // user-defined conversion sequence (see 13.3.3 and
3991  // 13.3.3.1).
3992  User.After = Best->FinalConversion;
3993  return Result;
3994  }
3995  llvm_unreachable("Not a constructor or conversion function?");
3996 
3997  case OR_No_Viable_Function:
3998  return OR_No_Viable_Function;
3999 
4000  case OR_Ambiguous:
4001  return OR_Ambiguous;
4002  }
4003 
4004  llvm_unreachable("Invalid OverloadResult!");
4005 }
4006 
4007 bool
4010  OverloadCandidateSet CandidateSet(From->getExprLoc(),
4012  OverloadingResult OvResult =
4013  IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4014  CandidateSet, AllowedExplicit::None, false);
4015 
4016  if (!(OvResult == OR_Ambiguous ||
4017  (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4018  return false;
4019 
4020  auto Cands = CandidateSet.CompleteCandidates(
4021  *this,
4023  From);
4024  if (OvResult == OR_Ambiguous)
4025  Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4026  << From->getType() << ToType << From->getSourceRange();
4027  else { // OR_No_Viable_Function && !CandidateSet.empty()
4028  if (!RequireCompleteType(From->getBeginLoc(), ToType,
4029  diag::err_typecheck_nonviable_condition_incomplete,
4030  From->getType(), From->getSourceRange()))
4031  Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4032  << false << From->getType() << From->getSourceRange() << ToType;
4033  }
4034 
4035  CandidateSet.NoteCandidates(
4036  *this, From, Cands);
4037  return true;
4038 }
4039 
4040 // Helper for compareConversionFunctions that gets the FunctionType that the
4041 // conversion-operator return value 'points' to, or nullptr.
4042 static const FunctionType *
4044  const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4045  const PointerType *RetPtrTy =
4046  ConvFuncTy->getReturnType()->getAs<PointerType>();
4047 
4048  if (!RetPtrTy)
4049  return nullptr;
4050 
4051  return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4052 }
4053 
4054 /// Compare the user-defined conversion functions or constructors
4055 /// of two user-defined conversion sequences to determine whether any ordering
4056 /// is possible.
4059  FunctionDecl *Function2) {
4060  CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4061  CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4062  if (!Conv1 || !Conv2)
4064 
4065  if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4067 
4068  // Objective-C++:
4069  // If both conversion functions are implicitly-declared conversions from
4070  // a lambda closure type to a function pointer and a block pointer,
4071  // respectively, always prefer the conversion to a function pointer,
4072  // because the function pointer is more lightweight and is more likely
4073  // to keep code working.
4074  if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4075  bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4076  bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4077  if (Block1 != Block2)
4078  return Block1 ? ImplicitConversionSequence::Worse
4080  }
4081 
4082  // In order to support multiple calling conventions for the lambda conversion
4083  // operator (such as when the free and member function calling convention is
4084  // different), prefer the 'free' mechanism, followed by the calling-convention
4085  // of operator(). The latter is in place to support the MSVC-like solution of
4086  // defining ALL of the possible conversions in regards to calling-convention.
4087  const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4088  const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4089 
4090  if (Conv1FuncRet && Conv2FuncRet &&
4091  Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4092  CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4093  CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4094 
4095  CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4096  const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4097 
4098  CallingConv CallOpCC =
4099  CallOp->getType()->castAs<FunctionType>()->getCallConv();
4101  CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4103  CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4104 
4105  CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4106  for (CallingConv CC : PrefOrder) {
4107  if (Conv1CC == CC)
4109  if (Conv2CC == CC)
4111  }
4112  }
4113 
4115 }
4116 
4118  const ImplicitConversionSequence &ICS) {
4119  return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4120  (ICS.isUserDefined() &&
4122 }
4123 
4124 /// CompareImplicitConversionSequences - Compare two implicit
4125 /// conversion sequences to determine whether one is better than the
4126 /// other or if they are indistinguishable (C++ 13.3.3.2).
4129  const ImplicitConversionSequence& ICS1,
4130  const ImplicitConversionSequence& ICS2)
4131 {
4132  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4133  // conversion sequences (as defined in 13.3.3.1)
4134  // -- a standard conversion sequence (13.3.3.1.1) is a better
4135  // conversion sequence than a user-defined conversion sequence or
4136  // an ellipsis conversion sequence, and
4137  // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4138  // conversion sequence than an ellipsis conversion sequence
4139  // (13.3.3.1.3).
4140  //
4141  // C++0x [over.best.ics]p10:
4142  // For the purpose of ranking implicit conversion sequences as
4143  // described in 13.3.3.2, the ambiguous conversion sequence is
4144  // treated as a user-defined sequence that is indistinguishable
4145  // from any other user-defined conversion sequence.
4146 
4147  // String literal to 'char *' conversion has been deprecated in C++03. It has
4148  // been removed from C++11. We still accept this conversion, if it happens at
4149  // the best viable function. Otherwise, this conversion is considered worse
4150  // than ellipsis conversion. Consider this as an extension; this is not in the
4151  // standard. For example:
4152  //
4153  // int &f(...); // #1
4154  // void f(char*); // #2
4155  // void g() { int &r = f("foo"); }
4156  //
4157  // In C++03, we pick #2 as the best viable function.
4158  // In C++11, we pick #1 as the best viable function, because ellipsis
4159  // conversion is better than string-literal to char* conversion (since there
4160  // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4161  // convert arguments, #2 would be the best viable function in C++11.
4162  // If the best viable function has this conversion, a warning will be issued
4163  // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4164 
4165  if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4168  // Ill-formedness must not differ
4169  ICS1.isBad() == ICS2.isBad())
4173 
4174  if (ICS1.getKindRank() < ICS2.getKindRank())
4176  if (ICS2.getKindRank() < ICS1.getKindRank())
4178 
4179  // The following checks require both conversion sequences to be of
4180  // the same kind.
4181  if (ICS1.getKind() != ICS2.getKind())
4183 
4186 
4187  // Two implicit conversion sequences of the same form are
4188  // indistinguishable conversion sequences unless one of the
4189  // following rules apply: (C++ 13.3.3.2p3):
4190 
4191  // List-initialization sequence L1 is a better conversion sequence than
4192  // list-initialization sequence L2 if:
4193  // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4194  // if not that,
4195  // — L1 and L2 convert to arrays of the same element type, and either the
4196  // number of elements n_1 initialized by L1 is less than the number of
4197  // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4198  // an array of unknown bound and L1 does not,
4199  // even if one of the other rules in this paragraph would otherwise apply.
4200  if (!ICS1.isBad()) {
4201  bool StdInit1 = false, StdInit2 = false;
4204  nullptr);
4207  nullptr);
4208  if (StdInit1 != StdInit2)
4209  return StdInit1 ? ImplicitConversionSequence::Better
4211 
4212  if (ICS1.hasInitializerListContainerType() &&
4214  if (auto *CAT1 = S.Context.getAsConstantArrayType(
4216  if (auto *CAT2 = S.Context.getAsConstantArrayType(
4218  if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4219  CAT2->getElementType())) {
4220  // Both to arrays of the same element type
4221  if (CAT1->getSize() != CAT2->getSize())
4222  // Different sized, the smaller wins
4223  return CAT1->getSize().ult(CAT2->getSize())
4228  // One is incomplete, it loses
4232  }
4233  }
4234  }
4235 
4236  if (ICS1.isStandard())
4237  // Standard conversion sequence S1 is a better conversion sequence than
4238  // standard conversion sequence S2 if [...]
4240  ICS1.Standard, ICS2.Standard);
4241  else if (ICS1.isUserDefined()) {
4242  // User-defined conversion sequence U1 is a better conversion
4243  // sequence than another user-defined conversion sequence U2 if
4244  // they contain the same user-defined conversion function or
4245  // constructor and if the second standard conversion sequence of
4246  // U1 is better than the second standard conversion sequence of
4247  // U2 (C++ 13.3.3.2p3).
4248  if (ICS1.UserDefined.ConversionFunction ==
4251  ICS1.UserDefined.After,
4252  ICS2.UserDefined.After);
4253  else
4254  Result = compareConversionFunctions(S,
4257  }
4258 
4259  return Result;
4260 }
4261 
4262 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4263 // determine if one is a proper subset of the other.
4266  const StandardConversionSequence& SCS1,
4267  const StandardConversionSequence& SCS2) {
4270 
4271  // the identity conversion sequence is considered to be a subsequence of
4272  // any non-identity conversion sequence
4273  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4275  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4277 
4278  if (SCS1.Second != SCS2.Second) {
4279  if (SCS1.Second == ICK_Identity)
4281  else if (SCS2.Second == ICK_Identity)
4283  else
4285  } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4287 
4288  if (SCS1.Third == SCS2.Third) {
4289  return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4291  }
4292 
4293  if (SCS1.Third == ICK_Identity)
4294  return Result == ImplicitConversionSequence::Worse
4297 
4298  if (SCS2.Third == ICK_Identity)
4299  return Result == ImplicitConversionSequence::Better
4302 
4304 }
4305 
4306 /// Determine whether one of the given reference bindings is better
4307 /// than the other based on what kind of bindings they are.
4308 static bool
4310  const StandardConversionSequence &SCS2) {
4311  // C++0x [over.ics.rank]p3b4:
4312  // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4313  // implicit object parameter of a non-static member function declared
4314  // without a ref-qualifier, and *either* S1 binds an rvalue reference
4315  // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4316  // lvalue reference to a function lvalue and S2 binds an rvalue
4317  // reference*.
4318  //
4319  // FIXME: Rvalue references. We're going rogue with the above edits,
4320  // because the semantics in the current C++0x working paper (N3225 at the
4321  // time of this writing) break the standard definition of std::forward
4322  // and std::reference_wrapper when dealing with references to functions.
4323  // Proposed wording changes submitted to CWG for consideration.
4326  return false;
4327 
4328  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4329  SCS2.IsLvalueReference) ||
4330  (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4332 }
4333 
4335  None,
4338 };
4339 
4340 /// Returns kind of fixed enum promotion the \a SCS uses.
4341 static FixedEnumPromotion
4343 
4344  if (SCS.Second != ICK_Integral_Promotion)
4345  return FixedEnumPromotion::None;
4346 
4347  QualType FromType = SCS.getFromType();
4348  if (!FromType->isEnumeralType())
4349  return FixedEnumPromotion::None;
4350 
4351  EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4352  if (!Enum->isFixed())
4353  return FixedEnumPromotion::None;
4354 
4355  QualType UnderlyingType = Enum->getIntegerType();
4356  if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4358 
4360 }
4361 
4364  assert(LHS->isVectorType() == RHS->isVectorType() &&
4365  "Either both elements should be vectors or neither should.");
4366  if (const auto *VT = LHS->getAs<VectorType>())
4367  LHS = VT->getElementType();
4368 
4369  if (const auto *VT = RHS->getAs<VectorType>())
4370  RHS = VT->getElementType();
4371 
4372  const auto L = LHS->getAs<BuiltinType>()->getKind();
4373  const auto R = RHS->getAs<BuiltinType>()->getKind();
4374  if (L == R)
4376  return L < R ? ImplicitConversionSequence::Better
4378 }
4379 
4380 /// CompareStandardConversionSequences - Compare two standard
4381 /// conversion sequences to determine whether one is better than the
4382 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4385  const StandardConversionSequence& SCS1,
4386  const StandardConversionSequence& SCS2)
4387 {
4388  // Standard conversion sequence S1 is a better conversion sequence
4389  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4390 
4391  // -- S1 is a proper subsequence of S2 (comparing the conversion
4392  // sequences in the canonical form defined by 13.3.3.1.1,
4393  // excluding any Lvalue Transformation; the identity conversion
4394  // sequence is considered to be a subsequence of any
4395  // non-identity conversion sequence) or, if not that,
4397  = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4398  return CK;
4399 
4400  // -- the rank of S1 is better than the rank of S2 (by the rules
4401  // defined below), or, if not that,
4402  ImplicitConversionRank Rank1 = SCS1.getRank();
4403  ImplicitConversionRank Rank2 = SCS2.getRank();
4404  if (Rank1 < Rank2)
4406  else if (Rank2 < Rank1)
4408 
4409  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4410  // are indistinguishable unless one of the following rules
4411  // applies:
4412 
4413  // A conversion that is not a conversion of a pointer, or
4414  // pointer to member, to bool is better than another conversion
4415  // that is such a conversion.
4417  return SCS2.isPointerConversionToBool()
4420 
4421  // C++14 [over.ics.rank]p4b2:
4422  // This is retroactively applied to C++11 by CWG 1601.
4423  //
4424  // A conversion that promotes an enumeration whose underlying type is fixed
4425  // to its underlying type is better than one that promotes to the promoted
4426  // underlying type, if the two are different.
4427  FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4428  FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4429  if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4430  FEP1 != FEP2)
4434 
4435  // C++ [over.ics.rank]p4b2:
4436  //
4437  // If class B is derived directly or indirectly from class A,
4438  // conversion of B* to A* is better than conversion of B* to
4439  // void*, and conversion of A* to void* is better than conversion
4440  // of B* to void*.
4441  bool SCS1ConvertsToVoid
4443  bool SCS2ConvertsToVoid
4445  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4446  // Exactly one of the conversion sequences is a conversion to
4447  // a void pointer; it's the worse conversion.
4448  return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4450  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4451  // Neither conversion sequence converts to a void pointer; compare
4452  // their derived-to-base conversions.
4454  = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4455  return DerivedCK;
4456  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4457  !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4458  // Both conversion sequences are conversions to void
4459  // pointers. Compare the source types to determine if there's an
4460  // inheritance relationship in their sources.
4461  QualType FromType1 = SCS1.getFromType();
4462  QualType FromType2 = SCS2.getFromType();
4463 
4464  // Adjust the types we're converting from via the array-to-pointer
4465  // conversion, if we need to.
4466  if (SCS1.First == ICK_Array_To_Pointer)
4467  FromType1 = S.Context.getArrayDecayedType(FromType1);
4468  if (SCS2.First == ICK_Array_To_Pointer)
4469  FromType2 = S.Context.getArrayDecayedType(FromType2);
4470 
4471  QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4472  QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4473 
4474  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4476  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4478 
4479  // Objective-C++: If one interface is more specific than the
4480  // other, it is the better one.
4481  const ObjCObjectPointerType* FromObjCPtr1
4482  = FromType1->getAs<ObjCObjectPointerType>();
4483  const ObjCObjectPointerType* FromObjCPtr2
4484  = FromType2->getAs<ObjCObjectPointerType>();
4485  if (FromObjCPtr1 && FromObjCPtr2) {
4486  bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4487  FromObjCPtr2);
4488  bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4489  FromObjCPtr1);
4490  if (AssignLeft != AssignRight) {
4491  return AssignLeft? ImplicitConversionSequence::Better
4493  }
4494  }
4495  }
4496 
4497  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4498  // Check for a better reference binding based on the kind of bindings.
4499  if (isBetterReferenceBindingKind(SCS1, SCS2))
4501  else if (isBetterReferenceBindingKind(SCS2, SCS1))
4503  }
4504 
4505  // Compare based on qualification conversions (C++ 13.3.3.2p3,
4506  // bullet 3).
4508  = CompareQualificationConversions(S, SCS1, SCS2))
4509  return QualCK;
4510 
4511  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512  // C++ [over.ics.rank]p3b4:
4513  // -- S1 and S2 are reference bindings (8.5.3), and the types to
4514  // which the references refer are the same type except for
4515  // top-level cv-qualifiers, and the type to which the reference
4516  // initialized by S2 refers is more cv-qualified than the type
4517  // to which the reference initialized by S1 refers.
4518  QualType T1 = SCS1.getToType(2);
4519  QualType T2 = SCS2.getToType(2);
4520  T1 = S.Context.getCanonicalType(T1);
4521  T2 = S.Context.getCanonicalType(T2);
4522  Qualifiers T1Quals, T2Quals;
4523  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4524  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4525  if (UnqualT1 == UnqualT2) {
4526  // Objective-C++ ARC: If the references refer to objects with different
4527  // lifetimes, prefer bindings that don't change lifetime.
4528  if (SCS1.ObjCLifetimeConversionBinding !=
4530  return SCS1.ObjCLifetimeConversionBinding
4533  }
4534 
4535  // If the type is an array type, promote the element qualifiers to the
4536  // type for comparison.
4537  if (isa<ArrayType>(T1) && T1Quals)
4538  T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4539  if (isa<ArrayType>(T2) && T2Quals)
4540  T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4541  if (T2.isMoreQualifiedThan(T1))
4543  if (T1.isMoreQualifiedThan(T2))
4545  }
4546  }
4547 
4548  // In Microsoft mode (below 19.28), prefer an integral conversion to a
4549  // floating-to-integral conversion if the integral conversion
4550  // is between types of the same size.
4551  // For example:
4552  // void f(float);
4553  // void f(int);
4554  // int main {
4555  // long a;
4556  // f(a);
4557  // }
4558  // Here, MSVC will call f(int) instead of generating a compile error
4559  // as clang will do in standard mode.
4560  if (S.getLangOpts().MSVCCompat &&
4562  SCS1.Second == ICK_Integral_Conversion &&
4563  SCS2.Second == ICK_Floating_Integral &&
4564  S.Context.getTypeSize(SCS1.getFromType()) ==
4565  S.Context.getTypeSize(SCS1.getToType(2)))
4567 
4568  // Prefer a compatible vector conversion over a lax vector conversion
4569  // For example:
4570  //
4571  // typedef float __v4sf __attribute__((__vector_size__(16)));
4572  // void f(vector float);
4573  // void f(vector signed int);
4574  // int main() {
4575  // __v4sf a;
4576  // f(a);
4577  // }
4578  // Here, we'd like to choose f(vector float) and not
4579  // report an ambiguous call error
4580  if (SCS1.Second == ICK_Vector_Conversion &&
4581  SCS2.Second == ICK_Vector_Conversion) {
4582  bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4583  SCS1.getFromType(), SCS1.getToType(2));
4584  bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4585  SCS2.getFromType(), SCS2.getToType(2));
4586 
4587  if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4588  return SCS1IsCompatibleVectorConversion
4591  }
4592 
4593  if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4595  bool SCS1IsCompatibleSVEVectorConversion =
4597  bool SCS2IsCompatibleSVEVectorConversion =
4599 
4600  if (SCS1IsCompatibleSVEVectorConversion !=
4601  SCS2IsCompatibleSVEVectorConversion)
4602  return SCS1IsCompatibleSVEVectorConversion
4605  }
4606 
4607  if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4609  bool SCS1IsCompatibleRVVVectorConversion =
4611  bool SCS2IsCompatibleRVVVectorConversion =
4613 
4614  if (SCS1IsCompatibleRVVVectorConversion !=
4615  SCS2IsCompatibleRVVVectorConversion)
4616  return SCS1IsCompatibleRVVVectorConversion
4619  }
4620 
4621  if (S.getLangOpts().HLSL) {
4622  // On a promotion we prefer the lower rank to disambiguate.
4623  if ((SCS1.Second == ICK_Floating_Promotion &&
4624  SCS2.Second == ICK_Floating_Promotion) ||
4625  (SCS1.Element == ICK_Floating_Promotion &&
4627  return HLSLCompareFloatingRank(SCS1.getToType(2), SCS2.getToType(2));
4628  // On a conversion we prefer the higher rank to disambiguate.
4629  if ((SCS1.Second == ICK_Floating_Conversion &&
4630  SCS2.Second == ICK_Floating_Conversion) ||
4631  (SCS1.Element == ICK_Floating_Conversion &&
4633  return HLSLCompareFloatingRank(SCS2.getToType(2), SCS1.getToType(2));
4634  }
4635 
4637 }
4638 
4639 /// CompareQualificationConversions - Compares two standard conversion
4640 /// sequences to determine whether they can be ranked based on their
4641 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4644  const StandardConversionSequence& SCS1,
4645  const StandardConversionSequence& SCS2) {
4646  // C++ [over.ics.rank]p3:
4647  // -- S1 and S2 differ only in their qualification conversion and
4648  // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4649  // [C++98]
4650  // [...] and the cv-qualification signature of type T1 is a proper subset
4651  // of the cv-qualification signature of type T2, and S1 is not the
4652  // deprecated string literal array-to-pointer conversion (4.2).
4653  // [C++2a]
4654  // [...] where T1 can be converted to T2 by a qualification conversion.
4655  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4656  SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4658 
4659  // FIXME: the example in the standard doesn't use a qualification
4660  // conversion (!)
4661  QualType T1 = SCS1.getToType(2);
4662  QualType T2 = SCS2.getToType(2);
4663  T1 = S.Context.getCanonicalType(T1);
4664  T2 = S.Context.getCanonicalType(T2);
4665  assert(!T1->isReferenceType() && !T2->isReferenceType());
4666  Qualifiers T1Quals, T2Quals;
4667  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4668  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4669 
4670  // If the types are the same, we won't learn anything by unwrapping
4671  // them.
4672  if (UnqualT1 == UnqualT2)
4674 
4675  // Don't ever prefer a standard conversion sequence that uses the deprecated
4676  // string literal array to pointer conversion.
4677  bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4678  bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4679 
4680  // Objective-C++ ARC:
4681  // Prefer qualification conversions not involving a change in lifetime
4682  // to qualification conversions that do change lifetime.
4685  CanPick1 = false;
4688  CanPick2 = false;
4689 
4690  bool ObjCLifetimeConversion;
4691  if (CanPick1 &&
4692  !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4693  CanPick1 = false;
4694  // FIXME: In Objective-C ARC, we can have qualification conversions in both
4695  // directions, so we can't short-cut this second check in general.
4696  if (CanPick2 &&
4697  !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4698  CanPick2 = false;
4699 
4700  if (CanPick1 != CanPick2)
4701  return CanPick1 ? ImplicitConversionSequence::Better
4704 }
4705 
4706 /// CompareDerivedToBaseConversions - Compares two standard conversion
4707 /// sequences to determine whether they can be ranked based on their
4708 /// various kinds of derived-to-base conversions (C++
4709 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4710 /// conversions between Objective-C interface types.
4713  const StandardConversionSequence& SCS1,
4714  const StandardConversionSequence& SCS2) {
4715  QualType FromType1 = SCS1.getFromType();
4716  QualType ToType1 = SCS1.getToType(1);
4717  QualType FromType2 = SCS2.getFromType();
4718  QualType ToType2 = SCS2.getToType(1);
4719 
4720  // Adjust the types we're converting from via the array-to-pointer
4721  // conversion, if we need to.
4722  if (SCS1.First == ICK_Array_To_Pointer)
4723  FromType1 = S.Context.getArrayDecayedType(FromType1);
4724  if (SCS2.First == ICK_Array_To_Pointer)
4725  FromType2 = S.Context.getArrayDecayedType(FromType2);
4726 
4727  // Canonicalize all of the types.
4728  FromType1 = S.Context.getCanonicalType(FromType1);
4729  ToType1 = S.Context.getCanonicalType(ToType1);
4730  FromType2 = S.Context.getCanonicalType(FromType2);
4731  ToType2 = S.Context.getCanonicalType(ToType2);
4732 
4733  // C++ [over.ics.rank]p4b3:
4734  //
4735  // If class B is derived directly or indirectly from class A and
4736  // class C is derived directly or indirectly from B,
4737  //
4738  // Compare based on pointer conversions.
4739  if (SCS1.Second == ICK_Pointer_Conversion &&
4740  SCS2.Second == ICK_Pointer_Conversion &&
4741  /*FIXME: Remove if Objective-C id conversions get their own rank*/
4742  FromType1->isPointerType() && FromType2->isPointerType() &&
4743  ToType1->isPointerType() && ToType2->isPointerType()) {
4744  QualType FromPointee1 =
4745  FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4746  QualType ToPointee1 =
4747  ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4748  QualType FromPointee2 =
4749  FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4750  QualType ToPointee2 =
4751  ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4752 
4753  // -- conversion of C* to B* is better than conversion of C* to A*,
4754  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4755  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4757  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4759  }
4760 
4761  // -- conversion of B* to A* is better than conversion of C* to A*,
4762  if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4763  if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4765  else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4767  }
4768  } else if (SCS1.Second == ICK_Pointer_Conversion &&
4769  SCS2.Second == ICK_Pointer_Conversion) {
4770  const ObjCObjectPointerType *FromPtr1
4771  = FromType1->getAs<ObjCObjectPointerType>();
4772  const ObjCObjectPointerType *FromPtr2
4773  = FromType2->getAs<ObjCObjectPointerType>();
4774  const ObjCObjectPointerType *ToPtr1
4775  = ToType1->getAs<ObjCObjectPointerType>();
4776  const ObjCObjectPointerType *ToPtr2
4777  = ToType2->getAs<ObjCObjectPointerType>();
4778 
4779  if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4780  // Apply the same conversion ranking rules for Objective-C pointer types
4781  // that we do for C++ pointers to class types. However, we employ the
4782  // Objective-C pseudo-subtyping relationship used for assignment of
4783  // Objective-C pointer types.
4784  bool FromAssignLeft
4785  = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4786  bool FromAssignRight
4787  = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4788  bool ToAssignLeft
4789  = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4790  bool ToAssignRight
4791  = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4792 
4793  // A conversion to an a non-id object pointer type or qualified 'id'
4794  // type is better than a conversion to 'id'.
4795  if (ToPtr1->isObjCIdType() &&
4796  (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4798  if (ToPtr2->isObjCIdType() &&
4799  (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4801 
4802  // A conversion to a non-id object pointer type is better than a
4803  // conversion to a qualified 'id' type
4804  if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4806  if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4808 
4809  // A conversion to an a non-Class object pointer type or qualified 'Class'
4810  // type is better than a conversion to 'Class'.
4811  if (ToPtr1->isObjCClassType() &&
4812  (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4814  if (ToPtr2->isObjCClassType() &&
4815  (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4817 
4818  // A conversion to a non-Class object pointer type is better than a
4819  // conversion to a qualified 'Class' type.
4820  if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4822  if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4824 
4825  // -- "conversion of C* to B* is better than conversion of C* to A*,"
4826  if (S.Context.hasSameType(FromType1, FromType2) &&
4827  !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4828  (ToAssignLeft != ToAssignRight)) {
4829  if (FromPtr1->isSpecialized()) {
4830  // "conversion of B<A> * to B * is better than conversion of B * to
4831  // C *.
4832  bool IsFirstSame =
4833  FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4834  bool IsSecondSame =
4835  FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4836  if (IsFirstSame) {
4837  if (!IsSecondSame)
4839  } else if (IsSecondSame)
4841  }
4842  return ToAssignLeft? ImplicitConversionSequence::Worse
4844  }
4845 
4846  // -- "conversion of B* to A* is better than conversion of C* to A*,"
4847  if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4848  (FromAssignLeft != FromAssignRight))
4849  return FromAssignLeft? ImplicitConversionSequence::Better
4851  }
4852  }
4853 
4854  // Ranking of member-pointer types.
4855  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4856  FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4857  ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4858  const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4859  const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4860  const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4861  const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4862  const Type *FromPointeeType1 = FromMemPointer1->getClass();
4863  const Type *ToPointeeType1 = ToMemPointer1->getClass();
4864  const Type *FromPointeeType2 = FromMemPointer2->getClass();
4865  const Type *ToPointeeType2 = ToMemPointer2->getClass();
4866  QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4867  QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4868  QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4869  QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4870  // conversion of A::* to B::* is better than conversion of A::* to C::*,
4871  if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4872  if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4874  else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4876  }
4877  // conversion of B::* to C::* is better than conversion of A::* to C::*
4878  if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4879  if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4881  else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4883  }
4884  }
4885 
4886  if (SCS1.Second == ICK_Derived_To_Base) {
4887  // -- conversion of C to B is better than conversion of C to A,
4888  // -- binding of an expression of type C to a reference of type
4889  // B& is better than binding an expression of type C to a
4890  // reference of type A&,
4891  if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4892  !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4893  if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4895  else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4897  }
4898 
4899  // -- conversion of B to A is better than conversion of C to A.
4900  // -- binding of an expression of type B to a reference of type
4901  // A& is better than binding an expression of type C to a
4902  // reference of type A&,
4903  if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4904  S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4905  if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4907  else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4909  }
4910  }
4911 
4913 }
4914 
4916  if (!T.getQualifiers().hasUnaligned())
4917  return T;
4918 
4919  Qualifiers Q;
4920  T = Ctx.getUnqualifiedArrayType(T, Q);
4921  Q.removeUnaligned();
4922  return Ctx.getQualifiedType(T, Q);
4923 }
4924 
4925 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4926 /// determine whether they are reference-compatible,
4927 /// reference-related, or incompatible, for use in C++ initialization by
4928 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4929 /// type, and the first type (T1) is the pointee type of the reference
4930 /// type being initialized.
4933  QualType OrigT1, QualType OrigT2,
4934  ReferenceConversions *ConvOut) {
4935  assert(!OrigT1->isReferenceType() &&
4936  "T1 must be the pointee type of the reference type");
4937  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4938 
4939  QualType T1 = Context.getCanonicalType(OrigT1);
4940  QualType T2 = Context.getCanonicalType(OrigT2);
4941  Qualifiers T1Quals, T2Quals;
4942  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4943  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4944 
4945  ReferenceConversions ConvTmp;
4946  ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4947  Conv = ReferenceConversions();
4948 
4949  // C++2a [dcl.init.ref]p4:
4950  // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4951  // reference-related to "cv2 T2" if T1 is similar to T2, or
4952  // T1 is a base class of T2.
4953  // "cv1 T1" is reference-compatible with "cv2 T2" if
4954  // a prvalue of type "pointer to cv2 T2" can be converted to the type
4955  // "pointer to cv1 T1" via a standard conversion sequence.
4956 
4957  // Check for standard conversions we can apply to pointers: derived-to-base
4958  // conversions, ObjC pointer conversions, and function pointer conversions.
4959  // (Qualification conversions are checked last.)
4960  QualType ConvertedT2;
4961  if (UnqualT1 == UnqualT2) {
4962  // Nothing to do.
4963  } else if (isCompleteType(Loc, OrigT2) &&
4964  IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4965  Conv |= ReferenceConversions::DerivedToBase;
4966  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4967  UnqualT2->isObjCObjectOrInterfaceType() &&
4968  Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4970  else if (UnqualT2->isFunctionType() &&
4971  IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4972  Conv |= ReferenceConversions::Function;
4973  // No need to check qualifiers; function types don't have them.
4974  return Ref_Compatible;
4975  }
4976  bool ConvertedReferent = Conv != 0;
4977 
4978  // We can have a qualification conversion. Compute whether the types are
4979  // similar at the same time.
4980  bool PreviousToQualsIncludeConst = true;
4981  bool TopLevel = true;
4982  do {
4983  if (T1 == T2)
4984  break;
4985 
4986  // We will need a qualification conversion.
4987  Conv |= ReferenceConversions::Qualification;
4988 
4989  // Track whether we performed a qualification conversion anywhere other
4990  // than the top level. This matters for ranking reference bindings in
4991  // overload resolution.
4992  if (!TopLevel)
4993  Conv |= ReferenceConversions::NestedQualification;
4994 
4995  // MS compiler ignores __unaligned qualifier for references; do the same.
4996  T1 = withoutUnaligned(Context, T1);
4997  T2 = withoutUnaligned(Context, T2);
4998 
4999  // If we find a qualifier mismatch, the types are not reference-compatible,
5000  // but are still be reference-related if they're similar.
5001  bool ObjCLifetimeConversion = false;
5002  if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5003  PreviousToQualsIncludeConst,
5004  ObjCLifetimeConversion))
5005  return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5006  ? Ref_Related
5007  : Ref_Incompatible;
5008 
5009  // FIXME: Should we track this for any level other than the first?
5010  if (ObjCLifetimeConversion)
5011  Conv |= ReferenceConversions::ObjCLifetime;
5012 
5013  TopLevel = false;
5014  } while (Context.UnwrapSimilarTypes(T1, T2));
5015 
5016  // At this point, if the types are reference-related, we must either have the
5017  // same inner type (ignoring qualifiers), or must have already worked out how
5018  // to convert the referent.
5019  return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5020  ? Ref_Compatible
5021  : Ref_Incompatible;
5022 }
5023 
5024 /// Look for a user-defined conversion to a value reference-compatible
5025 /// with DeclType. Return true if something definite is found.
5026 static bool
5028  QualType DeclType, SourceLocation DeclLoc,
5029  Expr *Init, QualType T2, bool AllowRvalues,
5030  bool AllowExplicit) {
5031  assert(T2->isRecordType() && "Can only find conversions of record types.");
5032  auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5033 
5034  OverloadCandidateSet CandidateSet(
5036  const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5037  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5038  NamedDecl *D = *I;
5039  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5040  if (isa<UsingShadowDecl>(D))
5041  D = cast<UsingShadowDecl>(D)->getTargetDecl();
5042 
5043  FunctionTemplateDecl *ConvTemplate
5044  = dyn_cast<FunctionTemplateDecl>(D);
5045  CXXConversionDecl *Conv;
5046  if (ConvTemplate)
5047  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5048  else
5049  Conv = cast<CXXConversionDecl>(D);
5050 
5051  if (AllowRvalues) {
5052  // If we are initializing an rvalue reference, don't permit conversion
5053  // functions that return lvalues.
5054  if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5055  const ReferenceType *RefType
5057  if (RefType && !RefType->getPointeeType()->isFunctionType())
5058  continue;
5059  }
5060 
5061  if (!ConvTemplate &&
5063  DeclLoc,
5064  Conv->getConversionType()
5066  .getUnqualifiedType(),
5067  DeclType.getNonReferenceType().getUnqualifiedType()) ==
5069  continue;
5070  } else {
5071  // If the conversion function doesn't return a reference type,
5072  // it can't be considered for this conversion. An rvalue reference
5073  // is only acceptable if its referencee is a function type.
5074 
5075  const ReferenceType *RefType =
5077  if (!RefType ||
5078  (!RefType->isLValueReferenceType() &&
5079  !RefType->getPointeeType()->isFunctionType()))
5080  continue;
5081  }
5082 
5083  if (ConvTemplate)
5085  ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5086  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5087  else
5089  Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5090  /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5091  }
5092 
5093  bool HadMultipleCandidates = (CandidateSet.size() > 1);
5094 
5096  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5097  case OR_Success:
5098  // C++ [over.ics.ref]p1:
5099  //
5100  // [...] If the parameter binds directly to the result of
5101  // applying a conversion function to the argument
5102  // expression, the implicit conversion sequence is a
5103  // user-defined conversion sequence (13.3.3.1.2), with the
5104  // second standard conversion sequence either an identity
5105  // conversion or, if the conversion function returns an
5106  // entity of a type that is a derived class of the parameter
5107  // type, a derived-to-base Conversion.
5108  if (!Best->FinalConversion.DirectBinding)
5109  return false;
5110 
5111  ICS.setUserDefined();
5112  ICS.UserDefined.Before = Best->Conversions[0].Standard;
5113  ICS.UserDefined.After = Best->FinalConversion;
5114  ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5115  ICS.UserDefined.ConversionFunction = Best->Function;
5116  ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5117  ICS.UserDefined.EllipsisConversion = false;
5118  assert(ICS.UserDefined.After.ReferenceBinding &&
5120  "Expected a direct reference binding!");
5121  return true;
5122 
5123  case OR_Ambiguous:
5124  ICS.setAmbiguous();
5125  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5126  Cand != CandidateSet.end(); ++Cand)
5127  if (Cand->Best)
5128  ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5129  return true;
5130 
5131  case OR_No_Viable_Function:
5132  case OR_Deleted:
5133  // There was no suitable conversion, or we found a deleted
5134  // conversion; continue with other checks.
5135  return false;
5136  }
5137 
5138  llvm_unreachable("Invalid OverloadResult!");
5139 }
5140 
5141 /// Compute an implicit conversion sequence for reference
5142 /// initialization.
5144 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5145  SourceLocation DeclLoc,
5146  bool SuppressUserConversions,
5147  bool AllowExplicit) {
5148  assert(DeclType->isReferenceType() && "Reference init needs a reference");
5149 
5150  // Most paths end in a failed conversion.
5152  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5153 
5154  QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5155  QualType T2 = Init->getType();
5156 
5157  // If the initializer is the address of an overloaded function, try
5158  // to resolve the overloaded function. If all goes well, T2 is the
5159  // type of the resulting function.
5160  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5161  DeclAccessPair Found;
5162  if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5163  false, Found))
5164  T2 = Fn->getType();
5165  }
5166 
5167  // Compute some basic properties of the types and the initializer.
5168  bool isRValRef = DeclType->isRValueReferenceType();
5169  Expr::Classification InitCategory = Init->Classify(S.Context);
5170 
5172  Sema::ReferenceCompareResult RefRelationship =
5173  S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5174 
5175  auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5176  ICS.setStandard();
5177  ICS.Standard.First = ICK_Identity;
5178  // FIXME: A reference binding can be a function conversion too. We should
5179  // consider that when ordering reference-to-function bindings.
5180  ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5182  : (RefConv & Sema::ReferenceConversions::ObjC)
5184  : ICK_Identity;
5186  // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5187  // a reference binding that performs a non-top-level qualification
5188  // conversion as a qualification conversion, not as an identity conversion.
5189  ICS.Standard.Third = (RefConv &
5190  Sema::ReferenceConversions::NestedQualification)
5192  : ICK_Identity;
5193  ICS.Standard.setFromType(T2);
5194  ICS.Standard.setToType(0, T2);
5195  ICS.Standard.setToType(1, T1);
5196  ICS.Standard.setToType(2, T1);
5197  ICS.Standard.ReferenceBinding = true;
5198  ICS.Standard.DirectBinding = BindsDirectly;
5199  ICS.Standard.IsLvalueReference = !isRValRef;
5201  ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5204  (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5205  ICS.Standard.CopyConstructor = nullptr;
5207  };
5208 
5209  // C++0x [dcl.init.ref]p5:
5210  // A reference to type "cv1 T1" is initialized by an expression
5211  // of type "cv2 T2" as follows:
5212 
5213  // -- If reference is an lvalue reference and the initializer expression
5214  if (!isRValRef) {
5215  // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5216  // reference-compatible with "cv2 T2," or
5217  //
5218  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5219  if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5220  // C++ [over.ics.ref]p1:
5221  // When a parameter of reference type binds directly (8.5.3)
5222  // to an argument expression, the implicit conversion sequence
5223  // is the identity conversion, unless the argument expression
5224  // has a type that is a derived class of the parameter type,
5225  // in which case the implicit conversion sequence is a
5226  // derived-to-base Conversion (13.3.3.1).
5227  SetAsReferenceBinding(/*BindsDirectly=*/true);
5228 
5229  // Nothing more to do: the inaccessibility/ambiguity check for
5230  // derived-to-base conversions is suppressed when we're
5231  // computing the implicit conversion sequence (C++
5232  // [over.best.ics]p2).
5233  return ICS;
5234  }
5235 
5236  // -- has a class type (i.e., T2 is a class type), where T1 is
5237  // not reference-related to T2, and can be implicitly
5238  // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5239  // is reference-compatible with "cv3 T3" 92) (this
5240  // conversion is selected by enumerating the applicable
5241  // conversion functions (13.3.1.6) and choosing the best
5242  // one through overload resolution (13.3)),
5243  if (!SuppressUserConversions && T2->isRecordType() &&
5244  S.isCompleteType(DeclLoc, T2) &&
5245  RefRelationship == Sema::Ref_Incompatible) {
5246  if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5247  Init, T2, /*AllowRvalues=*/false,
5248  AllowExplicit))
5249  return ICS;
5250  }
5251  }
5252 
5253  // -- Otherwise, the reference shall be an lvalue reference to a
5254  // non-volatile const type (i.e., cv1 shall be const), or the reference
5255  // shall be an rvalue reference.
5256  if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5257  if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5259  return ICS;
5260  }
5261 
5262  // -- If the initializer expression
5263  //
5264  // -- is an xvalue, class prvalue, array prvalue or function
5265  // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5266  if (RefRelationship == Sema::Ref_Compatible &&
5267  (InitCategory.isXValue() ||
5268  (InitCategory.isPRValue() &&
5269  (T2->isRecordType() || T2->isArrayType())) ||
5270  (InitCategory.isLValue() && T2->isFunctionType()))) {
5271  // In C++11, this is always a direct binding. In C++98/03, it's a direct
5272  // binding unless we're binding to a class prvalue.
5273  // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5274  // allow the use of rvalue references in C++98/03 for the benefit of
5275  // standard library implementors; therefore, we need the xvalue check here.
5276  SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5277  !(InitCategory.isPRValue() || T2->isRecordType()));
5278  return ICS;
5279  }
5280 
5281  // -- has a class type (i.e., T2 is a class type), where T1 is not
5282  // reference-related to T2, and can be implicitly converted to
5283  // an xvalue, class prvalue, or function lvalue of type
5284  // "cv3 T3", where "cv1 T1" is reference-compatible with
5285  // "cv3 T3",
5286  //
5287  // then the reference is bound to the value of the initializer
5288  // expression in the first case and to the result of the conversion
5289  // in the second case (or, in either case, to an appropriate base
5290  // class subobject).
5291  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5292  T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5293  FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5294  Init, T2, /*AllowRvalues=*/true,
5295  AllowExplicit)) {
5296  // In the second case, if the reference is an rvalue reference
5297  // and the second standard conversion sequence of the
5298  // user-defined conversion sequence includes an lvalue-to-rvalue
5299  // conversion, the program is ill-formed.
5300  if (ICS.isUserDefined() && isRValRef &&
5302  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5303 
5304  return ICS;
5305  }
5306 
5307  // A temporary of function type cannot be created; don't even try.
5308  if (T1->isFunctionType())
5309  return ICS;
5310 
5311  // -- Otherwise, a temporary of type "cv1 T1" is created and
5312  // initialized from the initializer expression using the
5313  // rules for a non-reference copy initialization (8.5). The
5314  // reference is then bound to the temporary. If T1 is
5315  // reference-related to T2, cv1 must be the same
5316  // cv-qualification as, or greater cv-qualification than,
5317  // cv2; otherwise, the program is ill-formed.
5318  if (RefRelationship == Sema::Ref_Related) {
5319  // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5320  // we would be reference-compatible or reference-compatible with
5321  // added qualification. But that wasn't the case, so the reference
5322  // initialization fails.
5323  //
5324  // Note that we only want to check address spaces and cvr-qualifiers here.
5325  // ObjC GC, lifetime and unaligned qualifiers aren't important.
5326  Qualifiers T1Quals = T1.getQualifiers();
5327  Qualifiers T2Quals = T2.getQualifiers();
5328  T1Quals.removeObjCGCAttr();
5329  T1Quals.removeObjCLifetime();
5330  T2Quals.removeObjCGCAttr();
5331  T2Quals.removeObjCLifetime();
5332  // MS compiler ignores __unaligned qualifier for references; do the same.
5333  T1Quals.removeUnaligned();
5334  T2Quals.removeUnaligned();
5335  if (!T1Quals.compatiblyIncludes(T2Quals))
5336  return ICS;
5337  }
5338 
5339  // If at least one of the types is a class type, the types are not
5340  // related, and we aren't allowed any user conversions, the
5341  // reference binding fails. This case is important for breaking
5342  // recursion, since TryImplicitConversion below will attempt to
5343  // create a temporary through the use of a copy constructor.
5344  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5345  (T1->isRecordType() || T2->isRecordType()))
5346  return ICS;
5347 
5348  // If T1 is reference-related to T2 and the reference is an rvalue
5349  // reference, the initializer expression shall not be an lvalue.
5350  if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5351  Init->Classify(S.Context).isLValue()) {
5353  return ICS;
5354  }
5355 
5356  // C++ [over.ics.ref]p2:
5357  // When a parameter of reference type is not bound directly to
5358  // an argument expression, the conversion sequence is the one
5359  // required to convert the argument expression to the
5360  // underlying type of the reference according to
5361  // 13.3.3.1. Conceptually, this conversion sequence corresponds
5362  // to copy-initializing a temporary of the underlying type with
5363  // the argument expression. Any difference in top-level
5364  // cv-qualification is subsumed by the initialization itself
5365  // and does not constitute a conversion.
5366  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5367  AllowedExplicit::None,
5368  /*InOverloadResolution=*/false,
5369  /*CStyle=*/false,
5370  /*AllowObjCWritebackConversion=*/false,
5371  /*AllowObjCConversionOnExplicit=*/false);
5372 
5373  // Of course, that's still a reference binding.
5374  if (ICS.isStandard()) {
5375  ICS.Standard.ReferenceBinding = true;
5376  ICS.Standard.IsLvalueReference = !isRValRef;
5377  ICS.Standard.BindsToFunctionLvalue = false;
5378  ICS.Standard.BindsToRvalue = true;
5381  } else if (ICS.isUserDefined()) {
5382  const ReferenceType *LValRefType =
5385 
5386  // C++ [over.ics.ref]p3:
5387  // Except for an implicit object parameter, for which see 13.3.1, a
5388  // standard conversion sequence cannot be formed if it requires [...]
5389  // binding an rvalue reference to an lvalue other than a function
5390  // lvalue.
5391  // Note that the function case is not possible here.
5392  if (isRValRef && LValRefType) {
5393  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5394  return ICS;
5395  }
5396 
5397  ICS.UserDefined.After.ReferenceBinding = true;
5398  ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5400  ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5403  }
5404 
5405  return ICS;
5406 }
5407 
5409 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5410  bool SuppressUserConversions,
5411  bool InOverloadResolution,
5412  bool AllowObjCWritebackConversion,
5413  bool AllowExplicit = false);
5414 
5415 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5416 /// initializer list From.
5419  bool SuppressUserConversions,
5420  bool InOverloadResolution,
5421  bool AllowObjCWritebackConversion) {
5422  // C++11 [over.ics.list]p1:
5423  // When an argument is an initializer list, it is not an expression and
5424  // special rules apply for converting it to a parameter type.
5425 
5427  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5428 
5429  // We need a complete type for what follows. With one C++20 exception,
5430  // incomplete types can never be initialized from init lists.
5431  QualType InitTy = ToType;
5432  const ArrayType *AT = S.Context.getAsArrayType(ToType);
5433  if (AT && S.getLangOpts().CPlusPlus20)
5434  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5435  // C++20 allows list initialization of an incomplete array type.
5436  InitTy = IAT->getElementType();
5437  if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5438  return Result;
5439 
5440  // C++20 [over.ics.list]/2:
5441  // If the initializer list is a designated-initializer-list, a conversion
5442  // is only possible if the parameter has an aggregate type
5443  //
5444  // FIXME: The exception for reference initialization here is not part of the
5445  // language rules, but follow other compilers in adding it as a tentative DR
5446  // resolution.
5447  bool IsDesignatedInit = From->hasDesignatedInit();
5448  if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5449  IsDesignatedInit)
5450  return Result;
5451 
5452  // Per DR1467:
5453  // If the parameter type is a class X and the initializer list has a single
5454  // element of type cv U, where U is X or a class derived from X, the
5455  // implicit conversion sequence is the one required to convert the element
5456  // to the parameter type.
5457  //
5458  // Otherwise, if the parameter type is a character array [... ]
5459  // and the initializer list has a single element that is an
5460  // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5461  // implicit conversion sequence is the identity conversion.
5462  if (From->getNumInits() == 1 && !IsDesignatedInit) {
5463  if (ToType->isRecordType()) {
5464  QualType InitType = From->getInit(0)->getType();
5465  if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5466  S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5467  return TryCopyInitialization(S, From->getInit(0), ToType,
5468  SuppressUserConversions,
5469  InOverloadResolution,
5470  AllowObjCWritebackConversion);
5471  }
5472 
5473  if (AT && S.IsStringInit(From->getInit(0), AT)) {
5474  InitializedEntity Entity =
5476  /*Consumed=*/false);
5477  if (S.CanPerformCopyInitialization(Entity, From)) {
5478  Result.setStandard();
5479  Result.Standard.setAsIdentityConversion();
5480  Result.Standard.setFromType(ToType);
5481  Result.Standard.setAllToTypes(ToType);
5482  return Result;
5483  }
5484  }
5485  }
5486 
5487  // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5488  // C++11 [over.ics.list]p2:
5489  // If the parameter type is std::initializer_list<X> or "array of X" and
5490  // all the elements can be implicitly converted to X, the implicit
5491  // conversion sequence is the worst conversion necessary to convert an
5492  // element of the list to X.
5493  //
5494  // C++14 [over.ics.list]p3:
5495  // Otherwise, if the parameter type is "array of N X", if the initializer
5496  // list has exactly N elements or if it has fewer than N elements and X is
5497  // default-constructible, and if all the elements of the initializer list
5498  // can be implicitly converted to X, the implicit conversion sequence is
5499  // the worst conversion necessary to convert an element of the list to X.
5500  if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5501  unsigned e = From->getNumInits();
5504  QualType());
5505  QualType ContTy = ToType;
5506  bool IsUnbounded = false;
5507  if (AT) {
5508  InitTy = AT->getElementType();
5509  if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5510  if (CT->getSize().ult(e)) {
5511  // Too many inits, fatally bad
5513  ToType);
5514  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5515  return Result;
5516  }
5517  if (CT->getSize().ugt(e)) {
5518  // Need an init from empty {}, is there one?
5519  InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5520  From->getEndLoc());
5521  EmptyList.setType(S.Context.VoidTy);
5522  DfltElt = TryListConversion(
5523  S, &EmptyList, InitTy, SuppressUserConversions,
5524  InOverloadResolution, AllowObjCWritebackConversion);
5525  if (DfltElt.isBad()) {
5526  // No {} init, fatally bad
5527  Result.setBad(BadConversionSequence::too_few_initializers, From,
5528  ToType);
5529  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5530  return Result;
5531  }
5532  }
5533  } else {
5534  assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5535  IsUnbounded = true;
5536  if (!e) {
5537  // Cannot convert to zero-sized.
5538  Result.setBad(BadConversionSequence::too_few_initializers, From,
5539  ToType);
5540  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5541  return Result;
5542  }
5544  ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5546  }
5547  }
5548 
5549  Result.setStandard();
5550  Result.Standard.setAsIdentityConversion();
5551  Result.Standard.setFromType(InitTy);
5552  Result.Standard.setAllToTypes(InitTy);
5553  for (unsigned i = 0; i < e; ++i) {
5554  Expr *Init = From->getInit(i);
5556  S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5557  AllowObjCWritebackConversion);
5558 
5559  // Keep the worse conversion seen so far.
5560  // FIXME: Sequences are not totally ordered, so 'worse' can be
5561  // ambiguous. CWG has been informed.
5562  if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5563  Result) ==
5565  Result = ICS;
5566  // Bail as soon as we find something unconvertible.
5567  if (Result.isBad()) {
5568  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5569  return Result;
5570  }
5571  }
5572  }
5573 
5574  // If we needed any implicit {} initialization, compare that now.
5575  // over.ics.list/6 indicates we should compare that conversion. Again CWG
5576  // has been informed that this might not be the best thing.
5577  if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5578  S, From->getEndLoc(), DfltElt, Result) ==
5580  Result = DfltElt;
5581  // Record the type being initialized so that we may compare sequences
5582  Result.setInitializerListContainerType(ContTy, IsUnbounded);
5583  return Result;
5584  }
5585 
5586  // C++14 [over.ics.list]p4:
5587  // C++11 [over.ics.list]p3:
5588  // Otherwise, if the parameter is a non-aggregate class X and overload
5589  // resolution chooses a single best constructor [...] the implicit
5590  // conversion sequence is a user-defined conversion sequence. If multiple
5591  // constructors are viable but none is better than the others, the
5592  // implicit conversion sequence is a user-defined conversion sequence.
5593  if (ToType->isRecordType() && !ToType->isAggregateType()) {
5594  // This function can deal with initializer lists.
5595  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5596  AllowedExplicit::None,
5597  InOverloadResolution, /*CStyle=*/false,
5598  AllowObjCWritebackConversion,
5599  /*AllowObjCConversionOnExplicit=*/false);
5600  }
5601 
5602  // C++14 [over.ics.list]p5:
5603  // C++11 [over.ics.list]p4:
5604  // Otherwise, if the parameter has an aggregate type which can be
5605  // initialized from the initializer list [...] the implicit conversion
5606  // sequence is a user-defined conversion sequence.
5607  if (ToType->isAggregateType()) {
5608  // Type is an aggregate, argument is an init list. At this point it comes
5609  // down to checking whether the initialization works.
5610  // FIXME: Find out whether this parameter is consumed or not.
5611  InitializedEntity Entity =
5613  /*Consumed=*/false);
5615  From)) {
5616  Result.setUserDefined();
5617  Result.UserDefined.Before.setAsIdentityConversion();
5618  // Initializer lists don't have a type.
5619  Result.UserDefined.Before.setFromType(QualType());
5620  Result.UserDefined.Before.setAllToTypes(QualType());
5621 
5622  Result.UserDefined.After.setAsIdentityConversion();
5623  Result.UserDefined.After.setFromType(ToType);
5624  Result.UserDefined.After.setAllToTypes(ToType);
5625  Result.UserDefined.ConversionFunction = nullptr;
5626  }
5627  return Result;
5628  }
5629 
5630  // C++14 [over.ics.list]p6:
5631  // C++11 [over.ics.list]p5:
5632  // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5633  if (ToType->isReferenceType()) {
5634  // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5635  // mention initializer lists in any way. So we go by what list-
5636  // initialization would do and try to extrapolate from that.
5637 
5638  QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5639 
5640  // If the initializer list has a single element that is reference-related
5641  // to the parameter type, we initialize the reference from that.
5642  if (From->getNumInits() == 1 && !IsDesignatedInit) {
5643  Expr *Init = From->getInit(0);
5644 
5645  QualType T2 = Init->getType();
5646 
5647  // If the initializer is the address of an overloaded function, try
5648  // to resolve the overloaded function. If all goes well, T2 is the
5649  // type of the resulting function.
5650  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5651  DeclAccessPair Found;
5653  Init, ToType, false, Found))
5654  T2 = Fn->getType();
5655  }
5656 
5657  // Compute some basic properties of the types and the initializer.
5658  Sema::ReferenceCompareResult RefRelationship =
5659  S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5660 
5661  if (RefRelationship >= Sema::Ref_Related) {
5662  return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5663  SuppressUserConversions,
5664  /*AllowExplicit=*/false);
5665  }
5666  }
5667 
5668  // Otherwise, we bind the reference to a temporary created from the
5669  // initializer list.
5670  Result = TryListConversion(S, From, T1, SuppressUserConversions,
5671  InOverloadResolution,
5672  AllowObjCWritebackConversion);
5673  if (Result.isFailure())
5674  return Result;
5675  assert(!Result.isEllipsis() &&
5676  "Sub-initialization cannot result in ellipsis conversion.");
5677 
5678  // Can we even bind to a temporary?
5679  if (ToType->isRValueReferenceType() ||
5680  (T1.isConstQualified() && !T1.isVolatileQualified())) {
5681  StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5682  Result.UserDefined.After;
5683  SCS.ReferenceBinding = true;
5684  SCS.IsLvalueReference = ToType->isLValueReferenceType();
5685  SCS.BindsToRvalue = true;
5686  SCS.BindsToFunctionLvalue = false;
5688  SCS.ObjCLifetimeConversionBinding = false;
5689  } else
5691  From, ToType);
5692  return Result;
5693  }
5694 
5695  // C++14 [over.ics.list]p7:
5696  // C++11 [over.ics.list]p6:
5697  // Otherwise, if the parameter type is not a class:
5698  if (!ToType->isRecordType()) {
5699  // - if the initializer list has one element that is not itself an
5700  // initializer list, the implicit conversion sequence is the one
5701  // required to convert the element to the parameter type.
5702  unsigned NumInits = From->getNumInits();
5703  if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5704  Result = TryCopyInitialization(S, From->getInit(0), ToType,
5705  SuppressUserConversions,
5706  InOverloadResolution,
5707  AllowObjCWritebackConversion);
5708  // - if the initializer list has no elements, the implicit conversion
5709  // sequence is the identity conversion.
5710  else if (NumInits == 0) {
5711  Result.setStandard();
5712  Result.Standard.setAsIdentityConversion();
5713  Result.Standard.setFromType(ToType);
5714  Result.Standard.setAllToTypes(ToType);
5715  }
5716  return Result;
5717  }
5718 
5719  // C++14 [over.ics.list]p8:
5720  // C++11 [over.ics.list]p7:
5721  // In all cases other than those enumerated above, no conversion is possible
5722  return Result;
5723 }
5724 
5725 /// TryCopyInitialization - Try to copy-initialize a value of type
5726 /// ToType from the expression From. Return the implicit conversion
5727 /// sequence required to pass this argument, which may be a bad
5728 /// conversion sequence (meaning that the argument cannot be passed to
5729 /// a parameter of this type). If @p SuppressUserConversions, then we
5730 /// do not permit any user-defined conversion sequences.
5733  bool SuppressUserConversions,
5734  bool InOverloadResolution,
5735  bool AllowObjCWritebackConversion,
5736  bool AllowExplicit) {
5737  if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5738  return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5739  InOverloadResolution,AllowObjCWritebackConversion);
5740 
5741  if (ToType->isReferenceType())
5742  return TryReferenceInit(S, From, ToType,
5743  /*FIXME:*/ From->getBeginLoc(),
5744  SuppressUserConversions, AllowExplicit);
5745 
5746  return TryImplicitConversion(S, From, ToType,
5747  SuppressUserConversions,
5748  AllowedExplicit::None,
5749  InOverloadResolution,
5750  /*CStyle=*/false,
5751  AllowObjCWritebackConversion,
5752  /*AllowObjCConversionOnExplicit=*/false);
5753 }
5754 
5755 static bool TryCopyInitialization(const CanQualType FromQTy,
5756  const CanQualType ToQTy,
5757  Sema &S,
5759  ExprValueKind FromVK) {
5760  OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5762  TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5763 
5764  return !ICS.isBad();
5765 }
5766 
5767 /// TryObjectArgumentInitialization - Try to initialize the object
5768 /// parameter of the given member function (@c Method) from the
5769 /// expression @p From.
5771  Sema &S, SourceLocation Loc, QualType FromType,
5772  Expr::Classification FromClassification, CXXMethodDecl *Method,
5773  const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5774  QualType ExplicitParameterType = QualType(),
5775  bool SuppressUserConversion = false) {
5776 
5777  // We need to have an object of class type.
5778  if (const auto *PT = FromType->getAs<PointerType>()) {
5779  FromType = PT->getPointeeType();
5780 
5781  // When we had a pointer, it's implicitly dereferenced, so we
5782  // better have an lvalue.
5783  assert(FromClassification.isLValue());
5784  }
5785 
5786  auto ValueKindFromClassification = [](Expr::Classification C) {
5787  if (C.isPRValue())
5788  return clang::VK_PRValue;
5789  if (C.isXValue())
5790  return VK_XValue;
5791  return clang::VK_LValue;
5792  };
5793 
5794  if (Method->isExplicitObjectMemberFunction()) {
5795  if (ExplicitParameterType.isNull())
5796  ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5797  OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5798  ValueKindFromClassification(FromClassification));
5800  S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5801  /*InOverloadResolution=*/true, false);
5802  if (ICS.isBad())
5803  ICS.Bad.FromExpr = nullptr;
5804  return ICS;
5805  }
5806 
5807  assert(FromType->isRecordType());
5808 
5809  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5810  // C++98 [class.dtor]p2:
5811  // A destructor can be invoked for a const, volatile or const volatile
5812  // object.
5813  // C++98 [over.match.funcs]p4:
5814  // For static member functions, the implicit object parameter is considered
5815  // to match any object (since if the function is selected, the object is
5816  // discarded).
5817  Qualifiers Quals = Method->getMethodQualifiers();
5818  if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5819  Quals.addConst();
5820  Quals.addVolatile();
5821  }
5822 
5823  QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5824 
5825  // Set up the conversion sequence as a "bad" conversion, to allow us
5826  // to exit early.
5828 
5829  // C++0x [over.match.funcs]p4:
5830  // For non-static member functions, the type of the implicit object
5831  // parameter is
5832  //
5833  // - "lvalue reference to cv X" for functions declared without a
5834  // ref-qualifier or with the & ref-qualifier
5835  // - "rvalue reference to cv X" for functions declared with the &&
5836  // ref-qualifier
5837  //
5838  // where X is the class of which the function is a member and cv is the
5839  // cv-qualification on the member function declaration.
5840  //
5841  // However, when finding an implicit conversion sequence for the argument, we
5842  // are not allowed to perform user-defined conversions
5843  // (C++ [over.match.funcs]p5). We perform a simplified version of
5844  // reference binding here, that allows class rvalues to bind to
5845  // non-constant references.
5846 
5847  // First check the qualifiers.
5848  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5849  // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5850  if (ImplicitParamType.getCVRQualifiers() !=
5851  FromTypeCanon.getLocalCVRQualifiers() &&
5852  !ImplicitParamType.isAtLeastAsQualifiedAs(
5853  withoutUnaligned(S.Context, FromTypeCanon))) {
5855  FromType, ImplicitParamType);
5856  return ICS;
5857  }
5858 
5859  if (FromTypeCanon.hasAddressSpace()) {
5860  Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5861  Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5862  if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5864  FromType, ImplicitParamType);
5865  return ICS;
5866  }
5867  }
5868 
5869  // Check that we have either the same type or a derived type. It
5870  // affects the conversion rank.
5871  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5872  ImplicitConversionKind SecondKind;
5873  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5874  SecondKind = ICK_Identity;
5875  } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5876  SecondKind = ICK_Derived_To_Base;
5877  } else if (!Method->isExplicitObjectMemberFunction()) {
5879  FromType, ImplicitParamType);
5880  return ICS;
5881  }
5882 
5883  // Check the ref-qualifier.
5884  switch (Method->getRefQualifier()) {
5885  case RQ_None:
5886  // Do nothing; we don't care about lvalueness or rvalueness.
5887  break;
5888 
5889  case RQ_LValue:
5890  if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5891  // non-const lvalue reference cannot bind to an rvalue
5893  ImplicitParamType);
5894  return ICS;
5895  }
5896  break;
5897 
5898  case RQ_RValue:
5899  if (!FromClassification.isRValue()) {
5900  // rvalue reference cannot bind to an lvalue
5902  ImplicitParamType);
5903  return ICS;
5904  }
5905  break;
5906  }
5907 
5908  // Success. Mark this as a reference binding.
5909  ICS.setStandard();
5911  ICS.Standard.Second = SecondKind;
5912  ICS.Standard.setFromType(FromType);
5913  ICS.Standard.setAllToTypes(ImplicitParamType);
5914  ICS.Standard.ReferenceBinding = true;
5915  ICS.Standard.DirectBinding = true;
5917  ICS.Standard.BindsToFunctionLvalue = false;
5918  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5920  = (Method->getRefQualifier() == RQ_None);
5921  return ICS;
5922 }
5923 
5924 /// PerformObjectArgumentInitialization - Perform initialization of
5925 /// the implicit object parameter for the given Method with the given
5926 /// expression.
5928  Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5929  CXXMethodDecl *Method) {
5930  QualType FromRecordType, DestType;
5931  QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5932 
5933  Expr::Classification FromClassification;
5934  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5935  FromRecordType = PT->getPointeeType();
5936  DestType = Method->getThisType();
5937  FromClassification = Expr::Classification::makeSimpleLValue();
5938  } else {
5939  FromRecordType = From->getType();
5940  DestType = ImplicitParamRecordType;
5941  FromClassification = From->Classify(Context);
5942 
5943  // When performing member access on a prvalue, materialize a temporary.
5944  if (From->isPRValue()) {
5945  From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5946  Method->getRefQualifier() !=
5948  }
5949  }
5950 
5951  // Note that we always use the true parent context when performing
5952  // the actual argument initialization.
5954  *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5955  Method->getParent());
5956  if (ICS.isBad()) {
5957  switch (ICS.Bad.Kind) {
5959  Qualifiers FromQs = FromRecordType.getQualifiers();
5960  Qualifiers ToQs = DestType.getQualifiers();
5961  unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5962  if (CVR) {
5963  Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5964  << Method->getDeclName() << FromRecordType << (CVR - 1)
5965  << From->getSourceRange();
5966  Diag(Method->getLocation(), diag::note_previous_decl)
5967  << Method->getDeclName();
5968  return ExprError();
5969  }
5970  break;
5971  }
5972 
5975  bool IsRValueQualified =
5977  Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5978  << Method->getDeclName() << FromClassification.isRValue()
5979  << IsRValueQualified;
5980  Diag(Method->getLocation(), diag::note_previous_decl)
5981  << Method->getDeclName();
5982  return ExprError();
5983  }
5984 
5987  break;
5988 
5991  llvm_unreachable("Lists are not objects");
5992  }
5993 
5994  return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5995  << ImplicitParamRecordType << FromRecordType
5996  << From->getSourceRange();
5997  }
5998 
5999  if (ICS.Standard.Second == ICK_Derived_To_Base) {
6000  ExprResult FromRes =
6001  PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6002  if (FromRes.isInvalid())
6003  return ExprError();
6004  From = FromRes.get();
6005  }
6006 
6007  if (!Context.hasSameType(From->getType(), DestType)) {
6008  CastKind CK;
6009  QualType PteeTy = DestType->getPointeeType();
6010  LangAS DestAS =
6011  PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6012  if (FromRecordType.getAddressSpace() != DestAS)
6013  CK = CK_AddressSpaceConversion;
6014  else
6015  CK = CK_NoOp;
6016  From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6017  }
6018  return From;
6019 }
6020 
6021 /// TryContextuallyConvertToBool - Attempt to contextually convert the
6022 /// expression From to bool (C++0x [conv]p3).
6025  // C++ [dcl.init]/17.8:
6026  // - Otherwise, if the initialization is direct-initialization, the source
6027  // type is std::nullptr_t, and the destination type is bool, the initial
6028  // value of the object being initialized is false.
6029  if (From->getType()->isNullPtrType())
6031  S.Context.BoolTy,
6032  From->isGLValue());
6033 
6034  // All other direct-initialization of bool is equivalent to an implicit
6035  // conversion to bool in which explicit conversions are permitted.
6036  return TryImplicitConversion(S, From, S.Context.BoolTy,
6037  /*SuppressUserConversions=*/false,
6038  AllowedExplicit::Conversions,
6039  /*InOverloadResolution=*/false,
6040  /*CStyle=*/false,
6041  /*AllowObjCWritebackConversion=*/false,
6042  /*AllowObjCConversionOnExplicit=*/false);
6043 }
6044 
6045 /// PerformContextuallyConvertToBool - Perform a contextual conversion
6046 /// of the expression From to bool (C++0x [conv]p3).
6048  if (checkPlaceholderForOverload(*this, From))
6049  return ExprError();
6050 
6052  if (!ICS.isBad())
6054 
6056  return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6057  << From->getType() << From->getSourceRange();
6058  return ExprError();
6059 }
6060 
6061 /// Check that the specified conversion is permitted in a converted constant
6062 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
6063 /// is acceptable.
6066  // Since we know that the target type is an integral or unscoped enumeration
6067  // type, most conversion kinds are impossible. All possible First and Third
6068  // conversions are fine.
6069  switch (SCS.Second) {
6070  case ICK_Identity:
6072  case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6074  return true;
6075 
6077  // Conversion from an integral or unscoped enumeration type to bool is
6078  // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6079  // conversion, so we allow it in a converted constant expression.
6080  //
6081  // FIXME: Per core issue 1407, we should not allow this, but that breaks
6082  // a lot of popular code. We should at least add a warning for this
6083  // (non-conforming) extension.
6085  SCS.getToType(2)->isBooleanType();
6086 
6088  case ICK_Pointer_Member:
6089  // C++1z: null pointer conversions and null member pointer conversions are
6090  // only permitted if the source type is std::nullptr_t.
6091  return SCS.getFromType()->isNullPtrType();
6092 
6094  case ICK_Complex_Promotion:
6097  case ICK_Floating_Integral:
6099  case ICK_Derived_To_Base:
6100  case ICK_Vector_Conversion:
6103  case ICK_Vector_Splat:
6104  case ICK_Complex_Real:
6109  case ICK_C_Only_Conversion:
6113  return false;
6114 
6115  case ICK_Lvalue_To_Rvalue:
6116  case ICK_Array_To_Pointer:
6118  case ICK_HLSL_Array_RValue:
6119  llvm_unreachable("found a first conversion kind in Second");
6120 
6122  case ICK_Qualification:
6123  llvm_unreachable("found a third conversion kind in Second");
6124 
6126  break;
6127  }
6128 
6129  llvm_unreachable("unknown conversion kind");
6130 }
6131 
6132 /// BuildConvertedConstantExpression - Check that the expression From is a
6133 /// converted constant expression of type T, perform the conversion but
6134 /// does not evaluate the expression
6136  QualType T,
6137  Sema::CCEKind CCE,
6138  NamedDecl *Dest,
6139  APValue &PreNarrowingValue) {
6140  assert(S.getLangOpts().CPlusPlus11 &&
6141  "converted constant expression outside C++11");
6142 
6143  if (checkPlaceholderForOverload(S, From))
6144  return ExprError();
6145 
6146  // C++1z [expr.const]p3:
6147  // A converted constant expression of type T is an expression,
6148  // implicitly converted to type T, where the converted
6149  // expression is a constant expression and the implicit conversion
6150  // sequence contains only [... list of conversions ...].
6152  (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6153  ? TryContextuallyConvertToBool(S, From)
6154  : TryCopyInitialization(S, From, T,
6155  /*SuppressUserConversions=*/false,
6156  /*InOverloadResolution=*/false,
6157  /*AllowObjCWritebackConversion=*/false,
6158  /*AllowExplicit=*/false);
6159  StandardConversionSequence *SCS = nullptr;
6160  switch (ICS.getKind()) {
6162  SCS = &ICS.Standard;
6163  break;
6165  if (T->isRecordType())
6166  SCS = &ICS.UserDefined.Before;
6167  else
6168  SCS = &ICS.UserDefined.After;
6169  break;
6173  return S.Diag(From->getBeginLoc(),
6174  diag::err_typecheck_converted_constant_expression)
6175  << From->getType() << From->getSourceRange() << T;
6176  return ExprError();
6177 
6180  llvm_unreachable("bad conversion in converted constant expression");
6181  }
6182 
6183  // Check that we would only use permitted conversions.
6184  if (!CheckConvertedConstantConversions(S, *SCS)) {
6185  return S.Diag(From->getBeginLoc(),
6186  diag::err_typecheck_converted_constant_expression_disallowed)
6187  << From->getType() << From->getSourceRange() << T;
6188  }
6189  // [...] and where the reference binding (if any) binds directly.
6190  if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6191  return S.Diag(From->getBeginLoc(),
6192  diag::err_typecheck_converted_constant_expression_indirect)
6193  << From->getType() << From->getSourceRange() << T;
6194  }
6195  // 'TryCopyInitialization' returns incorrect info for attempts to bind
6196  // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6197  // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6198  // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6199  // case explicitly.
6200  if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6201  return S.Diag(From->getBeginLoc(),
6202  diag::err_reference_bind_to_bitfield_in_cce)
6203  << From->getSourceRange();
6204  }
6205 
6206  // Usually we can simply apply the ImplicitConversionSequence we formed
6207  // earlier, but that's not guaranteed to work when initializing an object of
6208  // class type.
6209  ExprResult Result;
6210  if (T->isRecordType()) {
6211  assert(CCE == Sema::CCEK_TemplateArg &&
6212  "unexpected class type converted constant expr");
6213  Result = S.PerformCopyInitialization(
6215  T, cast<NonTypeTemplateParmDecl>(Dest)),
6216  SourceLocation(), From);
6217  } else {
6218  Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
6219  }
6220  if (Result.isInvalid())
6221  return Result;
6222 
6223  // C++2a [intro.execution]p5:
6224  // A full-expression is [...] a constant-expression [...]
6225  Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6226  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6227  CCE == Sema::CCEKind::CCEK_TemplateArg);
6228  if (Result.isInvalid())
6229  return Result;
6230 
6231  // Check for a narrowing implicit conversion.
6232  bool ReturnPreNarrowingValue = false;
6233  QualType PreNarrowingType;
6234  switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6235  PreNarrowingType)) {
6237  // Implicit conversion to a narrower type, but the expression is
6238  // value-dependent so we can't tell whether it's actually narrowing.
6239  case NK_Variable_Narrowing:
6240  // Implicit conversion to a narrower type, and the value is not a constant
6241  // expression. We'll diagnose this in a moment.
6242  case NK_Not_Narrowing:
6243  break;
6244 
6245  case NK_Constant_Narrowing:
6246  if (CCE == Sema::CCEK_ArrayBound &&
6247  PreNarrowingType->isIntegralOrEnumerationType() &&
6248  PreNarrowingValue.isInt()) {
6249  // Don't diagnose array bound narrowing here; we produce more precise
6250  // errors by allowing the un-narrowed value through.
6251  ReturnPreNarrowingValue = true;
6252  break;
6253  }
6254  S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6255  << CCE << /*Constant*/ 1
6256  << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6257  break;
6258 
6259  case NK_Type_Narrowing:
6260  // FIXME: It would be better to diagnose that the expression is not a
6261  // constant expression.
6262  S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6263  << CCE << /*Constant*/ 0 << From->getType() << T;
6264  break;
6265  }
6266  if (!ReturnPreNarrowingValue)
6267  PreNarrowingValue = {};
6268 
6269  return Result;
6270 }
6271 
6272 /// CheckConvertedConstantExpression - Check that the expression From is a
6273 /// converted constant expression of type T, perform the conversion and produce
6274 /// the converted expression, per C++11 [expr.const]p3.
6276  QualType T, APValue &Value,
6277  Sema::CCEKind CCE,
6278  bool RequireInt,
6279  NamedDecl *Dest) {
6280 
6281  APValue PreNarrowingValue;
6282  ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6283  PreNarrowingValue);
6284  if (Result.isInvalid() || Result.get()->isValueDependent()) {
6285  Value = APValue();
6286  return Result;
6287  }
6288  return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6289  RequireInt, PreNarrowingValue);
6290 }
6291 
6293  CCEKind CCE,
6294  NamedDecl *Dest) {
6295  APValue PreNarrowingValue;
6296  return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6297  PreNarrowingValue);
6298 }
6299 
6301  APValue &Value, CCEKind CCE,
6302  NamedDecl *Dest) {
6303  return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6304  Dest);
6305 }
6306 
6309  CCEKind CCE) {
6310  assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6311 
6312  APValue V;
6313  auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6314  /*Dest=*/nullptr);
6315  if (!R.isInvalid() && !R.get()->isValueDependent())
6316  Value = V.getInt();
6317  return R;
6318 }
6319 
6320 /// EvaluateConvertedConstantExpression - Evaluate an Expression
6321 /// That is a converted constant expression
6322 /// (which was built with BuildConvertedConstantExpression)
6323 ExprResult
6325  Sema::CCEKind CCE, bool RequireInt,
6326  const APValue &PreNarrowingValue) {
6327 
6328  ExprResult Result = E;
6329  // Check the expression is a constant expression.
6331  Expr::EvalResult Eval;
6332  Eval.Diag = &Notes;
6333 
6335  if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6337  else if (CCE == Sema::CCEK_TemplateArg)
6339  else
6341 
6342  if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6343  (RequireInt && !Eval.Val.isInt())) {
6344  // The expression can't be folded, so we can't keep it at this position in
6345  // the AST.
6346  Result = ExprError();
6347  } else {
6348  Value = Eval.Val;
6349 
6350  if (Notes.empty()) {
6351  // It's a constant expression.
6352  Expr *E = Result.get();
6353  if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6354  // We expect a ConstantExpr to have a value associated with it
6355  // by this point.
6356  assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6357  "ConstantExpr has no value associated with it");
6358  (void)CE;
6359  } else {
6360  E = ConstantExpr::Create(Context, Result.get(), Value);
6361  }
6362  if (!PreNarrowingValue.isAbsent())
6363  Value = std::move(PreNarrowingValue);
6364  return E;
6365  }
6366  }
6367 
6368  // It's not a constant expression. Produce an appropriate diagnostic.
6369  if (Notes.size() == 1 &&
6370  Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6371  Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6372  } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6373  diag::note_constexpr_invalid_template_arg) {
6374  Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6375  for (unsigned I = 0; I < Notes.size(); ++I)
6376  Diag(Notes[I].first, Notes[I].second);
6377  } else {
6378  Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6379  << CCE << E->getSourceRange();
6380  for (unsigned I = 0; I < Notes.size(); ++I)
6381  Diag(Notes[I].first, Notes[I].second);
6382  }
6383  return ExprError();
6384 }
6385 
6386 /// dropPointerConversions - If the given standard conversion sequence
6387 /// involves any pointer conversions, remove them. This may change
6388 /// the result type of the conversion sequence.
6390  if (SCS.Second == ICK_Pointer_Conversion) {
6391  SCS.Second = ICK_Identity;
6392  SCS.Element = ICK_Identity;
6393  SCS.Third = ICK_Identity;
6394  SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6395  }
6396 }
6397 
6398 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6399 /// convert the expression From to an Objective-C pointer type.
6402  // Do an implicit conversion to 'id'.
6403  QualType Ty = S.Context.getObjCIdType();
6405  = TryImplicitConversion(S, From, Ty,
6406  // FIXME: Are these flags correct?
6407  /*SuppressUserConversions=*/false,
6408  AllowedExplicit::Conversions,
6409  /*InOverloadResolution=*/false,
6410  /*CStyle=*/false,
6411  /*AllowObjCWritebackConversion=*/false,
6412  /*AllowObjCConversionOnExplicit=*/true);
6413 
6414  // Strip off any final conversions to 'id'.
6415  switch (ICS.getKind()) {
6420  break;
6421 
6424  break;
6425 
6428  break;
6429  }
6430 
6431  return ICS;
6432 }
6433 
6434 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6435 /// conversion of the expression From to an Objective-C pointer type.
6436 /// Returns a valid but null ExprResult if no conversion sequence exists.
6438  if (checkPlaceholderForOverload(*this, From))
6439  return ExprError();
6440 
6444  if (!ICS.isBad())
6445  return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6446  return ExprResult();
6447 }
6448 
6449 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6450  const Expr *Base = nullptr;
6451  assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6452  "expected a member expression");
6453 
6454  if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6455  M && !M->isImplicitAccess())
6456  Base = M->getBase();
6457  else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6458  M && !M->isImplicitAccess())
6459  Base = M->getBase();
6460 
6461  QualType T = Base ? Base->getType() : S.getCurrentThisType();
6462 
6463  if (T->isPointerType())
6464  T = T->getPointeeType();
6465 
6466  return T;
6467 }
6468 
6470  const FunctionDecl *Fun) {
6471  QualType ObjType = Obj->getType();
6472  if (ObjType->isPointerType()) {
6473  ObjType = ObjType->getPointeeType();
6474  Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6476  /*CanOverflow=*/false, FPOptionsOverride());
6477  }
6478  if (Obj->Classify(S.getASTContext()).isPRValue()) {
6480  ObjType, Obj,
6481  !Fun->getParamDecl(0)->getType()->isRValueReferenceType());
6482  }
6483  return Obj;
6484 }
6485 
6487  FunctionDecl *Fun) {
6488  Obj = GetExplicitObjectExpr(S, Obj, Fun);
6489  return S.PerformCopyInitialization(
6491  Obj->getExprLoc(), Obj);
6492 }
6493 
6495  Expr *Object, MultiExprArg &Args,
6496  SmallVectorImpl<Expr *> &NewArgs) {
6497  assert(Method->isExplicitObjectMemberFunction() &&
6498  "Method is not an explicit member function");
6499  assert(NewArgs.empty() && "NewArgs should be empty");
6500 
6501  NewArgs.reserve(Args.size() + 1);
6502  Expr *This = GetExplicitObjectExpr(S, Object, Method);
6503  NewArgs.push_back(This);
6504  NewArgs.append(Args.begin(), Args.end());
6505  Args = NewArgs;
6507  Method, Object->getBeginLoc());
6508 }
6509 
6510 /// Determine whether the provided type is an integral type, or an enumeration
6511 /// type of a permitted flavor.
6513  return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6515 }
6516 
6517 static ExprResult
6520  QualType T, UnresolvedSetImpl &ViableConversions) {
6521 
6522  if (Converter.Suppress)
6523  return ExprError();
6524 
6525  Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6526  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6527  CXXConversionDecl *Conv =
6528  cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6529  QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6530  Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6531  }
6532  return From;
6533 }
6534 
6535 static bool
6538  QualType T, bool HadMultipleCandidates,
6539  UnresolvedSetImpl &ExplicitConversions) {
6540  if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6541  DeclAccessPair Found = ExplicitConversions[0];
6542  CXXConversionDecl *Conversion =
6543  cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6544 
6545  // The user probably meant to invoke the given explicit
6546  // conversion; use it.
6547  QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6548  std::string TypeStr;
6549  ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6550 
6551  Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6553  "static_cast<" + TypeStr + ">(")
6555  SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6556  Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6557 
6558  // If we aren't in a SFINAE context, build a call to the
6559  // explicit conversion function.
6560  if (SemaRef.isSFINAEContext())
6561  return true;
6562 
6563  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6564  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6565  HadMultipleCandidates);
6566  if (Result.isInvalid())
6567  return true;
6568 
6569  // Replace the conversion with a RecoveryExpr, so we don't try to
6570  // instantiate it later, but can further diagnose here.
6571  Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6572  From, Result.get()->getType());
6573  if (Result.isInvalid())
6574  return true;
6575  From = Result.get();
6576  }
6577  return false;
6578 }
6579 
6582  QualType T, bool HadMultipleCandidates,
6583  DeclAccessPair &Found) {
6584  CXXConversionDecl *Conversion =
6585  cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6586  SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6587 
6588  QualType ToType = Conversion->getConversionType().getNonReferenceType();
6589  if (!Converter.SuppressConversion) {
6590  if (SemaRef.isSFINAEContext())
6591  return true;
6592 
6593  Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6594  << From->getSourceRange();
6595  }
6596 
6597  ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6598  HadMultipleCandidates);
6599  if (Result.isInvalid())
6600  return true;
6601  // Record usage of conversion in an implicit cast.
6602  From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6603  CK_UserDefinedConversion, Result.get(),
6604  nullptr, Result.get()->getValueKind(),
6606  return false;
6607 }
6608 
6610  Sema &SemaRef, SourceLocation Loc, Expr *From,
6611  Sema::ContextualImplicitConverter &Converter) {
6612  if (!Converter.match(From->getType()) && !Converter.Suppress)
6613  Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6614  << From->getSourceRange();
6615 
6616  return SemaRef.DefaultLvalueConversion(From);
6617 }
6618 
6619 static void
6621  UnresolvedSetImpl &ViableConversions,
6622  OverloadCandidateSet &CandidateSet) {
6623  for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6624  DeclAccessPair FoundDecl = ViableConversions[I];
6625  NamedDecl *D = FoundDecl.getDecl();
6626  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6627  if (isa<UsingShadowDecl>(D))
6628  D = cast<UsingShadowDecl>(D)->getTargetDecl();
6629 
6630  CXXConversionDecl *Conv;
6631  FunctionTemplateDecl *ConvTemplate;
6632  if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6633  Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6634  else
6635  Conv = cast<CXXConversionDecl>(D);
6636 
6637  if (ConvTemplate)
6639  ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6640  /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6641  else
6642  SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6643  ToType, CandidateSet,
6644  /*AllowObjCConversionOnExplicit=*/false,
6645  /*AllowExplicit*/ true);
6646  }
6647 }
6648 
6649 /// Attempt to convert the given expression to a type which is accepted
6650 /// by the given converter.
6651 ///
6652 /// This routine will attempt to convert an expression of class type to a
6653 /// type accepted by the specified converter. In C++11 and before, the class
6654 /// must have a single non-explicit conversion function converting to a matching
6655 /// type. In C++1y, there can be multiple such conversion functions, but only
6656 /// one target type.
6657 ///
6658 /// \param Loc The source location of the construct that requires the
6659 /// conversion.
6660 ///
6661 /// \param From The expression we're converting from.
6662 ///
6663 /// \param Converter Used to control and diagnose the conversion process.
6664 ///
6665 /// \returns The expression, converted to an integral or enumeration type if
6666 /// successful.
6668  SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6669  // We can't perform any more checking for type-dependent expressions.
6670  if (From->isTypeDependent())
6671  return From;
6672 
6673  // Process placeholders immediately.
6674  if (From->hasPlaceholderType()) {
6675  ExprResult result = CheckPlaceholderExpr(From);
6676  if (result.isInvalid())
6677  return result;
6678  From = result.get();
6679  }
6680 
6681  // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6682  ExprResult Converted = DefaultLvalueConversion(From);
6683  QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6684  // If the expression already has a matching type, we're golden.
6685  if (Converter.match(T))
6686  return Converted;
6687 
6688  // FIXME: Check for missing '()' if T is a function type?
6689 
6690  // We can only perform contextual implicit conversions on objects of class
6691  // type.
6692  const RecordType *RecordTy = T->getAs<RecordType>();
6693  if (!RecordTy || !getLangOpts().CPlusPlus) {
6694  if (!Converter.Suppress)
6695  Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6696  return From;
6697  }
6698 
6699  // We must have a complete class type.
6700  struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6701  ContextualImplicitConverter &Converter;
6702  Expr *From;
6703 
6704  TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6705  : Converter(Converter), From(From) {}
6706 
6707  void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6708  Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6709  }
6710  } IncompleteDiagnoser(Converter, From);
6711 
6712  if (Converter.Suppress ? !isCompleteType(Loc, T)
6713  : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6714  return From;
6715 
6716  // Look for a conversion to an integral or enumeration type.
6718  ViableConversions; // These are *potentially* viable in C++1y.
6719  UnresolvedSet<4> ExplicitConversions;
6720  const auto &Conversions =
6721  cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6722 
6723  bool HadMultipleCandidates =
6724  (std::distance(Conversions.begin(), Conversions.end()) > 1);
6725 
6726  // To check that there is only one target type, in C++1y:
6727  QualType ToType;
6728  bool HasUniqueTargetType = true;
6729 
6730  // Collect explicit or viable (potentially in C++1y) conversions.
6731  for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6732  NamedDecl *D = (*I)->getUnderlyingDecl();
6733  CXXConversionDecl *Conversion;
6734  FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6735  if (ConvTemplate) {
6736  if (getLangOpts().CPlusPlus14)
6737  Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6738  else
6739  continue; // C++11 does not consider conversion operator templates(?).
6740  } else
6741  Conversion = cast<CXXConversionDecl>(D);
6742 
6743  assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6744  "Conversion operator templates are considered potentially "
6745  "viable in C++1y");
6746 
6747  QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6748  if (Converter.match(CurToType) || ConvTemplate) {
6749 
6750  if (Conversion->isExplicit()) {
6751  // FIXME: For C++1y, do we need this restriction?
6752  // cf. diagnoseNoViableConversion()
6753  if (!ConvTemplate)
6754  ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6755  } else {
6756  if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6757  if (ToType.isNull())
6758  ToType = CurToType.getUnqualifiedType();
6759  else if (HasUniqueTargetType &&
6760  (CurToType.getUnqualifiedType() != ToType))
6761  HasUniqueTargetType = false;
6762  }
6763  ViableConversions.addDecl(I.getDecl(), I.getAccess());
6764  }
6765  }
6766  }
6767 
6768  if (getLangOpts().CPlusPlus14) {
6769  // C++1y [conv]p6:
6770  // ... An expression e of class type E appearing in such a context
6771  // is said to be contextually implicitly converted to a specified
6772  // type T and is well-formed if and only if e can be implicitly
6773  // converted to a type T that is determined as follows: E is searched
6774  // for conversion functions whose return type is cv T or reference to
6775  // cv T such that T is allowed by the context. There shall be
6776  // exactly one such T.
6777 
6778  // If no unique T is found:
6779  if (ToType.isNull()) {
6780  if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6781  HadMultipleCandidates,
6782  ExplicitConversions))
6783  return ExprError();
6784  return finishContextualImplicitConversion(*this, Loc, From, Converter);
6785  }
6786 
6787  // If more than one unique Ts are found:
6788  if (!HasUniqueTargetType)
6789  return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6790  ViableConversions);
6791 
6792  // If one unique T is found:
6793  // First, build a candidate set from the previously recorded
6794  // potentially viable conversions.
6796  collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6797  CandidateSet);
6798 
6799  // Then, perform overload resolution over the candidate set.
6801  switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6802  case OR_Success: {
6803  // Apply this conversion.
6804  DeclAccessPair Found =
6805  DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6806  if (recordConversion(*this, Loc, From, Converter, T,
6807  HadMultipleCandidates, Found))
6808  return ExprError();
6809  break;
6810  }
6811  case OR_Ambiguous:
6812  return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6813  ViableConversions);
6814  case OR_No_Viable_Function:
6815  if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6816  HadMultipleCandidates,
6817  ExplicitConversions))
6818  return ExprError();
6819  [[fallthrough]];
6820  case OR_Deleted:
6821  // We'll complain below about a non-integral condition type.
6822  break;
6823  }
6824  } else {
6825  switch (ViableConversions.size()) {
6826  case 0: {
6827  if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6828  HadMultipleCandidates,
6829  ExplicitConversions))
6830  return ExprError();
6831 
6832  // We'll complain below about a non-integral condition type.
6833  break;
6834  }
6835  case 1: {
6836  // Apply this conversion.
6837  DeclAccessPair Found = ViableConversions[0];
6838  if (recordConversion(*this, Loc, From, Converter, T,
6839  HadMultipleCandidates, Found))
6840  return ExprError();
6841  break;
6842  }
6843  default:
6844  return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6845  ViableConversions);
6846  }
6847  }
6848 
6849  return finishContextualImplicitConversion(*this, Loc, From, Converter);
6850 }
6851 
6852 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6853 /// an acceptable non-member overloaded operator for a call whose
6854 /// arguments have types T1 (and, if non-empty, T2). This routine
6855 /// implements the check in C++ [over.match.oper]p3b2 concerning
6856 /// enumeration types.
6858  FunctionDecl *Fn,
6859  ArrayRef<Expr *> Args) {
6860  QualType T1 = Args[0]->getType();
6861  QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6862 
6863  if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6864  return true;
6865 
6866  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6867  return true;
6868 
6869  const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6870  if (Proto->getNumParams() < 1)
6871  return false;
6872 
6873  if (T1->isEnumeralType()) {
6874  QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6875  if (Context.hasSameUnqualifiedType(T1, ArgType))
6876  return true;
6877  }
6878 
6879  if (Proto->getNumParams() < 2)
6880  return false;
6881 
6882  if (!T2.isNull() && T2->isEnumeralType()) {
6883  QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6884  if (Context.hasSameUnqualifiedType(T2, ArgType))
6885  return true;
6886  }
6887 
6888  return false;
6889 }
6890 
6892  if (FD->isTargetMultiVersionDefault())
6893  return false;
6894 
6895  if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6896  return FD->isTargetMultiVersion();
6897 
6898  if (!FD->isMultiVersion())
6899  return false;
6900 
6901  // Among multiple target versions consider either the default,
6902  // or the first non-default in the absence of default version.
6903  unsigned SeenAt = 0;
6904  unsigned I = 0;
6905  bool HasDefault = false;
6907  FD, [&](const FunctionDecl *CurFD) {
6908  if (FD == CurFD)
6909  SeenAt = I;
6910  else if (CurFD->isTargetMultiVersionDefault())
6911  HasDefault = true;
6912  ++I;
6913  });
6914  return HasDefault || SeenAt != 0;
6915 }
6916 
6917 /// AddOverloadCandidate - Adds the given function to the set of
6918 /// candidate functions, using the given function call arguments. If
6919 /// @p SuppressUserConversions, then don't allow user-defined
6920 /// conversions via constructors or conversion operators.
6921 ///
6922 /// \param PartialOverloading true if we are performing "partial" overloading
6923 /// based on an incomplete set of function arguments. This feature is used by
6924 /// code completion.
6926  FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6927  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6928  bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6929  ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6930  OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6931  const FunctionProtoType *Proto
6932  = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6933  assert(Proto && "Functions without a prototype cannot be overloaded");
6934  assert(!Function->getDescribedFunctionTemplate() &&
6935  "Use AddTemplateOverloadCandidate for function templates");
6936 
6937  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6938  if (!isa<CXXConstructorDecl>(Method)) {
6939  // If we get here, it's because we're calling a member function
6940  // that is named without a member access expression (e.g.,
6941  // "this->f") that was either written explicitly or created
6942  // implicitly. This can happen with a qualified call to a member
6943  // function, e.g., X::f(). We use an empty type for the implied
6944  // object argument (C++ [over.call.func]p3), and the acting context
6945  // is irrelevant.
6946  AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6948  CandidateSet, SuppressUserConversions,
6949  PartialOverloading, EarlyConversions, PO);
6950  return;
6951  }
6952  // We treat a constructor like a non-member function, since its object
6953  // argument doesn't participate in overload resolution.
6954  }
6955 
6956  if (!CandidateSet.isNewCandidate(Function, PO))
6957  return;
6958 
6959  // C++11 [class.copy]p11: [DR1402]
6960  // A defaulted move constructor that is defined as deleted is ignored by
6961  // overload resolution.
6962  CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6963  if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6964  Constructor->isMoveConstructor())
6965  return;
6966 
6967  // Overload resolution is always an unevaluated context.
6970 
6971  // C++ [over.match.oper]p3:
6972  // if no operand has a class type, only those non-member functions in the
6973  // lookup set that have a first parameter of type T1 or "reference to
6974  // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6975  // is a right operand) a second parameter of type T2 or "reference to
6976  // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6977  // candidate functions.
6978  if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6980  return;
6981 
6982  // Add this candidate
6983  OverloadCandidate &Candidate =
6984  CandidateSet.addCandidate(Args.size(), EarlyConversions);
6985  Candidate.FoundDecl = FoundDecl;
6986  Candidate.Function = Function;
6987  Candidate.Viable = true;
6988  Candidate.RewriteKind =
6989  CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6990  Candidate.IsSurrogate = false;
6991  Candidate.IsADLCandidate = IsADLCandidate;
6992  Candidate.IgnoreObjectArgument = false;
6993  Candidate.ExplicitCallArguments = Args.size();
6994 
6995  // Explicit functions are not actually candidates at all if we're not
6996  // allowing them in this context, but keep them around so we can point
6997  // to them in diagnostics.
6998  if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6999  Candidate.Viable = false;
7000  Candidate.FailureKind = ovl_fail_explicit;
7001  return;
7002  }
7003 
7004  // Functions with internal linkage are only viable in the same module unit.
7005  if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7006  /// FIXME: Currently, the semantics of linkage in clang is slightly
7007  /// different from the semantics in C++ spec. In C++ spec, only names
7008  /// have linkage. So that all entities of the same should share one
7009  /// linkage. But in clang, different entities of the same could have
7010  /// different linkage.
7011  NamedDecl *ND = Function;
7012  if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
7013  ND = SpecInfo->getTemplate();
7014 
7015  if (ND->getFormalLinkage() == Linkage::Internal) {
7016  Candidate.Viable = false;
7018  return;
7019  }
7020  }
7021 
7023  Candidate.Viable = false;
7025  return;
7026  }
7027 
7028  if (Constructor) {
7029  // C++ [class.copy]p3:
7030  // A member function template is never instantiated to perform the copy
7031  // of a class object to an object of its class type.
7032  QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7033  if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7034  (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7035  IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7036  ClassType))) {
7037  Candidate.Viable = false;
7039  return;
7040  }
7041 
7042  // C++ [over.match.funcs]p8: (proposed DR resolution)
7043  // A constructor inherited from class type C that has a first parameter
7044  // of type "reference to P" (including such a constructor instantiated
7045  // from a template) is excluded from the set of candidate functions when
7046  // constructing an object of type cv D if the argument list has exactly
7047  // one argument and D is reference-related to P and P is reference-related
7048  // to C.
7049  auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7050  if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7051  Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7052  QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7053  QualType C = Context.getRecordType(Constructor->getParent());
7054  QualType D = Context.getRecordType(Shadow->getParent());
7055  SourceLocation Loc = Args.front()->getExprLoc();
7056  if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7058  Candidate.Viable = false;
7059  Candidate.FailureKind = ovl_fail_inhctor_slice;
7060  return;
7061  }
7062  }
7063 
7064  // Check that the constructor is capable of constructing an object in the
7065  // destination address space.
7067  Constructor->getMethodQualifiers().getAddressSpace(),
7068  CandidateSet.getDestAS())) {
7069  Candidate.Viable = false;
7071  }
7072  }
7073 
7074  unsigned NumParams = Proto->getNumParams();
7075 
7076  // (C++ 13.3.2p2): A candidate function having fewer than m
7077  // parameters is viable only if it has an ellipsis in its parameter
7078  // list (8.3.5).
7079  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7080  !Proto->isVariadic() &&
7081  shouldEnforceArgLimit(PartialOverloading, Function)) {
7082  Candidate.Viable = false;
7084  return;
7085  }
7086 
7087  // (C++ 13.3.2p2): A candidate function having more than m parameters
7088  // is viable only if the (m+1)st parameter has a default argument
7089  // (8.3.6). For the purposes of overload resolution, the
7090  // parameter list is truncated on the right, so that there are
7091  // exactly m parameters.
7092  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7093  if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7094  !PartialOverloading) {
7095  // Not enough arguments.
7096  Candidate.Viable = false;
7098  return;
7099  }
7100 
7101  // (CUDA B.1): Check for invalid calls between targets.
7102  if (getLangOpts().CUDA) {
7103  const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7104  // Skip the check for callers that are implicit members, because in this
7105  // case we may not yet know what the member's target is; the target is
7106  // inferred for the member automatically, based on the bases and fields of
7107  // the class.
7108  if (!(Caller && Caller->isImplicit()) &&
7109  !CUDA().IsAllowedCall(Caller, Function)) {
7110  Candidate.Viable = false;
7111  Candidate.FailureKind = ovl_fail_bad_target;
7112  return;
7113  }
7114  }
7115 
7116  if (Function->getTrailingRequiresClause()) {
7117  ConstraintSatisfaction Satisfaction;
7118  if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7119  /*ForOverloadResolution*/ true) ||
7120  !Satisfaction.IsSatisfied) {
7121  Candidate.Viable = false;
7123  return;
7124  }
7125  }
7126 
7127  // Determine the implicit conversion sequences for each of the
7128  // arguments.
7129  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7130  unsigned ConvIdx =
7131  PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7132  if (Candidate.Conversions[ConvIdx].isInitialized()) {
7133  // We already formed a conversion sequence for this parameter during
7134  // template argument deduction.
7135  } else if (ArgIdx < NumParams) {
7136  // (C++ 13.3.2p3): for F to be a viable function, there shall
7137  // exist for each argument an implicit conversion sequence
7138  // (13.3.3.1) that converts that argument to the corresponding
7139  // parameter of F.
7140  QualType ParamType = Proto->getParamType(ArgIdx);
7141  Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7142  *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7143  /*InOverloadResolution=*/true,
7144  /*AllowObjCWritebackConversion=*/
7145  getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7146  if (Candidate.Conversions[ConvIdx].isBad()) {
7147  Candidate.Viable = false;
7149  return;
7150  }
7151  } else {
7152  // (C++ 13.3.2p2): For the purposes of overload resolution, any
7153  // argument for which there is no corresponding parameter is
7154  // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7155  Candidate.Conversions[ConvIdx].setEllipsis();
7156  }
7157  }
7158 
7159  if (EnableIfAttr *FailedAttr =
7160  CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7161  Candidate.Viable = false;
7162  Candidate.FailureKind = ovl_fail_enable_if;
7163  Candidate.DeductionFailure.Data = FailedAttr;
7164  return;
7165  }
7166 }
7167 
7169 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7171  if (Methods.size() <= 1)
7172  return nullptr;
7173 
7174  for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7175  bool Match = true;
7176  ObjCMethodDecl *Method = Methods[b];
7177  unsigned NumNamedArgs = Sel.getNumArgs();
7178  // Method might have more arguments than selector indicates. This is due
7179  // to addition of c-style arguments in method.
7180  if (Method->param_size() > NumNamedArgs)
7181  NumNamedArgs = Method->param_size();
7182  if (Args.size() < NumNamedArgs)
7183  continue;
7184 
7185  for (unsigned i = 0; i < NumNamedArgs; i++) {
7186  // We can't do any type-checking on a type-dependent argument.
7187  if (Args[i]->isTypeDependent()) {
7188  Match = false;
7189  break;
7190  }
7191 
7192  ParmVarDecl *param = Method->parameters()[i];
7193  Expr *argExpr = Args[i];
7194  assert(argExpr && "SelectBestMethod(): missing expression");
7195 
7196  // Strip the unbridged-cast placeholder expression off unless it's
7197  // a consumed argument.
7198  if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7199  !param->hasAttr<CFConsumedAttr>())
7200  argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7201 
7202  // If the parameter is __unknown_anytype, move on to the next method.
7203  if (param->getType() == Context.UnknownAnyTy) {
7204  Match = false;
7205  break;
7206  }
7207 
7208  ImplicitConversionSequence ConversionState
7209  = TryCopyInitialization(*this, argExpr, param->getType(),
7210  /*SuppressUserConversions*/false,
7211  /*InOverloadResolution=*/true,
7212  /*AllowObjCWritebackConversion=*/
7213  getLangOpts().ObjCAutoRefCount,
7214  /*AllowExplicit*/false);
7215  // This function looks for a reasonably-exact match, so we consider
7216  // incompatible pointer conversions to be a failure here.
7217  if (ConversionState.isBad() ||
7218  (ConversionState.isStandard() &&
7219  ConversionState.Standard.Second ==
7221  Match = false;
7222  break;
7223  }
7224  }
7225  // Promote additional arguments to variadic methods.
7226  if (Match && Method->isVariadic()) {
7227  for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7228  if (Args[i]->isTypeDependent()) {
7229  Match = false;
7230  break;
7231  }
7233  nullptr);
7234  if (Arg.isInvalid()) {
7235  Match = false;
7236  break;
7237  }
7238  }
7239  } else {
7240  // Check for extra arguments to non-variadic methods.
7241  if (Args.size() != NumNamedArgs)
7242  Match = false;
7243  else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7244  // Special case when selectors have no argument. In this case, select
7245  // one with the most general result type of 'id'.
7246  for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7247  QualType ReturnT = Methods[b]->getReturnType();
7248  if (ReturnT->isObjCIdType())
7249  return Methods[b];
7250  }
7251  }
7252  }
7253 
7254  if (Match)
7255  return Method;
7256  }
7257  return nullptr;
7258 }
7259 
7261  Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7262  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7263  Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7264  if (ThisArg) {
7265  CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7266  assert(!isa<CXXConstructorDecl>(Method) &&
7267  "Shouldn't have `this` for ctors!");
7268  assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7270  ThisArg, /*Qualifier=*/nullptr, Method, Method);
7271  if (R.isInvalid())
7272  return false;
7273  ConvertedThis = R.get();
7274  } else {
7275  if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7276  (void)MD;
7277  assert((MissingImplicitThis || MD->isStatic() ||
7278  isa<CXXConstructorDecl>(MD)) &&
7279  "Expected `this` for non-ctor instance methods");
7280  }
7281  ConvertedThis = nullptr;
7282  }
7283 
7284  // Ignore any variadic arguments. Converting them is pointless, since the
7285  // user can't refer to them in the function condition.
7286  unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7287 
7288  // Convert the arguments.
7289  for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7290  ExprResult R;
7292  S.Context, Function->getParamDecl(I)),
7293  SourceLocation(), Args[I]);
7294 
7295  if (R.isInvalid())
7296  return false;
7297 
7298  ConvertedArgs.push_back(R.get());
7299  }
7300 
7301  if (Trap.hasErrorOccurred())
7302  return false;
7303 
7304  // Push default arguments if needed.
7305  if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7306  for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7307  ParmVarDecl *P = Function->getParamDecl(i);
7308  if (!P->hasDefaultArg())
7309  return false;
7310  ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7311  if (R.isInvalid())
7312  return false;
7313  ConvertedArgs.push_back(R.get());
7314  }
7315 
7316  if (Trap.hasErrorOccurred())
7317  return false;
7318  }
7319  return true;
7320 }
7321 
7322 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7323  SourceLocation CallLoc,
7324  ArrayRef<Expr *> Args,
7325  bool MissingImplicitThis) {
7326  auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7327  if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7328  return nullptr;
7329 
7330  SFINAETrap Trap(*this);
7331  SmallVector<Expr *, 16> ConvertedArgs;
7332  // FIXME: We should look into making enable_if late-parsed.
7333  Expr *DiscardedThis;
7335  *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7336  /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7337  return *EnableIfAttrs.begin();
7338 
7339  for (auto *EIA : EnableIfAttrs) {
7340  APValue Result;
7341  // FIXME: This doesn't consider value-dependent cases, because doing so is
7342  // very difficult. Ideally, we should handle them more gracefully.
7343  if (EIA->getCond()->isValueDependent() ||
7344  !EIA->getCond()->EvaluateWithSubstitution(
7345  Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7346  return EIA;
7347 
7348  if (!Result.isInt() || !Result.getInt().getBoolValue())
7349  return EIA;
7350  }
7351  return nullptr;
7352 }
7353 
7354 template <typename CheckFn>
7355 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7356  bool ArgDependent, SourceLocation Loc,
7357  CheckFn &&IsSuccessful) {
7359  for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7360  if (ArgDependent == DIA->getArgDependent())
7361  Attrs.push_back(DIA);
7362  }
7363 
7364  // Common case: No diagnose_if attributes, so we can quit early.
7365  if (Attrs.empty())
7366  return false;
7367 
7368  auto WarningBegin = std::stable_partition(
7369  Attrs.begin(), Attrs.end(),
7370  [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7371 
7372  // Note that diagnose_if attributes are late-parsed, so they appear in the
7373  // correct order (unlike enable_if attributes).
7374  auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7375  IsSuccessful);
7376  if (ErrAttr != WarningBegin) {
7377  const DiagnoseIfAttr *DIA = *ErrAttr;
7378  S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7379  S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7380  << DIA->getParent() << DIA->getCond()->getSourceRange();
7381  return true;
7382  }
7383 
7384  for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7385  if (IsSuccessful(DIA)) {
7386  S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7387  S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7388  << DIA->getParent() << DIA->getCond()->getSourceRange();
7389  }
7390 
7391  return false;
7392 }
7393 
7395  const Expr *ThisArg,
7397  SourceLocation Loc) {
7399  *this, Function, /*ArgDependent=*/true, Loc,
7400  [&](const DiagnoseIfAttr *DIA) {
7401  APValue Result;
7402  // It's sane to use the same Args for any redecl of this function, since
7403  // EvaluateWithSubstitution only cares about the position of each
7404  // argument in the arg list, not the ParmVarDecl* it maps to.
7405  if (!DIA->getCond()->EvaluateWithSubstitution(
7406  Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7407  return false;
7408  return Result.isInt() && Result.getInt().getBoolValue();
7409  });
7410 }
7411 
7413  SourceLocation Loc) {
7415  *this, ND, /*ArgDependent=*/false, Loc,
7416  [&](const DiagnoseIfAttr *DIA) {
7417  bool Result;
7418  return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7419  Result;
7420  });
7421 }
7422 
7423 /// Add all of the function declarations in the given function set to
7424 /// the overload candidate set.
7426  ArrayRef<Expr *> Args,
7427  OverloadCandidateSet &CandidateSet,
7428  TemplateArgumentListInfo *ExplicitTemplateArgs,
7429  bool SuppressUserConversions,
7430  bool PartialOverloading,
7431  bool FirstArgumentIsBase) {
7432  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7433  NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7434  ArrayRef<Expr *> FunctionArgs = Args;
7435 
7436  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7437  FunctionDecl *FD =
7438  FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7439 
7440  if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7441  QualType ObjectType;
7442  Expr::Classification ObjectClassification;
7443  if (Args.size() > 0) {
7444  if (Expr *E = Args[0]) {
7445  // Use the explicit base to restrict the lookup:
7446  ObjectType = E->getType();
7447  // Pointers in the object arguments are implicitly dereferenced, so we
7448  // always classify them as l-values.
7449  if (!ObjectType.isNull() && ObjectType->isPointerType())
7450  ObjectClassification = Expr::Classification::makeSimpleLValue();
7451  else
7452  ObjectClassification = E->Classify(Context);
7453  } // .. else there is an implicit base.
7454  FunctionArgs = Args.slice(1);
7455  }
7456  if (FunTmpl) {
7458  FunTmpl, F.getPair(),
7459  cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7460  ExplicitTemplateArgs, ObjectType, ObjectClassification,
7461  FunctionArgs, CandidateSet, SuppressUserConversions,
7462  PartialOverloading);
7463  } else {
7464  AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7465  cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7466  ObjectClassification, FunctionArgs, CandidateSet,
7467  SuppressUserConversions, PartialOverloading);
7468  }
7469  } else {
7470  // This branch handles both standalone functions and static methods.
7471 
7472  // Slice the first argument (which is the base) when we access
7473  // static method as non-static.
7474  if (Args.size() > 0 &&
7475  (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7476  !isa<CXXConstructorDecl>(FD)))) {
7477  assert(cast<CXXMethodDecl>(FD)->isStatic());
7478  FunctionArgs = Args.slice(1);
7479  }
7480  if (FunTmpl) {
7481  AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7482  ExplicitTemplateArgs, FunctionArgs,
7483  CandidateSet, SuppressUserConversions,
7484  PartialOverloading);
7485  } else {
7486  AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7487  SuppressUserConversions, PartialOverloading);
7488  }
7489  }
7490  }
7491 }
7492 
7493 /// AddMethodCandidate - Adds a named decl (which is some kind of
7494 /// method) as a method candidate to the given overload set.
7496  Expr::Classification ObjectClassification,
7497  ArrayRef<Expr *> Args,
7498  OverloadCandidateSet &CandidateSet,
7499  bool SuppressUserConversions,
7501  NamedDecl *Decl = FoundDecl.getDecl();
7502  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7503 
7504  if (isa<UsingShadowDecl>(Decl))
7505  Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7506 
7507  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7508  assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7509  "Expected a member function template");
7510  AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7511  /*ExplicitArgs*/ nullptr, ObjectType,
7512  ObjectClassification, Args, CandidateSet,
7513  SuppressUserConversions, false, PO);
7514  } else {
7515  AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7516  ObjectType, ObjectClassification, Args, CandidateSet,
7517  SuppressUserConversions, false, std::nullopt, PO);
7518  }
7519 }
7520 
7521 /// AddMethodCandidate - Adds the given C++ member function to the set
7522 /// of candidate functions, using the given function call arguments
7523 /// and the object argument (@c Object). For example, in a call
7524 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7525 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7526 /// allow user-defined conversions via constructors or conversion
7527 /// operators.
7528 void
7530  CXXRecordDecl *ActingContext, QualType ObjectType,
7531  Expr::Classification ObjectClassification,
7532  ArrayRef<Expr *> Args,
7533  OverloadCandidateSet &CandidateSet,
7534  bool SuppressUserConversions,
7535  bool PartialOverloading,
7536  ConversionSequenceList EarlyConversions,
7538  const FunctionProtoType *Proto
7539  = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7540  assert(Proto && "Methods without a prototype cannot be overloaded");
7541  assert(!isa<CXXConstructorDecl>(Method) &&
7542  "Use AddOverloadCandidate for constructors");
7543 
7544  if (!CandidateSet.isNewCandidate(Method, PO))
7545  return;
7546 
7547  // C++11 [class.copy]p23: [DR1402]
7548  // A defaulted move assignment operator that is defined as deleted is
7549  // ignored by overload resolution.
7550  if (Method->isDefaulted() && Method->isDeleted() &&
7551  Method->isMoveAssignmentOperator())
7552  return;
7553 
7554  // Overload resolution is always an unevaluated context.
7557 
7558  // Add this candidate
7559  OverloadCandidate &Candidate =
7560  CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7561  Candidate.FoundDecl = FoundDecl;
7562  Candidate.Function = Method;
7563  Candidate.RewriteKind =
7564  CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7565  Candidate.IsSurrogate = false;
7566  Candidate.IgnoreObjectArgument = false;
7567  Candidate.ExplicitCallArguments = Args.size();
7568 
7569  unsigned NumParams = Method->getNumExplicitParams();
7570  unsigned ExplicitOffset = Method->isExplicitObjectMemberFunction() ? 1 : 0;
7571 
7572  // (C++ 13.3.2p2): A candidate function having fewer than m
7573  // parameters is viable only if it has an ellipsis in its parameter
7574  // list (8.3.5).
7575  if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7576  !Proto->isVariadic() &&
7577  shouldEnforceArgLimit(PartialOverloading, Method)) {
7578  Candidate.Viable = false;
7580  return;
7581  }
7582 
7583  // (C++ 13.3.2p2): A candidate function having more than m parameters
7584  // is viable only if the (m+1)st parameter has a default argument
7585  // (8.3.6). For the purposes of overload resolution, the
7586  // parameter list is truncated on the right, so that there are
7587  // exactly m parameters.
7588  unsigned MinRequiredArgs = Method->getMinRequiredExplicitArguments();
7589  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7590  // Not enough arguments.
7591  Candidate.Viable = false;
7593  return;
7594  }
7595 
7596  Candidate.Viable = true;
7597 
7598  unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7599  if (ObjectType.isNull())
7600  Candidate.IgnoreObjectArgument = true;
7601  else if (Method->isStatic()) {
7602  // [over.best.ics.general]p8
7603  // When the parameter is the implicit object parameter of a static member
7604  // function, the implicit conversion sequence is a standard conversion
7605  // sequence that is neither better nor worse than any other standard
7606  // conversion sequence.
7607  //
7608  // This is a rule that was introduced in C++23 to support static lambdas. We
7609  // apply it retroactively because we want to support static lambdas as an
7610  // extension and it doesn't hurt previous code.
7611  Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7612  } else {
7613  // Determine the implicit conversion sequence for the object
7614  // parameter.
7615  Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7616  *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7617  Method, ActingContext, /*InOverloadResolution=*/true);
7618  if (Candidate.Conversions[FirstConvIdx].isBad()) {
7619  Candidate.Viable = false;
7621  return;
7622  }
7623  }
7624 
7625  // (CUDA B.1): Check for invalid calls between targets.
7626  if (getLangOpts().CUDA)
7627  if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7628  Method)) {
7629  Candidate.Viable = false;
7630  Candidate.FailureKind = ovl_fail_bad_target;
7631  return;
7632  }
7633 
7634  if (Method->getTrailingRequiresClause()) {
7635  ConstraintSatisfaction Satisfaction;
7636  if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7637  /*ForOverloadResolution*/ true) ||
7638  !Satisfaction.IsSatisfied) {
7639  Candidate.Viable = false;
7641  return;
7642  }
7643  }
7644 
7645  // Determine the implicit conversion sequences for each of the
7646  // arguments.
7647  for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7648  unsigned ConvIdx =
7649  PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7650  if (Candidate.Conversions[ConvIdx].isInitialized()) {
7651  // We already formed a conversion sequence for this parameter during
7652  // template argument deduction.
7653  } else if (ArgIdx < NumParams) {
7654  // (C++ 13.3.2p3): for F to be a viable function, there shall
7655  // exist for each argument an implicit conversion sequence
7656  // (13.3.3.1) that converts that argument to the corresponding
7657  // parameter of F.
7658  QualType ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7659  Candidate.Conversions[ConvIdx]
7660  = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7661  SuppressUserConversions,
7662  /*InOverloadResolution=*/true,
7663  /*AllowObjCWritebackConversion=*/
7664  getLangOpts().ObjCAutoRefCount);
7665  if (Candidate.Conversions[ConvIdx].isBad()) {
7666  Candidate.Viable = false;
7668  return;
7669  }
7670  } else {
7671  // (C++ 13.3.2p2): For the purposes of overload resolution, any
7672  // argument for which there is no corresponding parameter is
7673  // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7674  Candidate.Conversions[ConvIdx].setEllipsis();
7675  }
7676  }
7677 
7678  if (EnableIfAttr *FailedAttr =
7679  CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7680  Candidate.Viable = false;
7681  Candidate.FailureKind = ovl_fail_enable_if;
7682  Candidate.DeductionFailure.Data = FailedAttr;
7683  return;
7684  }
7685 
7686  if (isNonViableMultiVersionOverload(Method)) {
7687  Candidate.Viable = false;
7689  }
7690 }
7691 
7692 /// Add a C++ member function template as a candidate to the candidate
7693 /// set, using template argument deduction to produce an appropriate member
7694 /// function template specialization.
7696  FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7697  CXXRecordDecl *ActingContext,
7698  TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7699  Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7700  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7701  bool PartialOverloading, OverloadCandidateParamOrder PO) {
7702  if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7703  return;
7704 
7705  // C++ [over.match.funcs]p7:
7706  // In each case where a candidate is a function template, candidate
7707  // function template specializations are generated using template argument
7708  // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7709  // candidate functions in the usual way.113) A given name can refer to one
7710  // or more function templates and also to a set of overloaded non-template
7711  // functions. In such a case, the candidate functions generated from each
7712  // function template are combined with the set of non-template candidate
7713  // functions.
7714  TemplateDeductionInfo Info(CandidateSet.getLocation());
7715  FunctionDecl *Specialization = nullptr;
7716  ConversionSequenceList Conversions;
7718  MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7719  PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7720  ObjectClassification,
7721  [&](ArrayRef<QualType> ParamTypes) {
7723  MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7724  SuppressUserConversions, ActingContext, ObjectType,
7725  ObjectClassification, PO);
7726  });
7728  OverloadCandidate &Candidate =
7729  CandidateSet.addCandidate(Conversions.size(), Conversions);
7730  Candidate.FoundDecl = FoundDecl;
7731  Candidate.Function = MethodTmpl->getTemplatedDecl();
7732  Candidate.Viable = false;
7733  Candidate.RewriteKind =
7734  CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7735  Candidate.IsSurrogate = false;
7736  Candidate.IgnoreObjectArgument =
7737  cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7738  ObjectType.isNull();
7739  Candidate.ExplicitCallArguments = Args.size();
7742  else {
7743  Candidate.FailureKind = ovl_fail_bad_deduction;
7745  Info);
7746  }
7747  return;
7748  }
7749 
7750  // Add the function template specialization produced by template argument
7751  // deduction as a candidate.
7752  assert(Specialization && "Missing member function template specialization?");
7753  assert(isa<CXXMethodDecl>(Specialization) &&
7754  "Specialization is not a member function?");
7755  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7756  ActingContext, ObjectType, ObjectClassification, Args,
7757  CandidateSet, SuppressUserConversions, PartialOverloading,
7758  Conversions, PO);
7759 }
7760 
7761 /// Determine whether a given function template has a simple explicit specifier
7762 /// or a non-value-dependent explicit-specification that evaluates to true.
7765 }
7766 
7767 /// Add a C++ function template specialization as a candidate
7768 /// in the candidate set, using template argument deduction to produce
7769 /// an appropriate function template specialization.
7771  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7772  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7773  OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7774  bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7775  OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7776  if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7777  return;
7778 
7779  // If the function template has a non-dependent explicit specification,
7780  // exclude it now if appropriate; we are not permitted to perform deduction
7781  // and substitution in this case.
7782  if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7783  OverloadCandidate &Candidate = CandidateSet.addCandidate();
7784  Candidate.FoundDecl = FoundDecl;
7785  Candidate.Function = FunctionTemplate->getTemplatedDecl();
7786  Candidate.Viable = false;
7787  Candidate.FailureKind = ovl_fail_explicit;
7788  return;
7789  }
7790 
7791  // C++ [over.match.funcs]p7:
7792  // In each case where a candidate is a function template, candidate
7793  // function template specializations are generated using template argument
7794  // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7795  // candidate functions in the usual way.113) A given name can refer to one
7796  // or more function templates and also to a set of overloaded non-template
7797  // functions. In such a case, the candidate functions generated from each
7798  // function template are combined with the set of non-template candidate
7799  // functions.
7800  TemplateDeductionInfo Info(CandidateSet.getLocation(),
7801  FunctionTemplate->getTemplateDepth());
7802  FunctionDecl *Specialization = nullptr;
7803  ConversionSequenceList Conversions;
7805  FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7806  PartialOverloading, AggregateCandidateDeduction,
7807  /*ObjectType=*/QualType(),
7808  /*ObjectClassification=*/Expr::Classification(),
7809  [&](ArrayRef<QualType> ParamTypes) {
7811  FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7812  SuppressUserConversions, nullptr, QualType(), {}, PO);
7813  });
7815  OverloadCandidate &Candidate =
7816  CandidateSet.addCandidate(Conversions.size(), Conversions);
7817  Candidate.FoundDecl = FoundDecl;
7818  Candidate.Function = FunctionTemplate->getTemplatedDecl();
7819  Candidate.Viable = false;
7820  Candidate.RewriteKind =
7821  CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7822  Candidate.IsSurrogate = false;
7823  Candidate.IsADLCandidate = IsADLCandidate;
7824  // Ignore the object argument if there is one, since we don't have an object
7825  // type.
7826  Candidate.IgnoreObjectArgument =
7827  isa<CXXMethodDecl>(Candidate.Function) &&
7828  !isa<CXXConstructorDecl>(Candidate.Function);
7829  Candidate.ExplicitCallArguments = Args.size();
7832  else {
7833  Candidate.FailureKind = ovl_fail_bad_deduction;
7835  Info);
7836  }
7837  return;
7838  }
7839 
7840  // Add the function template specialization produced by template argument
7841  // deduction as a candidate.
7842  assert(Specialization && "Missing function template specialization?");
7844  Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7845  PartialOverloading, AllowExplicit,
7846  /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7848 }
7849 
7850 /// Check that implicit conversion sequences can be formed for each argument
7851 /// whose corresponding parameter has a non-dependent type, per DR1391's
7852 /// [temp.deduct.call]p10.
7854  FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7855  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7856  ConversionSequenceList &Conversions, bool SuppressUserConversions,
7857  CXXRecordDecl *ActingContext, QualType ObjectType,
7858  Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7859  // FIXME: The cases in which we allow explicit conversions for constructor
7860  // arguments never consider calling a constructor template. It's not clear
7861  // that is correct.
7862  const bool AllowExplicit = false;
7863 
7864  auto *FD = FunctionTemplate->getTemplatedDecl();
7865  auto *Method = dyn_cast<CXXMethodDecl>(FD);
7866  bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7867  unsigned ThisConversions = HasThisConversion ? 1 : 0;
7868 
7869  Conversions =
7870  CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7871 
7872  // Overload resolution is always an unevaluated context.
7875 
7876  // For a method call, check the 'this' conversion here too. DR1391 doesn't
7877  // require that, but this check should never result in a hard error, and
7878  // overload resolution is permitted to sidestep instantiations.
7879  if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7880  !ObjectType.isNull()) {
7881  unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7882  if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7883  !ParamTypes[0]->isDependentType()) {
7884  Conversions[ConvIdx] = TryObjectArgumentInitialization(
7885  *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7886  Method, ActingContext, /*InOverloadResolution=*/true,
7887  FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7888  : QualType());
7889  if (Conversions[ConvIdx].isBad())
7890  return true;
7891  }
7892  }
7893 
7894  unsigned Offset =
7895  Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7896 
7897  for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7898  I != N; ++I) {
7899  QualType ParamType = ParamTypes[I + Offset];
7900  if (!ParamType->isDependentType()) {
7901  unsigned ConvIdx;
7903  ConvIdx = Args.size() - 1 - I;
7904  assert(Args.size() + ThisConversions == 2 &&
7905  "number of args (including 'this') must be exactly 2 for "
7906  "reversed order");
7907  // For members, there would be only one arg 'Args[0]' whose ConvIdx
7908  // would also be 0. 'this' got ConvIdx = 1 previously.
7909  assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7910  } else {
7911  // For members, 'this' got ConvIdx = 0 previously.
7912  ConvIdx = ThisConversions + I;
7913  }
7914  Conversions[ConvIdx]
7915  = TryCopyInitialization(*this, Args[I], ParamType,
7916  SuppressUserConversions,
7917  /*InOverloadResolution=*/true,
7918  /*AllowObjCWritebackConversion=*/
7919  getLangOpts().ObjCAutoRefCount,
7920  AllowExplicit);
7921  if (Conversions[ConvIdx].isBad())
7922  return true;
7923  }
7924  }
7925 
7926  return false;
7927 }
7928 
7929 /// Determine whether this is an allowable conversion from the result
7930 /// of an explicit conversion operator to the expected type, per C++
7931 /// [over.match.conv]p1 and [over.match.ref]p1.
7932 ///
7933 /// \param ConvType The return type of the conversion function.
7934 ///
7935 /// \param ToType The type we are converting to.
7936 ///
7937 /// \param AllowObjCPointerConversion Allow a conversion from one
7938 /// Objective-C pointer to another.
7939 ///
7940 /// \returns true if the conversion is allowable, false otherwise.
7942  QualType ConvType, QualType ToType,
7943  bool AllowObjCPointerConversion) {
7944  QualType ToNonRefType = ToType.getNonReferenceType();
7945 
7946  // Easy case: the types are the same.
7947  if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7948  return true;
7949 
7950  // Allow qualification conversions.
7951  bool ObjCLifetimeConversion;
7952  if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7953  ObjCLifetimeConversion))
7954  return true;
7955 
7956  // If we're not allowed to consider Objective-C pointer conversions,
7957  // we're done.
7958  if (!AllowObjCPointerConversion)
7959  return false;
7960 
7961  // Is this an Objective-C pointer conversion?
7962  bool IncompatibleObjC = false;
7963  QualType ConvertedType;
7964  return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7965  IncompatibleObjC);
7966 }
7967 
7968 /// AddConversionCandidate - Add a C++ conversion function as a
7969 /// candidate in the candidate set (C++ [over.match.conv],
7970 /// C++ [over.match.copy]). From is the expression we're converting from,
7971 /// and ToType is the type that we're eventually trying to convert to
7972 /// (which may or may not be the same type as the type that the
7973 /// conversion function produces).
7975  CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7976  CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7977  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7978  bool AllowExplicit, bool AllowResultConversion) {
7979  assert(!Conversion->getDescribedFunctionTemplate() &&
7980  "Conversion function templates use AddTemplateConversionCandidate");
7981  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7982  if (!CandidateSet.isNewCandidate(Conversion))
7983  return;
7984 
7985  // If the conversion function has an undeduced return type, trigger its
7986  // deduction now.
7987  if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7988  if (DeduceReturnType(Conversion, From->getExprLoc()))
7989  return;
7990  ConvType = Conversion->getConversionType().getNonReferenceType();
7991  }
7992 
7993  // If we don't allow any conversion of the result type, ignore conversion
7994  // functions that don't convert to exactly (possibly cv-qualified) T.
7995  if (!AllowResultConversion &&
7996  !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7997  return;
7998 
7999  // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8000  // operator is only a candidate if its return type is the target type or
8001  // can be converted to the target type with a qualification conversion.
8002  //
8003  // FIXME: Include such functions in the candidate list and explain why we
8004  // can't select them.
8005  if (Conversion->isExplicit() &&
8006  !isAllowableExplicitConversion(*this, ConvType, ToType,
8007  AllowObjCConversionOnExplicit))
8008  return;
8009 
8010  // Overload resolution is always an unevaluated context.
8013 
8014  // Add this candidate
8015  OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8016  Candidate.FoundDecl = FoundDecl;
8017  Candidate.Function = Conversion;
8018  Candidate.IsSurrogate = false;
8019  Candidate.IgnoreObjectArgument = false;
8021  Candidate.FinalConversion.setFromType(ConvType);
8022  Candidate.FinalConversion.setAllToTypes(ToType);
8023  Candidate.Viable = true;
8024  Candidate.ExplicitCallArguments = 1;
8025 
8026  // Explicit functions are not actually candidates at all if we're not
8027  // allowing them in this context, but keep them around so we can point
8028  // to them in diagnostics.
8029  if (!AllowExplicit && Conversion->isExplicit()) {
8030  Candidate.Viable = false;
8031  Candidate.FailureKind = ovl_fail_explicit;
8032  return;
8033  }
8034 
8035  // C++ [over.match.funcs]p4:
8036  // For conversion functions, the function is considered to be a member of
8037  // the class of the implicit implied object argument for the purpose of
8038  // defining the type of the implicit object parameter.
8039  //
8040  // Determine the implicit conversion sequence for the implicit
8041  // object parameter.
8042  QualType ObjectType = From->getType();
8043  if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8044  ObjectType = FromPtrType->getPointeeType();
8045  const auto *ConversionContext =
8046  cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8047 
8048  // C++23 [over.best.ics.general]
8049  // However, if the target is [...]
8050  // - the object parameter of a user-defined conversion function
8051  // [...] user-defined conversion sequences are not considered.
8053  *this, CandidateSet.getLocation(), From->getType(),
8054  From->Classify(Context), Conversion, ConversionContext,
8055  /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8056  /*SuppressUserConversion*/ true);
8057 
8058  if (Candidate.Conversions[0].isBad()) {
8059  Candidate.Viable = false;
8061  return;
8062  }
8063 
8064  if (Conversion->getTrailingRequiresClause()) {
8065  ConstraintSatisfaction Satisfaction;
8066  if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8067  !Satisfaction.IsSatisfied) {
8068  Candidate.Viable = false;
8070  return;
8071  }
8072  }
8073 
8074  // We won't go through a user-defined type conversion function to convert a
8075  // derived to base as such conversions are given Conversion Rank. They only
8076  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8077  QualType FromCanon
8080  if (FromCanon == ToCanon ||
8081  IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8082  Candidate.Viable = false;
8084  return;
8085  }
8086 
8087  // To determine what the conversion from the result of calling the
8088  // conversion function to the type we're eventually trying to
8089  // convert to (ToType), we need to synthesize a call to the
8090  // conversion function and attempt copy initialization from it. This
8091  // makes sure that we get the right semantics with respect to
8092  // lvalues/rvalues and the type. Fortunately, we can allocate this
8093  // call on the stack and we don't need its arguments to be
8094  // well-formed.
8095  DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8096  VK_LValue, From->getBeginLoc());
8098  Context.getPointerType(Conversion->getType()),
8099  CK_FunctionToPointerDecay, &ConversionRef,
8101 
8102  QualType ConversionType = Conversion->getConversionType();
8103  if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8104  Candidate.Viable = false;
8106  return;
8107  }
8108 
8109  ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8110 
8111  // Note that it is safe to allocate CallExpr on the stack here because
8112  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8113  // allocator).
8114  QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8115 
8116  alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8117  CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8118  Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8119 
8121  TryCopyInitialization(*this, TheTemporaryCall, ToType,
8122  /*SuppressUserConversions=*/true,
8123  /*InOverloadResolution=*/false,
8124  /*AllowObjCWritebackConversion=*/false);
8125 
8126  switch (ICS.getKind()) {
8128  Candidate.FinalConversion = ICS.Standard;
8129 
8130  // C++ [over.ics.user]p3:
8131  // If the user-defined conversion is specified by a specialization of a
8132  // conversion function template, the second standard conversion sequence
8133  // shall have exact match rank.
8134  if (Conversion->getPrimaryTemplate() &&
8136  Candidate.Viable = false;
8138  return;
8139  }
8140 
8141  // C++0x [dcl.init.ref]p5:
8142  // In the second case, if the reference is an rvalue reference and
8143  // the second standard conversion sequence of the user-defined
8144  // conversion sequence includes an lvalue-to-rvalue conversion, the
8145  // program is ill-formed.
8146  if (ToType->isRValueReferenceType() &&
8148  Candidate.Viable = false;
8150  return;
8151  }
8152  break;
8153 
8155  Candidate.Viable = false;
8157  return;
8158 
8159  default:
8160  llvm_unreachable(
8161  "Can only end up with a standard conversion sequence or failure");
8162  }
8163 
8164  if (EnableIfAttr *FailedAttr =
8165  CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8166  Candidate.Viable = false;
8167  Candidate.FailureKind = ovl_fail_enable_if;
8168  Candidate.DeductionFailure.Data = FailedAttr;
8169  return;
8170  }
8171 
8172  if (isNonViableMultiVersionOverload(Conversion)) {
8173  Candidate.Viable = false;
8175  }
8176 }
8177 
8178 /// Adds a conversion function template specialization
8179 /// candidate to the overload set, using template argument deduction
8180 /// to deduce the template arguments of the conversion function
8181 /// template from the type that we are converting to (C++
8182 /// [temp.deduct.conv]).
8184  FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8185  CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8186  OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8187  bool AllowExplicit, bool AllowResultConversion) {
8188  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8189  "Only conversion function templates permitted here");
8190 
8191  if (!CandidateSet.isNewCandidate(FunctionTemplate))
8192  return;
8193 
8194  // If the function template has a non-dependent explicit specification,
8195  // exclude it now if appropriate; we are not permitted to perform deduction
8196  // and substitution in this case.
8197  if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8198  OverloadCandidate &Candidate = CandidateSet.addCandidate();
8199  Candidate.FoundDecl = FoundDecl;
8200  Candidate.Function = FunctionTemplate->getTemplatedDecl();
8201  Candidate.Viable = false;
8202  Candidate.FailureKind = ovl_fail_explicit;
8203  return;
8204  }
8205 
8206  QualType ObjectType = From->getType();
8207  Expr::Classification ObjectClassification = From->Classify(getASTContext());
8208 
8209  TemplateDeductionInfo Info(CandidateSet.getLocation());
8210  CXXConversionDecl *Specialization = nullptr;
8212  FunctionTemplate, ObjectType, ObjectClassification, ToType,
8213  Specialization, Info);
8215  OverloadCandidate &Candidate = CandidateSet.addCandidate();
8216  Candidate.FoundDecl = FoundDecl;
8217  Candidate.Function = FunctionTemplate->getTemplatedDecl();
8218  Candidate.Viable = false;
8219  Candidate.FailureKind = ovl_fail_bad_deduction;
8220  Candidate.IsSurrogate = false;
8221  Candidate.IgnoreObjectArgument = false;
8222  Candidate.ExplicitCallArguments = 1;
8224  Info);
8225  return;
8226  }
8227 
8228  // Add the conversion function template specialization produced by
8229  // template argument deduction as a candidate.
8230  assert(Specialization && "Missing function template specialization?");
8231  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8232  CandidateSet, AllowObjCConversionOnExplicit,
8233  AllowExplicit, AllowResultConversion);
8234 }
8235 
8236 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8237 /// converts the given @c Object to a function pointer via the
8238 /// conversion function @c Conversion, and then attempts to call it
8239 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
8240 /// the type of function that we'll eventually be calling.
8242  DeclAccessPair FoundDecl,
8243  CXXRecordDecl *ActingContext,
8244  const FunctionProtoType *Proto,
8245  Expr *Object,
8246  ArrayRef<Expr *> Args,
8247  OverloadCandidateSet& CandidateSet) {
8248  if (!CandidateSet.isNewCandidate(Conversion))
8249  return;
8250 
8251  // Overload resolution is always an unevaluated context.
8254 
8255  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8256  Candidate.FoundDecl = FoundDecl;
8257  Candidate.Function = nullptr;
8258  Candidate.Surrogate = Conversion;
8259  Candidate.Viable = true;
8260  Candidate.IsSurrogate = true;
8261  Candidate.IgnoreObjectArgument = false;
8262  Candidate.ExplicitCallArguments = Args.size();
8263 
8264  // Determine the implicit conversion sequence for the implicit
8265  // object parameter.
8266  ImplicitConversionSequence ObjectInit;
8267  if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8268  ObjectInit = TryCopyInitialization(*this, Object,
8269  Conversion->getParamDecl(0)->getType(),
8270  /*SuppressUserConversions=*/false,
8271  /*InOverloadResolution=*/true, false);
8272  } else {
8273  ObjectInit = TryObjectArgumentInitialization(
8274  *this, CandidateSet.getLocation(), Object->getType(),
8275  Object->Classify(Context), Conversion, ActingContext);
8276  }
8277 
8278  if (ObjectInit.isBad()) {
8279  Candidate.Viable = false;
8281  Candidate.Conversions[0] = ObjectInit;
8282  return;
8283  }
8284 
8285  // The first conversion is actually a user-defined conversion whose
8286  // first conversion is ObjectInit's standard conversion (which is
8287  // effectively a reference binding). Record it as such.
8288  Candidate.Conversions[0].setUserDefined();
8289  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8290  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8291  Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8292  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8293  Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8294  Candidate.Conversions[0].UserDefined.After
8295  = Candidate.Conversions[0].UserDefined.Before;
8296  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8297 
8298  // Find the
8299  unsigned NumParams = Proto->getNumParams();
8300 
8301  // (C++ 13.3.2p2): A candidate function having fewer than m
8302  // parameters is viable only if it has an ellipsis in its parameter
8303  // list (8.3.5).
8304  if (Args.size() > NumParams && !Proto->isVariadic()) {
8305  Candidate.Viable = false;
8307  return;
8308  }
8309 
8310  // Function types don't have any default arguments, so just check if
8311  // we have enough arguments.
8312  if (Args.size() < NumParams) {
8313  // Not enough arguments.
8314  Candidate.Viable = false;
8316  return;
8317  }
8318 
8319  // Determine the implicit conversion sequences for each of the
8320  // arguments.
8321  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8322  if (ArgIdx < NumParams) {
8323  // (C++ 13.3.2p3): for F to be a viable function, there shall
8324  // exist for each argument an implicit conversion sequence
8325  // (13.3.3.1) that converts that argument to the corresponding
8326  // parameter of F.
8327  QualType ParamType = Proto->getParamType(ArgIdx);
8328  Candidate.Conversions[ArgIdx + 1]
8329  = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8330  /*SuppressUserConversions=*/false,
8331  /*InOverloadResolution=*/false,
8332  /*AllowObjCWritebackConversion=*/
8333  getLangOpts().ObjCAutoRefCount);
8334  if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8335  Candidate.Viable = false;
8337  return;
8338  }
8339  } else {
8340  // (C++ 13.3.2p2): For the purposes of overload resolution, any
8341  // argument for which there is no corresponding parameter is
8342  // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8343  Candidate.Conversions[ArgIdx + 1].setEllipsis();
8344  }
8345  }
8346 
8347  if (Conversion->getTrailingRequiresClause()) {
8348  ConstraintSatisfaction Satisfaction;
8349  if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8350  /*ForOverloadResolution*/ true) ||
8351  !Satisfaction.IsSatisfied) {
8352  Candidate.Viable = false;
8354  return;
8355  }
8356  }
8357 
8358  if (EnableIfAttr *FailedAttr =
8359  CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
8360  Candidate.Viable = false;
8361  Candidate.FailureKind = ovl_fail_enable_if;
8362  Candidate.DeductionFailure.Data = FailedAttr;
8363  return;
8364  }
8365 }
8366 
8367 /// Add all of the non-member operator function declarations in the given
8368 /// function set to the overload candidate set.
8370  const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8371  OverloadCandidateSet &CandidateSet,
8372  TemplateArgumentListInfo *ExplicitTemplateArgs) {
8373  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8374  NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8375  ArrayRef<Expr *> FunctionArgs = Args;
8376 
8377  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8378  FunctionDecl *FD =
8379  FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8380 
8381  // Don't consider rewritten functions if we're not rewriting.
8382  if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8383  continue;
8384 
8385  assert(!isa<CXXMethodDecl>(FD) &&
8386  "unqualified operator lookup found a member function");
8387 
8388  if (FunTmpl) {
8389  AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8390  FunctionArgs, CandidateSet);
8391  if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8393  FunTmpl, F.getPair(), ExplicitTemplateArgs,
8394  {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8396  } else {
8397  if (ExplicitTemplateArgs)
8398  continue;
8399  AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8400  if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8402  FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8403  false, false, true, false, ADLCallKind::NotADL, std::nullopt,
8405  }
8406  }
8407 }
8408 
8409 /// Add overload candidates for overloaded operators that are
8410 /// member functions.
8411 ///
8412 /// Add the overloaded operator candidates that are member functions
8413 /// for the operator Op that was used in an operator expression such
8414 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
8415 /// CandidateSet will store the added overload candidates. (C++
8416 /// [over.match.oper]).
8418  SourceLocation OpLoc,
8419  ArrayRef<Expr *> Args,
8420  OverloadCandidateSet &CandidateSet,
8423 
8424  // C++ [over.match.oper]p3:
8425  // For a unary operator @ with an operand of a type whose
8426  // cv-unqualified version is T1, and for a binary operator @ with
8427  // a left operand of a type whose cv-unqualified version is T1 and
8428  // a right operand of a type whose cv-unqualified version is T2,
8429  // three sets of candidate functions, designated member
8430  // candidates, non-member candidates and built-in candidates, are
8431  // constructed as follows:
8432  QualType T1 = Args[0]->getType();
8433 
8434  // -- If T1 is a complete class type or a class currently being
8435  // defined, the set of member candidates is the result of the
8436  // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8437  // the set of member candidates is empty.
8438  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8439  // Complete the type if it can be completed.
8440  if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8441  return;
8442  // If the type is neither complete nor being defined, bail out now.
8443  if (!T1Rec->getDecl()->getDefinition())
8444  return;
8445 
8446  LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8447  LookupQualifiedName(Operators, T1Rec->getDecl());
8448  Operators.suppressAccessDiagnostics();
8449 
8450  for (LookupResult::iterator Oper = Operators.begin(),
8451  OperEnd = Operators.end();
8452  Oper != OperEnd; ++Oper) {
8453  if (Oper->getAsFunction() &&
8455  !CandidateSet.getRewriteInfo().shouldAddReversed(
8456  *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8457  continue;
8458  AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8459  Args[0]->Classify(Context), Args.slice(1),
8460  CandidateSet, /*SuppressUserConversion=*/false, PO);
8461  }
8462  }
8463 }
8464 
8465 /// AddBuiltinCandidate - Add a candidate for a built-in
8466 /// operator. ResultTy and ParamTys are the result and parameter types
8467 /// of the built-in candidate, respectively. Args and NumArgs are the
8468 /// arguments being passed to the candidate. IsAssignmentOperator
8469 /// should be true when this built-in candidate is an assignment
8470 /// operator. NumContextualBoolArguments is the number of arguments
8471 /// (at the beginning of the argument list) that will be contextually
8472 /// converted to bool.
8474  OverloadCandidateSet& CandidateSet,
8475  bool IsAssignmentOperator,
8476  unsigned NumContextualBoolArguments) {
8477  // Overload resolution is always an unevaluated context.
8480 
8481  // Add this candidate
8482  OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8483  Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8484  Candidate.Function = nullptr;
8485  Candidate.IsSurrogate = false;
8486  Candidate.IgnoreObjectArgument = false;
8487  std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8488 
8489  // Determine the implicit conversion sequences for each of the
8490  // arguments.
8491  Candidate.Viable = true;
8492  Candidate.ExplicitCallArguments = Args.size();
8493  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8494  // C++ [over.match.oper]p4:
8495  // For the built-in assignment operators, conversions of the
8496  // left operand are restricted as follows:
8497  // -- no temporaries are introduced to hold the left operand, and
8498  // -- no user-defined conversions are applied to the left
8499  // operand to achieve a type match with the left-most
8500  // parameter of a built-in candidate.
8501  //
8502  // We block these conversions by turning off user-defined
8503  // conversions, since that is the only way that initialization of
8504  // a reference to a non-class type can occur from something that
8505  // is not of the same type.
8506  if (ArgIdx < NumContextualBoolArguments) {
8507  assert(ParamTys[ArgIdx] == Context.BoolTy &&
8508  "Contextual conversion to bool requires bool type");
8509  Candidate.Conversions[ArgIdx]
8510  = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8511  } else {
8512  Candidate.Conversions[ArgIdx]
8513  = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8514  ArgIdx == 0 && IsAssignmentOperator,
8515  /*InOverloadResolution=*/false,
8516  /*AllowObjCWritebackConversion=*/
8517  getLangOpts().ObjCAutoRefCount);
8518  }
8519  if (Candidate.Conversions[ArgIdx].isBad()) {
8520  Candidate.Viable = false;
8522  break;
8523  }
8524  }
8525 }
8526 
8527 namespace {
8528 
8529 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8530 /// candidate operator functions for built-in operators (C++
8531 /// [over.built]). The types are separated into pointer types and
8532 /// enumeration types.
8533 class BuiltinCandidateTypeSet {
8534  /// TypeSet - A set of types.
8535  typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8536 
8537  /// PointerTypes - The set of pointer types that will be used in the
8538  /// built-in candidates.
8539  TypeSet PointerTypes;
8540 
8541  /// MemberPointerTypes - The set of member pointer types that will be
8542  /// used in the built-in candidates.
8543  TypeSet MemberPointerTypes;
8544 
8545  /// EnumerationTypes - The set of enumeration types that will be
8546  /// used in the built-in candidates.
8547  TypeSet EnumerationTypes;
8548 
8549  /// The set of vector types that will be used in the built-in
8550  /// candidates.
8551  TypeSet VectorTypes;
8552 
8553  /// The set of matrix types that will be used in the built-in
8554  /// candidates.
8555  TypeSet MatrixTypes;
8556 
8557  /// The set of _BitInt types that will be used in the built-in candidates.
8558  TypeSet BitIntTypes;
8559 
8560  /// A flag indicating non-record types are viable candidates
8561  bool HasNonRecordTypes;
8562 
8563  /// A flag indicating whether either arithmetic or enumeration types
8564  /// were present in the candidate set.
8565  bool HasArithmeticOrEnumeralTypes;
8566 
8567  /// A flag indicating whether the nullptr type was present in the
8568  /// candidate set.
8569  bool HasNullPtrType;
8570 
8571  /// Sema - The semantic analysis instance where we are building the
8572  /// candidate type set.
8573  Sema &SemaRef;
8574 
8575  /// Context - The AST context in which we will build the type sets.
8577 
8578  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8579  const Qualifiers &VisibleQuals);
8580  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8581 
8582 public:
8583  /// iterator - Iterates through the types that are part of the set.
8584  typedef TypeSet::iterator iterator;
8585 
8586  BuiltinCandidateTypeSet(Sema &SemaRef)
8587  : HasNonRecordTypes(false),
8588  HasArithmeticOrEnumeralTypes(false),
8589  HasNullPtrType(false),
8590  SemaRef(SemaRef),
8591  Context(SemaRef.Context) { }
8592 
8593  void AddTypesConvertedFrom(QualType Ty,
8595  bool AllowUserConversions,
8596  bool AllowExplicitConversions,
8597  const Qualifiers &VisibleTypeConversionsQuals);
8598 
8599  llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8600  llvm::iterator_range<iterator> member_pointer_types() {
8601  return MemberPointerTypes;
8602  }
8603  llvm::iterator_range<iterator> enumeration_types() {
8604  return EnumerationTypes;
8605  }
8606  llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8607  llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8608  llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8609 
8610  bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8611  bool hasNonRecordTypes() { return HasNonRecordTypes; }
8612  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8613  bool hasNullPtrType() const { return HasNullPtrType; }
8614 };
8615 
8616 } // end anonymous namespace
8617 
8618 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8619 /// the set of pointer types along with any more-qualified variants of
8620 /// that type. For example, if @p Ty is "int const *", this routine
8621 /// will add "int const *", "int const volatile *", "int const
8622 /// restrict *", and "int const volatile restrict *" to the set of
8623 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8624 /// false otherwise.
8625 ///
8626 /// FIXME: what to do about extended qualifiers?
8627 bool
8628 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8629  const Qualifiers &VisibleQuals) {
8630 
8631  // Insert this type.
8632  if (!PointerTypes.insert(Ty))
8633  return false;
8634 
8635  QualType PointeeTy;
8636  const PointerType *PointerTy = Ty->getAs<PointerType>();
8637  bool buildObjCPtr = false;
8638  if (!PointerTy) {
8640  PointeeTy = PTy->getPointeeType();
8641  buildObjCPtr = true;
8642  } else {
8643  PointeeTy = PointerTy->getPointeeType();
8644  }
8645 
8646  // Don't add qualified variants of arrays. For one, they're not allowed
8647  // (the qualifier would sink to the element type), and for another, the
8648  // only overload situation where it matters is subscript or pointer +- int,
8649  // and those shouldn't have qualifier variants anyway.
8650  if (PointeeTy->isArrayType())
8651  return true;
8652 
8653  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8654  bool hasVolatile = VisibleQuals.hasVolatile();
8655  bool hasRestrict = VisibleQuals.hasRestrict();
8656 
8657  // Iterate through all strict supersets of BaseCVR.
8658  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8659  if ((CVR | BaseCVR) != CVR) continue;
8660  // Skip over volatile if no volatile found anywhere in the types.
8661  if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8662 
8663  // Skip over restrict if no restrict found anywhere in the types, or if
8664  // the type cannot be restrict-qualified.
8665  if ((CVR & Qualifiers::Restrict) &&
8666  (!hasRestrict ||
8667  (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8668  continue;
8669 
8670  // Build qualified pointee type.
8671  QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8672 
8673  // Build qualified pointer type.
8674  QualType QPointerTy;
8675  if (!buildObjCPtr)
8676  QPointerTy = Context.getPointerType(QPointeeTy);
8677  else
8678  QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8679 
8680  // Insert qualified pointer type.
8681  PointerTypes.insert(QPointerTy);
8682  }
8683 
8684  return true;
8685 }
8686 
8687 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8688 /// to the set of pointer types along with any more-qualified variants of
8689 /// that type. For example, if @p Ty is "int const *", this routine
8690 /// will add "int const *", "int const volatile *", "int const
8691 /// restrict *", and "int const volatile restrict *" to the set of
8692 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8693 /// false otherwise.
8694 ///
8695 /// FIXME: what to do about extended qualifiers?
8696 bool
8697 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8698  QualType Ty) {
8699  // Insert this type.
8700  if (!MemberPointerTypes.insert(Ty))
8701  return false;
8702 
8703  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8704  assert(PointerTy && "type was not a member pointer type!");
8705 
8706  QualType PointeeTy = PointerTy->getPointeeType();
8707  // Don't add qualified variants of arrays. For one, they're not allowed
8708  // (the qualifier would sink to the element type), and for another, the
8709  // only overload situation where it matters is subscript or pointer +- int,
8710  // and those shouldn't have qualifier variants anyway.
8711  if (PointeeTy->isArrayType())
8712  return true;
8713  const Type *ClassTy = PointerTy->getClass();
8714 
8715  // Iterate through all strict supersets of the pointee type's CVR
8716  // qualifiers.
8717  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8718  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8719  if ((CVR | BaseCVR) != CVR) continue;
8720 
8721  QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8722  MemberPointerTypes.insert(
8723  Context.getMemberPointerType(QPointeeTy, ClassTy));
8724  }
8725 
8726  return true;
8727 }
8728 
8729 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8730 /// Ty can be implicit converted to the given set of @p Types. We're
8731 /// primarily interested in pointer types and enumeration types. We also
8732 /// take member pointer types, for the conditional operator.
8733 /// AllowUserConversions is true if we should look at the conversion
8734 /// functions of a class type, and AllowExplicitConversions if we
8735 /// should also include the explicit conversion functions of a class
8736 /// type.
8737 void
8738 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8740  bool AllowUserConversions,
8741  bool AllowExplicitConversions,
8742  const Qualifiers &VisibleQuals) {
8743  // Only deal with canonical types.
8744  Ty = Context.getCanonicalType(Ty);
8745 
8746  // Look through reference types; they aren't part of the type of an
8747  // expression for the purposes of conversions.
8748  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8749  Ty = RefTy->getPointeeType();
8750 
8751  // If we're dealing with an array type, decay to the pointer.
8752  if (Ty->isArrayType())
8754 
8755  // Otherwise, we don't care about qualifiers on the type.
8756  Ty = Ty.getLocalUnqualifiedType();
8757 
8758  // Flag if we ever add a non-record type.
8759  const RecordType *TyRec = Ty->getAs<RecordType>();
8760  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8761 
8762  // Flag if we encounter an arithmetic type.
8763  HasArithmeticOrEnumeralTypes =
8764  HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8765 
8766  if (Ty->isObjCIdType() || Ty->isObjCClassType())
8767  PointerTypes.insert(Ty);
8768  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8769  // Insert our type, and its more-qualified variants, into the set
8770  // of types.
8771  if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8772  return;
8773  } else if (Ty->isMemberPointerType()) {
8774  // Member pointers are far easier, since the pointee can't be converted.
8775  if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8776  return;
8777  } else if (Ty->isEnumeralType()) {
8778  HasArithmeticOrEnumeralTypes = true;
8779  EnumerationTypes.insert(Ty);
8780  } else if (Ty->isBitIntType()) {
8781  HasArithmeticOrEnumeralTypes = true;
8782  BitIntTypes.insert(Ty);
8783  } else if (Ty->isVectorType()) {
8784  // We treat vector types as arithmetic types in many contexts as an
8785  // extension.
8786  HasArithmeticOrEnumeralTypes = true;
8787  VectorTypes.insert(Ty);
8788  } else if (Ty->isMatrixType()) {
8789  // Similar to vector types, we treat vector types as arithmetic types in
8790  // many contexts as an extension.
8791  HasArithmeticOrEnumeralTypes = true;
8792  MatrixTypes.insert(Ty);
8793  } else if (Ty->isNullPtrType()) {
8794  HasNullPtrType = true;
8795  } else if (AllowUserConversions && TyRec) {
8796  // No conversion functions in incomplete types.
8797  if (!SemaRef.isCompleteType(Loc, Ty))
8798  return;
8799 
8800  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8801  for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8802  if (isa<UsingShadowDecl>(D))
8803  D = cast<UsingShadowDecl>(D)->getTargetDecl();
8804 
8805  // Skip conversion function templates; they don't tell us anything
8806  // about which builtin types we can convert to.
8807  if (isa<FunctionTemplateDecl>(D))
8808  continue;
8809 
8810  CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8811  if (AllowExplicitConversions || !Conv->isExplicit()) {
8812  AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8813  VisibleQuals);
8814  }
8815  }
8816  }
8817 }
8818 /// Helper function for adjusting address spaces for the pointer or reference
8819 /// operands of builtin operators depending on the argument.
8821  Expr *Arg) {
8823 }
8824 
8825 /// Helper function for AddBuiltinOperatorCandidates() that adds
8826 /// the volatile- and non-volatile-qualified assignment operators for the
8827 /// given type to the candidate set.
8829  QualType T,
8830  ArrayRef<Expr *> Args,
8831  OverloadCandidateSet &CandidateSet) {
8832  QualType ParamTypes[2];
8833 
8834  // T& operator=(T&, T)
8835  ParamTypes[0] = S.Context.getLValueReferenceType(
8837  ParamTypes[1] = T;
8838  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8839  /*IsAssignmentOperator=*/true);
8840 
8842  // volatile T& operator=(volatile T&, T)
8843  ParamTypes[0] = S.Context.getLValueReferenceType(
8845  Args[0]));
8846  ParamTypes[1] = T;
8847  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8848  /*IsAssignmentOperator=*/true);
8849  }
8850 }
8851 
8852 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8853 /// if any, found in visible type conversion functions found in ArgExpr's type.
8855  Qualifiers VRQuals;
8856  const RecordType *TyRec;
8857  if (const MemberPointerType *RHSMPType =
8858  ArgExpr->getType()->getAs<MemberPointerType>())
8859  TyRec = RHSMPType->getClass()->getAs<RecordType>();
8860  else
8861  TyRec = ArgExpr->getType()->getAs<RecordType>();
8862  if (!TyRec) {
8863  // Just to be safe, assume the worst case.
8864  VRQuals.addVolatile();
8865  VRQuals.addRestrict();
8866  return VRQuals;
8867  }
8868 
8869  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8870  if (!ClassDecl->hasDefinition())
8871  return VRQuals;
8872 
8873  for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8874  if (isa<UsingShadowDecl>(D))
8875  D = cast<UsingShadowDecl>(D)->getTargetDecl();
8876  if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8877  QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8878  if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8879  CanTy = ResTypeRef->getPointeeType();
8880  // Need to go down the pointer/mempointer chain and add qualifiers
8881  // as see them.
8882  bool done = false;
8883  while (!done) {
8884  if (CanTy.isRestrictQualified())
8885  VRQuals.addRestrict();
8886  if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8887  CanTy = ResTypePtr->getPointeeType();
8888  else if (const MemberPointerType *ResTypeMPtr =
8889  CanTy->getAs<MemberPointerType>())
8890  CanTy = ResTypeMPtr->getPointeeType();
8891  else
8892  done = true;
8893  if (CanTy.isVolatileQualified())
8894  VRQuals.addVolatile();
8895  if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8896  return VRQuals;
8897  }
8898  }
8899  }
8900  return VRQuals;
8901 }
8902 
8903 // Note: We're currently only handling qualifiers that are meaningful for the
8904 // LHS of compound assignment overloading.
8906  QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8907  llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8908  // _Atomic
8909  if (Available.hasAtomic()) {
8910  Available.removeAtomic();
8911  forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8912  forAllQualifierCombinationsImpl(Available, Applied, Callback);
8913  return;
8914  }
8915 
8916  // volatile
8917  if (Available.hasVolatile()) {
8918  Available.removeVolatile();
8919  assert(!Applied.hasVolatile());
8920  forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8921  Callback);
8922  forAllQualifierCombinationsImpl(Available, Applied, Callback);
8923  return;
8924  }
8925 
8926  Callback(Applied);
8927 }
8928 
8930  QualifiersAndAtomic Quals,
8931  llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8933  Callback);
8934 }
8935 
8937  QualifiersAndAtomic Quals,
8938  Sema &S) {
8939  if (Quals.hasAtomic())
8941  if (Quals.hasVolatile())
8944 }
8945 
8946 namespace {
8947 
8948 /// Helper class to manage the addition of builtin operator overload
8949 /// candidates. It provides shared state and utility methods used throughout
8950 /// the process, as well as a helper method to add each group of builtin
8951 /// operator overloads from the standard to a candidate set.
8952 class BuiltinOperatorOverloadBuilder {
8953  // Common instance state available to all overload candidate addition methods.
8954  Sema &S;
8955  ArrayRef<Expr *> Args;
8956  QualifiersAndAtomic VisibleTypeConversionsQuals;
8957  bool HasArithmeticOrEnumeralCandidateType;
8959  OverloadCandidateSet &CandidateSet;
8960 
8961  static constexpr int ArithmeticTypesCap = 26;
8963 
8964  // Define some indices used to iterate over the arithmetic types in
8965  // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8966  // types are that preserved by promotion (C++ [over.built]p2).
8967  unsigned FirstIntegralType,
8968  LastIntegralType;
8969  unsigned FirstPromotedIntegralType,
8970  LastPromotedIntegralType;
8971  unsigned FirstPromotedArithmeticType,
8972  LastPromotedArithmeticType;
8973  unsigned NumArithmeticTypes;
8974 
8975  void InitArithmeticTypes() {
8976  // Start of promoted types.
8977  FirstPromotedArithmeticType = 0;
8978  ArithmeticTypes.push_back(S.Context.FloatTy);
8979  ArithmeticTypes.push_back(S.Context.DoubleTy);
8980  ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8982  ArithmeticTypes.push_back(S.Context.Float128Ty);
8984  ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8985 
8986  // Start of integral types.
8987  FirstIntegralType = ArithmeticTypes.size();
8988  FirstPromotedIntegralType = ArithmeticTypes.size();
8989  ArithmeticTypes.push_back(S.Context.IntTy);
8990  ArithmeticTypes.push_back(S.Context.LongTy);
8991  ArithmeticTypes.push_back(S.Context.LongLongTy);
8992  if (S.Context.getTargetInfo().hasInt128Type() ||
8993  (S.Context.getAuxTargetInfo() &&
8995  ArithmeticTypes.push_back(S.Context.Int128Ty);
8996  ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8997  ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8998  ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8999  if (S.Context.getTargetInfo().hasInt128Type() ||
9000  (S.Context.getAuxTargetInfo() &&
9002  ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9003 
9004  /// We add candidates for the unique, unqualified _BitInt types present in
9005  /// the candidate type set. The candidate set already handled ensuring the
9006  /// type is unqualified and canonical, but because we're adding from N
9007  /// different sets, we need to do some extra work to unique things. Insert
9008  /// the candidates into a unique set, then move from that set into the list
9009  /// of arithmetic types.
9010  llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9011  llvm::for_each(CandidateTypes, [&BitIntCandidates](
9012  BuiltinCandidateTypeSet &Candidate) {
9013  for (QualType BitTy : Candidate.bitint_types())
9014  BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9015  });
9016  llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9017  LastPromotedIntegralType = ArithmeticTypes.size();
9018  LastPromotedArithmeticType = ArithmeticTypes.size();
9019  // End of promoted types.
9020 
9021  ArithmeticTypes.push_back(S.Context.BoolTy);
9022  ArithmeticTypes.push_back(S.Context.CharTy);
9023  ArithmeticTypes.push_back(S.Context.WCharTy);
9024  if (S.Context.getLangOpts().Char8)
9025  ArithmeticTypes.push_back(S.Context.Char8Ty);
9026  ArithmeticTypes.push_back(S.Context.Char16Ty);
9027  ArithmeticTypes.push_back(S.Context.Char32Ty);
9028  ArithmeticTypes.push_back(S.Context.SignedCharTy);
9029  ArithmeticTypes.push_back(S.Context.ShortTy);
9030  ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9031  ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9032  LastIntegralType = ArithmeticTypes.size();
9033  NumArithmeticTypes = ArithmeticTypes.size();
9034  // End of integral types.
9035  // FIXME: What about complex? What about half?
9036 
9037  // We don't know for sure how many bit-precise candidates were involved, so
9038  // we subtract those from the total when testing whether we're under the
9039  // cap or not.
9040  assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9041  ArithmeticTypesCap &&
9042  "Enough inline storage for all arithmetic types.");
9043  }
9044 
9045  /// Helper method to factor out the common pattern of adding overloads
9046  /// for '++' and '--' builtin operators.
9047  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9048  bool HasVolatile,
9049  bool HasRestrict) {
9050  QualType ParamTypes[2] = {
9051  S.Context.getLValueReferenceType(CandidateTy),
9052  S.Context.IntTy
9053  };
9054 
9055  // Non-volatile version.
9056  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9057 
9058  // Use a heuristic to reduce number of builtin candidates in the set:
9059  // add volatile version only if there are conversions to a volatile type.
9060  if (HasVolatile) {
9061  ParamTypes[0] =
9063  S.Context.getVolatileType(CandidateTy));
9064  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9065  }
9066 
9067  // Add restrict version only if there are conversions to a restrict type
9068  // and our candidate type is a non-restrict-qualified pointer.
9069  if (HasRestrict && CandidateTy->isAnyPointerType() &&
9070  !CandidateTy.isRestrictQualified()) {
9071  ParamTypes[0]
9074  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9075 
9076  if (HasVolatile) {
9077  ParamTypes[0]
9079  S.Context.getCVRQualifiedType(CandidateTy,
9082  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9083  }
9084  }
9085 
9086  }
9087 
9088  /// Helper to add an overload candidate for a binary builtin with types \p L
9089  /// and \p R.
9090  void AddCandidate(QualType L, QualType R) {
9091  QualType LandR[2] = {L, R};
9092  S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9093  }
9094 
9095 public:
9096  BuiltinOperatorOverloadBuilder(
9097  Sema &S, ArrayRef<Expr *> Args,
9098  QualifiersAndAtomic VisibleTypeConversionsQuals,
9099  bool HasArithmeticOrEnumeralCandidateType,
9101  OverloadCandidateSet &CandidateSet)
9102  : S(S), Args(Args),
9103  VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9104  HasArithmeticOrEnumeralCandidateType(
9105  HasArithmeticOrEnumeralCandidateType),
9106  CandidateTypes(CandidateTypes),
9107  CandidateSet(CandidateSet) {
9108 
9109  InitArithmeticTypes();
9110  }
9111 
9112  // Increment is deprecated for bool since C++17.
9113  //
9114  // C++ [over.built]p3:
9115  //
9116  // For every pair (T, VQ), where T is an arithmetic type other
9117  // than bool, and VQ is either volatile or empty, there exist
9118  // candidate operator functions of the form
9119  //
9120  // VQ T& operator++(VQ T&);
9121  // T operator++(VQ T&, int);
9122  //
9123  // C++ [over.built]p4:
9124  //
9125  // For every pair (T, VQ), where T is an arithmetic type other
9126  // than bool, and VQ is either volatile or empty, there exist
9127  // candidate operator functions of the form
9128  //
9129  // VQ T& operator--(VQ T&);
9130  // T operator--(VQ T&, int);
9131  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9132  if (!HasArithmeticOrEnumeralCandidateType)
9133  return;
9134 
9135  for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9136  const auto TypeOfT = ArithmeticTypes[Arith];
9137  if (TypeOfT == S.Context.BoolTy) {
9138  if (Op == OO_MinusMinus)
9139  continue;
9140  if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9141  continue;
9142  }
9143  addPlusPlusMinusMinusStyleOverloads(
9144  TypeOfT,
9145  VisibleTypeConversionsQuals.hasVolatile(),
9146  VisibleTypeConversionsQuals.hasRestrict());
9147  }
9148  }
9149 
9150  // C++ [over.built]p5:
9151  //
9152  // For every pair (T, VQ), where T is a cv-qualified or
9153  // cv-unqualified object type, and VQ is either volatile or
9154  // empty, there exist candidate operator functions of the form
9155  //
9156  // T*VQ& operator++(T*VQ&);
9157  // T*VQ& operator--(T*VQ&);
9158  // T* operator++(T*VQ&, int);
9159  // T* operator--(T*VQ&, int);
9160  void addPlusPlusMinusMinusPointerOverloads() {
9161  for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9162  // Skip pointer types that aren't pointers to object types.
9163  if (!PtrTy->getPointeeType()->isObjectType())
9164  continue;
9165 
9166  addPlusPlusMinusMinusStyleOverloads(
9167  PtrTy,
9168  (!PtrTy.isVolatileQualified() &&
9169  VisibleTypeConversionsQuals.hasVolatile()),
9170  (!PtrTy.isRestrictQualified() &&
9171  VisibleTypeConversionsQuals.hasRestrict()));
9172  }
9173  }
9174 
9175  // C++ [over.built]p6:
9176  // For every cv-qualified or cv-unqualified object type T, there
9177  // exist candidate operator functions of the form
9178  //
9179  // T& operator*(T*);
9180  //
9181  // C++ [over.built]p7:
9182  // For every function type T that does not have cv-qualifiers or a
9183  // ref-qualifier, there exist candidate operator functions of the form
9184  // T& operator*(T*);
9185  void addUnaryStarPointerOverloads() {
9186  for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9187  QualType PointeeTy = ParamTy->getPointeeType();
9188  if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9189  continue;
9190 
9191  if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9192  if (Proto->getMethodQuals() || Proto->getRefQualifier())
9193  continue;
9194 
9195  S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9196  }
9197  }
9198 
9199  // C++ [over.built]p9:
9200  // For every promoted arithmetic type T, there exist candidate
9201  // operator functions of the form
9202  //
9203  // T operator+(T);
9204  // T operator-(T);
9205  void addUnaryPlusOrMinusArithmeticOverloads() {
9206  if (!HasArithmeticOrEnumeralCandidateType)
9207  return;
9208 
9209  for (unsigned Arith = FirstPromotedArithmeticType;
9210  Arith < LastPromotedArithmeticType; ++Arith) {
9211  QualType ArithTy = ArithmeticTypes[Arith];
9212  S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9213  }
9214 
9215  // Extension: We also add these operators for vector types.
9216  for (QualType VecTy : CandidateTypes[0].vector_types())
9217  S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9218  }
9219 
9220  // C++ [over.built]p8:
9221  // For every type T, there exist candidate operator functions of
9222  // the form
9223  //
9224  // T* operator+(T*);
9225  void addUnaryPlusPointerOverloads() {
9226  for (QualType ParamTy : CandidateTypes[0].pointer_types())
9227  S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9228  }
9229 
9230  // C++ [over.built]p10:
9231  // For every promoted integral type T, there exist candidate
9232  // operator functions of the form
9233  //
9234  // T operator~(T);
9235  void addUnaryTildePromotedIntegralOverloads() {
9236  if (!HasArithmeticOrEnumeralCandidateType)
9237  return;
9238 
9239  for (unsigned Int = FirstPromotedIntegralType;
9240  Int < LastPromotedIntegralType; ++Int) {
9241  QualType IntTy = ArithmeticTypes[Int];
9242  S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9243  }
9244 
9245  // Extension: We also add this operator for vector types.
9246  for (QualType VecTy : CandidateTypes[0].vector_types())
9247  S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9248  }
9249 
9250  // C++ [over.match.oper]p16:
9251  // For every pointer to member type T or type std::nullptr_t, there
9252  // exist candidate operator functions of the form
9253  //
9254  // bool operator==(T,T);
9255  // bool operator!=(T,T);
9256  void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9257  /// Set of (canonical) types that we've already handled.
9258  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9259 
9260  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9261  for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9262  // Don't add the same builtin candidate twice.
9263  if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9264  continue;
9265 
9266  QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9267  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9268  }
9269 
9270  if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9272  if (AddedTypes.insert(NullPtrTy).second) {
9273  QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9274  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9275  }
9276  }
9277  }
9278  }
9279 
9280  // C++ [over.built]p15:
9281  //
9282  // For every T, where T is an enumeration type or a pointer type,
9283  // there exist candidate operator functions of the form
9284  //
9285  // bool operator<(T, T);
9286  // bool operator>(T, T);
9287  // bool operator<=(T, T);
9288  // bool operator>=(T, T);
9289  // bool operator==(T, T);
9290  // bool operator!=(T, T);
9291  // R operator<=>(T, T)
9292  void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9293  // C++ [over.match.oper]p3:
9294  // [...]the built-in candidates include all of the candidate operator
9295  // functions defined in 13.6 that, compared to the given operator, [...]
9296  // do not have the same parameter-type-list as any non-template non-member
9297  // candidate.
9298  //
9299  // Note that in practice, this only affects enumeration types because there
9300  // aren't any built-in candidates of record type, and a user-defined operator
9301  // must have an operand of record or enumeration type. Also, the only other
9302  // overloaded operator with enumeration arguments, operator=,
9303  // cannot be overloaded for enumeration types, so this is the only place
9304  // where we must suppress candidates like this.
9306  UserDefinedBinaryOperators;
9307 
9308  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9309  if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9310  for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9311  CEnd = CandidateSet.end();
9312  C != CEnd; ++C) {
9313  if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9314  continue;
9315 
9316  if (C->Function->isFunctionTemplateSpecialization())
9317  continue;
9318 
9319  // We interpret "same parameter-type-list" as applying to the
9320  // "synthesized candidate, with the order of the two parameters
9321  // reversed", not to the original function.
9322  bool Reversed = C->isReversed();
9323  QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9324  ->getType()
9325  .getUnqualifiedType();
9326  QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9327  ->getType()
9328  .getUnqualifiedType();
9329 
9330  // Skip if either parameter isn't of enumeral type.
9331  if (!FirstParamType->isEnumeralType() ||
9332  !SecondParamType->isEnumeralType())
9333  continue;
9334 
9335  // Add this operator to the set of known user-defined operators.
9336  UserDefinedBinaryOperators.insert(
9337  std::make_pair(S.Context.getCanonicalType(FirstParamType),
9338  S.Context.getCanonicalType(SecondParamType)));
9339  }
9340  }
9341  }
9342 
9343  /// Set of (canonical) types that we've already handled.
9344  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9345 
9346  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9347  for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9348  // Don't add the same builtin candidate twice.
9349  if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9350  continue;
9351  if (IsSpaceship && PtrTy->isFunctionPointerType())
9352  continue;
9353 
9354  QualType ParamTypes[2] = {PtrTy, PtrTy};
9355  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9356  }
9357  for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9358  CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9359 
9360  // Don't add the same builtin candidate twice, or if a user defined
9361  // candidate exists.
9362  if (!AddedTypes.insert(CanonType).second ||
9363  UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9364  CanonType)))
9365  continue;
9366  QualType ParamTypes[2] = {EnumTy, EnumTy};
9367  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9368  }
9369  }
9370  }
9371 
9372  // C++ [over.built]p13:
9373  //
9374  // For every cv-qualified or cv-unqualified object type T
9375  // there exist candidate operator functions of the form
9376  //
9377  // T* operator+(T*, ptrdiff_t);
9378  // T& operator[](T*, ptrdiff_t); [BELOW]
9379  // T* operator-(T*, ptrdiff_t);
9380  // T* operator+(ptrdiff_t, T*);
9381  // T& operator[](ptrdiff_t, T*); [BELOW]
9382  //
9383  // C++ [over.built]p14:
9384  //
9385  // For every T, where T is a pointer to object type, there
9386  // exist candidate operator functions of the form
9387  //
9388  // ptrdiff_t operator-(T, T);
9389  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9390  /// Set of (canonical) types that we've already handled.
9391  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9392 
9393  for (int Arg = 0; Arg < 2; ++Arg) {
9394  QualType AsymmetricParamTypes[2] = {
9397  };
9398  for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9399  QualType PointeeTy = PtrTy->getPointeeType();
9400  if (!PointeeTy->isObjectType())
9401  continue;
9402 
9403  AsymmetricParamTypes[Arg] = PtrTy;
9404  if (Arg == 0 || Op == OO_Plus) {
9405  // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9406  // T* operator+(ptrdiff_t, T*);
9407  S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9408  }
9409  if (Op == OO_Minus) {
9410  // ptrdiff_t operator-(T, T);
9411  if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9412  continue;
9413 
9414  QualType ParamTypes[2] = {PtrTy, PtrTy};
9415  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9416  }
9417  }
9418  }
9419  }
9420 
9421  // C++ [over.built]p12:
9422  //
9423  // For every pair of promoted arithmetic types L and R, there
9424  // exist candidate operator functions of the form
9425  //
9426  // LR operator*(L, R);
9427  // LR operator/(L, R);
9428  // LR operator+(L, R);
9429  // LR operator-(L, R);
9430  // bool operator<(L, R);
9431  // bool operator>(L, R);
9432  // bool operator<=(L, R);
9433  // bool operator>=(L, R);
9434  // bool operator==(L, R);
9435  // bool operator!=(L, R);
9436  //
9437  // where LR is the result of the usual arithmetic conversions
9438  // between types L and R.
9439  //
9440  // C++ [over.built]p24:
9441  //
9442  // For every pair of promoted arithmetic types L and R, there exist
9443  // candidate operator functions of the form
9444  //
9445  // LR operator?(bool, L, R);
9446  //
9447  // where LR is the result of the usual arithmetic conversions
9448  // between types L and R.
9449  // Our candidates ignore the first parameter.
9450  void addGenericBinaryArithmeticOverloads() {
9451  if (!HasArithmeticOrEnumeralCandidateType)
9452  return;
9453 
9454  for (unsigned Left = FirstPromotedArithmeticType;
9455  Left < LastPromotedArithmeticType; ++Left) {
9456  for (unsigned Right = FirstPromotedArithmeticType;
9457  Right < LastPromotedArithmeticType; ++Right) {
9458  QualType LandR[2] = { ArithmeticTypes[Left],
9459  ArithmeticTypes[Right] };
9460  S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9461  }
9462  }
9463 
9464  // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9465  // conditional operator for vector types.
9466  for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9467  for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9468  QualType LandR[2] = {Vec1Ty, Vec2Ty};
9469  S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9470  }
9471  }
9472 
9473  /// Add binary operator overloads for each candidate matrix type M1, M2:
9474  /// * (M1, M1) -> M1
9475  /// * (M1, M1.getElementType()) -> M1
9476  /// * (M2.getElementType(), M2) -> M2
9477  /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9478  void addMatrixBinaryArithmeticOverloads() {
9479  if (!HasArithmeticOrEnumeralCandidateType)
9480  return;
9481 
9482  for (QualType M1 : CandidateTypes[0].matrix_types()) {
9483  AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9484  AddCandidate(M1, M1);
9485  }
9486 
9487  for (QualType M2 : CandidateTypes[1].matrix_types()) {
9488  AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9489  if (!CandidateTypes[0].containsMatrixType(M2))
9490  AddCandidate(M2, M2);
9491  }
9492  }
9493 
9494  // C++2a [over.built]p14:
9495  //
9496  // For every integral type T there exists a candidate operator function
9497  // of the form
9498  //
9499  // std::strong_ordering operator<=>(T, T)
9500  //
9501  // C++2a [over.built]p15:
9502  //
9503  // For every pair of floating-point types L and R, there exists a candidate
9504  // operator function of the form
9505  //
9506  // std::partial_ordering operator<=>(L, R);
9507  //
9508  // FIXME: The current specification for integral types doesn't play nice with
9509  // the direction of p0946r0, which allows mixed integral and unscoped-enum
9510  // comparisons. Under the current spec this can lead to ambiguity during
9511  // overload resolution. For example:
9512  //
9513  // enum A : int {a};
9514  // auto x = (a <=> (long)42);
9515  //
9516  // error: call is ambiguous for arguments 'A' and 'long'.
9517  // note: candidate operator<=>(int, int)
9518  // note: candidate operator<=>(long, long)
9519  //
9520  // To avoid this error, this function deviates from the specification and adds
9521  // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9522  // arithmetic types (the same as the generic relational overloads).
9523  //
9524  // For now this function acts as a placeholder.
9525  void addThreeWayArithmeticOverloads() {
9526  addGenericBinaryArithmeticOverloads();
9527  }
9528 
9529  // C++ [over.built]p17:
9530  //
9531  // For every pair of promoted integral types L and R, there
9532  // exist candidate operator functions of the form
9533  //
9534  // LR operator%(L, R);
9535  // LR operator&(L, R);
9536  // LR operator^(L, R);
9537  // LR operator|(L, R);
9538  // L operator<<(L, R);
9539  // L operator>>(L, R);
9540  //
9541  // where LR is the result of the usual arithmetic conversions
9542  // between types L and R.
9543  void addBinaryBitwiseArithmeticOverloads() {
9544  if (!HasArithmeticOrEnumeralCandidateType)
9545  return;
9546 
9547  for (unsigned Left = FirstPromotedIntegralType;
9548  Left < LastPromotedIntegralType; ++Left) {
9549  for (unsigned Right = FirstPromotedIntegralType;
9550  Right < LastPromotedIntegralType; ++Right) {
9551  QualType LandR[2] = { ArithmeticTypes[Left],
9552  ArithmeticTypes[Right] };
9553  S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9554  }
9555  }
9556  }
9557 
9558  // C++ [over.built]p20:
9559  //
9560  // For every pair (T, VQ), where T is an enumeration or
9561  // pointer to member type and VQ is either volatile or
9562  // empty, there exist candidate operator functions of the form
9563  //
9564  // VQ T& operator=(VQ T&, T);
9565  void addAssignmentMemberPointerOrEnumeralOverloads() {
9566  /// Set of (canonical) types that we've already handled.
9567  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9568 
9569  for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9570  for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9571  if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9572  continue;
9573 
9574  AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9575  }
9576 
9577  for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9578  if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9579  continue;
9580 
9581  AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9582  }
9583  }
9584  }
9585 
9586  // C++ [over.built]p19:
9587  //
9588  // For every pair (T, VQ), where T is any type and VQ is either
9589  // volatile or empty, there exist candidate operator functions
9590  // of the form
9591  //
9592  // T*VQ& operator=(T*VQ&, T*);
9593  //
9594  // C++ [over.built]p21:
9595  //
9596  // For every pair (T, VQ), where T is a cv-qualified or
9597  // cv-unqualified object type and VQ is either volatile or
9598  // empty, there exist candidate operator functions of the form
9599  //
9600  // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9601  // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9602  void addAssignmentPointerOverloads(bool isEqualOp) {
9603  /// Set of (canonical) types that we've already handled.
9604  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9605 
9606  for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9607  // If this is operator=, keep track of the builtin candidates we added.
9608  if (isEqualOp)
9609  AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9610  else if (!PtrTy->getPointeeType()->isObjectType())
9611  continue;
9612 
9613  // non-volatile version
9614  QualType ParamTypes[2] = {
9616  isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9617  };
9618  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9619  /*IsAssignmentOperator=*/ isEqualOp);
9620 
9621  bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9622  VisibleTypeConversionsQuals.hasVolatile();
9623  if (NeedVolatile) {
9624  // volatile version
9625  ParamTypes[0] =
9627  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9628  /*IsAssignmentOperator=*/isEqualOp);
9629  }
9630 
9631  if (!PtrTy.isRestrictQualified() &&
9632  VisibleTypeConversionsQuals.hasRestrict()) {
9633  // restrict version
9634  ParamTypes[0] =
9636  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9637  /*IsAssignmentOperator=*/isEqualOp);
9638 
9639  if (NeedVolatile) {
9640  // volatile restrict version
9641  ParamTypes[0] =
9644  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9645  /*IsAssignmentOperator=*/isEqualOp);
9646  }
9647  }
9648  }
9649 
9650  if (isEqualOp) {
9651  for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9652  // Make sure we don't add the same candidate twice.
9653  if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9654  continue;
9655 
9656  QualType ParamTypes[2] = {
9658  PtrTy,
9659  };
9660 
9661  // non-volatile version
9662  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9663  /*IsAssignmentOperator=*/true);
9664 
9665  bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9666  VisibleTypeConversionsQuals.hasVolatile();
9667  if (NeedVolatile) {
9668  // volatile version
9669  ParamTypes[0] = S.Context.getLValueReferenceType(
9670  S.Context.getVolatileType(PtrTy));
9671  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9672  /*IsAssignmentOperator=*/true);
9673  }
9674 
9675  if (!PtrTy.isRestrictQualified() &&
9676  VisibleTypeConversionsQuals.hasRestrict()) {
9677  // restrict version
9678  ParamTypes[0] = S.Context.getLValueReferenceType(
9679  S.Context.getRestrictType(PtrTy));
9680  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9681  /*IsAssignmentOperator=*/true);
9682 
9683  if (NeedVolatile) {
9684  // volatile restrict version
9685  ParamTypes[0] =
9688  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9689  /*IsAssignmentOperator=*/true);
9690  }
9691  }
9692  }
9693  }
9694  }
9695 
9696  // C++ [over.built]p18:
9697  //
9698  // For every triple (L, VQ, R), where L is an arithmetic type,
9699  // VQ is either volatile or empty, and R is a promoted
9700  // arithmetic type, there exist candidate operator functions of
9701  // the form
9702  //
9703  // VQ L& operator=(VQ L&, R);
9704  // VQ L& operator*=(VQ L&, R);
9705  // VQ L& operator/=(VQ L&, R);
9706  // VQ L& operator+=(VQ L&, R);
9707  // VQ L& operator-=(VQ L&, R);
9708  void addAssignmentArithmeticOverloads(bool isEqualOp) {
9709  if (!HasArithmeticOrEnumeralCandidateType)
9710  return;
9711 
9712  for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9713  for (unsigned Right = FirstPromotedArithmeticType;
9714  Right < LastPromotedArithmeticType; ++Right) {
9715  QualType ParamTypes[2];
9716  ParamTypes[1] = ArithmeticTypes[Right];
9717  auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9718  S, ArithmeticTypes[Left], Args[0]);
9719 
9721  VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9722  ParamTypes[0] =
9723  makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9724  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9725  /*IsAssignmentOperator=*/isEqualOp);
9726  });
9727  }
9728  }
9729 
9730  // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9731  for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9732  for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9733  QualType ParamTypes[2];
9734  ParamTypes[1] = Vec2Ty;
9735  // Add this built-in operator as a candidate (VQ is empty).
9736  ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9737  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9738  /*IsAssignmentOperator=*/isEqualOp);
9739 
9740  // Add this built-in operator as a candidate (VQ is 'volatile').
9741  if (VisibleTypeConversionsQuals.hasVolatile()) {
9742  ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9743  ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9744  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9745  /*IsAssignmentOperator=*/isEqualOp);
9746  }
9747  }
9748  }
9749 
9750  // C++ [over.built]p22:
9751  //
9752  // For every triple (L, VQ, R), where L is an integral type, VQ
9753  // is either volatile or empty, and R is a promoted integral
9754  // type, there exist candidate operator functions of the form
9755  //
9756  // VQ L& operator%=(VQ L&, R);
9757  // VQ L& operator<<=(VQ L&, R);
9758  // VQ L& operator>>=(VQ L&, R);
9759  // VQ L& operator&=(VQ L&, R);
9760  // VQ L& operator^=(VQ L&, R);
9761  // VQ L& operator|=(VQ L&, R);
9762  void addAssignmentIntegralOverloads() {
9763  if (!HasArithmeticOrEnumeralCandidateType)
9764  return;
9765 
9766  for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9767  for (unsigned Right = FirstPromotedIntegralType;
9768  Right < LastPromotedIntegralType; ++Right) {
9769  QualType ParamTypes[2];
9770  ParamTypes[1] = ArithmeticTypes[Right];
9771  auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9772  S, ArithmeticTypes[Left], Args[0]);
9773 
9775  VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9776  ParamTypes[0] =
9777  makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9778  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9779  });
9780  }
9781  }
9782  }
9783 
9784  // C++ [over.operator]p23:
9785  //
9786  // There also exist candidate operator functions of the form
9787  //
9788  // bool operator!(bool);
9789  // bool operator&&(bool, bool);
9790  // bool operator||(bool, bool);
9791  void addExclaimOverload() {
9792  QualType ParamTy = S.Context.BoolTy;
9793  S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9794  /*IsAssignmentOperator=*/false,
9795  /*NumContextualBoolArguments=*/1);
9796  }
9797  void addAmpAmpOrPipePipeOverload() {
9798  QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9799  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9800  /*IsAssignmentOperator=*/false,
9801  /*NumContextualBoolArguments=*/2);
9802  }
9803 
9804  // C++ [over.built]p13:
9805  //
9806  // For every cv-qualified or cv-unqualified object type T there
9807  // exist candidate operator functions of the form
9808  //
9809  // T* operator+(T*, ptrdiff_t); [ABOVE]
9810  // T& operator[](T*, ptrdiff_t);
9811  // T* operator-(T*, ptrdiff_t); [ABOVE]
9812  // T* operator+(ptrdiff_t, T*); [ABOVE]
9813  // T& operator[](ptrdiff_t, T*);
9814  void addSubscriptOverloads() {
9815  for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9816  QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9817  QualType PointeeType = PtrTy->getPointeeType();
9818  if (!PointeeType->isObjectType())
9819  continue;
9820 
9821  // T& operator[](T*, ptrdiff_t)
9822  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9823  }
9824 
9825  for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9826  QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9827  QualType PointeeType = PtrTy->getPointeeType();
9828  if (!PointeeType->isObjectType())
9829  continue;
9830 
9831  // T& operator[](ptrdiff_t, T*)
9832  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9833  }
9834  }
9835 
9836  // C++ [over.built]p11:
9837  // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9838  // C1 is the same type as C2 or is a derived class of C2, T is an object
9839  // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9840  // there exist candidate operator functions of the form
9841  //
9842  // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9843  //
9844  // where CV12 is the union of CV1 and CV2.
9845  void addArrowStarOverloads() {
9846  for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9847  QualType C1Ty = PtrTy;
9848  QualType C1;
9849  QualifierCollector Q1;
9850  C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9851  if (!isa<RecordType>(C1))
9852  continue;
9853  // heuristic to reduce number of builtin candidates in the set.
9854  // Add volatile/restrict version only if there are conversions to a
9855  // volatile/restrict type.
9856  if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9857  continue;
9858  if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9859  continue;
9860  for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9861  const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9862  QualType C2 = QualType(mptr->getClass(), 0);
9863  C2 = C2.getUnqualifiedType();
9864  if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9865  break;
9866  QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9867  // build CV12 T&
9868  QualType T = mptr->getPointeeType();
9869  if (!VisibleTypeConversionsQuals.hasVolatile() &&
9870  T.isVolatileQualified())
9871  continue;
9872  if (!VisibleTypeConversionsQuals.hasRestrict() &&
9873  T.isRestrictQualified())
9874  continue;
9875  T = Q1.apply(S.Context, T);
9876  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9877  }
9878  }
9879  }
9880 
9881  // Note that we don't consider the first argument, since it has been
9882  // contextually converted to bool long ago. The candidates below are
9883  // therefore added as binary.
9884  //
9885  // C++ [over.built]p25:
9886  // For every type T, where T is a pointer, pointer-to-member, or scoped
9887  // enumeration type, there exist candidate operator functions of the form
9888  //
9889  // T operator?(bool, T, T);
9890  //
9891  void addConditionalOperatorOverloads() {
9892  /// Set of (canonical) types that we've already handled.
9893  llvm::SmallPtrSet<QualType, 8> AddedTypes;
9894 
9895  for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9896  for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9897  if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9898  continue;
9899 
9900  QualType ParamTypes[2] = {PtrTy, PtrTy};
9901  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9902  }
9903 
9904  for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9905  if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9906  continue;
9907 
9908  QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9909  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9910  }
9911 
9912  if (S.getLangOpts().CPlusPlus11) {
9913  for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9914  if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9915  continue;
9916 
9917  if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9918  continue;
9919 
9920  QualType ParamTypes[2] = {EnumTy, EnumTy};
9921  S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9922  }
9923  }
9924  }
9925  }
9926 };
9927 
9928 } // end anonymous namespace
9929 
9930 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9931 /// operator overloads to the candidate set (C++ [over.built]), based
9932 /// on the operator @p Op and the arguments given. For example, if the
9933 /// operator is a binary '+', this routine might add "int
9934 /// operator+(int, int)" to cover integer addition.
9936  SourceLocation OpLoc,
9937  ArrayRef<Expr *> Args,
9938  OverloadCandidateSet &CandidateSet) {
9939  // Find all of the types that the arguments can convert to, but only
9940  // if the operator we're looking at has built-in operator candidates
9941  // that make use of these types. Also record whether we encounter non-record
9942  // candidate types or either arithmetic or enumeral candidate types.
9943  QualifiersAndAtomic VisibleTypeConversionsQuals;
9944  VisibleTypeConversionsQuals.addConst();
9945  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9946  VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9947  if (Args[ArgIdx]->getType()->isAtomicType())
9948  VisibleTypeConversionsQuals.addAtomic();
9949  }
9950 
9951  bool HasNonRecordCandidateType = false;
9952  bool HasArithmeticOrEnumeralCandidateType = false;
9954  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9955  CandidateTypes.emplace_back(*this);
9956  CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9957  OpLoc,
9958  true,
9959  (Op == OO_Exclaim ||
9960  Op == OO_AmpAmp ||
9961  Op == OO_PipePipe),
9962  VisibleTypeConversionsQuals);
9963  HasNonRecordCandidateType = HasNonRecordCandidateType ||
9964  CandidateTypes[ArgIdx].hasNonRecordTypes();
9965  HasArithmeticOrEnumeralCandidateType =
9966  HasArithmeticOrEnumeralCandidateType ||
9967  CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9968  }
9969 
9970  // Exit early when no non-record types have been added to the candidate set
9971  // for any of the arguments to the operator.
9972  //
9973  // We can't exit early for !, ||, or &&, since there we have always have
9974  // 'bool' overloads.
9975  if (!HasNonRecordCandidateType &&
9976  !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9977  return;
9978 
9979  // Setup an object to manage the common state for building overloads.
9980  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9981  VisibleTypeConversionsQuals,
9982  HasArithmeticOrEnumeralCandidateType,
9983  CandidateTypes, CandidateSet);
9984 
9985  // Dispatch over the operation to add in only those overloads which apply.
9986  switch (Op) {
9987  case OO_None:
9989  llvm_unreachable("Expected an overloaded operator");
9990 
9991  case OO_New:
9992  case OO_Delete:
9993  case OO_Array_New:
9994  case OO_Array_Delete:
9995  case OO_Call:
9996  llvm_unreachable(
9997  "Special operators don't use AddBuiltinOperatorCandidates");
9998 
9999  case OO_Comma:
10000  case OO_Arrow:
10001  case OO_Coawait:
10002  // C++ [over.match.oper]p3:
10003  // -- For the operator ',', the unary operator '&', the
10004  // operator '->', or the operator 'co_await', the
10005  // built-in candidates set is empty.
10006  break;
10007 
10008  case OO_Plus: // '+' is either unary or binary
10009  if (Args.size() == 1)
10010  OpBuilder.addUnaryPlusPointerOverloads();
10011  [[fallthrough]];
10012 
10013  case OO_Minus: // '-' is either unary or binary
10014  if (Args.size() == 1) {
10015  OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10016  } else {
10017  OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10018  OpBuilder.addGenericBinaryArithmeticOverloads();
10019  OpBuilder.addMatrixBinaryArithmeticOverloads();
10020  }
10021  break;
10022 
10023  case OO_Star: // '*' is either unary or binary
10024  if (Args.size() == 1)
10025  OpBuilder.addUnaryStarPointerOverloads();
10026  else {
10027  OpBuilder.addGenericBinaryArithmeticOverloads();
10028  OpBuilder.addMatrixBinaryArithmeticOverloads();
10029  }
10030  break;
10031 
10032  case OO_Slash:
10033  OpBuilder.addGenericBinaryArithmeticOverloads();
10034  break;
10035 
10036  case OO_PlusPlus:
10037  case OO_MinusMinus:
10038  OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10039  OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10040  break;
10041 
10042  case OO_EqualEqual:
10043  case OO_ExclaimEqual:
10044  OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10045  OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10046  OpBuilder.addGenericBinaryArithmeticOverloads();
10047  break;
10048 
10049  case OO_Less:
10050  case OO_Greater:
10051  case OO_LessEqual:
10052  case OO_GreaterEqual:
10053  OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10054  OpBuilder.addGenericBinaryArithmeticOverloads();
10055  break;
10056 
10057  case OO_Spaceship:
10058  OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10059  OpBuilder.addThreeWayArithmeticOverloads();
10060  break;
10061 
10062  case OO_Percent:
10063  case OO_Caret:
10064  case OO_Pipe:
10065  case OO_LessLess:
10066  case OO_GreaterGreater:
10067  OpBuilder.addBinaryBitwiseArithmeticOverloads();
10068  break;
10069 
10070  case OO_Amp: // '&' is either unary or binary
10071  if (Args.size() == 1)
10072  // C++ [over.match.oper]p3:
10073  // -- For the operator ',', the unary operator '&', or the
10074  // operator '->', the built-in candidates set is empty.
10075  break;
10076 
10077  OpBuilder.addBinaryBitwiseArithmeticOverloads();
10078  break;
10079 
10080  case OO_Tilde:
10081  OpBuilder.addUnaryTildePromotedIntegralOverloads();
10082  break;
10083 
10084  case OO_Equal:
10085  OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10086  [[fallthrough]];
10087 
10088  case OO_PlusEqual:
10089  case OO_MinusEqual:
10090  OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10091  [[fallthrough]];
10092 
10093  case OO_StarEqual:
10094  case OO_SlashEqual:
10095  OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10096  break;
10097 
10098  case OO_PercentEqual:
10099  case OO_LessLessEqual:
10100  case OO_GreaterGreaterEqual:
10101  case OO_AmpEqual:
10102  case OO_CaretEqual:
10103  case OO_PipeEqual:
10104  OpBuilder.addAssignmentIntegralOverloads();
10105  break;
10106 
10107  case OO_Exclaim:
10108  OpBuilder.addExclaimOverload();
10109  break;
10110 
10111  case OO_AmpAmp:
10112  case OO_PipePipe:
10113  OpBuilder.addAmpAmpOrPipePipeOverload();
10114  break;
10115 
10116  case OO_Subscript:
10117  if (Args.size() == 2)
10118  OpBuilder.addSubscriptOverloads();
10119  break;
10120 
10121  case OO_ArrowStar:
10122  OpBuilder.addArrowStarOverloads();
10123  break;
10124 
10125  case OO_Conditional:
10126  OpBuilder.addConditionalOperatorOverloads();
10127  OpBuilder.addGenericBinaryArithmeticOverloads();
10128  break;
10129  }
10130 }
10131 
10132 /// Add function candidates found via argument-dependent lookup
10133 /// to the set of overloading candidates.
10134 ///
10135 /// This routine performs argument-dependent name lookup based on the
10136 /// given function name (which may also be an operator name) and adds
10137 /// all of the overload candidates found by ADL to the overload
10138 /// candidate set (C++ [basic.lookup.argdep]).
10139 void
10142  ArrayRef<Expr *> Args,
10143  TemplateArgumentListInfo *ExplicitTemplateArgs,
10144  OverloadCandidateSet& CandidateSet,
10145  bool PartialOverloading) {
10146  ADLResult Fns;
10147 
10148  // FIXME: This approach for uniquing ADL results (and removing
10149  // redundant candidates from the set) relies on pointer-equality,
10150  // which means we need to key off the canonical decl. However,
10151  // always going back to the canonical decl might not get us the
10152  // right set of default arguments. What default arguments are
10153  // we supposed to consider on ADL candidates, anyway?
10154 
10155  // FIXME: Pass in the explicit template arguments?
10156  ArgumentDependentLookup(Name, Loc, Args, Fns);
10157 
10158  // Erase all of the candidates we already knew about.
10159  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10160  CandEnd = CandidateSet.end();
10161  Cand != CandEnd; ++Cand)
10162  if (Cand->Function) {
10163  Fns.erase(Cand->Function);
10164  if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
10165  Fns.erase(FunTmpl);
10166  }
10167 
10168  // For each of the ADL candidates we found, add it to the overload
10169  // set.
10170  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10171  DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
10172 
10173  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10174  if (ExplicitTemplateArgs)
10175  continue;
10176 
10178  FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10179  PartialOverloading, /*AllowExplicit=*/true,
10180  /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10181  if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10183  FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10184  /*SuppressUserConversions=*/false, PartialOverloading,
10185  /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10186  ADLCallKind::UsesADL, std::nullopt,
10188  }
10189  } else {
10190  auto *FTD = cast<FunctionTemplateDecl>(*I);
10192  FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10193  /*SuppressUserConversions=*/false, PartialOverloading,
10194  /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10195  if (CandidateSet.getRewriteInfo().shouldAddReversed(
10196  *this, Args, FTD->getTemplatedDecl())) {
10198  FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10199  CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10200  /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10202  }
10203  }
10204  }
10205 }
10206 
10207 namespace {
10208 enum class Comparison { Equal, Better, Worse };
10209 }
10210 
10211 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10212 /// overload resolution.
10213 ///
10214 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10215 /// Cand1's first N enable_if attributes have precisely the same conditions as
10216 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10217 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10218 ///
10219 /// Note that you can have a pair of candidates such that Cand1's enable_if
10220 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10221 /// worse than Cand1's.
10222 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10223  const FunctionDecl *Cand2) {
10224  // Common case: One (or both) decls don't have enable_if attrs.
10225  bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10226  bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10227  if (!Cand1Attr || !Cand2Attr) {
10228  if (Cand1Attr == Cand2Attr)
10229  return Comparison::Equal;
10230  return Cand1Attr ? Comparison::Better : Comparison::Worse;
10231  }
10232 
10233  auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10234  auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10235 
10236  llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10237  for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10238  std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10239  std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10240 
10241  // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10242  // has fewer enable_if attributes than Cand2, and vice versa.
10243  if (!Cand1A)
10244  return Comparison::Worse;
10245  if (!Cand2A)
10246  return Comparison::Better;
10247 
10248  Cand1ID.clear();
10249  Cand2ID.clear();
10250 
10251  (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10252  (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10253  if (Cand1ID != Cand2ID)
10254  return Comparison::Worse;
10255  }
10256 
10257  return Comparison::Equal;
10258 }
10259 
10260 static Comparison
10262  const OverloadCandidate &Cand2) {
10263  if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10264  !Cand2.Function->isMultiVersion())
10265  return Comparison::Equal;
10266 
10267  // If both are invalid, they are equal. If one of them is invalid, the other
10268  // is better.
10269  if (Cand1.Function->isInvalidDecl()) {
10270  if (Cand2.Function->isInvalidDecl())
10271  return Comparison::Equal;
10272  return Comparison::Worse;
10273  }
10274  if (Cand2.Function->isInvalidDecl())
10275  return Comparison::Better;
10276 
10277  // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10278  // cpu_dispatch, else arbitrarily based on the identifiers.
10279  bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10280  bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10281  const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10282  const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10283 
10284  if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10285  return Comparison::Equal;
10286 
10287  if (Cand1CPUDisp && !Cand2CPUDisp)
10288  return Comparison::Better;
10289  if (Cand2CPUDisp && !Cand1CPUDisp)
10290  return Comparison::Worse;
10291 
10292  if (Cand1CPUSpec && Cand2CPUSpec) {
10293  if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10294  return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10295  ? Comparison::Better
10296  : Comparison::Worse;
10297 
10298  std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10299  FirstDiff = std::mismatch(
10300  Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10301  Cand2CPUSpec->cpus_begin(),
10302  [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10303  return LHS->getName() == RHS->getName();
10304  });
10305 
10306  assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10307  "Two different cpu-specific versions should not have the same "
10308  "identifier list, otherwise they'd be the same decl!");
10309  return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10310  ? Comparison::Better
10311  : Comparison::Worse;
10312  }
10313  llvm_unreachable("No way to get here unless both had cpu_dispatch");
10314 }
10315 
10316 /// Compute the type of the implicit object parameter for the given function,
10317 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10318 /// null QualType if there is a 'matches anything' implicit object parameter.
10319 static std::optional<QualType>
10321  if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10322  return std::nullopt;
10323 
10324  auto *M = cast<CXXMethodDecl>(F);
10325  // Static member functions' object parameters match all types.
10326  if (M->isStatic())
10327  return QualType();
10328  return M->getFunctionObjectParameterReferenceType();
10329 }
10330 
10331 // As a Clang extension, allow ambiguity among F1 and F2 if they represent
10332 // represent the same entity.
10334  const FunctionDecl *F2) {
10335  if (declaresSameEntity(F1, F2))
10336  return true;
10337  auto PT1 = F1->getPrimaryTemplate();
10338  auto PT2 = F2->getPrimaryTemplate();
10339  if (PT1 && PT2) {
10340  if (declaresSameEntity(PT1, PT2) ||
10341  declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10342  PT2->getInstantiatedFromMemberTemplate()))
10343  return true;
10344  }
10345  // TODO: It is not clear whether comparing parameters is necessary (i.e.
10346  // different functions with same params). Consider removing this (as no test
10347  // fail w/o it).
10348  auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10349  if (First) {
10350  if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10351  return *T;
10352  }
10353  assert(I < F->getNumParams());
10354  return F->getParamDecl(I++)->getType();
10355  };
10356 
10357  unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10358  unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10359 
10360  if (F1NumParams != F2NumParams)
10361  return false;
10362 
10363  unsigned I1 = 0, I2 = 0;
10364  for (unsigned I = 0; I != F1NumParams; ++I) {
10365  QualType T1 = NextParam(F1, I1, I == 0);
10366  QualType T2 = NextParam(F2, I2, I == 0);
10367  assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10368  if (!Context.hasSameUnqualifiedType(T1, T2))
10369  return false;
10370  }
10371  return true;
10372 }
10373 
10374 /// We're allowed to use constraints partial ordering only if the candidates
10375 /// have the same parameter types:
10376 /// [over.match.best.general]p2.6
10377 /// F1 and F2 are non-template functions with the same
10378 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10380  const OverloadCandidate &Cand1,
10381  const OverloadCandidate &Cand2) {
10382  if (!Cand1.Function || !Cand2.Function)
10383  return false;
10384 
10385  FunctionDecl *Fn1 = Cand1.Function;
10386  FunctionDecl *Fn2 = Cand2.Function;
10387 
10388  if (Fn1->isVariadic() != Fn1->isVariadic())
10389  return false;
10390 
10392  Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10393  return false;
10394 
10395  auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10396  auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10397  if (Mem1 && Mem2) {
10398  // if they are member functions, both are direct members of the same class,
10399  // and
10400  if (Mem1->getParent() != Mem2->getParent())
10401  return false;
10402  // if both are non-static member functions, they have the same types for
10403  // their object parameters
10404  if (Mem1->isInstance() && Mem2->isInstance() &&
10406  Mem1->getFunctionObjectParameterReferenceType(),
10407  Mem1->getFunctionObjectParameterReferenceType()))
10408  return false;
10409  }
10410  return true;
10411 }
10412 
10413 /// isBetterOverloadCandidate - Determines whether the first overload
10414 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10416  Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10418  // Define viable functions to be better candidates than non-viable
10419  // functions.
10420  if (!Cand2.Viable)
10421  return Cand1.Viable;
10422  else if (!Cand1.Viable)
10423  return false;
10424 
10425  // [CUDA] A function with 'never' preference is marked not viable, therefore
10426  // is never shown up here. The worst preference shown up here is 'wrong side',
10427  // e.g. an H function called by a HD function in device compilation. This is
10428  // valid AST as long as the HD function is not emitted, e.g. it is an inline
10429  // function which is called only by an H function. A deferred diagnostic will
10430  // be triggered if it is emitted. However a wrong-sided function is still
10431  // a viable candidate here.
10432  //
10433  // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10434  // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10435  // can be emitted, Cand1 is not better than Cand2. This rule should have
10436  // precedence over other rules.
10437  //
10438  // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10439  // other rules should be used to determine which is better. This is because
10440  // host/device based overloading resolution is mostly for determining
10441  // viability of a function. If two functions are both viable, other factors
10442  // should take precedence in preference, e.g. the standard-defined preferences
10443  // like argument conversion ranks or enable_if partial-ordering. The
10444  // preference for pass-object-size parameters is probably most similar to a
10445  // type-based-overloading decision and so should take priority.
10446  //
10447  // If other rules cannot determine which is better, CUDA preference will be
10448  // used again to determine which is better.
10449  //
10450  // TODO: Currently IdentifyPreference does not return correct values
10451  // for functions called in global variable initializers due to missing
10452  // correct context about device/host. Therefore we can only enforce this
10453  // rule when there is a caller. We should enforce this rule for functions
10454  // in global variable initializers once proper context is added.
10455  //
10456  // TODO: We can only enable the hostness based overloading resolution when
10457  // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10458  // overloading resolution diagnostics.
10459  if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10460  S.getLangOpts().GPUExcludeWrongSideOverloads) {
10461  if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10462  bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10463  bool IsCand1ImplicitHD =
10465  bool IsCand2ImplicitHD =
10467  auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10468  auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10469  assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10470  // The implicit HD function may be a function in a system header which
10471  // is forced by pragma. In device compilation, if we prefer HD candidates
10472  // over wrong-sided candidates, overloading resolution may change, which
10473  // may result in non-deferrable diagnostics. As a workaround, we let
10474  // implicit HD candidates take equal preference as wrong-sided candidates.
10475  // This will preserve the overloading resolution.
10476  // TODO: We still need special handling of implicit HD functions since
10477  // they may incur other diagnostics to be deferred. We should make all
10478  // host/device related diagnostics deferrable and remove special handling
10479  // of implicit HD functions.
10480  auto EmitThreshold =
10481  (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10482  (IsCand1ImplicitHD || IsCand2ImplicitHD))
10485  auto Cand1Emittable = P1 > EmitThreshold;
10486  auto Cand2Emittable = P2 > EmitThreshold;
10487  if (Cand1Emittable && !Cand2Emittable)
10488  return true;
10489  if (!Cand1Emittable && Cand2Emittable)
10490  return false;
10491  }
10492  }
10493 
10494  // C++ [over.match.best]p1: (Changed in C++23)
10495  //
10496  // -- if F is a static member function, ICS1(F) is defined such
10497  // that ICS1(F) is neither better nor worse than ICS1(G) for
10498  // any function G, and, symmetrically, ICS1(G) is neither
10499  // better nor worse than ICS1(F).
10500  unsigned StartArg = 0;
10501  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10502  StartArg = 1;
10503 
10504  auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10505  // We don't allow incompatible pointer conversions in C++.
10506  if (!S.getLangOpts().CPlusPlus)
10507  return ICS.isStandard() &&
10508  ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10509 
10510  // The only ill-formed conversion we allow in C++ is the string literal to
10511  // char* conversion, which is only considered ill-formed after C++11.
10512  return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10514  };
10515 
10516  // Define functions that don't require ill-formed conversions for a given
10517  // argument to be better candidates than functions that do.
10518  unsigned NumArgs = Cand1.Conversions.size();
10519  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10520  bool HasBetterConversion = false;
10521  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10522  bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10523  bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10524  if (Cand1Bad != Cand2Bad) {
10525  if (Cand1Bad)
10526  return false;
10527  HasBetterConversion = true;
10528  }
10529  }
10530 
10531  if (HasBetterConversion)
10532  return true;
10533 
10534  // C++ [over.match.best]p1:
10535  // A viable function F1 is defined to be a better function than another
10536  // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10537  // conversion sequence than ICSi(F2), and then...
10538  bool HasWorseConversion = false;
10539  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10541  Cand1.Conversions[ArgIdx],
10542  Cand2.Conversions[ArgIdx])) {
10544  // Cand1 has a better conversion sequence.
10545  HasBetterConversion = true;
10546  break;
10547 
10549  if (Cand1.Function && Cand2.Function &&
10550  Cand1.isReversed() != Cand2.isReversed() &&
10551  allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10552  // Work around large-scale breakage caused by considering reversed
10553  // forms of operator== in C++20:
10554  //
10555  // When comparing a function against a reversed function, if we have a
10556  // better conversion for one argument and a worse conversion for the
10557  // other, the implicit conversion sequences are treated as being equally
10558  // good.
10559  //
10560  // This prevents a comparison function from being considered ambiguous
10561  // with a reversed form that is written in the same way.
10562  //
10563  // We diagnose this as an extension from CreateOverloadedBinOp.
10564  HasWorseConversion = true;
10565  break;
10566  }
10567 
10568  // Cand1 can't be better than Cand2.
10569  return false;
10570 
10572  // Do nothing.
10573  break;
10574  }
10575  }
10576 
10577  // -- for some argument j, ICSj(F1) is a better conversion sequence than
10578  // ICSj(F2), or, if not that,
10579  if (HasBetterConversion && !HasWorseConversion)
10580  return true;
10581 
10582  // -- the context is an initialization by user-defined conversion
10583  // (see 8.5, 13.3.1.5) and the standard conversion sequence
10584  // from the return type of F1 to the destination type (i.e.,
10585  // the type of the entity being initialized) is a better
10586  // conversion sequence than the standard conversion sequence
10587  // from the return type of F2 to the destination type.
10589  Cand1.Function && Cand2.Function &&
10590  isa<CXXConversionDecl>(Cand1.Function) &&
10591  isa<CXXConversionDecl>(Cand2.Function)) {
10592  // First check whether we prefer one of the conversion functions over the
10593  // other. This only distinguishes the results in non-standard, extension
10594  // cases such as the conversion from a lambda closure type to a function
10595  // pointer or block.
10597  compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10600  Cand1.FinalConversion,
10601  Cand2.FinalConversion);
10602 
10604  return Result == ImplicitConversionSequence::Better;
10605 
10606  // FIXME: Compare kind of reference binding if conversion functions
10607  // convert to a reference type used in direct reference binding, per
10608  // C++14 [over.match.best]p1 section 2 bullet 3.
10609  }
10610 
10611  // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10612  // as combined with the resolution to CWG issue 243.
10613  //
10614  // When the context is initialization by constructor ([over.match.ctor] or
10615  // either phase of [over.match.list]), a constructor is preferred over
10616  // a conversion function.
10617  if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10618  Cand1.Function && Cand2.Function &&
10619  isa<CXXConstructorDecl>(Cand1.Function) !=
10620  isa<CXXConstructorDecl>(Cand2.Function))
10621  return isa<CXXConstructorDecl>(Cand1.Function);
10622 
10623  // -- F1 is a non-template function and F2 is a function template
10624  // specialization, or, if not that,
10625  bool Cand1IsSpecialization = Cand1.Function &&
10626  Cand1.Function->getPrimaryTemplate();
10627  bool Cand2IsSpecialization = Cand2.Function &&
10628  Cand2.Function->getPrimaryTemplate();
10629  if (Cand1IsSpecialization != Cand2IsSpecialization)
10630  return Cand2IsSpecialization;
10631 
10632  // -- F1 and F2 are function template specializations, and the function
10633  // template for F1 is more specialized than the template for F2
10634  // according to the partial ordering rules described in 14.5.5.2, or,
10635  // if not that,
10636  if (Cand1IsSpecialization && Cand2IsSpecialization) {
10637  const auto *Obj1Context =
10638  dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10639  const auto *Obj2Context =
10640  dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10641  if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10642  Cand1.Function->getPrimaryTemplate(),
10643  Cand2.Function->getPrimaryTemplate(), Loc,
10644  isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10645  : TPOC_Call,
10646  Cand1.ExplicitCallArguments,
10647  Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10648  : QualType{},
10649  Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10650  : QualType{},
10651  Cand1.isReversed() ^ Cand2.isReversed())) {
10652  return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10653  }
10654  }
10655 
10656  // -— F1 and F2 are non-template functions with the same
10657  // parameter-type-lists, and F1 is more constrained than F2 [...],
10658  if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10659  sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10660  S.getMoreConstrainedFunction(Cand1.Function, Cand2.Function) ==
10661  Cand1.Function)
10662  return true;
10663 
10664  // -- F1 is a constructor for a class D, F2 is a constructor for a base
10665  // class B of D, and for all arguments the corresponding parameters of
10666  // F1 and F2 have the same type.
10667  // FIXME: Implement the "all parameters have the same type" check.
10668  bool Cand1IsInherited =
10669  isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10670  bool Cand2IsInherited =
10671  isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10672  if (Cand1IsInherited != Cand2IsInherited)
10673  return Cand2IsInherited;
10674  else if (Cand1IsInherited) {
10675  assert(Cand2IsInherited);
10676  auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10677  auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10678  if (Cand1Class->isDerivedFrom(Cand2Class))
10679  return true;
10680  if (Cand2Class->isDerivedFrom(Cand1Class))
10681  return false;
10682  // Inherited from sibling base classes: still ambiguous.
10683  }
10684 
10685  // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10686  // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10687  // with reversed order of parameters and F1 is not
10688  //
10689  // We rank reversed + different operator as worse than just reversed, but
10690  // that comparison can never happen, because we only consider reversing for
10691  // the maximally-rewritten operator (== or <=>).
10692  if (Cand1.RewriteKind != Cand2.RewriteKind)
10693  return Cand1.RewriteKind < Cand2.RewriteKind;
10694 
10695  // Check C++17 tie-breakers for deduction guides.
10696  {
10697  auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10698  auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10699  if (Guide1 && Guide2) {
10700  // -- F1 is generated from a deduction-guide and F2 is not
10701  if (Guide1->isImplicit() != Guide2->isImplicit())
10702  return Guide2->isImplicit();
10703 
10704  // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10705  if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10706  return true;
10707  if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10708  return false;
10709 
10710  // --F1 is generated from a non-template constructor and F2 is generated
10711  // from a constructor template
10712  const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10713  const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10714  if (Constructor1 && Constructor2) {
10715  bool isC1Templated = Constructor1->getTemplatedKind() !=
10716  FunctionDecl::TemplatedKind::TK_NonTemplate;
10717  bool isC2Templated = Constructor2->getTemplatedKind() !=
10718  FunctionDecl::TemplatedKind::TK_NonTemplate;
10719  if (isC1Templated != isC2Templated)
10720  return isC2Templated;
10721  }
10722  }
10723  }
10724 
10725  // Check for enable_if value-based overload resolution.
10726  if (Cand1.Function && Cand2.Function) {
10727  Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10728  if (Cmp != Comparison::Equal)
10729  return Cmp == Comparison::Better;
10730  }
10731 
10732  bool HasPS1 = Cand1.Function != nullptr &&
10734  bool HasPS2 = Cand2.Function != nullptr &&
10736  if (HasPS1 != HasPS2 && HasPS1)
10737  return true;
10738 
10739  auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10740  if (MV == Comparison::Better)
10741  return true;
10742  if (MV == Comparison::Worse)
10743  return false;
10744 
10745  // If other rules cannot determine which is better, CUDA preference is used
10746  // to determine which is better.
10747  if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10748  FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10749  return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10750  S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10751  }
10752 
10753  // General member function overloading is handled above, so this only handles
10754  // constructors with address spaces.
10755  // This only handles address spaces since C++ has no other
10756  // qualifier that can be used with constructors.
10757  const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10758  const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10759  if (CD1 && CD2) {
10760  LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10761  LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10762  if (AS1 != AS2) {
10764  return true;
10766  return false;
10767  }
10768  }
10769 
10770  return false;
10771 }
10772 
10773 /// Determine whether two declarations are "equivalent" for the purposes of
10774 /// name lookup and overload resolution. This applies when the same internal/no
10775 /// linkage entity is defined by two modules (probably by textually including
10776 /// the same header). In such a case, we don't consider the declarations to
10777 /// declare the same entity, but we also don't want lookups with both
10778 /// declarations visible to be ambiguous in some cases (this happens when using
10779 /// a modularized libstdc++).
10781  const NamedDecl *B) {
10782  auto *VA = dyn_cast_or_null<ValueDecl>(A);
10783  auto *VB = dyn_cast_or_null<ValueDecl>(B);
10784  if (!VA || !VB)
10785  return false;
10786 
10787  // The declarations must be declaring the same name as an internal linkage
10788  // entity in different modules.
10789  if (!VA->getDeclContext()->getRedeclContext()->Equals(
10790  VB->getDeclContext()->getRedeclContext()) ||
10791  getOwningModule(VA) == getOwningModule(VB) ||
10792  VA->isExternallyVisible() || VB->isExternallyVisible())
10793  return false;
10794 
10795  // Check that the declarations appear to be equivalent.
10796  //
10797  // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10798  // For constants and functions, we should check the initializer or body is
10799  // the same. For non-constant variables, we shouldn't allow it at all.
10800  if (Context.hasSameType(VA->getType(), VB->getType()))
10801  return true;
10802 
10803  // Enum constants within unnamed enumerations will have different types, but
10804  // may still be similar enough to be interchangeable for our purposes.
10805  if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10806  if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10807  // Only handle anonymous enums. If the enumerations were named and
10808  // equivalent, they would have been merged to the same type.
10809  auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10810  auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10811  if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10812  !Context.hasSameType(EnumA->getIntegerType(),
10813  EnumB->getIntegerType()))
10814  return false;
10815  // Allow this only if the value is the same for both enumerators.
10816  return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10817  }
10818  }
10819 
10820  // Nothing else is sufficiently similar.
10821  return false;
10822 }
10823 
10826  assert(D && "Unknown declaration");
10827  Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10828 
10829  Module *M = getOwningModule(D);
10830  Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10831  << !M << (M ? M->getFullModuleName() : "");
10832 
10833  for (auto *E : Equiv) {
10834  Module *M = getOwningModule(E);
10835  Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10836  << !M << (M ? M->getFullModuleName() : "");
10837  }
10838 }
10839 
10841  return FailureKind == ovl_fail_bad_deduction &&
10842  static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10844  static_cast<CNSInfo *>(DeductionFailure.Data)
10845  ->Satisfaction.ContainsErrors;
10846 }
10847 
10848 /// Computes the best viable function (C++ 13.3.3)
10849 /// within an overload candidate set.
10850 ///
10851 /// \param Loc The location of the function name (or operator symbol) for
10852 /// which overload resolution occurs.
10853 ///
10854 /// \param Best If overload resolution was successful or found a deleted
10855 /// function, \p Best points to the candidate function found.
10856 ///
10857 /// \returns The result of overload resolution.
10860  iterator &Best) {
10862  std::transform(begin(), end(), std::back_inserter(Candidates),
10863  [](OverloadCandidate &Cand) { return &Cand; });
10864 
10865  // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10866  // are accepted by both clang and NVCC. However, during a particular
10867  // compilation mode only one call variant is viable. We need to
10868  // exclude non-viable overload candidates from consideration based
10869  // only on their host/device attributes. Specifically, if one
10870  // candidate call is WrongSide and the other is SameSide, we ignore
10871  // the WrongSide candidate.
10872  // We only need to remove wrong-sided candidates here if
10873  // -fgpu-exclude-wrong-side-overloads is off. When
10874  // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10875  // uniformly in isBetterOverloadCandidate.
10876  if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10877  const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10878  bool ContainsSameSideCandidate =
10879  llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10880  // Check viable function only.
10881  return Cand->Viable && Cand->Function &&
10882  S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10884  });
10885  if (ContainsSameSideCandidate) {
10886  auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10887  // Check viable function only to avoid unnecessary data copying/moving.
10888  return Cand->Viable && Cand->Function &&
10889  S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10891  };
10892  llvm::erase_if(Candidates, IsWrongSideCandidate);
10893  }
10894  }
10895 
10896  // Find the best viable function.
10897  Best = end();
10898  for (auto *Cand : Candidates) {
10899  Cand->Best = false;
10900  if (Cand->Viable) {
10901  if (Best == end() ||
10902  isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10903  Best = Cand;
10904  } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10905  // This candidate has constraint that we were unable to evaluate because
10906  // it referenced an expression that contained an error. Rather than fall
10907  // back onto a potentially unintended candidate (made worse by
10908  // subsuming constraints), treat this as 'no viable candidate'.
10909  Best = end();
10910  return OR_No_Viable_Function;
10911  }
10912  }
10913 
10914  // If we didn't find any viable functions, abort.
10915  if (Best == end())
10916  return OR_No_Viable_Function;
10917 
10919 
10921  PendingBest.push_back(&*Best);
10922  Best->Best = true;
10923 
10924  // Make sure that this function is better than every other viable
10925  // function. If not, we have an ambiguity.
10926  while (!PendingBest.empty()) {
10927  auto *Curr = PendingBest.pop_back_val();
10928  for (auto *Cand : Candidates) {
10929  if (Cand->Viable && !Cand->Best &&
10930  !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10931  PendingBest.push_back(Cand);
10932  Cand->Best = true;
10933 
10935  Curr->Function))
10936  EquivalentCands.push_back(Cand->Function);
10937  else
10938  Best = end();
10939  }
10940  }
10941  }
10942 
10943  // If we found more than one best candidate, this is ambiguous.
10944  if (Best == end())
10945  return OR_Ambiguous;
10946 
10947  // Best is the best viable function.
10948  if (Best->Function && Best->Function->isDeleted())
10949  return OR_Deleted;
10950 
10951  if (!EquivalentCands.empty())
10953  EquivalentCands);
10954 
10955  return OR_Success;
10956 }
10957 
10958 namespace {
10959 
10960 enum OverloadCandidateKind {
10961  oc_function,
10962  oc_method,
10963  oc_reversed_binary_operator,
10964  oc_constructor,
10965  oc_implicit_default_constructor,
10966  oc_implicit_copy_constructor,
10967  oc_implicit_move_constructor,
10968  oc_implicit_copy_assignment,
10969  oc_implicit_move_assignment,
10970  oc_implicit_equality_comparison,
10971  oc_inherited_constructor
10972 };
10973 
10974 enum OverloadCandidateSelect {
10975  ocs_non_template,
10976  ocs_template,
10977  ocs_described_template,
10978 };
10979 
10980 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10981 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10982  const FunctionDecl *Fn,
10984  std::string &Description) {
10985 
10986  bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10987  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10988  isTemplate = true;
10989  Description = S.getTemplateArgumentBindingsText(
10990  FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10991  }
10992 
10993  OverloadCandidateSelect Select = [&]() {
10994  if (!Description.empty())
10995  return ocs_described_template;
10996  return isTemplate ? ocs_template : ocs_non_template;
10997  }();
10998 
10999  OverloadCandidateKind Kind = [&]() {
11000  if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11001  return oc_implicit_equality_comparison;
11002 
11003  if (CRK & CRK_Reversed)
11004  return oc_reversed_binary_operator;
11005 
11006  if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11007  if (!Ctor->isImplicit()) {
11008  if (isa<ConstructorUsingShadowDecl>(Found))
11009  return oc_inherited_constructor;
11010  else
11011  return oc_constructor;
11012  }
11013 
11014  if (Ctor->isDefaultConstructor())
11015  return oc_implicit_default_constructor;
11016 
11017  if (Ctor->isMoveConstructor())
11018  return oc_implicit_move_constructor;
11019 
11020  assert(Ctor->isCopyConstructor() &&
11021  "unexpected sort of implicit constructor");
11022  return oc_implicit_copy_constructor;
11023  }
11024 
11025  if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11026  // This actually gets spelled 'candidate function' for now, but
11027  // it doesn't hurt to split it out.
11028  if (!Meth->isImplicit())
11029  return oc_method;
11030 
11031  if (Meth->isMoveAssignmentOperator())
11032  return oc_implicit_move_assignment;
11033 
11034  if (Meth->isCopyAssignmentOperator())
11035  return oc_implicit_copy_assignment;
11036 
11037  assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11038  return oc_method;
11039  }
11040 
11041  return oc_function;
11042  }();
11043 
11044  return std::make_pair(Kind, Select);
11045 }
11046 
11047 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11048  // FIXME: It'd be nice to only emit a note once per using-decl per overload
11049  // set.
11050  if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11051  S.Diag(FoundDecl->getLocation(),
11052  diag::note_ovl_candidate_inherited_constructor)
11053  << Shadow->getNominatedBaseClass();
11054 }
11055 
11056 } // end anonymous namespace
11057 
11058 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11059  const FunctionDecl *FD) {
11060  for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11061  bool AlwaysTrue;
11062  if (EnableIf->getCond()->isValueDependent() ||
11063  !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11064  return false;
11065  if (!AlwaysTrue)
11066  return false;
11067  }
11068  return true;
11069 }
11070 
11071 /// Returns true if we can take the address of the function.
11072 ///
11073 /// \param Complain - If true, we'll emit a diagnostic
11074 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11075 /// we in overload resolution?
11076 /// \param Loc - The location of the statement we're complaining about. Ignored
11077 /// if we're not complaining, or if we're in overload resolution.
11079  bool Complain,
11080  bool InOverloadResolution,
11081  SourceLocation Loc) {
11082  if (Complain && S.getLangOpts().SYCLIsDevice &&
11083  S.getLangOpts().SYCLAllowFuncPtr) {
11084  if (!FD->hasAttr<SYCLDeviceIndirectlyCallableAttr>()) {
11086  diag::err_sycl_taking_address_of_wrong_function,
11088  }
11089  }
11090 
11091  if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11092  if (Complain) {
11093  if (InOverloadResolution)
11094  S.Diag(FD->getBeginLoc(),
11095  diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11096  else
11097  S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11098  }
11099  return false;
11100  }
11101 
11102  if (FD->getTrailingRequiresClause()) {
11103  ConstraintSatisfaction Satisfaction;
11104  if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11105  return false;
11106  if (!Satisfaction.IsSatisfied) {
11107  if (Complain) {
11108  if (InOverloadResolution) {
11109  SmallString<128> TemplateArgString;
11110  if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11111  TemplateArgString += " ";
11112  TemplateArgString += S.getTemplateArgumentBindingsText(
11113  FunTmpl->getTemplateParameters(),
11115  }
11116 
11117  S.Diag(FD->getBeginLoc(),
11118  diag::note_ovl_candidate_unsatisfied_constraints)
11119  << TemplateArgString;
11120  } else
11121  S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11122  << FD;
11123  S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11124  }
11125  return false;
11126  }
11127  }
11128 
11129  auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11130  return P->hasAttr<PassObjectSizeAttr>();
11131  });
11132  if (I == FD->param_end())
11133  return true;
11134 
11135  if (Complain) {
11136  // Add one to ParamNo because it's user-facing
11137  unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11138  if (InOverloadResolution)
11139  S.Diag(FD->getLocation(),
11140  diag::note_ovl_candidate_has_pass_object_size_params)
11141  << ParamNo;
11142  else
11143  S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11144  << FD << ParamNo;
11145  }
11146  return false;
11147 }
11148 
11150  const FunctionDecl *FD) {
11151  return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11152  /*InOverloadResolution=*/true,
11153  /*Loc=*/SourceLocation());
11154 }
11155 
11157  bool Complain,
11158  SourceLocation Loc) {
11160  /*InOverloadResolution=*/false,
11161  Loc);
11162 }
11163 
11164 // Don't print candidates other than the one that matches the calling
11165 // convention of the call operator, since that is guaranteed to exist.
11167  const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11168 
11169  if (!ConvD)
11170  return false;
11171  const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11172  if (!RD->isLambda())
11173  return false;
11174 
11175  CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11176  CallingConv CallOpCC =
11177  CallOp->getType()->castAs<FunctionType>()->getCallConv();
11178  QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11179  CallingConv ConvToCC =
11180  ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11181 
11182  return ConvToCC != CallOpCC;
11183 }
11184 
11185 // Notes the location of an overload candidate.
11187  OverloadCandidateRewriteKind RewriteKind,
11188  QualType DestType, bool TakingAddress) {
11189  if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11190  return;
11191  if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11192  !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11193  return;
11194  if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11195  !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11196  return;
11198  return;
11199 
11200  std::string FnDesc;
11201  std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11202  ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11203  PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11204  << (unsigned)KSPair.first << (unsigned)KSPair.second
11205  << Fn << FnDesc;
11206 
11207  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11208  Diag(Fn->getLocation(), PD);
11209  MaybeEmitInheritedConstructorNote(*this, Found);
11210 }
11211 
11212 static void
11214  // Perhaps the ambiguity was caused by two atomic constraints that are
11215  // 'identical' but not equivalent:
11216  //
11217  // void foo() requires (sizeof(T) > 4) { } // #1
11218  // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11219  //
11220  // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11221  // #2 to subsume #1, but these constraint are not considered equivalent
11222  // according to the subsumption rules because they are not the same
11223  // source-level construct. This behavior is quite confusing and we should try
11224  // to help the user figure out what happened.
11225 
11226  SmallVector<const Expr *, 3> FirstAC, SecondAC;
11227  FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11228  for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11229  if (!I->Function)
11230  continue;
11232  if (auto *Template = I->Function->getPrimaryTemplate())
11233  Template->getAssociatedConstraints(AC);
11234  else
11235  I->Function->getAssociatedConstraints(AC);
11236  if (AC.empty())
11237  continue;
11238  if (FirstCand == nullptr) {
11239  FirstCand = I->Function;
11240  FirstAC = AC;
11241  } else if (SecondCand == nullptr) {
11242  SecondCand = I->Function;
11243  SecondAC = AC;
11244  } else {
11245  // We have more than one pair of constrained functions - this check is
11246  // expensive and we'd rather not try to diagnose it.
11247  return;
11248  }
11249  }
11250  if (!SecondCand)
11251  return;
11252  // The diagnostic can only happen if there are associated constraints on
11253  // both sides (there needs to be some identical atomic constraint).
11254  if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11255  SecondCand, SecondAC))
11256  // Just show the user one diagnostic, they'll probably figure it out
11257  // from here.
11258  return;
11259 }
11260 
11261 // Notes the location of all overload candidates designated through
11262 // OverloadedExpr
11263 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11264  bool TakingAddress) {
11265  assert(OverloadedExpr->getType() == Context.OverloadTy);
11266 
11267  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11268  OverloadExpr *OvlExpr = Ovl.Expression;
11269 
11270  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11271  IEnd = OvlExpr->decls_end();
11272  I != IEnd; ++I) {
11273  if (FunctionTemplateDecl *FunTmpl =
11274  dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11275  NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11276  TakingAddress);
11277  } else if (FunctionDecl *Fun
11278  = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11279  NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11280  }
11281  }
11282 }
11283 
11284 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
11285 /// "lead" diagnostic; it will be given two arguments, the source and
11286 /// target types of the conversion.
11288  Sema &S,
11289  SourceLocation CaretLoc,
11290  const PartialDiagnostic &PDiag) const {
11291  S.Diag(CaretLoc, PDiag)
11292  << Ambiguous.getFromType() << Ambiguous.getToType();
11293  unsigned CandsShown = 0;
11295  for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11296  if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11297  break;
11298  ++CandsShown;
11299  S.NoteOverloadCandidate(I->first, I->second);
11300  }
11301  S.Diags.overloadCandidatesShown(CandsShown);
11302  if (I != E)
11303  S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11304 }
11305 
11307  unsigned I, bool TakingCandidateAddress) {
11308  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11309  assert(Conv.isBad());
11310  assert(Cand->Function && "for now, candidate must be a function");
11311  FunctionDecl *Fn = Cand->Function;
11312 
11313  // There's a conversion slot for the object argument if this is a
11314  // non-constructor method. Note that 'I' corresponds the
11315  // conversion-slot index.
11316  bool isObjectArgument = false;
11317  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11318  if (I == 0)
11319  isObjectArgument = true;
11320  else
11321  I--;
11322  }
11323 
11324  std::string FnDesc;
11325  std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11326  ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11327  FnDesc);
11328 
11329  Expr *FromExpr = Conv.Bad.FromExpr;
11330  QualType FromTy = Conv.Bad.getFromType();
11331  QualType ToTy = Conv.Bad.getToType();
11332  SourceRange ToParamRange;
11333 
11334  // FIXME: In presence of parameter packs we can't determine parameter range
11335  // reliably, as we don't have access to instantiation.
11336  bool HasParamPack =
11337  llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11338  return Parm->isParameterPack();
11339  });
11340  if (!isObjectArgument && !HasParamPack)
11341  ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11342 
11343  if (FromTy == S.Context.OverloadTy) {
11344  assert(FromExpr && "overload set argument came from implicit argument?");
11345  Expr *E = FromExpr->IgnoreParens();
11346  if (isa<UnaryOperator>(E))
11347  E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11348  DeclarationName Name = cast<OverloadExpr>(E)->getName();
11349 
11350  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11351  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11352  << ToParamRange << ToTy << Name << I + 1;
11353  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11354  return;
11355  }
11356 
11357  // Do some hand-waving analysis to see if the non-viability is due
11358  // to a qualifier mismatch.
11359  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11360  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11361  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11362  CToTy = RT->getPointeeType();
11363  else {
11364  // TODO: detect and diagnose the full richness of const mismatches.
11365  if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11366  if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11367  CFromTy = FromPT->getPointeeType();
11368  CToTy = ToPT->getPointeeType();
11369  }
11370  }
11371 
11372  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11373  !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
11374  Qualifiers FromQs = CFromTy.getQualifiers();
11375  Qualifiers ToQs = CToTy.getQualifiers();
11376 
11377  if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11378  if (isObjectArgument)
11379  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11380  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11381  << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11382  else
11383  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11384  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11385  << FnDesc << ToParamRange << FromQs.getAddressSpace()
11386  << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11387  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11388  return;
11389  }
11390 
11391  if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11392  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11393  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11394  << ToParamRange << FromTy << FromQs.getObjCLifetime()
11395  << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11396  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11397  return;
11398  }
11399 
11400  if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11401  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11402  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11403  << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11404  << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11405  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11406  return;
11407  }
11408 
11409  unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11410  assert(CVR && "expected qualifiers mismatch");
11411 
11412  if (isObjectArgument) {
11413  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11414  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11415  << FromTy << (CVR - 1);
11416  } else {
11417  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11418  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11419  << ToParamRange << FromTy << (CVR - 1) << I + 1;
11420  }
11421  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11422  return;
11423  }
11424 
11427  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11428  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11429  << (unsigned)isObjectArgument << I + 1
11431  << ToParamRange;
11432  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11433  return;
11434  }
11435 
11436  // Special diagnostic for failure to convert an initializer list, since
11437  // telling the user that it has type void is not useful.
11438  if (FromExpr && isa<InitListExpr>(FromExpr)) {
11439  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11440  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11441  << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11444  ? 2
11445  : 0);
11446  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11447  return;
11448  }
11449 
11450  // Diagnose references or pointers to incomplete types differently,
11451  // since it's far from impossible that the incompleteness triggered
11452  // the failure.
11453  QualType TempFromTy = FromTy.getNonReferenceType();
11454  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11455  TempFromTy = PTy->getPointeeType();
11456  if (TempFromTy->isIncompleteType()) {
11457  // Emit the generic diagnostic and, optionally, add the hints to it.
11458  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11459  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11460  << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11461  << (unsigned)(Cand->Fix.Kind);
11462 
11463  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11464  return;
11465  }
11466 
11467  // Diagnose base -> derived pointer conversions.
11468  unsigned BaseToDerivedConversion = 0;
11469  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11470  if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11471  if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11472  FromPtrTy->getPointeeType()) &&
11473  !FromPtrTy->getPointeeType()->isIncompleteType() &&
11474  !ToPtrTy->getPointeeType()->isIncompleteType() &&
11475  S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11476  FromPtrTy->getPointeeType()))
11477  BaseToDerivedConversion = 1;
11478  }
11479  } else if (const ObjCObjectPointerType *FromPtrTy
11480  = FromTy->getAs<ObjCObjectPointerType>()) {
11481  if (const ObjCObjectPointerType *ToPtrTy
11482  = ToTy->getAs<ObjCObjectPointerType>())
11483  if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11484  if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11485  if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11486  FromPtrTy->getPointeeType()) &&
11487  FromIface->isSuperClassOf(ToIface))
11488  BaseToDerivedConversion = 2;
11489  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11490  if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
11491  !FromTy->isIncompleteType() &&
11492  !ToRefTy->getPointeeType()->isIncompleteType() &&
11493  S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11494  BaseToDerivedConversion = 3;
11495  }
11496  }
11497 
11498  if (BaseToDerivedConversion) {
11499  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11500  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11501  << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11502  << I + 1;
11503  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11504  return;
11505  }
11506 
11507  if (isa<ObjCObjectPointerType>(CFromTy) &&
11508  isa<PointerType>(CToTy)) {
11509  Qualifiers FromQs = CFromTy.getQualifiers();
11510  Qualifiers ToQs = CToTy.getQualifiers();
11511  if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11512  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11513  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11514  << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11515  << I + 1;
11516  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11517  return;
11518  }
11519  }
11520 
11521  if (TakingCandidateAddress &&
11523  return;
11524 
11525  // Emit the generic diagnostic and, optionally, add the hints to it.
11526  PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11527  FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11528  << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11529  << (unsigned)(Cand->Fix.Kind);
11530 
11531  // Check that location of Fn is not in system header.
11532  if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11533  // If we can fix the conversion, suggest the FixIts.
11534  for (const FixItHint &HI : Cand->Fix.Hints)
11535  FDiag << HI;
11536  }
11537 
11538  S.Diag(Fn->getLocation(), FDiag);
11539 
11540  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11541 }
11542 
11543 /// Additional arity mismatch diagnosis specific to a function overload
11544 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11545 /// over a candidate in any candidate set.
11547  unsigned NumArgs) {
11548  FunctionDecl *Fn = Cand->Function;
11549  unsigned MinParams = Fn->getMinRequiredArguments();
11550 
11551  // With invalid overloaded operators, it's possible that we think we
11552  // have an arity mismatch when in fact it looks like we have the
11553  // right number of arguments, because only overloaded operators have
11554  // the weird behavior of overloading member and non-member functions.
11555  // Just don't report anything.
11556  if (Fn->isInvalidDecl() &&
11558  return true;
11559 
11560  if (NumArgs < MinParams) {
11561  assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11562  (Cand->FailureKind == ovl_fail_bad_deduction &&
11563  Cand->DeductionFailure.getResult() ==
11565  } else {
11566  assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11567  (Cand->FailureKind == ovl_fail_bad_deduction &&
11568  Cand->DeductionFailure.getResult() ==
11570  }
11571 
11572  return false;
11573 }
11574 
11575 /// General arity mismatch diagnosis over a candidate in a candidate set.
11576 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11577  unsigned NumFormalArgs) {
11578  assert(isa<FunctionDecl>(D) &&
11579  "The templated declaration should at least be a function"
11580  " when diagnosing bad template argument deduction due to too many"
11581  " or too few arguments");
11582 
11583  FunctionDecl *Fn = cast<FunctionDecl>(D);
11584 
11585  // TODO: treat calls to a missing default constructor as a special case
11586  const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11587  unsigned MinParams = Fn->getMinRequiredExplicitArguments();
11588 
11589  // at least / at most / exactly
11590  bool HasExplicitObjectParam = Fn->hasCXXExplicitFunctionObjectParameter();
11591  unsigned ParamCount = FnTy->getNumParams() - (HasExplicitObjectParam ? 1 : 0);
11592  unsigned mode, modeCount;
11593  if (NumFormalArgs < MinParams) {
11594  if (MinParams != ParamCount || FnTy->isVariadic() ||
11595  FnTy->isTemplateVariadic())
11596  mode = 0; // "at least"
11597  else
11598  mode = 2; // "exactly"
11599  modeCount = MinParams;
11600  } else {
11601  if (MinParams != ParamCount)
11602  mode = 1; // "at most"
11603  else
11604  mode = 2; // "exactly"
11605  modeCount = ParamCount;
11606  }
11607 
11608  std::string Description;
11609  std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11610  ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11611 
11612  if (modeCount == 1 &&
11613  Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11614  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11615  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11616  << Description << mode
11617  << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11618  << HasExplicitObjectParam << Fn->getParametersSourceRange();
11619  else
11620  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11621  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11622  << Description << mode << modeCount << NumFormalArgs
11623  << HasExplicitObjectParam << Fn->getParametersSourceRange();
11624 
11625  MaybeEmitInheritedConstructorNote(S, Found);
11626 }
11627 
11628 /// Arity mismatch diagnosis specific to a function overload candidate.
11630  unsigned NumFormalArgs) {
11631  if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11632  DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11633 }
11634 
11636  if (TemplateDecl *TD = Templated->getDescribedTemplate())
11637  return TD;
11638  llvm_unreachable("Unsupported: Getting the described template declaration"
11639  " for bad deduction diagnosis");
11640 }
11641 
11642 /// Diagnose a failed template-argument deduction.
11643 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11644  DeductionFailureInfo &DeductionFailure,
11645  unsigned NumArgs,
11646  bool TakingCandidateAddress) {
11647  TemplateParameter Param = DeductionFailure.getTemplateParameter();
11648  NamedDecl *ParamD;
11649  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11650  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11651  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11652  switch (DeductionFailure.getResult()) {
11654  llvm_unreachable(
11655  "TemplateDeductionResult::Success while diagnosing bad deduction");
11657  llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11658  "while diagnosing bad deduction");
11661  return;
11662 
11664  assert(ParamD && "no parameter found for incomplete deduction result");
11665  S.Diag(Templated->getLocation(),
11666  diag::note_ovl_candidate_incomplete_deduction)
11667  << ParamD->getDeclName();
11668  MaybeEmitInheritedConstructorNote(S, Found);
11669  return;
11670  }
11671 
11673  assert(ParamD && "no parameter found for incomplete deduction result");
11674  S.Diag(Templated->getLocation(),
11675  diag::note_ovl_candidate_incomplete_deduction_pack)
11676  << ParamD->getDeclName()
11677  << (DeductionFailure.getFirstArg()->pack_size() + 1)
11678  << *DeductionFailure.getFirstArg();
11679  MaybeEmitInheritedConstructorNote(S, Found);
11680  return;
11681  }
11682 
11684  assert(ParamD && "no parameter found for bad qualifiers deduction result");
11685  TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11686 
11687  QualType Param = DeductionFailure.getFirstArg()->getAsType();
11688 
11689  // Param will have been canonicalized, but it should just be a
11690  // qualified version of ParamD, so move the qualifiers to that.
11691  QualifierCollector Qs;
11692  Qs.strip(Param);
11693  QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11694  assert(S.Context.hasSameType(Param, NonCanonParam));
11695 
11696  // Arg has also been canonicalized, but there's nothing we can do
11697  // about that. It also doesn't matter as much, because it won't
11698  // have any template parameters in it (because deduction isn't
11699  // done on dependent types).
11700  QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11701 
11702  S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11703  << ParamD->getDeclName() << Arg << NonCanonParam;
11704  MaybeEmitInheritedConstructorNote(S, Found);
11705  return;
11706  }
11707 
11709  assert(ParamD && "no parameter found for inconsistent deduction result");
11710  int which = 0;
11711  if (isa<TemplateTypeParmDecl>(ParamD))
11712  which = 0;
11713  else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11714  // Deduction might have failed because we deduced arguments of two
11715  // different types for a non-type template parameter.
11716  // FIXME: Use a different TDK value for this.
11717  QualType T1 =
11718  DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11719  QualType T2 =
11720  DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11721  if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11722  S.Diag(Templated->getLocation(),
11723  diag::note_ovl_candidate_inconsistent_deduction_types)
11724  << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11725  << *DeductionFailure.getSecondArg() << T2;
11726  MaybeEmitInheritedConstructorNote(S, Found);
11727  return;
11728  }
11729 
11730  which = 1;
11731  } else {
11732  which = 2;
11733  }
11734 
11735  // Tweak the diagnostic if the problem is that we deduced packs of
11736  // different arities. We'll print the actual packs anyway in case that
11737  // includes additional useful information.
11738  if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11739  DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11740  DeductionFailure.getFirstArg()->pack_size() !=
11741  DeductionFailure.getSecondArg()->pack_size()) {
11742  which = 3;
11743  }
11744 
11745  S.Diag(Templated->getLocation(),
11746  diag::note_ovl_candidate_inconsistent_deduction)
11747  << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11748  << *DeductionFailure.getSecondArg();
11749  MaybeEmitInheritedConstructorNote(S, Found);
11750  return;
11751  }
11752 
11754  assert(ParamD && "no parameter found for invalid explicit arguments");
11755  if (ParamD->getDeclName())
11756  S.Diag(Templated->getLocation(),
11757  diag::note_ovl_candidate_explicit_arg_mismatch_named)
11758  << ParamD->getDeclName();
11759  else {
11760  int index = 0;
11761  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11762  index = TTP->getIndex();
11763  else if (NonTypeTemplateParmDecl *NTTP
11764  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11765  index = NTTP->getIndex();
11766  else
11767  index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11768  S.Diag(Templated->getLocation(),
11769  diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11770  << (index + 1);
11771  }
11772  MaybeEmitInheritedConstructorNote(S, Found);
11773  return;
11774 
11776  // Format the template argument list into the argument string.
11777  SmallString<128> TemplateArgString;
11778  TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11779  TemplateArgString = " ";
11780  TemplateArgString += S.getTemplateArgumentBindingsText(
11781  getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11782  if (TemplateArgString.size() == 1)
11783  TemplateArgString.clear();
11784  S.Diag(Templated->getLocation(),
11785  diag::note_ovl_candidate_unsatisfied_constraints)
11786  << TemplateArgString;
11787 
11789  static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11790  return;
11791  }
11794  DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11795  return;
11796 
11798  S.Diag(Templated->getLocation(),
11799  diag::note_ovl_candidate_instantiation_depth);
11800  MaybeEmitInheritedConstructorNote(S, Found);
11801  return;
11802 
11804  // Format the template argument list into the argument string.
11805  SmallString<128> TemplateArgString;
11806  if (TemplateArgumentList *Args =
11807  DeductionFailure.getTemplateArgumentList()) {
11808  TemplateArgString = " ";
11809  TemplateArgString += S.getTemplateArgumentBindingsText(
11810  getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11811  if (TemplateArgString.size() == 1)
11812  TemplateArgString.clear();
11813  }
11814 
11815  // If this candidate was disabled by enable_if, say so.
11816  PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11817  if (PDiag && PDiag->second.getDiagID() ==
11818  diag::err_typename_nested_not_found_enable_if) {
11819  // FIXME: Use the source range of the condition, and the fully-qualified
11820  // name of the enable_if template. These are both present in PDiag.
11821  S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11822  << "'enable_if'" << TemplateArgString;
11823  return;
11824  }
11825 
11826  // We found a specific requirement that disabled the enable_if.
11827  if (PDiag && PDiag->second.getDiagID() ==
11828  diag::err_typename_nested_not_found_requirement) {
11829  S.Diag(Templated->getLocation(),
11830  diag::note_ovl_candidate_disabled_by_requirement)
11831  << PDiag->second.getStringArg(0) << TemplateArgString;
11832  return;
11833  }
11834 
11835  // Format the SFINAE diagnostic into the argument string.
11836  // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11837  // formatted message in another diagnostic.
11838  SmallString<128> SFINAEArgString;
11839  SourceRange R;
11840  if (PDiag) {
11841  SFINAEArgString = ": ";
11842  R = SourceRange(PDiag->first, PDiag->first);
11843  PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11844  }
11845 
11846  S.Diag(Templated->getLocation(),
11847  diag::note_ovl_candidate_substitution_failure)
11848  << TemplateArgString << SFINAEArgString << R;
11849  MaybeEmitInheritedConstructorNote(S, Found);
11850  return;
11851  }
11852 
11855  // Format the template argument list into the argument string.
11856  SmallString<128> TemplateArgString;
11857  if (TemplateArgumentList *Args =
11858  DeductionFailure.getTemplateArgumentList()) {
11859  TemplateArgString = " ";
11860  TemplateArgString += S.getTemplateArgumentBindingsText(
11861  getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11862  if (TemplateArgString.size() == 1)
11863  TemplateArgString.clear();
11864  }
11865 
11866  S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11867  << (*DeductionFailure.getCallArgIndex() + 1)
11868  << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11869  << TemplateArgString
11870  << (DeductionFailure.getResult() ==
11872  break;
11873  }
11874 
11876  // FIXME: Provide a source location to indicate what we couldn't match.
11877  TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11878  TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11879  if (FirstTA.getKind() == TemplateArgument::Template &&
11880  SecondTA.getKind() == TemplateArgument::Template) {
11881  TemplateName FirstTN = FirstTA.getAsTemplate();
11882  TemplateName SecondTN = SecondTA.getAsTemplate();
11883  if (FirstTN.getKind() == TemplateName::Template &&
11884  SecondTN.getKind() == TemplateName::Template) {
11885  if (FirstTN.getAsTemplateDecl()->getName() ==
11886  SecondTN.getAsTemplateDecl()->getName()) {
11887  // FIXME: This fixes a bad diagnostic where both templates are named
11888  // the same. This particular case is a bit difficult since:
11889  // 1) It is passed as a string to the diagnostic printer.
11890  // 2) The diagnostic printer only attempts to find a better
11891  // name for types, not decls.
11892  // Ideally, this should folded into the diagnostic printer.
11893  S.Diag(Templated->getLocation(),
11894  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11895  << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11896  return;
11897  }
11898  }
11899  }
11900 
11901  if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11902  !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11903  return;
11904 
11905  // FIXME: For generic lambda parameters, check if the function is a lambda
11906  // call operator, and if so, emit a prettier and more informative
11907  // diagnostic that mentions 'auto' and lambda in addition to
11908  // (or instead of?) the canonical template type parameters.
11909  S.Diag(Templated->getLocation(),
11910  diag::note_ovl_candidate_non_deduced_mismatch)
11911  << FirstTA << SecondTA;
11912  return;
11913  }
11914  // TODO: diagnose these individually, then kill off
11915  // note_ovl_candidate_bad_deduction, which is uselessly vague.
11917  S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11918  MaybeEmitInheritedConstructorNote(S, Found);
11919  return;
11921  S.Diag(Templated->getLocation(),
11922  diag::note_cuda_ovl_candidate_target_mismatch);
11923  return;
11924  }
11925 }
11926 
11927 /// Diagnose a failed template-argument deduction, for function calls.
11929  unsigned NumArgs,
11930  bool TakingCandidateAddress) {
11934  if (CheckArityMismatch(S, Cand, NumArgs))
11935  return;
11936  }
11937  DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11938  Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11939 }
11940 
11941 /// CUDA: diagnose an invalid call across targets.
11942 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11943  FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11944  FunctionDecl *Callee = Cand->Function;
11945 
11946  CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11947  CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11948 
11949  std::string FnDesc;
11950  std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11951  ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11952  Cand->getRewriteKind(), FnDesc);
11953 
11954  S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11955  << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11956  << FnDesc /* Ignored */
11957  << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11958 
11959  // This could be an implicit constructor for which we could not infer the
11960  // target due to a collsion. Diagnose that case.
11961  CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11962  if (Meth != nullptr && Meth->isImplicit()) {
11963  CXXRecordDecl *ParentClass = Meth->getParent();
11965 
11966  switch (FnKindPair.first) {
11967  default:
11968  return;
11969  case oc_implicit_default_constructor:
11971  break;
11972  case oc_implicit_copy_constructor:
11974  break;
11975  case oc_implicit_move_constructor:
11977  break;
11978  case oc_implicit_copy_assignment:
11980  break;
11981  case oc_implicit_move_assignment:
11983  break;
11984  };
11985 
11986  bool ConstRHS = false;
11987  if (Meth->getNumParams()) {
11988  if (const ReferenceType *RT =
11989  Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11990  ConstRHS = RT->getPointeeType().isConstQualified();
11991  }
11992  }
11993 
11994  S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11995  /* ConstRHS */ ConstRHS,
11996  /* Diagnose */ true);
11997  }
11998 }
11999 
12001  FunctionDecl *Callee = Cand->Function;
12002  EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12003 
12004  S.Diag(Callee->getLocation(),
12005  diag::note_ovl_candidate_disabled_by_function_cond_attr)
12006  << Attr->getCond()->getSourceRange() << Attr->getMessage();
12007 }
12008 
12011  assert(ES.isExplicit() && "not an explicit candidate");
12012 
12013  unsigned Kind;
12014  switch (Cand->Function->getDeclKind()) {
12015  case Decl::Kind::CXXConstructor:
12016  Kind = 0;
12017  break;
12018  case Decl::Kind::CXXConversion:
12019  Kind = 1;
12020  break;
12021  case Decl::Kind::CXXDeductionGuide:
12022  Kind = Cand->Function->isImplicit() ? 0 : 2;
12023  break;
12024  default:
12025  llvm_unreachable("invalid Decl");
12026  }
12027 
12028  // Note the location of the first (in-class) declaration; a redeclaration
12029  // (particularly an out-of-class definition) will typically lack the
12030  // 'explicit' specifier.
12031  // FIXME: This is probably a good thing to do for all 'candidate' notes.
12033  if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12034  First = Pattern->getFirstDecl();
12035 
12036  S.Diag(First->getLocation(),
12037  diag::note_ovl_candidate_explicit)
12038  << Kind << (ES.getExpr() ? 1 : 0)
12039  << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12040 }
12041 
12042 /// Generates a 'note' diagnostic for an overload candidate. We've
12043 /// already generated a primary error at the call site.
12044 ///
12045 /// It really does need to be a single diagnostic with its caret
12046 /// pointed at the candidate declaration. Yes, this creates some
12047 /// major challenges of technical writing. Yes, this makes pointing
12048 /// out problems with specific arguments quite awkward. It's still
12049 /// better than generating twenty screens of text for every failed
12050 /// overload.
12051 ///
12052 /// It would be great to be able to express per-candidate problems
12053 /// more richly for those diagnostic clients that cared, but we'd
12054 /// still have to be just as careful with the default diagnostics.
12055 /// \param CtorDestAS Addr space of object being constructed (for ctor
12056 /// candidates only).
12058  unsigned NumArgs,
12059  bool TakingCandidateAddress,
12060  LangAS CtorDestAS = LangAS::Default) {
12061  FunctionDecl *Fn = Cand->Function;
12063  return;
12064 
12065  // There is no physical candidate declaration to point to for OpenCL builtins.
12066  // Except for failed conversions, the notes are identical for each candidate,
12067  // so do not generate such notes.
12068  if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12070  return;
12071 
12072  // Note deleted candidates, but only if they're viable.
12073  if (Cand->Viable) {
12074  if (Fn->isDeleted()) {
12075  std::string FnDesc;
12076  std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12077  ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12078  Cand->getRewriteKind(), FnDesc);
12079 
12080  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12081  << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12082  << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12083  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12084  return;
12085  }
12086 
12087  // We don't really have anything else to say about viable candidates.
12088  S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12089  return;
12090  }
12091 
12092  switch (Cand->FailureKind) {
12095  return DiagnoseArityMismatch(S, Cand, NumArgs);
12096 
12098  return DiagnoseBadDeduction(S, Cand, NumArgs,
12099  TakingCandidateAddress);
12100 
12102  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12103  << (Fn->getPrimaryTemplate() ? 1 : 0);
12104  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12105  return;
12106  }
12107 
12109  Qualifiers QualsForPrinting;
12110  QualsForPrinting.setAddressSpace(CtorDestAS);
12111  S.Diag(Fn->getLocation(),
12112  diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12113  << QualsForPrinting;
12114  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12115  return;
12116  }
12117 
12121  return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12122 
12123  case ovl_fail_bad_conversion: {
12124  unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12125  for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12126  if (Cand->Conversions[I].isBad())
12127  return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12128 
12129  // FIXME: this currently happens when we're called from SemaInit
12130  // when user-conversion overload fails. Figure out how to handle
12131  // those conditions and diagnose them well.
12132  return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12133  }
12134 
12135  case ovl_fail_bad_target:
12136  return DiagnoseBadTarget(S, Cand);
12137 
12138  case ovl_fail_enable_if:
12139  return DiagnoseFailedEnableIfAttr(S, Cand);
12140 
12141  case ovl_fail_explicit:
12142  return DiagnoseFailedExplicitSpec(S, Cand);
12143 
12145  // It's generally not interesting to note copy/move constructors here.
12146  if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12147  return;
12148  S.Diag(Fn->getLocation(),
12149  diag::note_ovl_candidate_inherited_constructor_slice)
12150  << (Fn->getPrimaryTemplate() ? 1 : 0)
12151  << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12152  MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12153  return;
12154 
12156  bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
12157  (void)Available;
12158  assert(!Available);
12159  break;
12160  }
12162  // Do nothing, these should simply be ignored.
12163  break;
12164 
12166  std::string FnDesc;
12167  std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12168  ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12169  Cand->getRewriteKind(), FnDesc);
12170 
12171  S.Diag(Fn->getLocation(),
12172  diag::note_ovl_candidate_constraints_not_satisfied)
12173  << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12174  << FnDesc /* Ignored */;
12175  ConstraintSatisfaction Satisfaction;
12176  if (S.CheckFunctionConstraints(Fn, Satisfaction))
12177  break;
12178  S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12179  }
12180  }
12181 }
12182 
12185  return;
12186 
12187  // Desugar the type of the surrogate down to a function type,
12188  // retaining as many typedefs as possible while still showing
12189  // the function type (and, therefore, its parameter types).
12190  QualType FnType = Cand->Surrogate->getConversionType();
12191  bool isLValueReference = false;
12192  bool isRValueReference = false;
12193  bool isPointer = false;
12194  if (const LValueReferenceType *FnTypeRef =
12195  FnType->getAs<LValueReferenceType>()) {
12196  FnType = FnTypeRef->getPointeeType();
12197  isLValueReference = true;
12198  } else if (const RValueReferenceType *FnTypeRef =
12199  FnType->getAs<RValueReferenceType>()) {
12200  FnType = FnTypeRef->getPointeeType();
12201  isRValueReference = true;
12202  }
12203  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12204  FnType = FnTypePtr->getPointeeType();
12205  isPointer = true;
12206  }
12207  // Desugar down to a function type.
12208  FnType = QualType(FnType->getAs<FunctionType>(), 0);
12209  // Reconstruct the pointer/reference as appropriate.
12210  if (isPointer) FnType = S.Context.getPointerType(FnType);
12211  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12212  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12213 
12214  if (!Cand->Viable &&
12216  S.Diag(Cand->Surrogate->getLocation(),
12217  diag::note_ovl_surrogate_constraints_not_satisfied)
12218  << Cand->Surrogate;
12219  ConstraintSatisfaction Satisfaction;
12220  if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12221  S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12222  } else {
12223  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12224  << FnType;
12225  }
12226 }
12227 
12228 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12229  SourceLocation OpLoc,
12230  OverloadCandidate *Cand) {
12231  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12232  std::string TypeStr("operator");
12233  TypeStr += Opc;
12234  TypeStr += "(";
12235  TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12236  if (Cand->Conversions.size() == 1) {
12237  TypeStr += ")";
12238  S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12239  } else {
12240  TypeStr += ", ";
12241  TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12242  TypeStr += ")";
12243  S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12244  }
12245 }
12246 
12248  OverloadCandidate *Cand) {
12249  for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12250  if (ICS.isBad()) break; // all meaningless after first invalid
12251  if (!ICS.isAmbiguous()) continue;
12252 
12254  S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12255  }
12256 }
12257 
12259  if (Cand->Function)
12260  return Cand->Function->getLocation();
12261  if (Cand->IsSurrogate)
12262  return Cand->Surrogate->getLocation();
12263  return SourceLocation();
12264 }
12265 
12266 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12267  switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12271  llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12272 
12276  return 1;
12277 
12280  return 2;
12281 
12289  return 3;
12290 
12292  return 4;
12293 
12295  return 5;
12296 
12299  return 6;
12300  }
12301  llvm_unreachable("Unhandled deduction result");
12302 }
12303 
12304 namespace {
12305 
12306 struct CompareOverloadCandidatesForDisplay {
12307  Sema &S;
12309  size_t NumArgs;
12311 
12312  CompareOverloadCandidatesForDisplay(
12313  Sema &S, SourceLocation Loc, size_t NArgs,
12315  : S(S), NumArgs(NArgs), CSK(CSK) {}
12316 
12317  OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12318  // If there are too many or too few arguments, that's the high-order bit we
12319  // want to sort by, even if the immediate failure kind was something else.
12320  if (C->FailureKind == ovl_fail_too_many_arguments ||
12321  C->FailureKind == ovl_fail_too_few_arguments)
12322  return static_cast<OverloadFailureKind>(C->FailureKind);
12323 
12324  if (C->Function) {
12325  if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12327  if (NumArgs < C->Function->getMinRequiredArguments())
12329  }
12330 
12331  return static_cast<OverloadFailureKind>(C->FailureKind);
12332  }
12333 
12334  bool operator()(const OverloadCandidate *L,
12335  const OverloadCandidate *R) {
12336  // Fast-path this check.
12337  if (L == R) return false;
12338 
12339  // Order first by viability.
12340  if (L->Viable) {
12341  if (!R->Viable) return true;
12342 
12343  if (int Ord = CompareConversions(*L, *R))
12344  return Ord < 0;
12345  // Use other tie breakers.
12346  } else if (R->Viable)
12347  return false;
12348 
12349  assert(L->Viable == R->Viable);
12350 
12351  // Criteria by which we can sort non-viable candidates:
12352  if (!L->Viable) {
12353  OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12354  OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12355 
12356  // 1. Arity mismatches come after other candidates.
12357  if (LFailureKind == ovl_fail_too_many_arguments ||
12358  LFailureKind == ovl_fail_too_few_arguments) {
12359  if (RFailureKind == ovl_fail_too_many_arguments ||
12360  RFailureKind == ovl_fail_too_few_arguments) {
12361  int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12362  int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12363  if (LDist == RDist) {
12364  if (LFailureKind == RFailureKind)
12365  // Sort non-surrogates before surrogates.
12366  return !L->IsSurrogate && R->IsSurrogate;
12367  // Sort candidates requiring fewer parameters than there were
12368  // arguments given after candidates requiring more parameters
12369  // than there were arguments given.
12370  return LFailureKind == ovl_fail_too_many_arguments;
12371  }
12372  return LDist < RDist;
12373  }
12374  return false;
12375  }
12376  if (RFailureKind == ovl_fail_too_many_arguments ||
12377  RFailureKind == ovl_fail_too_few_arguments)
12378  return true;
12379 
12380  // 2. Bad conversions come first and are ordered by the number
12381  // of bad conversions and quality of good conversions.
12382  if (LFailureKind == ovl_fail_bad_conversion) {
12383  if (RFailureKind != ovl_fail_bad_conversion)
12384  return true;
12385 
12386  // The conversion that can be fixed with a smaller number of changes,
12387  // comes first.
12388  unsigned numLFixes = L->Fix.NumConversionsFixed;
12389  unsigned numRFixes = R->Fix.NumConversionsFixed;
12390  numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12391  numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12392  if (numLFixes != numRFixes) {
12393  return numLFixes < numRFixes;
12394  }
12395 
12396  // If there's any ordering between the defined conversions...
12397  if (int Ord = CompareConversions(*L, *R))
12398  return Ord < 0;
12399  } else if (RFailureKind == ovl_fail_bad_conversion)
12400  return false;
12401 
12402  if (LFailureKind == ovl_fail_bad_deduction) {
12403  if (RFailureKind != ovl_fail_bad_deduction)
12404  return true;
12405 
12407  unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12408  unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12409  if (LRank != RRank)
12410  return LRank < RRank;
12411  }
12412  } else if (RFailureKind == ovl_fail_bad_deduction)
12413  return false;
12414 
12415  // TODO: others?
12416  }
12417 
12418  // Sort everything else by location.
12421 
12422  // Put candidates without locations (e.g. builtins) at the end.
12423  if (LLoc.isValid() && RLoc.isValid())
12424  return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12425  if (LLoc.isValid() && !RLoc.isValid())
12426  return true;
12427  if (RLoc.isValid() && !LLoc.isValid())
12428  return false;
12429  assert(!LLoc.isValid() && !RLoc.isValid());
12430  // For builtins and other functions without locations, fallback to the order
12431  // in which they were added into the candidate set.
12432  return L < R;
12433  }
12434 
12435 private:
12436  struct ConversionSignals {
12437  unsigned KindRank = 0;
12439 
12440  static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12441  ConversionSignals Sig;
12442  Sig.KindRank = Seq.getKindRank();
12443  if (Seq.isStandard())
12444  Sig.Rank = Seq.Standard.getRank();
12445  else if (Seq.isUserDefined())
12446  Sig.Rank = Seq.UserDefined.After.getRank();
12447  // We intend StaticObjectArgumentConversion to compare the same as
12448  // StandardConversion with ICR_ExactMatch rank.
12449  return Sig;
12450  }
12451 
12452  static ConversionSignals ForObjectArgument() {
12453  // We intend StaticObjectArgumentConversion to compare the same as
12454  // StandardConversion with ICR_ExactMatch rank. Default give us that.
12455  return {};
12456  }
12457  };
12458 
12459  // Returns -1 if conversions in L are considered better.
12460  // 0 if they are considered indistinguishable.
12461  // 1 if conversions in R are better.
12462  int CompareConversions(const OverloadCandidate &L,
12463  const OverloadCandidate &R) {
12464  // We cannot use `isBetterOverloadCandidate` because it is defined
12465  // according to the C++ standard and provides a partial order, but we need
12466  // a total order as this function is used in sort.
12467  assert(L.Conversions.size() == R.Conversions.size());
12468  for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12469  auto LS = L.IgnoreObjectArgument && I == 0
12470  ? ConversionSignals::ForObjectArgument()
12471  : ConversionSignals::ForSequence(L.Conversions[I]);
12472  auto RS = R.IgnoreObjectArgument
12473  ? ConversionSignals::ForObjectArgument()
12474  : ConversionSignals::ForSequence(R.Conversions[I]);
12475  if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12476  return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12477  ? -1
12478  : 1;
12479  }
12480  // FIXME: find a way to compare templates for being more or less
12481  // specialized that provides a strict weak ordering.
12482  return 0;
12483  }
12484 };
12485 }
12486 
12487 /// CompleteNonViableCandidate - Normally, overload resolution only
12488 /// computes up to the first bad conversion. Produces the FixIt set if
12489 /// possible.
12490 static void
12492  ArrayRef<Expr *> Args,
12494  assert(!Cand->Viable);
12495 
12496  // Don't do anything on failures other than bad conversion.
12497  if (Cand->FailureKind != ovl_fail_bad_conversion)
12498  return;
12499 
12500  // We only want the FixIts if all the arguments can be corrected.
12501  bool Unfixable = false;
12502  // Use a implicit copy initialization to check conversion fixes.
12504 
12505  // Attempt to fix the bad conversion.
12506  unsigned ConvCount = Cand->Conversions.size();
12507  for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12508  ++ConvIdx) {
12509  assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12510  if (Cand->Conversions[ConvIdx].isInitialized() &&
12511  Cand->Conversions[ConvIdx].isBad()) {
12512  Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12513  break;
12514  }
12515  }
12516 
12517  // FIXME: this should probably be preserved from the overload
12518  // operation somehow.
12519  bool SuppressUserConversions = false;
12520 
12521  unsigned ConvIdx = 0;
12522  unsigned ArgIdx = 0;
12523  ArrayRef<QualType> ParamTypes;
12524  bool Reversed = Cand->isReversed();
12525 
12526  if (Cand->IsSurrogate) {
12527  QualType ConvType
12529  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12530  ConvType = ConvPtrType->getPointeeType();
12531  ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12532  // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12533  ConvIdx = 1;
12534  } else if (Cand->Function) {
12535  ParamTypes =
12536  Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12537  if (isa<CXXMethodDecl>(Cand->Function) &&
12538  !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12539  // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12540  ConvIdx = 1;
12542  Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12544  OO_Subscript)
12545  // Argument 0 is 'this', which doesn't have a corresponding parameter.
12546  ArgIdx = 1;
12547  }
12548  } else {
12549  // Builtin operator.
12550  assert(ConvCount <= 3);
12551  ParamTypes = Cand->BuiltinParamTypes;
12552  }
12553 
12554  // Fill in the rest of the conversions.
12555  for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12556  ConvIdx != ConvCount;
12557  ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12558  assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12559  if (Cand->Conversions[ConvIdx].isInitialized()) {
12560  // We've already checked this conversion.
12561  } else if (ParamIdx < ParamTypes.size()) {
12562  if (ParamTypes[ParamIdx]->isDependentType())
12563  Cand->Conversions[ConvIdx].setAsIdentityConversion(
12564  Args[ArgIdx]->getType());
12565  else {
12566  Cand->Conversions[ConvIdx] =
12567  TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12568  SuppressUserConversions,
12569  /*InOverloadResolution=*/true,
12570  /*AllowObjCWritebackConversion=*/
12571  S.getLangOpts().ObjCAutoRefCount);
12572  // Store the FixIt in the candidate if it exists.
12573  if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12574  Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12575  }
12576  } else
12577  Cand->Conversions[ConvIdx].setEllipsis();
12578  }
12579 }
12580 
12583  SourceLocation OpLoc,
12584  llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12585  // Sort the candidates by viability and position. Sorting directly would
12586  // be prohibitive, so we make a set of pointers and sort those.
12588  if (OCD == OCD_AllCandidates) Cands.reserve(size());
12589  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12590  if (!Filter(*Cand))
12591  continue;
12592  switch (OCD) {
12593  case OCD_AllCandidates:
12594  if (!Cand->Viable) {
12595  if (!Cand->Function && !Cand->IsSurrogate) {
12596  // This a non-viable builtin candidate. We do not, in general,
12597  // want to list every possible builtin candidate.
12598  continue;
12599  }
12600  CompleteNonViableCandidate(S, Cand, Args, Kind);
12601  }
12602  break;
12603 
12604  case OCD_ViableCandidates:
12605  if (!Cand->Viable)
12606  continue;
12607  break;
12608 
12610  if (!Cand->Best)
12611  continue;
12612  break;
12613  }
12614 
12615  Cands.push_back(Cand);
12616  }
12617 
12618  llvm::stable_sort(
12619  Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12620 
12621  return Cands;
12622 }
12623 
12625  SourceLocation OpLoc) {
12626  bool DeferHint = false;
12627  if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12628  // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12629  // host device candidates.
12630  auto WrongSidedCands =
12631  CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12632  return (Cand.Viable == false &&
12633  Cand.FailureKind == ovl_fail_bad_target) ||
12634  (Cand.Function &&
12635  Cand.Function->template hasAttr<CUDAHostAttr>() &&
12636  Cand.Function->template hasAttr<CUDADeviceAttr>());
12637  });
12638  DeferHint = !WrongSidedCands.empty();
12639  }
12640  return DeferHint;
12641 }
12642 
12643 /// When overload resolution fails, prints diagnostic messages containing the
12644 /// candidates in the candidate set.
12647  ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12648  llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12649 
12650  auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12651 
12652  S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12653 
12654  // In WebAssembly we don't want to emit further diagnostics if a table is
12655  // passed as an argument to a function.
12656  bool NoteCands = true;
12657  for (const Expr *Arg : Args) {
12658  if (Arg->getType()->isWebAssemblyTableType())
12659  NoteCands = false;
12660  }
12661 
12662  if (NoteCands)
12663  NoteCandidates(S, Args, Cands, Opc, OpLoc);
12664 
12665  if (OCD == OCD_AmbiguousCandidates)
12666  MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12667 }
12668 
12671  StringRef Opc, SourceLocation OpLoc) {
12672  bool ReportedAmbiguousConversions = false;
12673 
12674  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12675  unsigned CandsShown = 0;
12676  auto I = Cands.begin(), E = Cands.end();
12677  for (; I != E; ++I) {
12678  OverloadCandidate *Cand = *I;
12679 
12680  if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12681  ShowOverloads == Ovl_Best) {
12682  break;
12683  }
12684  ++CandsShown;
12685 
12686  if (Cand->Function)
12687  NoteFunctionCandidate(S, Cand, Args.size(),
12688  /*TakingCandidateAddress=*/false, DestAS);
12689  else if (Cand->IsSurrogate)
12690  NoteSurrogateCandidate(S, Cand);
12691  else {
12692  assert(Cand->Viable &&
12693  "Non-viable built-in candidates are not added to Cands.");
12694  // Generally we only see ambiguities including viable builtin
12695  // operators if overload resolution got screwed up by an
12696  // ambiguous user-defined conversion.
12697  //
12698  // FIXME: It's quite possible for different conversions to see
12699  // different ambiguities, though.
12700  if (!ReportedAmbiguousConversions) {
12701  NoteAmbiguousUserConversions(S, OpLoc, Cand);
12702  ReportedAmbiguousConversions = true;
12703  }
12704 
12705  // If this is a viable builtin, print it.
12706  NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12707  }
12708  }
12709 
12710  // Inform S.Diags that we've shown an overload set with N elements. This may
12711  // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12712  S.Diags.overloadCandidatesShown(CandsShown);
12713 
12714  if (I != E)
12715  S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12716  shouldDeferDiags(S, Args, OpLoc))
12717  << int(E - I);
12718 }
12719 
12720 static SourceLocation
12722  return Cand->Specialization ? Cand->Specialization->getLocation()
12723  : SourceLocation();
12724 }
12725 
12726 namespace {
12727 struct CompareTemplateSpecCandidatesForDisplay {
12728  Sema &S;
12729  CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12730 
12731  bool operator()(const TemplateSpecCandidate *L,
12732  const TemplateSpecCandidate *R) {
12733  // Fast-path this check.
12734  if (L == R)
12735  return false;
12736 
12737  // Assuming that both candidates are not matches...
12738 
12739  // Sort by the ranking of deduction failures.
12743 
12744  // Sort everything else by location.
12747 
12748  // Put candidates without locations (e.g. builtins) at the end.
12749  if (LLoc.isInvalid())
12750  return false;
12751  if (RLoc.isInvalid())
12752  return true;
12753 
12754  return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12755  }
12756 };
12757 }
12758 
12759 /// Diagnose a template argument deduction failure.
12760 /// We are treating these failures as overload failures due to bad
12761 /// deductions.
12763  bool ForTakingAddress) {
12764  DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12765  DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12766 }
12767 
12768 void TemplateSpecCandidateSet::destroyCandidates() {
12769  for (iterator i = begin(), e = end(); i != e; ++i) {
12770  i->DeductionFailure.Destroy();
12771  }
12772 }
12773 
12775  destroyCandidates();
12776  Candidates.clear();
12777 }
12778 
12779 /// NoteCandidates - When no template specialization match is found, prints
12780 /// diagnostic messages containing the non-matching specializations that form
12781 /// the candidate set.
12782 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12783 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12785  // Sort the candidates by position (assuming no candidate is a match).
12786  // Sorting directly would be prohibitive, so we make a set of pointers
12787  // and sort those.
12789  Cands.reserve(size());
12790  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12791  if (Cand->Specialization)
12792  Cands.push_back(Cand);
12793  // Otherwise, this is a non-matching builtin candidate. We do not,
12794  // in general, want to list every possible builtin candidate.
12795  }
12796 
12797  llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12798 
12799  // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12800  // for generalization purposes (?).
12801  const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12802 
12804  unsigned CandsShown = 0;
12805  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12806  TemplateSpecCandidate *Cand = *I;
12807 
12808  // Set an arbitrary limit on the number of candidates we'll spam
12809  // the user with. FIXME: This limit should depend on details of the
12810  // candidate list.
12811  if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12812  break;
12813  ++CandsShown;
12814 
12815  assert(Cand->Specialization &&
12816  "Non-matching built-in candidates are not added to Cands.");
12817  Cand->NoteDeductionFailure(S, ForTakingAddress);
12818  }
12819 
12820  if (I != E)
12821  S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12822 }
12823 
12824 // [PossiblyAFunctionType] --> [Return]
12825 // NonFunctionType --> NonFunctionType
12826 // R (A) --> R(A)
12827 // R (*)(A) --> R (A)
12828 // R (&)(A) --> R (A)
12829 // R (S::*)(A) --> R (A)
12831  QualType Ret = PossiblyAFunctionType;
12832  if (const PointerType *ToTypePtr =
12833  PossiblyAFunctionType->getAs<PointerType>())
12834  Ret = ToTypePtr->getPointeeType();
12835  else if (const ReferenceType *ToTypeRef =
12836  PossiblyAFunctionType->getAs<ReferenceType>())
12837  Ret = ToTypeRef->getPointeeType();
12838  else if (const MemberPointerType *MemTypePtr =
12839  PossiblyAFunctionType->getAs<MemberPointerType>())
12840  Ret = MemTypePtr->getPointeeType();
12841  Ret =
12843  return Ret;
12844 }
12845 
12847  bool Complain = true) {
12848  if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12849  S.DeduceReturnType(FD, Loc, Complain))
12850  return true;
12851 
12852  auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12853  if (S.getLangOpts().CPlusPlus17 &&
12854  isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12855  !S.ResolveExceptionSpec(Loc, FPT))
12856  return true;
12857 
12858  return false;
12859 }
12860 
12861 namespace {
12862 // A helper class to help with address of function resolution
12863 // - allows us to avoid passing around all those ugly parameters
12864 class AddressOfFunctionResolver {
12865  Sema& S;
12866  Expr* SourceExpr;
12867  const QualType& TargetType;
12868  QualType TargetFunctionType; // Extracted function type from target type
12869 
12870  bool Complain;
12871  //DeclAccessPair& ResultFunctionAccessPair;
12873 
12874  bool TargetTypeIsNonStaticMemberFunction;
12875  bool FoundNonTemplateFunction;
12876  bool StaticMemberFunctionFromBoundPointer;
12877  bool HasComplained;
12878 
12879  OverloadExpr::FindResult OvlExprInfo;
12880  OverloadExpr *OvlExpr;
12881  TemplateArgumentListInfo OvlExplicitTemplateArgs;
12883  TemplateSpecCandidateSet FailedCandidates;
12884 
12885 public:
12886  AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12887  const QualType &TargetType, bool Complain)
12888  : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12889  Complain(Complain), Context(S.getASTContext()),
12890  TargetTypeIsNonStaticMemberFunction(
12891  !!TargetType->getAs<MemberPointerType>()),
12892  FoundNonTemplateFunction(false),
12893  StaticMemberFunctionFromBoundPointer(false),
12894  HasComplained(false),
12895  OvlExprInfo(OverloadExpr::find(SourceExpr)),
12896  OvlExpr(OvlExprInfo.Expression),
12897  FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12898  ExtractUnqualifiedFunctionTypeFromTargetType();
12899 
12900  if (TargetFunctionType->isFunctionType()) {
12901  if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12902  if (!UME->isImplicitAccess() &&
12904  StaticMemberFunctionFromBoundPointer = true;
12905  } else if (OvlExpr->hasExplicitTemplateArgs()) {
12906  DeclAccessPair dap;
12908  OvlExpr, false, &dap)) {
12909  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12910  if (!Method->isStatic()) {
12911  // If the target type is a non-function type and the function found
12912  // is a non-static member function, pretend as if that was the
12913  // target, it's the only possible type to end up with.
12914  TargetTypeIsNonStaticMemberFunction = true;
12915 
12916  // And skip adding the function if its not in the proper form.
12917  // We'll diagnose this due to an empty set of functions.
12918  if (!OvlExprInfo.HasFormOfMemberPointer)
12919  return;
12920  }
12921 
12922  Matches.push_back(std::make_pair(dap, Fn));
12923  }
12924  return;
12925  }
12926 
12927  if (OvlExpr->hasExplicitTemplateArgs())
12928  OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12929 
12930  if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12931  // C++ [over.over]p4:
12932  // If more than one function is selected, [...]
12933  if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12934  if (FoundNonTemplateFunction)
12935  EliminateAllTemplateMatches();
12936  else
12937  EliminateAllExceptMostSpecializedTemplate();
12938  }
12939  }
12940 
12941  if (S.getLangOpts().CUDA && Matches.size() > 1)
12942  EliminateSuboptimalCudaMatches();
12943  }
12944 
12945  bool hasComplained() const { return HasComplained; }
12946 
12947 private:
12948  bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12949  QualType Discard;
12950  return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12951  S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12952  }
12953 
12954  /// \return true if A is considered a better overload candidate for the
12955  /// desired type than B.
12956  bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12957  // If A doesn't have exactly the correct type, we don't want to classify it
12958  // as "better" than anything else. This way, the user is required to
12959  // disambiguate for us if there are multiple candidates and no exact match.
12960  return candidateHasExactlyCorrectType(A) &&
12961  (!candidateHasExactlyCorrectType(B) ||
12962  compareEnableIfAttrs(S, A, B) == Comparison::Better);
12963  }
12964 
12965  /// \return true if we were able to eliminate all but one overload candidate,
12966  /// false otherwise.
12967  bool eliminiateSuboptimalOverloadCandidates() {
12968  // Same algorithm as overload resolution -- one pass to pick the "best",
12969  // another pass to be sure that nothing is better than the best.
12970  auto Best = Matches.begin();
12971  for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12972  if (isBetterCandidate(I->second, Best->second))
12973  Best = I;
12974 
12975  const FunctionDecl *BestFn = Best->second;
12976  auto IsBestOrInferiorToBest = [this, BestFn](
12977  const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12978  return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12979  };
12980 
12981  // Note: We explicitly leave Matches unmodified if there isn't a clear best
12982  // option, so we can potentially give the user a better error
12983  if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12984  return false;
12985  Matches[0] = *Best;
12986  Matches.resize(1);
12987  return true;
12988  }
12989 
12990  bool isTargetTypeAFunction() const {
12991  return TargetFunctionType->isFunctionType();
12992  }
12993 
12994  // [ToType] [Return]
12995 
12996  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12997  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12998  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12999  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13000  TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13001  }
13002 
13003  // return true if any matching specializations were found
13004  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13005  const DeclAccessPair& CurAccessFunPair) {
13006  if (CXXMethodDecl *Method
13007  = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13008  // Skip non-static function templates when converting to pointer, and
13009  // static when converting to member pointer.
13010  bool CanConvertToFunctionPointer =
13011  Method->isStatic() || Method->isExplicitObjectMemberFunction();
13012  if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13013  return false;
13014  }
13015  else if (TargetTypeIsNonStaticMemberFunction)
13016  return false;
13017 
13018  // C++ [over.over]p2:
13019  // If the name is a function template, template argument deduction is
13020  // done (14.8.2.2), and if the argument deduction succeeds, the
13021  // resulting template argument list is used to generate a single
13022  // function template specialization, which is added to the set of
13023  // overloaded functions considered.
13024  FunctionDecl *Specialization = nullptr;
13025  TemplateDeductionInfo Info(FailedCandidates.getLocation());
13027  FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13028  Specialization, Info, /*IsAddressOfFunction*/ true);
13030  // Make a note of the failed deduction for diagnostics.
13031  FailedCandidates.addCandidate()
13032  .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13033  MakeDeductionFailureInfo(Context, Result, Info));
13034  return false;
13035  }
13036 
13037  // Template argument deduction ensures that we have an exact match or
13038  // compatible pointer-to-function arguments that would be adjusted by ICS.
13039  // This function template specicalization works.
13042  Context.getCanonicalType(TargetFunctionType)));
13043 
13044  if (!S.checkAddressOfFunctionIsAvailable(Specialization))
13045  return false;
13046 
13047  Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13048  return true;
13049  }
13050 
13051  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13052  const DeclAccessPair& CurAccessFunPair) {
13053  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13054  // Skip non-static functions when converting to pointer, and static
13055  // when converting to member pointer.
13056  bool CanConvertToFunctionPointer =
13057  Method->isStatic() || Method->isExplicitObjectMemberFunction();
13058  if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13059  return false;
13060  }
13061  else if (TargetTypeIsNonStaticMemberFunction)
13062  return false;
13063 
13064  if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13065  if (S.getLangOpts().CUDA) {
13066  FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13067  if (!(Caller && Caller->isImplicit()) &&
13068  !S.CUDA().IsAllowedCall(Caller, FunDecl))
13069  return false;
13070  }
13071  if (FunDecl->isMultiVersion()) {
13072  const auto *TA = FunDecl->getAttr<TargetAttr>();
13073  if (TA && !TA->isDefaultVersion())
13074  return false;
13075  const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13076  if (TVA && !TVA->isDefaultVersion())
13077  return false;
13078  }
13079 
13080  // If any candidate has a placeholder return type, trigger its deduction
13081  // now.
13082  if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13083  Complain)) {
13084  HasComplained |= Complain;
13085  return false;
13086  }
13087 
13088  if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13089  return false;
13090 
13091  // If we're in C, we need to support types that aren't exactly identical.
13092  if (!S.getLangOpts().CPlusPlus ||
13093  candidateHasExactlyCorrectType(FunDecl)) {
13094  Matches.push_back(std::make_pair(
13095  CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13096  FoundNonTemplateFunction = true;
13097  return true;
13098  }
13099  }
13100 
13101  return false;
13102  }
13103 
13104  bool FindAllFunctionsThatMatchTargetTypeExactly() {
13105  bool Ret = false;
13106 
13107  // If the overload expression doesn't have the form of a pointer to
13108  // member, don't try to convert it to a pointer-to-member type.
13109  if (IsInvalidFormOfPointerToMemberFunction())
13110  return false;
13111 
13112  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13113  E = OvlExpr->decls_end();
13114  I != E; ++I) {
13115  // Look through any using declarations to find the underlying function.
13116  NamedDecl *Fn = (*I)->getUnderlyingDecl();
13117 
13118  // C++ [over.over]p3:
13119  // Non-member functions and static member functions match
13120  // targets of type "pointer-to-function" or "reference-to-function."
13121  // Nonstatic member functions match targets of
13122  // type "pointer-to-member-function."
13123  // Note that according to DR 247, the containing class does not matter.
13124  if (FunctionTemplateDecl *FunctionTemplate
13125  = dyn_cast<FunctionTemplateDecl>(Fn)) {
13126  if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13127  Ret = true;
13128  }
13129  // If we have explicit template arguments supplied, skip non-templates.
13130  else if (!OvlExpr->hasExplicitTemplateArgs() &&
13131  AddMatchingNonTemplateFunction(Fn, I.getPair()))
13132  Ret = true;
13133  }
13134  assert(Ret || Matches.empty());
13135  return Ret;
13136  }
13137 
13138  void EliminateAllExceptMostSpecializedTemplate() {
13139  // [...] and any given function template specialization F1 is
13140  // eliminated if the set contains a second function template
13141  // specialization whose function template is more specialized
13142  // than the function template of F1 according to the partial
13143  // ordering rules of 14.5.5.2.
13144 
13145  // The algorithm specified above is quadratic. We instead use a
13146  // two-pass algorithm (similar to the one used to identify the
13147  // best viable function in an overload set) that identifies the
13148  // best function template (if it exists).
13149 
13150  UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13151  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13152  MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13153 
13154  // TODO: It looks like FailedCandidates does not serve much purpose
13155  // here, since the no_viable diagnostic has index 0.
13157  MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13158  SourceExpr->getBeginLoc(), S.PDiag(),
13159  S.PDiag(diag::err_addr_ovl_ambiguous)
13160  << Matches[0].second->getDeclName(),
13161  S.PDiag(diag::note_ovl_candidate)
13162  << (unsigned)oc_function << (unsigned)ocs_described_template,
13163  Complain, TargetFunctionType);
13164 
13165  if (Result != MatchesCopy.end()) {
13166  // Make it the first and only element
13167  Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13168  Matches[0].second = cast<FunctionDecl>(*Result);
13169  Matches.resize(1);
13170  } else
13171  HasComplained |= Complain;
13172  }
13173 
13174  void EliminateAllTemplateMatches() {
13175  // [...] any function template specializations in the set are
13176  // eliminated if the set also contains a non-template function, [...]
13177  for (unsigned I = 0, N = Matches.size(); I != N; ) {
13178  if (Matches[I].second->getPrimaryTemplate() == nullptr)
13179  ++I;
13180  else {
13181  Matches[I] = Matches[--N];
13182  Matches.resize(N);
13183  }
13184  }
13185  }
13186 
13187  void EliminateSuboptimalCudaMatches() {
13188  S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13189  Matches);
13190  }
13191 
13192 public:
13193  void ComplainNoMatchesFound() const {
13194  assert(Matches.empty());
13195  S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13196  << OvlExpr->getName() << TargetFunctionType
13197  << OvlExpr->getSourceRange();
13198  if (FailedCandidates.empty())
13199  S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13200  /*TakingAddress=*/true);
13201  else {
13202  // We have some deduction failure messages. Use them to diagnose
13203  // the function templates, and diagnose the non-template candidates
13204  // normally.
13205  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13206  IEnd = OvlExpr->decls_end();
13207  I != IEnd; ++I)
13208  if (FunctionDecl *Fun =
13209  dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13211  S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13212  /*TakingAddress=*/true);
13213  FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13214  }
13215  }
13216 
13217  bool IsInvalidFormOfPointerToMemberFunction() const {
13218  return TargetTypeIsNonStaticMemberFunction &&
13219  !OvlExprInfo.HasFormOfMemberPointer;
13220  }
13221 
13222  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13223  // TODO: Should we condition this on whether any functions might
13224  // have matched, or is it more appropriate to do that in callers?
13225  // TODO: a fixit wouldn't hurt.
13226  S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13227  << TargetType << OvlExpr->getSourceRange();
13228  }
13229 
13230  bool IsStaticMemberFunctionFromBoundPointer() const {
13231  return StaticMemberFunctionFromBoundPointer;
13232  }
13233 
13234  void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13235  S.Diag(OvlExpr->getBeginLoc(),
13236  diag::err_invalid_form_pointer_member_function)
13237  << OvlExpr->getSourceRange();
13238  }
13239 
13240  void ComplainOfInvalidConversion() const {
13241  S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13242  << OvlExpr->getName() << TargetType;
13243  }
13244 
13245  void ComplainMultipleMatchesFound() const {
13246  assert(Matches.size() > 1);
13247  S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13248  << OvlExpr->getName() << OvlExpr->getSourceRange();
13249  S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13250  /*TakingAddress=*/true);
13251  }
13252 
13253  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13254 
13255  int getNumMatches() const { return Matches.size(); }
13256 
13257  FunctionDecl* getMatchingFunctionDecl() const {
13258  if (Matches.size() != 1) return nullptr;
13259  return Matches[0].second;
13260  }
13261 
13262  const DeclAccessPair* getMatchingFunctionAccessPair() const {
13263  if (Matches.size() != 1) return nullptr;
13264  return &Matches[0].first;
13265  }
13266 };
13267 }
13268 
13269 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13270 /// an overloaded function (C++ [over.over]), where @p From is an
13271 /// expression with overloaded function type and @p ToType is the type
13272 /// we're trying to resolve to. For example:
13273 ///
13274 /// @code
13275 /// int f(double);
13276 /// int f(int);
13277 ///
13278 /// int (*pfd)(double) = f; // selects f(double)
13279 /// @endcode
13280 ///
13281 /// This routine returns the resulting FunctionDecl if it could be
13282 /// resolved, and NULL otherwise. When @p Complain is true, this
13283 /// routine will emit diagnostics if there is an error.
13284 FunctionDecl *
13286  QualType TargetType,
13287  bool Complain,
13288  DeclAccessPair &FoundResult,
13289  bool *pHadMultipleCandidates) {
13290  assert(AddressOfExpr->getType() == Context.OverloadTy);
13291 
13292  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13293  Complain);
13294  int NumMatches = Resolver.getNumMatches();
13295  FunctionDecl *Fn = nullptr;
13296  bool ShouldComplain = Complain && !Resolver.hasComplained();
13297  if (NumMatches == 0 && ShouldComplain) {
13298  if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13299  Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13300  else
13301  Resolver.ComplainNoMatchesFound();
13302  }
13303  else if (NumMatches > 1 && ShouldComplain)
13304  Resolver.ComplainMultipleMatchesFound();
13305  else if (NumMatches == 1) {
13306  Fn = Resolver.getMatchingFunctionDecl();
13307  assert(Fn);
13308  if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13309  ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13310  FoundResult = *Resolver.getMatchingFunctionAccessPair();
13311  if (Complain) {
13312  if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13313  Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13314  else
13315  CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13316  }
13317  }
13318 
13319  if (pHadMultipleCandidates)
13320  *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13321  return Fn;
13322 }
13323 
13324 /// Given an expression that refers to an overloaded function, try to
13325 /// resolve that function to a single function that can have its address taken.
13326 /// This will modify `Pair` iff it returns non-null.
13327 ///
13328 /// This routine can only succeed if from all of the candidates in the overload
13329 /// set for SrcExpr that can have their addresses taken, there is one candidate
13330 /// that is more constrained than the rest.
13331 FunctionDecl *
13334  OverloadExpr *Ovl = R.Expression;
13335  bool IsResultAmbiguous = false;
13336  FunctionDecl *Result = nullptr;
13337  DeclAccessPair DAP;
13338  SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13339 
13340  // Return positive for better, negative for worse, 0 for equal preference.
13341  auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13342  FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13343  return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13344  static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13345  };
13346 
13347  // Don't use the AddressOfResolver because we're specifically looking for
13348  // cases where we have one overload candidate that lacks
13349  // enable_if/pass_object_size/...
13350  for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13351  auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13352  if (!FD)
13353  return nullptr;
13354 
13356  continue;
13357 
13358  // If we found a better result, update Result.
13359  auto FoundBetter = [&]() {
13360  IsResultAmbiguous = false;
13361  DAP = I.getPair();
13362  Result = FD;
13363  };
13364 
13365  // We have more than one result - see if it is more constrained than the
13366  // previous one.
13367  if (Result) {
13368  // Check CUDA preference first. If the candidates have differennt CUDA
13369  // preference, choose the one with higher CUDA preference. Otherwise,
13370  // choose the one with more constraints.
13371  if (getLangOpts().CUDA) {
13372  int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13373  // FD has different preference than Result.
13374  if (PreferenceByCUDA != 0) {
13375  // FD is more preferable than Result.
13376  if (PreferenceByCUDA > 0)
13377  FoundBetter();
13378  continue;
13379  }
13380  }
13381  // FD has the same CUDA prefernece than Result. Continue check
13382  // constraints.
13383  FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13384  if (MoreConstrained != FD) {
13385  if (!MoreConstrained) {
13386  IsResultAmbiguous = true;
13387  AmbiguousDecls.push_back(FD);
13388  }
13389  continue;
13390  }
13391  // FD is more constrained - replace Result with it.
13392  }
13393  FoundBetter();
13394  }
13395 
13396  if (IsResultAmbiguous)
13397  return nullptr;
13398 
13399  if (Result) {
13401  // We skipped over some ambiguous declarations which might be ambiguous with
13402  // the selected result.
13403  for (FunctionDecl *Skipped : AmbiguousDecls) {
13404  // If skipped candidate has different CUDA preference than the result,
13405  // there is no ambiguity. Otherwise check whether they have different
13406  // constraints.
13407  if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13408  continue;
13409  if (!getMoreConstrainedFunction(Skipped, Result))
13410  return nullptr;
13411  }
13412  Pair = DAP;
13413  }
13414  return Result;
13415 }
13416 
13417 /// Given an overloaded function, tries to turn it into a non-overloaded
13418 /// function reference using resolveAddressOfSingleOverloadCandidate. This
13419 /// will perform access checks, diagnose the use of the resultant decl, and, if
13420 /// requested, potentially perform a function-to-pointer decay.
13421 ///
13422 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13423 /// Otherwise, returns true. This may emit diagnostics and return true.
13425  ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13426  Expr *E = SrcExpr.get();
13427  assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13428 
13429  DeclAccessPair DAP;
13431  if (!Found || Found->isCPUDispatchMultiVersion() ||
13432  Found->isCPUSpecificMultiVersion())
13433  return false;
13434 
13435  // Emitting multiple diagnostics for a function that is both inaccessible and
13436  // unavailable is consistent with our behavior elsewhere. So, always check
13437  // for both.
13438  DiagnoseUseOfDecl(Found, E->getExprLoc());
13440  ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13441  if (Res.isInvalid())
13442  return false;
13443  Expr *Fixed = Res.get();
13444  if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13445  SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13446  else
13447  SrcExpr = Fixed;
13448  return true;
13449 }
13450 
13451 /// Given an expression that refers to an overloaded function, try to
13452 /// resolve that overloaded function expression down to a single function.
13453 ///
13454 /// This routine can only resolve template-ids that refer to a single function
13455 /// template, where that template-id refers to a single template whose template
13456 /// arguments are either provided by the template-id or have defaults,
13457 /// as described in C++0x [temp.arg.explicit]p3.
13458 ///
13459 /// If no template-ids are found, no diagnostics are emitted and NULL is
13460 /// returned.
13462  OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13463  TemplateSpecCandidateSet *FailedTSC) {
13464  // C++ [over.over]p1:
13465  // [...] [Note: any redundant set of parentheses surrounding the
13466  // overloaded function name is ignored (5.1). ]
13467  // C++ [over.over]p1:
13468  // [...] The overloaded function name can be preceded by the &
13469  // operator.
13470 
13471  // If we didn't actually find any template-ids, we're done.
13472  if (!ovl->hasExplicitTemplateArgs())
13473  return nullptr;
13474 
13475  TemplateArgumentListInfo ExplicitTemplateArgs;
13476  ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13477 
13478  // Look through all of the overloaded functions, searching for one
13479  // whose type matches exactly.
13480  FunctionDecl *Matched = nullptr;
13481  for (UnresolvedSetIterator I = ovl->decls_begin(),
13482  E = ovl->decls_end(); I != E; ++I) {
13483  // C++0x [temp.arg.explicit]p3:
13484  // [...] In contexts where deduction is done and fails, or in contexts
13485  // where deduction is not done, if a template argument list is
13486  // specified and it, along with any default template arguments,
13487  // identifies a single function template specialization, then the
13488  // template-id is an lvalue for the function template specialization.
13489  FunctionTemplateDecl *FunctionTemplate
13490  = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13491 
13492  // C++ [over.over]p2:
13493  // If the name is a function template, template argument deduction is
13494  // done (14.8.2.2), and if the argument deduction succeeds, the
13495  // resulting template argument list is used to generate a single
13496  // function template specialization, which is added to the set of
13497  // overloaded functions considered.
13498  FunctionDecl *Specialization = nullptr;
13499  TemplateDeductionInfo Info(ovl->getNameLoc());
13501  FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13502  /*IsAddressOfFunction*/ true);
13504  // Make a note of the failed deduction for diagnostics.
13505  if (FailedTSC)
13506  FailedTSC->addCandidate().set(
13507  I.getPair(), FunctionTemplate->getTemplatedDecl(),
13508  MakeDeductionFailureInfo(Context, Result, Info));
13509  continue;
13510  }
13511 
13512  assert(Specialization && "no specialization and no error?");
13513 
13514  // Multiple matches; we can't resolve to a single declaration.
13515  if (Matched) {
13516  if (Complain) {
13517  Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13518  << ovl->getName();
13520  }
13521  return nullptr;
13522  }
13523 
13524  Matched = Specialization;
13525  if (FoundResult) *FoundResult = I.getPair();
13526  }
13527 
13528  if (Matched &&
13529  completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13530  return nullptr;
13531 
13532  return Matched;
13533 }
13534 
13535 // Resolve and fix an overloaded expression that can be resolved
13536 // because it identifies a single function template specialization.
13537 //
13538 // Last three arguments should only be supplied if Complain = true
13539 //
13540 // Return true if it was logically possible to so resolve the
13541 // expression, regardless of whether or not it succeeded. Always
13542 // returns true if 'complain' is set.
13544  ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13545  SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13546  unsigned DiagIDForComplaining) {
13547  assert(SrcExpr.get()->getType() == Context.OverloadTy);
13548 
13550 
13551  DeclAccessPair found;
13552  ExprResult SingleFunctionExpression;
13554  ovl.Expression, /*complain*/ false, &found)) {
13555  if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13556  SrcExpr = ExprError();
13557  return true;
13558  }
13559 
13560  // It is only correct to resolve to an instance method if we're
13561  // resolving a form that's permitted to be a pointer to member.
13562  // Otherwise we'll end up making a bound member expression, which
13563  // is illegal in all the contexts we resolve like this.
13564  if (!ovl.HasFormOfMemberPointer &&
13565  isa<CXXMethodDecl>(fn) &&
13566  cast<CXXMethodDecl>(fn)->isInstance()) {
13567  if (!complain) return false;
13568 
13569  Diag(ovl.Expression->getExprLoc(),
13570  diag::err_bound_member_function)
13571  << 0 << ovl.Expression->getSourceRange();
13572 
13573  // TODO: I believe we only end up here if there's a mix of
13574  // static and non-static candidates (otherwise the expression
13575  // would have 'bound member' type, not 'overload' type).
13576  // Ideally we would note which candidate was chosen and why
13577  // the static candidates were rejected.
13578  SrcExpr = ExprError();
13579  return true;
13580  }
13581 
13582  // Fix the expression to refer to 'fn'.
13583  SingleFunctionExpression =
13584  FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13585 
13586  // If desired, do function-to-pointer decay.
13587  if (doFunctionPointerConversion) {
13588  SingleFunctionExpression =
13589  DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13590  if (SingleFunctionExpression.isInvalid()) {
13591  SrcExpr = ExprError();
13592  return true;
13593  }
13594  }
13595  }
13596 
13597  if (!SingleFunctionExpression.isUsable()) {
13598  if (complain) {
13599  Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13600  << ovl.Expression->getName()
13601  << DestTypeForComplaining
13602  << OpRangeForComplaining
13604  NoteAllOverloadCandidates(SrcExpr.get());
13605 
13606  SrcExpr = ExprError();
13607  return true;
13608  }
13609 
13610  return false;
13611  }
13612 
13613  SrcExpr = SingleFunctionExpression;
13614  return true;
13615 }
13616 
13617 /// Add a single candidate to the overload set.
13619  DeclAccessPair FoundDecl,
13620  TemplateArgumentListInfo *ExplicitTemplateArgs,
13621  ArrayRef<Expr *> Args,
13622  OverloadCandidateSet &CandidateSet,
13623  bool PartialOverloading,
13624  bool KnownValid) {
13625  NamedDecl *Callee = FoundDecl.getDecl();
13626  if (isa<UsingShadowDecl>(Callee))
13627  Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13628 
13629  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13630  if (ExplicitTemplateArgs) {
13631  assert(!KnownValid && "Explicit template arguments?");
13632  return;
13633  }
13634  // Prevent ill-formed function decls to be added as overload candidates.
13635  if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13636  return;
13637 
13638  S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13639  /*SuppressUserConversions=*/false,
13640  PartialOverloading);
13641  return;
13642  }
13643 
13644  if (FunctionTemplateDecl *FuncTemplate
13645  = dyn_cast<FunctionTemplateDecl>(Callee)) {
13646  S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13647  ExplicitTemplateArgs, Args, CandidateSet,
13648  /*SuppressUserConversions=*/false,
13649  PartialOverloading);
13650  return;
13651  }
13652 
13653  assert(!KnownValid && "unhandled case in overloaded call candidate");
13654 }
13655 
13656 /// Add the overload candidates named by callee and/or found by argument
13657 /// dependent lookup to the given overload set.
13659  ArrayRef<Expr *> Args,
13660  OverloadCandidateSet &CandidateSet,
13661  bool PartialOverloading) {
13662 
13663 #ifndef NDEBUG
13664  // Verify that ArgumentDependentLookup is consistent with the rules
13665  // in C++0x [basic.lookup.argdep]p3:
13666  //
13667  // Let X be the lookup set produced by unqualified lookup (3.4.1)
13668  // and let Y be the lookup set produced by argument dependent
13669  // lookup (defined as follows). If X contains
13670  //
13671  // -- a declaration of a class member, or
13672  //
13673  // -- a block-scope function declaration that is not a
13674  // using-declaration, or
13675  //
13676  // -- a declaration that is neither a function or a function
13677  // template
13678  //
13679  // then Y is empty.
13680 
13681  if (ULE->requiresADL()) {
13683  E = ULE->decls_end(); I != E; ++I) {
13684  assert(!(*I)->getDeclContext()->isRecord());
13685  assert(isa<UsingShadowDecl>(*I) ||
13686  !(*I)->getDeclContext()->isFunctionOrMethod());
13687  assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13688  }
13689  }
13690 #endif
13691 
13692  // It would be nice to avoid this copy.
13693  TemplateArgumentListInfo TABuffer;
13694  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13695  if (ULE->hasExplicitTemplateArgs()) {
13696  ULE->copyTemplateArgumentsInto(TABuffer);
13697  ExplicitTemplateArgs = &TABuffer;
13698  }
13699 
13701  E = ULE->decls_end(); I != E; ++I)
13702  AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13703  CandidateSet, PartialOverloading,
13704  /*KnownValid*/ true);
13705 
13706  if (ULE->requiresADL())
13708  Args, ExplicitTemplateArgs,
13709  CandidateSet, PartialOverloading);
13710 }
13711 
13712 /// Add the call candidates from the given set of lookup results to the given
13713 /// overload set. Non-function lookup results are ignored.
13715  LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13716  ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13717  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13718  AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13719  CandidateSet, false, /*KnownValid*/ false);
13720 }
13721 
13722 /// Determine whether a declaration with the specified name could be moved into
13723 /// a different namespace.
13724 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13725  switch (Name.getCXXOverloadedOperator()) {
13726  case OO_New: case OO_Array_New:
13727  case OO_Delete: case OO_Array_Delete:
13728  return false;
13729 
13730  default:
13731  return true;
13732  }
13733 }
13734 
13735 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13736 /// template, where the non-dependent name was declared after the template
13737 /// was defined. This is common in code written for a compilers which do not
13738 /// correctly implement two-stage name lookup.
13739 ///
13740 /// Returns true if a viable candidate was found and a diagnostic was issued.
13742  Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13744  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13745  CXXRecordDecl **FoundInClass = nullptr) {
13746  if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13747  return false;
13748 
13749  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13750  if (DC->isTransparentContext())
13751  continue;
13752 
13754 
13755  if (!R.empty()) {
13756  R.suppressDiagnostics();
13757 
13758  OverloadCandidateSet Candidates(FnLoc, CSK);
13759  SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13760  Candidates);
13761 
13763  OverloadingResult OR =
13764  Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13765 
13766  if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13767  // We either found non-function declarations or a best viable function
13768  // at class scope. A class-scope lookup result disables ADL. Don't
13769  // look past this, but let the caller know that we found something that
13770  // either is, or might be, usable in this class.
13771  if (FoundInClass) {
13772  *FoundInClass = RD;
13773  if (OR == OR_Success) {
13774  R.clear();
13775  R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13776  R.resolveKind();
13777  }
13778  }
13779  return false;
13780  }
13781 
13782  if (OR != OR_Success) {
13783  // There wasn't a unique best function or function template.
13784  return false;
13785  }
13786 
13787  // Find the namespaces where ADL would have looked, and suggest
13788  // declaring the function there instead.
13789  Sema::AssociatedNamespaceSet AssociatedNamespaces;
13790  Sema::AssociatedClassSet AssociatedClasses;
13792  AssociatedNamespaces,
13793  AssociatedClasses);
13794  Sema::AssociatedNamespaceSet SuggestedNamespaces;
13797  for (Sema::AssociatedNamespaceSet::iterator
13798  it = AssociatedNamespaces.begin(),
13799  end = AssociatedNamespaces.end(); it != end; ++it) {
13800  // Never suggest declaring a function within namespace 'std'.
13801  if (Std && Std->Encloses(*it))
13802  continue;
13803 
13804  // Never suggest declaring a function within a namespace with a
13805  // reserved name, like __gnu_cxx.
13806  NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13807  if (NS &&
13808  NS->getQualifiedNameAsString().find("__") != std::string::npos)
13809  continue;
13810 
13811  SuggestedNamespaces.insert(*it);
13812  }
13813  }
13814 
13815  SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13816  << R.getLookupName();
13817  if (SuggestedNamespaces.empty()) {
13818  SemaRef.Diag(Best->Function->getLocation(),
13819  diag::note_not_found_by_two_phase_lookup)
13820  << R.getLookupName() << 0;
13821  } else if (SuggestedNamespaces.size() == 1) {
13822  SemaRef.Diag(Best->Function->getLocation(),
13823  diag::note_not_found_by_two_phase_lookup)
13824  << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13825  } else {
13826  // FIXME: It would be useful to list the associated namespaces here,
13827  // but the diagnostics infrastructure doesn't provide a way to produce
13828  // a localized representation of a list of items.
13829  SemaRef.Diag(Best->Function->getLocation(),
13830  diag::note_not_found_by_two_phase_lookup)
13831  << R.getLookupName() << 2;
13832  }
13833 
13834  // Try to recover by calling this function.
13835  return true;
13836  }
13837 
13838  R.clear();
13839  }
13840 
13841  return false;
13842 }
13843 
13844 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13845 /// template, where the non-dependent operator was declared after the template
13846 /// was defined.
13847 ///
13848 /// Returns true if a viable candidate was found and a diagnostic was issued.
13849 static bool
13851  SourceLocation OpLoc,
13852  ArrayRef<Expr *> Args) {
13853  DeclarationName OpName =
13855  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13856  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13858  /*ExplicitTemplateArgs=*/nullptr, Args);
13859 }
13860 
13861 namespace {
13862 class BuildRecoveryCallExprRAII {
13863  Sema &SemaRef;
13865 
13866 public:
13867  BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13868  assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13870  }
13871 
13872  ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13873 };
13874 }
13875 
13876 /// Attempts to recover from a call where no functions were found.
13877 ///
13878 /// This function will do one of three things:
13879 /// * Diagnose, recover, and return a recovery expression.
13880 /// * Diagnose, fail to recover, and return ExprError().
13881 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13882 /// expected to diagnose as appropriate.
13883 static ExprResult
13885  UnresolvedLookupExpr *ULE,
13886  SourceLocation LParenLoc,
13888  SourceLocation RParenLoc,
13889  bool EmptyLookup, bool AllowTypoCorrection) {
13890  // Do not try to recover if it is already building a recovery call.
13891  // This stops infinite loops for template instantiations like
13892  //
13893  // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13894  // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13896  return ExprResult();
13897  BuildRecoveryCallExprRAII RCE(SemaRef);
13898 
13899  CXXScopeSpec SS;
13900  SS.Adopt(ULE->getQualifierLoc());
13901  SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13902 
13903  TemplateArgumentListInfo TABuffer;
13904  TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13905  if (ULE->hasExplicitTemplateArgs()) {
13906  ULE->copyTemplateArgumentsInto(TABuffer);
13907  ExplicitTemplateArgs = &TABuffer;
13908  }
13909 
13910  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13912  CXXRecordDecl *FoundInClass = nullptr;
13913  if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13915  ExplicitTemplateArgs, Args, &FoundInClass)) {
13916  // OK, diagnosed a two-phase lookup issue.
13917  } else if (EmptyLookup) {
13918  // Try to recover from an empty lookup with typo correction.
13919  R.clear();
13920  NoTypoCorrectionCCC NoTypoValidator{};
13921  FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13922  ExplicitTemplateArgs != nullptr,
13923  dyn_cast<MemberExpr>(Fn));
13924  CorrectionCandidateCallback &Validator =
13925  AllowTypoCorrection
13926  ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13927  : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13928  if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13929  Args))
13930  return ExprError();
13931  } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13932  // We found a usable declaration of the name in a dependent base of some
13933  // enclosing class.
13934  // FIXME: We should also explain why the candidates found by name lookup
13935  // were not viable.
13937  return ExprError();
13938  } else {
13939  // We had viable candidates and couldn't recover; let the caller diagnose
13940  // this.
13941  return ExprResult();
13942  }
13943 
13944  // If we get here, we should have issued a diagnostic and formed a recovery
13945  // lookup result.
13946  assert(!R.empty() && "lookup results empty despite recovery");
13947 
13948  // If recovery created an ambiguity, just bail out.
13949  if (R.isAmbiguous()) {
13950  R.suppressDiagnostics();
13951  return ExprError();
13952  }
13953 
13954  // Build an implicit member call if appropriate. Just drop the
13955  // casts and such from the call, we don't really care.
13956  ExprResult NewFn = ExprError();
13957  if ((*R.begin())->isCXXClassMember())
13958  NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13959  ExplicitTemplateArgs, S);
13960  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13961  NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13962  ExplicitTemplateArgs);
13963  else
13964  NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13965 
13966  if (NewFn.isInvalid())
13967  return ExprError();
13968 
13969  // This shouldn't cause an infinite loop because we're giving it
13970  // an expression with viable lookup results, which should never
13971  // end up here.
13972  return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13973  MultiExprArg(Args.data(), Args.size()),
13974  RParenLoc);
13975 }
13976 
13977 /// Constructs and populates an OverloadedCandidateSet from
13978 /// the given function.
13979 /// \returns true when an the ExprResult output parameter has been set.
13981  UnresolvedLookupExpr *ULE,
13982  MultiExprArg Args,
13983  SourceLocation RParenLoc,
13984  OverloadCandidateSet *CandidateSet,
13985  ExprResult *Result) {
13986 #ifndef NDEBUG
13987  if (ULE->requiresADL()) {
13988  // To do ADL, we must have found an unqualified name.
13989  assert(!ULE->getQualifier() && "qualified name with ADL");
13990 
13991  // We don't perform ADL for implicit declarations of builtins.
13992  // Verify that this was correctly set up.
13993  FunctionDecl *F;
13994  if (ULE->decls_begin() != ULE->decls_end() &&
13995  ULE->decls_begin() + 1 == ULE->decls_end() &&
13996  (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13997  F->getBuiltinID() && F->isImplicit())
13998  llvm_unreachable("performing ADL for builtin");
13999 
14000  // We don't perform ADL in C.
14001  assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14002  }
14003 #endif
14004 
14005  UnbridgedCastsSet UnbridgedCasts;
14006  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14007  *Result = ExprError();
14008  return true;
14009  }
14010 
14011  // Add the functions denoted by the callee to the set of candidate
14012  // functions, including those from argument-dependent lookup.
14013  AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14014 
14015  if (getLangOpts().MSVCCompat &&
14017  (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14018 
14020  if (CandidateSet->empty() ||
14021  CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14023  // In Microsoft mode, if we are inside a template class member function
14024  // then create a type dependent CallExpr. The goal is to postpone name
14025  // lookup to instantiation time to be able to search into type dependent
14026  // base classes.
14027  CallExpr *CE =
14029  RParenLoc, CurFPFeatureOverrides());
14031  *Result = CE;
14032  return true;
14033  }
14034  }
14035 
14036  if (CandidateSet->empty())
14037  return false;
14038 
14039  UnbridgedCasts.restore();
14040  return false;
14041 }
14042 
14043 // Guess at what the return type for an unresolvable overload should be.
14046  std::optional<QualType> Result;
14047  // Adjust Type after seeing a candidate.
14048  auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14049  if (!Candidate.Function)
14050  return;
14051  if (Candidate.Function->isInvalidDecl())
14052  return;
14053  QualType T = Candidate.Function->getReturnType();
14054  if (T.isNull())
14055  return;
14056  if (!Result)
14057  Result = T;
14058  else if (Result != T)
14059  Result = QualType();
14060  };
14061 
14062  // Look for an unambiguous type from a progressively larger subset.
14063  // e.g. if types disagree, but all *viable* overloads return int, choose int.
14064  //
14065  // First, consider only the best candidate.
14066  if (Best && *Best != CS.end())
14067  ConsiderCandidate(**Best);
14068  // Next, consider only viable candidates.
14069  if (!Result)
14070  for (const auto &C : CS)
14071  if (C.Viable)
14072  ConsiderCandidate(C);
14073  // Finally, consider all candidates.
14074  if (!Result)
14075  for (const auto &C : CS)
14076  ConsiderCandidate(C);
14077 
14078  if (!Result)
14079  return QualType();
14080  auto Value = *Result;
14081  if (Value.isNull() || Value->isUndeducedType())
14082  return QualType();
14083  return Value;
14084 }
14085 
14086 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14087 /// the completed call expression. If overload resolution fails, emits
14088 /// diagnostics and returns ExprError()
14090  UnresolvedLookupExpr *ULE,
14091  SourceLocation LParenLoc,
14092  MultiExprArg Args,
14093  SourceLocation RParenLoc,
14094  Expr *ExecConfig,
14095  OverloadCandidateSet *CandidateSet,
14097  OverloadingResult OverloadResult,
14098  bool AllowTypoCorrection) {
14099  switch (OverloadResult) {
14100  case OR_Success: {
14101  FunctionDecl *FDecl = (*Best)->Function;
14102  SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14103  if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14104  return ExprError();
14105  ExprResult Res =
14106  SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14107  if (Res.isInvalid())
14108  return ExprError();
14110  Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14111  /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14112  }
14113 
14114  case OR_No_Viable_Function: {
14115  // Try to recover by looking for viable functions which the user might
14116  // have meant to call.
14117  ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14118  Args, RParenLoc,
14119  CandidateSet->empty(),
14120  AllowTypoCorrection);
14121  if (Recovery.isInvalid() || Recovery.isUsable())
14122  return Recovery;
14123 
14124  // If the user passes in a function that we can't take the address of, we
14125  // generally end up emitting really bad error messages. Here, we attempt to
14126  // emit better ones.
14127  for (const Expr *Arg : Args) {
14128  if (!Arg->getType()->isFunctionType())
14129  continue;
14130  if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14131  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14132  if (FD &&
14133  !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14134  Arg->getExprLoc()))
14135  return ExprError();
14136  }
14137  }
14138 
14139  CandidateSet->NoteCandidates(
14141  Fn->getBeginLoc(),
14142  SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14143  << ULE->getName() << Fn->getSourceRange()),
14144  SemaRef, OCD_AllCandidates, Args);
14145  break;
14146  }
14147 
14148  case OR_Ambiguous:
14149  CandidateSet->NoteCandidates(
14151  SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14152  << ULE->getName() << Fn->getSourceRange()),
14154  break;
14155 
14156  case OR_Deleted: {
14157  FunctionDecl *FDecl = (*Best)->Function;
14159  Fn->getSourceRange(), ULE->getName(),
14160  *CandidateSet, FDecl, Args);
14161 
14162  // We emitted an error for the unavailable/deleted function call but keep
14163  // the call in the AST.
14164  ExprResult Res =
14165  SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14166  if (Res.isInvalid())
14167  return ExprError();
14169  Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14170  /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14171  }
14172  }
14173 
14174  // Overload resolution failed, try to recover.
14175  SmallVector<Expr *, 8> SubExprs = {Fn};
14176  SubExprs.append(Args.begin(), Args.end());
14177  return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14178  chooseRecoveryType(*CandidateSet, Best));
14179 }
14180 
14182  OverloadCandidateSet &CS) {
14183  for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14184  if (I->Viable &&
14185  !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14186  I->Viable = false;
14187  I->FailureKind = ovl_fail_addr_not_available;
14188  }
14189  }
14190 }
14191 
14192 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
14193 /// (which eventually refers to the declaration Func) and the call
14194 /// arguments Args/NumArgs, attempt to resolve the function call down
14195 /// to a specific function. If overload resolution succeeds, returns
14196 /// the call expression produced by overload resolution.
14197 /// Otherwise, emits diagnostics and returns ExprError.
14199  UnresolvedLookupExpr *ULE,
14200  SourceLocation LParenLoc,
14201  MultiExprArg Args,
14202  SourceLocation RParenLoc,
14203  Expr *ExecConfig,
14204  bool AllowTypoCorrection,
14205  bool CalleesAddressIsTaken) {
14206  OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
14208  ExprResult result;
14209 
14210  if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14211  &result))
14212  return result;
14213 
14214  // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14215  // functions that aren't addressible are considered unviable.
14216  if (CalleesAddressIsTaken)
14217  markUnaddressableCandidatesUnviable(*this, CandidateSet);
14218 
14220  OverloadingResult OverloadResult =
14221  CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14222 
14223  // Model the case with a call to a templated function whose definition
14224  // encloses the call and whose return type contains a placeholder type as if
14225  // the UnresolvedLookupExpr was type-dependent.
14226  if (OverloadResult == OR_Success) {
14227  const FunctionDecl *FDecl = Best->Function;
14228  if (FDecl && FDecl->isTemplateInstantiation() &&
14229  FDecl->getReturnType()->isUndeducedType()) {
14230  if (const auto *TP =
14231  FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14232  TP && TP->willHaveBody()) {
14233  return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14234  VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14235  }
14236  }
14237  }
14238 
14239  return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14240  ExecConfig, &CandidateSet, &Best,
14241  OverloadResult, AllowTypoCorrection);
14242 }
14243 
14245  NestedNameSpecifierLoc NNSLoc,
14246  DeclarationNameInfo DNI,
14247  const UnresolvedSetImpl &Fns,
14248  bool PerformADL) {
14249  return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
14250  PerformADL, Fns.begin(), Fns.end(),
14251  /*KnownDependent=*/false);
14252 }
14253 
14255  CXXConversionDecl *Method,
14256  bool HadMultipleCandidates) {
14257  // Convert the expression to match the conversion function's implicit object
14258  // parameter.
14259  ExprResult Exp;
14260  if (Method->isExplicitObjectMemberFunction())
14261  Exp = InitializeExplicitObjectArgument(*this, E, Method);
14262  else
14263  Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14264  FoundDecl, Method);
14265  if (Exp.isInvalid())
14266  return true;
14267 
14268  if (Method->getParent()->isLambda() &&
14269  Method->getConversionType()->isBlockPointerType()) {
14270  // This is a lambda conversion to block pointer; check if the argument
14271  // was a LambdaExpr.
14272  Expr *SubE = E;
14273  auto *CE = dyn_cast<CastExpr>(SubE);
14274  if (CE && CE->getCastKind() == CK_NoOp)
14275  SubE = CE->getSubExpr();
14276  SubE = SubE->IgnoreParens();
14277  if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14278  SubE = BE->getSubExpr();
14279  if (isa<LambdaExpr>(SubE)) {
14280  // For the conversion to block pointer on a lambda expression, we
14281  // construct a special BlockLiteral instead; this doesn't really make
14282  // a difference in ARC, but outside of ARC the resulting block literal
14283  // follows the normal lifetime rules for block literals instead of being
14284  // autoreleased.
14288  Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14290 
14291  // FIXME: This note should be produced by a CodeSynthesisContext.
14292  if (BlockExp.isInvalid())
14293  Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14294  return BlockExp;
14295  }
14296  }
14297  CallExpr *CE;
14298  QualType ResultType = Method->getReturnType();
14299  ExprValueKind VK = Expr::getValueKindForType(ResultType);
14300  ResultType = ResultType.getNonLValueExprType(Context);
14301  if (Method->isExplicitObjectMemberFunction()) {
14302  ExprResult FnExpr =
14303  CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14304  HadMultipleCandidates, E->getBeginLoc());
14305  if (FnExpr.isInvalid())
14306  return ExprError();
14307  Expr *ObjectParam = Exp.get();
14308  CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14309  ResultType, VK, Exp.get()->getEndLoc(),
14311  } else {
14312  MemberExpr *ME =
14313  BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14315  DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14316  HadMultipleCandidates, DeclarationNameInfo(),
14318 
14319  CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14320  Exp.get()->getEndLoc(),
14322  }
14323 
14324  if (CheckFunctionCall(Method, CE,
14325  Method->getType()->castAs<FunctionProtoType>()))
14326  return ExprError();
14327 
14328  return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14329 }
14330 
14331 /// Create a unary operation that may resolve to an overloaded
14332 /// operator.
14333 ///
14334 /// \param OpLoc The location of the operator itself (e.g., '*').
14335 ///
14336 /// \param Opc The UnaryOperatorKind that describes this operator.
14337 ///
14338 /// \param Fns The set of non-member functions that will be
14339 /// considered by overload resolution. The caller needs to build this
14340 /// set based on the context using, e.g.,
14341 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14342 /// set should not contain any member functions; those will be added
14343 /// by CreateOverloadedUnaryOp().
14344 ///
14345 /// \param Input The input argument.
14346 ExprResult
14348  const UnresolvedSetImpl &Fns,
14349  Expr *Input, bool PerformADL) {
14351  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14353  // TODO: provide better source location info.
14354  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14355 
14356  if (checkPlaceholderForOverload(*this, Input))
14357  return ExprError();
14358 
14359  Expr *Args[2] = { Input, nullptr };
14360  unsigned NumArgs = 1;
14361 
14362  // For post-increment and post-decrement, add the implicit '0' as
14363  // the second argument, so that we know this is a post-increment or
14364  // post-decrement.
14365  if (Opc == UO_PostInc || Opc == UO_PostDec) {
14367  Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14368  SourceLocation());
14369  NumArgs = 2;
14370  }
14371 
14372  ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14373 
14374  if (Input->isTypeDependent()) {
14376  // [C++26][expr.unary.op][expr.pre.incr]
14377  // The * operator yields an lvalue of type
14378  // The pre/post increment operators yied an lvalue.
14379  if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14380  VK = VK_LValue;
14381 
14382  if (Fns.empty())
14383  return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14384  OK_Ordinary, OpLoc, false,
14386 
14387  CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14389  NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14390  if (Fn.isInvalid())
14391  return ExprError();
14392  return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14393  Context.DependentTy, VK_PRValue, OpLoc,
14395  }
14396 
14397  // Build an empty overload set.
14399 
14400  // Add the candidates from the given function set.
14401  AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14402 
14403  // Add operator candidates that are member functions.
14404  AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14405 
14406  // Add candidates from ADL.
14407  if (PerformADL) {
14408  AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14409  /*ExplicitTemplateArgs*/nullptr,
14410  CandidateSet);
14411  }
14412 
14413  // Add builtin operator candidates.
14414  AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14415 
14416  bool HadMultipleCandidates = (CandidateSet.size() > 1);
14417 
14418  // Perform overload resolution.
14420  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14421  case OR_Success: {
14422  // We found a built-in operator or an overloaded operator.
14423  FunctionDecl *FnDecl = Best->Function;
14424 
14425  if (FnDecl) {
14426  Expr *Base = nullptr;
14427  // We matched an overloaded operator. Build a call to that
14428  // operator.
14429 
14430  // Convert the arguments.
14431  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14432  CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14433 
14434  ExprResult InputInit;
14435  if (Method->isExplicitObjectMemberFunction())
14436  InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14437  else
14439  Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14440  if (InputInit.isInvalid())
14441  return ExprError();
14442  Base = Input = InputInit.get();
14443  } else {
14444  // Convert the arguments.
14445  ExprResult InputInit
14447  Context,
14448  FnDecl->getParamDecl(0)),
14449  SourceLocation(),
14450  Input);
14451  if (InputInit.isInvalid())
14452  return ExprError();
14453  Input = InputInit.get();
14454  }
14455 
14456  // Build the actual expression node.
14457  ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14458  Base, HadMultipleCandidates,
14459  OpLoc);
14460  if (FnExpr.isInvalid())
14461  return ExprError();
14462 
14463  // Determine the result type.
14464  QualType ResultTy = FnDecl->getReturnType();
14466  ResultTy = ResultTy.getNonLValueExprType(Context);
14467 
14468  Args[0] = Input;
14470  Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14471  CurFPFeatureOverrides(), Best->IsADLCandidate);
14472 
14473  if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14474  return ExprError();
14475 
14476  if (CheckFunctionCall(FnDecl, TheCall,
14477  FnDecl->getType()->castAs<FunctionProtoType>()))
14478  return ExprError();
14479  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14480  } else {
14481  // We matched a built-in operator. Convert the arguments, then
14482  // break out so that we will build the appropriate built-in
14483  // operator node.
14485  Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
14487  if (InputRes.isInvalid())
14488  return ExprError();
14489  Input = InputRes.get();
14490  break;
14491  }
14492  }
14493 
14494  case OR_No_Viable_Function:
14495  // This is an erroneous use of an operator which can be overloaded by
14496  // a non-member function. Check for non-member operators which were
14497  // defined too late to be candidates.
14498  if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14499  // FIXME: Recover by calling the found function.
14500  return ExprError();
14501 
14502  // No viable function; fall through to handling this as a
14503  // built-in operator, which will produce an error message for us.
14504  break;
14505 
14506  case OR_Ambiguous:
14507  CandidateSet.NoteCandidates(
14508  PartialDiagnosticAt(OpLoc,
14509  PDiag(diag::err_ovl_ambiguous_oper_unary)
14511  << Input->getType() << Input->getSourceRange()),
14512  *this, OCD_AmbiguousCandidates, ArgsArray,
14513  UnaryOperator::getOpcodeStr(Opc), OpLoc);
14514  return ExprError();
14515 
14516  case OR_Deleted: {
14517  // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14518  // object whose method was called. Later in NoteCandidates size of ArgsArray
14519  // is passed further and it eventually ends up compared to number of
14520  // function candidate parameters which never includes the object parameter,
14521  // so slice ArgsArray to make sure apples are compared to apples.
14522  StringLiteral *Msg = Best->Function->getDeletedMessage();
14523  CandidateSet.NoteCandidates(
14524  PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14526  << (Msg != nullptr)
14527  << (Msg ? Msg->getString() : StringRef())
14528  << Input->getSourceRange()),
14529  *this, OCD_AllCandidates, ArgsArray.drop_front(),
14530  UnaryOperator::getOpcodeStr(Opc), OpLoc);
14531  return ExprError();
14532  }
14533  }
14534 
14535  // Either we found no viable overloaded operator or we matched a
14536  // built-in operator. In either case, fall through to trying to
14537  // build a built-in operation.
14538  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14539 }
14540 
14541 /// Perform lookup for an overloaded binary operator.
14544  const UnresolvedSetImpl &Fns,
14545  ArrayRef<Expr *> Args, bool PerformADL) {
14546  SourceLocation OpLoc = CandidateSet.getLocation();
14547 
14548  OverloadedOperatorKind ExtraOp =
14551  : OO_None;
14552 
14553  // Add the candidates from the given function set. This also adds the
14554  // rewritten candidates using these functions if necessary.
14555  AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14556 
14557  // Add operator candidates that are member functions.
14558  AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14559  if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14560  AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14562 
14563  // In C++20, also add any rewritten member candidates.
14564  if (ExtraOp) {
14565  AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14566  if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14567  AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14568  CandidateSet,
14570  }
14571 
14572  // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14573  // performed for an assignment operator (nor for operator[] nor operator->,
14574  // which don't get here).
14575  if (Op != OO_Equal && PerformADL) {
14577  AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14578  /*ExplicitTemplateArgs*/ nullptr,
14579  CandidateSet);
14580  if (ExtraOp) {
14581  DeclarationName ExtraOpName =
14583  AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14584  /*ExplicitTemplateArgs*/ nullptr,
14585  CandidateSet);
14586  }
14587  }
14588 
14589  // Add builtin operator candidates.
14590  //
14591  // FIXME: We don't add any rewritten candidates here. This is strictly
14592  // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14593  // resulting in our selecting a rewritten builtin candidate. For example:
14594  //
14595  // enum class E { e };
14596  // bool operator!=(E, E) requires false;
14597  // bool k = E::e != E::e;
14598  //
14599  // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14600  // it seems unreasonable to consider rewritten builtin candidates. A core
14601  // issue has been filed proposing to removed this requirement.
14602  AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14603 }
14604 
14605 /// Create a binary operation that may resolve to an overloaded
14606 /// operator.
14607 ///
14608 /// \param OpLoc The location of the operator itself (e.g., '+').
14609 ///
14610 /// \param Opc The BinaryOperatorKind that describes this operator.
14611 ///
14612 /// \param Fns The set of non-member functions that will be
14613 /// considered by overload resolution. The caller needs to build this
14614 /// set based on the context using, e.g.,
14615 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14616 /// set should not contain any member functions; those will be added
14617 /// by CreateOverloadedBinOp().
14618 ///
14619 /// \param LHS Left-hand argument.
14620 /// \param RHS Right-hand argument.
14621 /// \param PerformADL Whether to consider operator candidates found by ADL.
14622 /// \param AllowRewrittenCandidates Whether to consider candidates found by
14623 /// C++20 operator rewrites.
14624 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
14625 /// the function in question. Such a function is never a candidate in
14626 /// our overload resolution. This also enables synthesizing a three-way
14627 /// comparison from < and == as described in C++20 [class.spaceship]p1.
14629  BinaryOperatorKind Opc,
14630  const UnresolvedSetImpl &Fns, Expr *LHS,
14631  Expr *RHS, bool PerformADL,
14632  bool AllowRewrittenCandidates,
14633  FunctionDecl *DefaultedFn) {
14634  Expr *Args[2] = { LHS, RHS };
14635  LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14636 
14637  if (!getLangOpts().CPlusPlus20)
14638  AllowRewrittenCandidates = false;
14639 
14641 
14642  // If either side is type-dependent, create an appropriate dependent
14643  // expression.
14644  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14645  if (Fns.empty()) {
14646  // If there are no functions to store, just build a dependent
14647  // BinaryOperator or CompoundAssignment.
14650  Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14653  return BinaryOperator::Create(
14654  Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14656  }
14657 
14658  // FIXME: save results of ADL from here?
14659  CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14660  // TODO: provide better source location info in DNLoc component.
14662  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14664  NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14665  if (Fn.isInvalid())
14666  return ExprError();
14667  return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14668  Context.DependentTy, VK_PRValue, OpLoc,
14670  }
14671 
14672  // If this is the .* operator, which is not overloadable, just
14673  // create a built-in binary operator.
14674  if (Opc == BO_PtrMemD) {
14675  auto CheckPlaceholder = [&](Expr *&Arg) {
14676  ExprResult Res = CheckPlaceholderExpr(Arg);
14677  if (Res.isUsable())
14678  Arg = Res.get();
14679  return !Res.isUsable();
14680  };
14681 
14682  // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14683  // expression that contains placeholders (in either the LHS or RHS).
14684  if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14685  return ExprError();
14686  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14687  }
14688 
14689  // Always do placeholder-like conversions on the RHS.
14690  if (checkPlaceholderForOverload(*this, Args[1]))
14691  return ExprError();
14692 
14693  // Do placeholder-like conversion on the LHS; note that we should
14694  // not get here with a PseudoObject LHS.
14695  assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14696  if (checkPlaceholderForOverload(*this, Args[0]))
14697  return ExprError();
14698 
14699  // If this is the assignment operator, we only perform overload resolution
14700  // if the left-hand side is a class or enumeration type. This is actually
14701  // a hack. The standard requires that we do overload resolution between the
14702  // various built-in candidates, but as DR507 points out, this can lead to
14703  // problems. So we do it this way, which pretty much follows what GCC does.
14704  // Note that we go the traditional code path for compound assignment forms.
14705  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14706  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14707 
14708  // Build the overload set.
14711  Op, OpLoc, AllowRewrittenCandidates));
14712  if (DefaultedFn)
14713  CandidateSet.exclude(DefaultedFn);
14714  LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14715 
14716  bool HadMultipleCandidates = (CandidateSet.size() > 1);
14717 
14718  // Perform overload resolution.
14720  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14721  case OR_Success: {
14722  // We found a built-in operator or an overloaded operator.
14723  FunctionDecl *FnDecl = Best->Function;
14724 
14725  bool IsReversed = Best->isReversed();
14726  if (IsReversed)
14727  std::swap(Args[0], Args[1]);
14728 
14729  if (FnDecl) {
14730 
14731  if (FnDecl->isInvalidDecl())
14732  return ExprError();
14733 
14734  Expr *Base = nullptr;
14735  // We matched an overloaded operator. Build a call to that
14736  // operator.
14737 
14738  OverloadedOperatorKind ChosenOp =
14740 
14741  // C++2a [over.match.oper]p9:
14742  // If a rewritten operator== candidate is selected by overload
14743  // resolution for an operator@, its return type shall be cv bool
14744  if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14745  !FnDecl->getReturnType()->isBooleanType()) {
14746  bool IsExtension =
14748  Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14749  : diag::err_ovl_rewrite_equalequal_not_bool)
14750  << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14751  << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14752  Diag(FnDecl->getLocation(), diag::note_declared_at);
14753  if (!IsExtension)
14754  return ExprError();
14755  }
14756 
14757  if (AllowRewrittenCandidates && !IsReversed &&
14758  CandidateSet.getRewriteInfo().isReversible()) {
14759  // We could have reversed this operator, but didn't. Check if some
14760  // reversed form was a viable candidate, and if so, if it had a
14761  // better conversion for either parameter. If so, this call is
14762  // formally ambiguous, and allowing it is an extension.
14764  for (OverloadCandidate &Cand : CandidateSet) {
14765  if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14766  allowAmbiguity(Context, Cand.Function, FnDecl)) {
14767  for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14769  *this, OpLoc, Cand.Conversions[ArgIdx],
14770  Best->Conversions[ArgIdx]) ==
14772  AmbiguousWith.push_back(Cand.Function);
14773  break;
14774  }
14775  }
14776  }
14777  }
14778 
14779  if (!AmbiguousWith.empty()) {
14780  bool AmbiguousWithSelf =
14781  AmbiguousWith.size() == 1 &&
14782  declaresSameEntity(AmbiguousWith.front(), FnDecl);
14783  Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14785  << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14786  << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14787  if (AmbiguousWithSelf) {
14788  Diag(FnDecl->getLocation(),
14789  diag::note_ovl_ambiguous_oper_binary_reversed_self);
14790  // Mark member== const or provide matching != to disallow reversed
14791  // args. Eg.
14792  // struct S { bool operator==(const S&); };
14793  // S()==S();
14794  if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14795  if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14796  !MD->isConst() &&
14797  !MD->hasCXXExplicitFunctionObjectParameter() &&
14799  MD->getFunctionObjectParameterType(),
14800  MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14802  MD->getFunctionObjectParameterType(),
14803  Args[0]->getType()) &&
14805  MD->getFunctionObjectParameterType(),
14806  Args[1]->getType()))
14807  Diag(FnDecl->getLocation(),
14808  diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14809  } else {
14810  Diag(FnDecl->getLocation(),
14811  diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14812  for (auto *F : AmbiguousWith)
14813  Diag(F->getLocation(),
14814  diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14815  }
14816  }
14817  }
14818 
14819  // Check for nonnull = nullable.
14820  // This won't be caught in the arg's initialization: the parameter to
14821  // the assignment operator is not marked nonnull.
14822  if (Op == OO_Equal)
14823  diagnoseNullableToNonnullConversion(Args[0]->getType(),
14824  Args[1]->getType(), OpLoc);
14825 
14826  // Convert the arguments.
14827  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14828  // Best->Access is only meaningful for class members.
14829  CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14830 
14831  ExprResult Arg0, Arg1;
14832  unsigned ParamIdx = 0;
14833  if (Method->isExplicitObjectMemberFunction()) {
14834  Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14835  ParamIdx = 1;
14836  } else {
14838  Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14839  }
14842  Context, FnDecl->getParamDecl(ParamIdx)),
14843  SourceLocation(), Args[1]);
14844  if (Arg0.isInvalid() || Arg1.isInvalid())
14845  return ExprError();
14846 
14847  Base = Args[0] = Arg0.getAs<Expr>();
14848  Args[1] = RHS = Arg1.getAs<Expr>();
14849  } else {
14850  // Convert the arguments.
14853  FnDecl->getParamDecl(0)),
14854  SourceLocation(), Args[0]);
14855  if (Arg0.isInvalid())
14856  return ExprError();
14857 
14858  ExprResult Arg1 =
14861  FnDecl->getParamDecl(1)),
14862  SourceLocation(), Args[1]);
14863  if (Arg1.isInvalid())
14864  return ExprError();
14865  Args[0] = LHS = Arg0.getAs<Expr>();
14866  Args[1] = RHS = Arg1.getAs<Expr>();
14867  }
14868 
14869  // Build the actual expression node.
14870  ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14871  Best->FoundDecl, Base,
14872  HadMultipleCandidates, OpLoc);
14873  if (FnExpr.isInvalid())
14874  return ExprError();
14875 
14876  // Determine the result type.
14877  QualType ResultTy = FnDecl->getReturnType();
14879  ResultTy = ResultTy.getNonLValueExprType(Context);
14880 
14881  CallExpr *TheCall;
14882  ArrayRef<const Expr *> ArgsArray(Args, 2);
14883  const Expr *ImplicitThis = nullptr;
14884 
14885  // We always create a CXXOperatorCallExpr, even for explicit object
14886  // members; CodeGen should take care not to emit the this pointer.
14887  TheCall = CXXOperatorCallExpr::Create(
14888  Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14889  CurFPFeatureOverrides(), Best->IsADLCandidate);
14890 
14891  if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14892  Method && Method->isImplicitObjectMemberFunction()) {
14893  // Cut off the implicit 'this'.
14894  ImplicitThis = ArgsArray[0];
14895  ArgsArray = ArgsArray.slice(1);
14896  }
14897 
14898  if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14899  FnDecl))
14900  return ExprError();
14901 
14902  // Check for a self move.
14903  if (Op == OO_Equal)
14904  DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14905 
14906  if (ImplicitThis) {
14907  QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14908  QualType ThisTypeFromDecl = Context.getPointerType(
14909  cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14910 
14911  CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14912  ThisTypeFromDecl);
14913  }
14914 
14915  checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14916  isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14918 
14919  ExprResult R = MaybeBindToTemporary(TheCall);
14920  if (R.isInvalid())
14921  return ExprError();
14922 
14923  R = CheckForImmediateInvocation(R, FnDecl);
14924  if (R.isInvalid())
14925  return ExprError();
14926 
14927  // For a rewritten candidate, we've already reversed the arguments
14928  // if needed. Perform the rest of the rewrite now.
14929  if ((Best->RewriteKind & CRK_DifferentOperator) ||
14930  (Op == OO_Spaceship && IsReversed)) {
14931  if (Op == OO_ExclaimEqual) {
14932  assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14933  R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14934  } else {
14935  assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14937  Expr *ZeroLiteral =
14939 
14942  Ctx.Entity = FnDecl;
14944 
14946  OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14947  IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14948  /*AllowRewrittenCandidates=*/false);
14949 
14951  }
14952  if (R.isInvalid())
14953  return ExprError();
14954  } else {
14955  assert(ChosenOp == Op && "unexpected operator name");
14956  }
14957 
14958  // Make a note in the AST if we did any rewriting.
14959  if (Best->RewriteKind != CRK_None)
14960  R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14961 
14962  return R;
14963  } else {
14964  // We matched a built-in operator. Convert the arguments, then
14965  // break out so that we will build the appropriate built-in
14966  // operator node.
14968  Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14970  if (ArgsRes0.isInvalid())
14971  return ExprError();
14972  Args[0] = ArgsRes0.get();
14973 
14975  Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14977  if (ArgsRes1.isInvalid())
14978  return ExprError();
14979  Args[1] = ArgsRes1.get();
14980  break;
14981  }
14982  }
14983 
14984  case OR_No_Viable_Function: {
14985  // C++ [over.match.oper]p9:
14986  // If the operator is the operator , [...] and there are no
14987  // viable functions, then the operator is assumed to be the
14988  // built-in operator and interpreted according to clause 5.
14989  if (Opc == BO_Comma)
14990  break;
14991 
14992  // When defaulting an 'operator<=>', we can try to synthesize a three-way
14993  // compare result using '==' and '<'.
14994  if (DefaultedFn && Opc == BO_Cmp) {
14995  ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14996  Args[1], DefaultedFn);
14997  if (E.isInvalid() || E.isUsable())
14998  return E;
14999  }
15000 
15001  // For class as left operand for assignment or compound assignment
15002  // operator do not fall through to handling in built-in, but report that
15003  // no overloaded assignment operator found
15004  ExprResult Result = ExprError();
15005  StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15006  auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15007  Args, OpLoc);
15008  DeferDiagsRAII DDR(*this,
15009  CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15010  if (Args[0]->getType()->isRecordType() &&
15011  Opc >= BO_Assign && Opc <= BO_OrAssign) {
15012  Diag(OpLoc, diag::err_ovl_no_viable_oper)
15014  << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15015  if (Args[0]->getType()->isIncompleteType()) {
15016  Diag(OpLoc, diag::note_assign_lhs_incomplete)
15017  << Args[0]->getType()
15018  << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15019  }
15020  } else {
15021  // This is an erroneous use of an operator which can be overloaded by
15022  // a non-member function. Check for non-member operators which were
15023  // defined too late to be candidates.
15024  if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15025  // FIXME: Recover by calling the found function.
15026  return ExprError();
15027 
15028  // No viable function; try to create a built-in operation, which will
15029  // produce an error. Then, show the non-viable candidates.
15030  Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15031  }
15032  assert(Result.isInvalid() &&
15033  "C++ binary operator overloading is missing candidates!");
15034  CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15035  return Result;
15036  }
15037 
15038  case OR_Ambiguous:
15039  CandidateSet.NoteCandidates(
15040  PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15042  << Args[0]->getType()
15043  << Args[1]->getType()
15044  << Args[0]->getSourceRange()
15045  << Args[1]->getSourceRange()),
15047  OpLoc);
15048  return ExprError();
15049 
15050  case OR_Deleted: {
15051  if (isImplicitlyDeleted(Best->Function)) {
15052  FunctionDecl *DeletedFD = Best->Function;
15054  if (DFK.isSpecialMember()) {
15055  Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15056  << Args[0]->getType()
15057  << llvm::to_underlying(DFK.asSpecialMember());
15058  } else {
15059  assert(DFK.isComparison());
15060  Diag(OpLoc, diag::err_ovl_deleted_comparison)
15061  << Args[0]->getType() << DeletedFD;
15062  }
15063 
15064  // The user probably meant to call this special member. Just
15065  // explain why it's deleted.
15066  NoteDeletedFunction(DeletedFD);
15067  return ExprError();
15068  }
15069 
15070  StringLiteral *Msg = Best->Function->getDeletedMessage();
15071  CandidateSet.NoteCandidates(
15073  OpLoc,
15074  PDiag(diag::err_ovl_deleted_oper)
15075  << getOperatorSpelling(Best->Function->getDeclName()
15076  .getCXXOverloadedOperator())
15077  << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15078  << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15080  OpLoc);
15081  return ExprError();
15082  }
15083  }
15084 
15085  // We matched a built-in operator; build it.
15086  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15087 }
15088 
15090  SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15091  FunctionDecl *DefaultedFn) {
15092  const ComparisonCategoryInfo *Info =
15094  // If we're not producing a known comparison category type, we can't
15095  // synthesize a three-way comparison. Let the caller diagnose this.
15096  if (!Info)
15097  return ExprResult((Expr*)nullptr);
15098 
15099  // If we ever want to perform this synthesis more generally, we will need to
15100  // apply the temporary materialization conversion to the operands.
15101  assert(LHS->isGLValue() && RHS->isGLValue() &&
15102  "cannot use prvalue expressions more than once");
15103  Expr *OrigLHS = LHS;
15104  Expr *OrigRHS = RHS;
15105 
15106  // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15107  // each of them multiple times below.
15108  LHS = new (Context)
15109  OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15110  LHS->getObjectKind(), LHS);
15111  RHS = new (Context)
15112  OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15113  RHS->getObjectKind(), RHS);
15114 
15115  ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15116  DefaultedFn);
15117  if (Eq.isInvalid())
15118  return ExprError();
15119 
15120  ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15121  true, DefaultedFn);
15122  if (Less.isInvalid())
15123  return ExprError();
15124 
15126  if (Info->isPartial()) {
15127  Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15128  DefaultedFn);
15129  if (Greater.isInvalid())
15130  return ExprError();
15131  }
15132 
15133  // Form the list of comparisons we're going to perform.
15134  struct Comparison {
15135  ExprResult Cmp;
15136  ComparisonCategoryResult Result;
15137  } Comparisons[4] =
15143  };
15144 
15145  int I = Info->isPartial() ? 3 : 2;
15146 
15147  // Combine the comparisons with suitable conditional expressions.
15148  ExprResult Result;
15149  for (; I >= 0; --I) {
15150  // Build a reference to the comparison category constant.
15151  auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15152  // FIXME: Missing a constant for a comparison category. Diagnose this?
15153  if (!VI)
15154  return ExprResult((Expr*)nullptr);
15155  ExprResult ThisResult =
15157  if (ThisResult.isInvalid())
15158  return ExprError();
15159 
15160  // Build a conditional unless this is the final case.
15161  if (Result.get()) {
15162  Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15163  ThisResult.get(), Result.get());
15164  if (Result.isInvalid())
15165  return ExprError();
15166  } else {
15167  Result = ThisResult;
15168  }
15169  }
15170 
15171  // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15172  // bind the OpaqueValueExprs before they're (repeatedly) used.
15173  Expr *SyntacticForm = BinaryOperator::Create(
15174  Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15175  Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15177  Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15178  return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15179 }
15180 
15182  Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15183  MultiExprArg Args, SourceLocation LParenLoc) {
15184 
15185  const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15186  unsigned NumParams = Proto->getNumParams();
15187  unsigned NumArgsSlots =
15188  MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15189  // Build the full argument list for the method call (the implicit object
15190  // parameter is placed at the beginning of the list).
15191  MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15192  bool IsError = false;
15193  // Initialize the implicit object parameter.
15194  // Check the argument types.
15195  for (unsigned i = 0; i != NumParams; i++) {
15196  Expr *Arg;
15197  if (i < Args.size()) {
15198  Arg = Args[i];
15199  ExprResult InputInit =
15201  S.Context, Method->getParamDecl(i)),
15202  SourceLocation(), Arg);
15203  IsError |= InputInit.isInvalid();
15204  Arg = InputInit.getAs<Expr>();
15205  } else {
15206  ExprResult DefArg =
15207  S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15208  if (DefArg.isInvalid()) {
15209  IsError = true;
15210  break;
15211  }
15212  Arg = DefArg.getAs<Expr>();
15213  }
15214 
15215  MethodArgs.push_back(Arg);
15216  }
15217  return IsError;
15218 }
15219 
15221  SourceLocation RLoc,
15222  Expr *Base,
15223  MultiExprArg ArgExpr) {
15225  Args.push_back(Base);
15226  for (auto *e : ArgExpr) {
15227  Args.push_back(e);
15228  }
15229  DeclarationName OpName =
15231 
15232  SourceRange Range = ArgExpr.empty()
15233  ? SourceRange{}
15234  : SourceRange(ArgExpr.front()->getBeginLoc(),
15235  ArgExpr.back()->getEndLoc());
15236 
15237  // If either side is type-dependent, create an appropriate dependent
15238  // expression.
15240 
15241  CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15242  // CHECKME: no 'operator' keyword?
15243  DeclarationNameInfo OpNameInfo(OpName, LLoc);
15244  OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15246  NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15247  if (Fn.isInvalid())
15248  return ExprError();
15249  // Can't add any actual overloads yet
15250 
15251  return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15254  }
15255 
15256  // Handle placeholders
15257  UnbridgedCastsSet UnbridgedCasts;
15258  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15259  return ExprError();
15260  }
15261  // Build an empty overload set.
15263 
15264  // Subscript can only be overloaded as a member function.
15265 
15266  // Add operator candidates that are member functions.
15267  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15268 
15269  // Add builtin operator candidates.
15270  if (Args.size() == 2)
15271  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15272 
15273  bool HadMultipleCandidates = (CandidateSet.size() > 1);
15274 
15275  // Perform overload resolution.
15277  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15278  case OR_Success: {
15279  // We found a built-in operator or an overloaded operator.
15280  FunctionDecl *FnDecl = Best->Function;
15281 
15282  if (FnDecl) {
15283  // We matched an overloaded operator. Build a call to that
15284  // operator.
15285 
15286  CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15287 
15288  // Convert the arguments.
15289  CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15290  SmallVector<Expr *, 2> MethodArgs;
15291 
15292  // Initialize the object parameter.
15293  if (Method->isExplicitObjectMemberFunction()) {
15294  ExprResult Res =
15295  InitializeExplicitObjectArgument(*this, Args[0], Method);
15296  if (Res.isInvalid())
15297  return ExprError();
15298  Args[0] = Res.get();
15299  ArgExpr = Args;
15300  } else {
15302  Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15303  if (Arg0.isInvalid())
15304  return ExprError();
15305 
15306  MethodArgs.push_back(Arg0.get());
15307  }
15308 
15310  *this, MethodArgs, Method, ArgExpr, LLoc);
15311  if (IsError)
15312  return ExprError();
15313 
15314  // Build the actual expression node.
15315  DeclarationNameInfo OpLocInfo(OpName, LLoc);
15316  OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15318  *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15319  OpLocInfo.getLoc(), OpLocInfo.getInfo());
15320  if (FnExpr.isInvalid())
15321  return ExprError();
15322 
15323  // Determine the result type
15324  QualType ResultTy = FnDecl->getReturnType();
15326  ResultTy = ResultTy.getNonLValueExprType(Context);
15327 
15329  Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15331 
15332  if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15333  return ExprError();
15334 
15335  if (CheckFunctionCall(Method, TheCall,
15336  Method->getType()->castAs<FunctionProtoType>()))
15337  return ExprError();
15338 
15340  FnDecl);
15341  } else {
15342  // We matched a built-in operator. Convert the arguments, then
15343  // break out so that we will build the appropriate built-in
15344  // operator node.
15346  Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15348  if (ArgsRes0.isInvalid())
15349  return ExprError();
15350  Args[0] = ArgsRes0.get();
15351 
15353  Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15355  if (ArgsRes1.isInvalid())
15356  return ExprError();
15357  Args[1] = ArgsRes1.get();
15358 
15359  break;
15360  }
15361  }
15362 
15363  case OR_No_Viable_Function: {
15364  PartialDiagnostic PD =
15365  CandidateSet.empty()
15366  ? (PDiag(diag::err_ovl_no_oper)
15367  << Args[0]->getType() << /*subscript*/ 0
15368  << Args[0]->getSourceRange() << Range)
15369  : (PDiag(diag::err_ovl_no_viable_subscript)
15370  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15371  CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15372  OCD_AllCandidates, ArgExpr, "[]", LLoc);
15373  return ExprError();
15374  }
15375 
15376  case OR_Ambiguous:
15377  if (Args.size() == 2) {
15378  CandidateSet.NoteCandidates(
15380  LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15381  << "[]" << Args[0]->getType() << Args[1]->getType()
15382  << Args[0]->getSourceRange() << Range),
15383  *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15384  } else {
15385  CandidateSet.NoteCandidates(
15386  PartialDiagnosticAt(LLoc,
15387  PDiag(diag::err_ovl_ambiguous_subscript_call)
15388  << Args[0]->getType()
15389  << Args[0]->getSourceRange() << Range),
15390  *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15391  }
15392  return ExprError();
15393 
15394  case OR_Deleted: {
15395  StringLiteral *Msg = Best->Function->getDeletedMessage();
15396  CandidateSet.NoteCandidates(
15397  PartialDiagnosticAt(LLoc,
15398  PDiag(diag::err_ovl_deleted_oper)
15399  << "[]" << (Msg != nullptr)
15400  << (Msg ? Msg->getString() : StringRef())
15401  << Args[0]->getSourceRange() << Range),
15402  *this, OCD_AllCandidates, Args, "[]", LLoc);
15403  return ExprError();
15404  }
15405  }
15406 
15407  // We matched a built-in operator; build it.
15408  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15409 }
15410 
15411 /// BuildCallToMemberFunction - Build a call to a member
15412 /// function. MemExpr is the expression that refers to the member
15413 /// function (and includes the object parameter), Args/NumArgs are the
15414 /// arguments to the function call (not including the object
15415 /// parameter). The caller needs to validate that the member
15416 /// expression refers to a non-static member function or an overloaded
15417 /// member function.
15419  SourceLocation LParenLoc,
15420  MultiExprArg Args,
15421  SourceLocation RParenLoc,
15422  Expr *ExecConfig, bool IsExecConfig,
15423  bool AllowRecovery) {
15424  assert(MemExprE->getType() == Context.BoundMemberTy ||
15425  MemExprE->getType() == Context.OverloadTy);
15426 
15427  // Dig out the member expression. This holds both the object
15428  // argument and the member function we're referring to.
15429  Expr *NakedMemExpr = MemExprE->IgnoreParens();
15430 
15431  // Determine whether this is a call to a pointer-to-member function.
15432  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15433  assert(op->getType() == Context.BoundMemberTy);
15434  assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15435 
15436  QualType fnType =
15437  op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15438 
15439  const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15440  QualType resultType = proto->getCallResultType(Context);
15442 
15443  // Check that the object type isn't more qualified than the
15444  // member function we're calling.
15445  Qualifiers funcQuals = proto->getMethodQuals();
15446 
15447  QualType objectType = op->getLHS()->getType();
15448  if (op->getOpcode() == BO_PtrMemI)
15449  objectType = objectType->castAs<PointerType>()->getPointeeType();
15450  Qualifiers objectQuals = objectType.getQualifiers();
15451 
15452  Qualifiers difference = objectQuals - funcQuals;
15453  difference.removeObjCGCAttr();
15454  difference.removeAddressSpace();
15455  if (difference) {
15456  std::string qualsString = difference.getAsString();
15457  Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15458  << fnType.getUnqualifiedType()
15459  << qualsString
15460  << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15461  }
15462 
15464  Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15465  CurFPFeatureOverrides(), proto->getNumParams());
15466 
15467  if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15468  call, nullptr))
15469  return ExprError();
15470 
15471  if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15472  return ExprError();
15473 
15474  if (CheckOtherCall(call, proto))
15475  return ExprError();
15476 
15477  return MaybeBindToTemporary(call);
15478  }
15479 
15480  // We only try to build a recovery expr at this level if we can preserve
15481  // the return type, otherwise we return ExprError() and let the caller
15482  // recover.
15483  auto BuildRecoveryExpr = [&](QualType Type) {
15484  if (!AllowRecovery)
15485  return ExprError();
15486  std::vector<Expr *> SubExprs = {MemExprE};
15487  llvm::append_range(SubExprs, Args);
15488  return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15489  Type);
15490  };
15491  if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15492  return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15493  RParenLoc, CurFPFeatureOverrides());
15494 
15495  UnbridgedCastsSet UnbridgedCasts;
15496  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15497  return ExprError();
15498 
15499  MemberExpr *MemExpr;
15500  CXXMethodDecl *Method = nullptr;
15501  bool HadMultipleCandidates = false;
15502  DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15503  NestedNameSpecifier *Qualifier = nullptr;
15504  if (isa<MemberExpr>(NakedMemExpr)) {
15505  MemExpr = cast<MemberExpr>(NakedMemExpr);
15506  Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15507  FoundDecl = MemExpr->getFoundDecl();
15508  Qualifier = MemExpr->getQualifier();
15509  UnbridgedCasts.restore();
15510  } else {
15511  UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15512  Qualifier = UnresExpr->getQualifier();
15513 
15514  QualType ObjectType = UnresExpr->getBaseType();
15515  Expr::Classification ObjectClassification
15517  : UnresExpr->getBase()->Classify(Context);
15518 
15519  // Add overload candidates
15520  OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15522 
15523  // FIXME: avoid copy.
15524  TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15525  if (UnresExpr->hasExplicitTemplateArgs()) {
15526  UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15527  TemplateArgs = &TemplateArgsBuffer;
15528  }
15529 
15530  for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15531  E = UnresExpr->decls_end(); I != E; ++I) {
15532 
15533  QualType ExplicitObjectType = ObjectType;
15534 
15535  NamedDecl *Func = *I;
15536  CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15537  if (isa<UsingShadowDecl>(Func))
15538  Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15539 
15540  bool HasExplicitParameter = false;
15541  if (const auto *M = dyn_cast<FunctionDecl>(Func);
15542  M && M->hasCXXExplicitFunctionObjectParameter())
15543  HasExplicitParameter = true;
15544  else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15545  M &&
15546  M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15547  HasExplicitParameter = true;
15548 
15549  if (HasExplicitParameter)
15550  ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15551 
15552  // Microsoft supports direct constructor calls.
15553  if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15554  AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15555  CandidateSet,
15556  /*SuppressUserConversions*/ false);
15557  } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15558  // If explicit template arguments were provided, we can't call a
15559  // non-template member function.
15560  if (TemplateArgs)
15561  continue;
15562 
15563  AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15564  ObjectClassification, Args, CandidateSet,
15565  /*SuppressUserConversions=*/false);
15566  } else {
15567  AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15568  I.getPair(), ActingDC, TemplateArgs,
15569  ExplicitObjectType, ObjectClassification,
15570  Args, CandidateSet,
15571  /*SuppressUserConversions=*/false);
15572  }
15573  }
15574 
15575  HadMultipleCandidates = (CandidateSet.size() > 1);
15576 
15577  DeclarationName DeclName = UnresExpr->getMemberName();
15578 
15579  UnbridgedCasts.restore();
15580 
15582  bool Succeeded = false;
15583  switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15584  Best)) {
15585  case OR_Success:
15586  Method = cast<CXXMethodDecl>(Best->Function);
15587  FoundDecl = Best->FoundDecl;
15588  CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15589  if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15590  break;
15591  // If FoundDecl is different from Method (such as if one is a template
15592  // and the other a specialization), make sure DiagnoseUseOfDecl is
15593  // called on both.
15594  // FIXME: This would be more comprehensively addressed by modifying
15595  // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15596  // being used.
15597  if (Method != FoundDecl.getDecl() &&
15598  DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15599  break;
15600  Succeeded = true;
15601  break;
15602 
15603  case OR_No_Viable_Function:
15604  CandidateSet.NoteCandidates(
15606  UnresExpr->getMemberLoc(),
15607  PDiag(diag::err_ovl_no_viable_member_function_in_call)
15608  << DeclName << MemExprE->getSourceRange()),
15609  *this, OCD_AllCandidates, Args);
15610  break;
15611  case OR_Ambiguous:
15612  CandidateSet.NoteCandidates(
15613  PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15614  PDiag(diag::err_ovl_ambiguous_member_call)
15615  << DeclName << MemExprE->getSourceRange()),
15616  *this, OCD_AmbiguousCandidates, Args);
15617  break;
15618  case OR_Deleted:
15620  UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15621  CandidateSet, Best->Function, Args, /*IsMember=*/true);
15622  break;
15623  }
15624  // Overload resolution fails, try to recover.
15625  if (!Succeeded)
15626  return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15627 
15628  ExprResult Res =
15629  FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15630  if (Res.isInvalid())
15631  return ExprError();
15632  MemExprE = Res.get();
15633 
15634  // If overload resolution picked a static member
15635  // build a non-member call based on that function.
15636  if (Method->isStatic()) {
15637  return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15638  ExecConfig, IsExecConfig);
15639  }
15640 
15641  MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15642  }
15643 
15644  QualType ResultType = Method->getReturnType();
15645  ExprValueKind VK = Expr::getValueKindForType(ResultType);
15646  ResultType = ResultType.getNonLValueExprType(Context);
15647 
15648  assert(Method && "Member call to something that isn't a method?");
15649  const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15650 
15651  CallExpr *TheCall = nullptr;
15653  if (Method->isExplicitObjectMemberFunction()) {
15654  if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15655  NewArgs))
15656  return ExprError();
15657 
15658  // Build the actual expression node.
15659  ExprResult FnExpr =
15660  CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15661  HadMultipleCandidates, MemExpr->getExprLoc());
15662  if (FnExpr.isInvalid())
15663  return ExprError();
15664 
15665  TheCall =
15666  CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15667  CurFPFeatureOverrides(), Proto->getNumParams());
15668  } else {
15669  // Convert the object argument (for a non-static member function call).
15670  // We only need to do this if there was actually an overload; otherwise
15671  // it was done at lookup.
15673  MemExpr->getBase(), Qualifier, FoundDecl, Method);
15674  if (ObjectArg.isInvalid())
15675  return ExprError();
15676  MemExpr->setBase(ObjectArg.get());
15677  TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15678  RParenLoc, CurFPFeatureOverrides(),
15679  Proto->getNumParams());
15680  }
15681 
15682  // Check for a valid return type.
15683  if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15684  TheCall, Method))
15685  return BuildRecoveryExpr(ResultType);
15686 
15687  // Convert the rest of the arguments
15688  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15689  RParenLoc))
15690  return BuildRecoveryExpr(ResultType);
15691 
15692  DiagnoseSentinelCalls(Method, LParenLoc, Args);
15693 
15694  if (CheckFunctionCall(Method, TheCall, Proto))
15695  return ExprError();
15696 
15697  // In the case the method to call was not selected by the overloading
15698  // resolution process, we still need to handle the enable_if attribute. Do
15699  // that here, so it will not hide previous -- and more relevant -- errors.
15700  if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15701  if (const EnableIfAttr *Attr =
15702  CheckEnableIf(Method, LParenLoc, Args, true)) {
15703  Diag(MemE->getMemberLoc(),
15704  diag::err_ovl_no_viable_member_function_in_call)
15705  << Method << Method->getSourceRange();
15706  Diag(Method->getLocation(),
15707  diag::note_ovl_candidate_disabled_by_function_cond_attr)
15708  << Attr->getCond()->getSourceRange() << Attr->getMessage();
15709  return ExprError();
15710  }
15711  }
15712 
15713  if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15714  TheCall->getDirectCallee()->isPureVirtual()) {
15715  const FunctionDecl *MD = TheCall->getDirectCallee();
15716 
15717  if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15718  MemExpr->performsVirtualDispatch(getLangOpts())) {
15719  Diag(MemExpr->getBeginLoc(),
15720  diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15721  << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15722  << MD->getParent();
15723 
15724  Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15725  if (getLangOpts().AppleKext)
15726  Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15727  << MD->getParent() << MD->getDeclName();
15728  }
15729  }
15730 
15731  if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15732  // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15733  bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15734  CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15735  CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15736  MemExpr->getMemberLoc());
15737  }
15738 
15740  TheCall->getDirectCallee());
15741 }
15742 
15743 /// BuildCallToObjectOfClassType - Build a call to an object of class
15744 /// type (C++ [over.call.object]), which can end up invoking an
15745 /// overloaded function call operator (@c operator()) or performing a
15746 /// user-defined conversion on the object argument.
15747 ExprResult
15749  SourceLocation LParenLoc,
15750  MultiExprArg Args,
15751  SourceLocation RParenLoc) {
15752  if (checkPlaceholderForOverload(*this, Obj))
15753  return ExprError();
15754  ExprResult Object = Obj;
15755 
15756  UnbridgedCastsSet UnbridgedCasts;
15757  if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15758  return ExprError();
15759 
15760  assert(Object.get()->getType()->isRecordType() &&
15761  "Requires object type argument");
15762 
15763  // C++ [over.call.object]p1:
15764  // If the primary-expression E in the function call syntax
15765  // evaluates to a class object of type "cv T", then the set of
15766  // candidate functions includes at least the function call
15767  // operators of T. The function call operators of T are obtained by
15768  // ordinary lookup of the name operator() in the context of
15769  // (E).operator().
15770  OverloadCandidateSet CandidateSet(LParenLoc,
15773 
15774  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15775  diag::err_incomplete_object_call, Object.get()))
15776  return true;
15777 
15778  const auto *Record = Object.get()->getType()->castAs<RecordType>();
15779  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15780  LookupQualifiedName(R, Record->getDecl());
15781  R.suppressAccessDiagnostics();
15782 
15783  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15784  Oper != OperEnd; ++Oper) {
15785  AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15786  Object.get()->Classify(Context), Args, CandidateSet,
15787  /*SuppressUserConversion=*/false);
15788  }
15789 
15790  // When calling a lambda, both the call operator, and
15791  // the conversion operator to function pointer
15792  // are considered. But when constraint checking
15793  // on the call operator fails, it will also fail on the
15794  // conversion operator as the constraints are always the same.
15795  // As the user probably does not intend to perform a surrogate call,
15796  // we filter them out to produce better error diagnostics, ie to avoid
15797  // showing 2 failed overloads instead of one.
15798  bool IgnoreSurrogateFunctions = false;
15799  if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15800  const OverloadCandidate &Candidate = *CandidateSet.begin();
15801  if (!Candidate.Viable &&
15803  IgnoreSurrogateFunctions = true;
15804  }
15805 
15806  // C++ [over.call.object]p2:
15807  // In addition, for each (non-explicit in C++0x) conversion function
15808  // declared in T of the form
15809  //
15810  // operator conversion-type-id () cv-qualifier;
15811  //
15812  // where cv-qualifier is the same cv-qualification as, or a
15813  // greater cv-qualification than, cv, and where conversion-type-id
15814  // denotes the type "pointer to function of (P1,...,Pn) returning
15815  // R", or the type "reference to pointer to function of
15816  // (P1,...,Pn) returning R", or the type "reference to function
15817  // of (P1,...,Pn) returning R", a surrogate call function [...]
15818  // is also considered as a candidate function. Similarly,
15819  // surrogate call functions are added to the set of candidate
15820  // functions for each conversion function declared in an
15821  // accessible base class provided the function is not hidden
15822  // within T by another intervening declaration.
15823  const auto &Conversions =
15824  cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15825  for (auto I = Conversions.begin(), E = Conversions.end();
15826  !IgnoreSurrogateFunctions && I != E; ++I) {
15827  NamedDecl *D = *I;
15828  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15829  if (isa<UsingShadowDecl>(D))
15830  D = cast<UsingShadowDecl>(D)->getTargetDecl();
15831 
15832  // Skip over templated conversion functions; they aren't
15833  // surrogates.
15834  if (isa<FunctionTemplateDecl>(D))
15835  continue;
15836 
15837  CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15838  if (!Conv->isExplicit()) {
15839  // Strip the reference type (if any) and then the pointer type (if
15840  // any) to get down to what might be a function type.
15841  QualType ConvType = Conv->getConversionType().getNonReferenceType();
15842  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15843  ConvType = ConvPtrType->getPointeeType();
15844 
15845  if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15846  {
15847  AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15848  Object.get(), Args, CandidateSet);
15849  }
15850  }
15851  }
15852 
15853  bool HadMultipleCandidates = (CandidateSet.size() > 1);
15854 
15855  // Perform overload resolution.
15857  switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15858  Best)) {
15859  case OR_Success:
15860  // Overload resolution succeeded; we'll build the appropriate call
15861  // below.
15862  break;
15863 
15864  case OR_No_Viable_Function: {
15865  PartialDiagnostic PD =
15866  CandidateSet.empty()
15867  ? (PDiag(diag::err_ovl_no_oper)
15868  << Object.get()->getType() << /*call*/ 1
15869  << Object.get()->getSourceRange())
15870  : (PDiag(diag::err_ovl_no_viable_object_call)
15871  << Object.get()->getType() << Object.get()->getSourceRange());
15872  CandidateSet.NoteCandidates(
15873  PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15874  OCD_AllCandidates, Args);
15875  break;
15876  }
15877  case OR_Ambiguous:
15878  if (!R.isAmbiguous())
15879  CandidateSet.NoteCandidates(
15880  PartialDiagnosticAt(Object.get()->getBeginLoc(),
15881  PDiag(diag::err_ovl_ambiguous_object_call)
15882  << Object.get()->getType()
15883  << Object.get()->getSourceRange()),
15884  *this, OCD_AmbiguousCandidates, Args);
15885  break;
15886 
15887  case OR_Deleted: {
15888  // FIXME: Is this diagnostic here really necessary? It seems that
15889  // 1. we don't have any tests for this diagnostic, and
15890  // 2. we already issue err_deleted_function_use for this later on anyway.
15891  StringLiteral *Msg = Best->Function->getDeletedMessage();
15892  CandidateSet.NoteCandidates(
15893  PartialDiagnosticAt(Object.get()->getBeginLoc(),
15894  PDiag(diag::err_ovl_deleted_object_call)
15895  << Object.get()->getType() << (Msg != nullptr)
15896  << (Msg ? Msg->getString() : StringRef())
15897  << Object.get()->getSourceRange()),
15898  *this, OCD_AllCandidates, Args);
15899  break;
15900  }
15901  }
15902 
15903  if (Best == CandidateSet.end())
15904  return true;
15905 
15906  UnbridgedCasts.restore();
15907 
15908  if (Best->Function == nullptr) {
15909  // Since there is no function declaration, this is one of the
15910  // surrogate candidates. Dig out the conversion function.
15911  CXXConversionDecl *Conv
15912  = cast<CXXConversionDecl>(
15913  Best->Conversions[0].UserDefined.ConversionFunction);
15914 
15915  CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15916  Best->FoundDecl);
15917  if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15918  return ExprError();
15919  assert(Conv == Best->FoundDecl.getDecl() &&
15920  "Found Decl & conversion-to-functionptr should be same, right?!");
15921  // We selected one of the surrogate functions that converts the
15922  // object parameter to a function pointer. Perform the conversion
15923  // on the object argument, then let BuildCallExpr finish the job.
15924 
15925  // Create an implicit member expr to refer to the conversion operator.
15926  // and then call it.
15927  ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15928  Conv, HadMultipleCandidates);
15929  if (Call.isInvalid())
15930  return ExprError();
15931  // Record usage of conversion in an implicit cast.
15932  Call = ImplicitCastExpr::Create(
15933  Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15934  nullptr, VK_PRValue, CurFPFeatureOverrides());
15935 
15936  return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15937  }
15938 
15939  CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15940 
15941  // We found an overloaded operator(). Build a CXXOperatorCallExpr
15942  // that calls this method, using Object for the implicit object
15943  // parameter and passing along the remaining arguments.
15944  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15945 
15946  // An error diagnostic has already been printed when parsing the declaration.
15947  if (Method->isInvalidDecl())
15948  return ExprError();
15949 
15950  const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15951  unsigned NumParams = Proto->getNumParams();
15952 
15953  DeclarationNameInfo OpLocInfo(
15954  Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15955  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15956  ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15957  Obj, HadMultipleCandidates,
15958  OpLocInfo.getLoc(),
15959  OpLocInfo.getInfo());
15960  if (NewFn.isInvalid())
15961  return true;
15962 
15963  SmallVector<Expr *, 8> MethodArgs;
15964  MethodArgs.reserve(NumParams + 1);
15965 
15966  bool IsError = false;
15967 
15968  // Initialize the object parameter.
15970  if (Method->isExplicitObjectMemberFunction()) {
15971  IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15972  } else {
15974  Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15975  if (ObjRes.isInvalid())
15976  IsError = true;
15977  else
15978  Object = ObjRes;
15979  MethodArgs.push_back(Object.get());
15980  }
15981 
15983  *this, MethodArgs, Method, Args, LParenLoc);
15984 
15985  // If this is a variadic call, handle args passed through "...".
15986  if (Proto->isVariadic()) {
15987  // Promote the arguments (C99 6.5.2.2p7).
15988  for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15990  nullptr);
15991  IsError |= Arg.isInvalid();
15992  MethodArgs.push_back(Arg.get());
15993  }
15994  }
15995 
15996  if (IsError)
15997  return true;
15998 
15999  DiagnoseSentinelCalls(Method, LParenLoc, Args);
16000 
16001  // Once we've built TheCall, all of the expressions are properly owned.
16002  QualType ResultTy = Method->getReturnType();
16004  ResultTy = ResultTy.getNonLValueExprType(Context);
16005 
16007  Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16009 
16010  if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16011  return true;
16012 
16013  if (CheckFunctionCall(Method, TheCall, Proto))
16014  return true;
16015 
16016  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16017 }
16018 
16019 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
16020 /// (if one exists), where @c Base is an expression of class type and
16021 /// @c Member is the name of the member we're trying to find.
16022 ExprResult
16024  bool *NoArrowOperatorFound) {
16025  assert(Base->getType()->isRecordType() &&
16026  "left-hand side must have class type");
16027 
16028  if (checkPlaceholderForOverload(*this, Base))
16029  return ExprError();
16030 
16031  SourceLocation Loc = Base->getExprLoc();
16032 
16033  // C++ [over.ref]p1:
16034  //
16035  // [...] An expression x->m is interpreted as (x.operator->())->m
16036  // for a class object x of type T if T::operator->() exists and if
16037  // the operator is selected as the best match function by the
16038  // overload resolution mechanism (13.3).
16039  DeclarationName OpName =
16042 
16043  if (RequireCompleteType(Loc, Base->getType(),
16044  diag::err_typecheck_incomplete_tag, Base))
16045  return ExprError();
16046 
16047  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16048  LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
16050 
16051  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16052  Oper != OperEnd; ++Oper) {
16053  AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16054  std::nullopt, CandidateSet,
16055  /*SuppressUserConversion=*/false);
16056  }
16057 
16058  bool HadMultipleCandidates = (CandidateSet.size() > 1);
16059 
16060  // Perform overload resolution.
16062  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16063  case OR_Success:
16064  // Overload resolution succeeded; we'll build the call below.
16065  break;
16066 
16067  case OR_No_Viable_Function: {
16068  auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16069  if (CandidateSet.empty()) {
16070  QualType BaseType = Base->getType();
16071  if (NoArrowOperatorFound) {
16072  // Report this specific error to the caller instead of emitting a
16073  // diagnostic, as requested.
16074  *NoArrowOperatorFound = true;
16075  return ExprError();
16076  }
16077  Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16078  << BaseType << Base->getSourceRange();
16079  if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16080  Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16081  << FixItHint::CreateReplacement(OpLoc, ".");
16082  }
16083  } else
16084  Diag(OpLoc, diag::err_ovl_no_viable_oper)
16085  << "operator->" << Base->getSourceRange();
16086  CandidateSet.NoteCandidates(*this, Base, Cands);
16087  return ExprError();
16088  }
16089  case OR_Ambiguous:
16090  if (!R.isAmbiguous())
16091  CandidateSet.NoteCandidates(
16092  PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16093  << "->" << Base->getType()
16094  << Base->getSourceRange()),
16095  *this, OCD_AmbiguousCandidates, Base);
16096  return ExprError();
16097 
16098  case OR_Deleted: {
16099  StringLiteral *Msg = Best->Function->getDeletedMessage();
16100  CandidateSet.NoteCandidates(
16101  PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16102  << "->" << (Msg != nullptr)
16103  << (Msg ? Msg->getString() : StringRef())
16104  << Base->getSourceRange()),
16105  *this, OCD_AllCandidates, Base);
16106  return ExprError();
16107  }
16108  }
16109 
16110  CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16111 
16112  // Convert the object parameter.
16113  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16114 
16115  if (Method->isExplicitObjectMemberFunction()) {
16116  ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16117  if (R.isInvalid())
16118  return ExprError();
16119  Base = R.get();
16120  } else {
16122  Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16123  if (BaseResult.isInvalid())
16124  return ExprError();
16125  Base = BaseResult.get();
16126  }
16127 
16128  // Build the operator call.
16129  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16130  Base, HadMultipleCandidates, OpLoc);
16131  if (FnExpr.isInvalid())
16132  return ExprError();
16133 
16134  QualType ResultTy = Method->getReturnType();
16136  ResultTy = ResultTy.getNonLValueExprType(Context);
16137 
16138  CallExpr *TheCall =
16139  CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16140  ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16141 
16142  if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16143  return ExprError();
16144 
16145  if (CheckFunctionCall(Method, TheCall,
16146  Method->getType()->castAs<FunctionProtoType>()))
16147  return ExprError();
16148 
16149  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16150 }
16151 
16152 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
16153 /// a literal operator described by the provided lookup results.
16155  DeclarationNameInfo &SuffixInfo,
16156  ArrayRef<Expr*> Args,
16157  SourceLocation LitEndLoc,
16158  TemplateArgumentListInfo *TemplateArgs) {
16159  SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16160 
16161  OverloadCandidateSet CandidateSet(UDSuffixLoc,
16163  AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16164  TemplateArgs);
16165 
16166  bool HadMultipleCandidates = (CandidateSet.size() > 1);
16167 
16168  // Perform overload resolution. This will usually be trivial, but might need
16169  // to perform substitutions for a literal operator template.
16171  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16172  case OR_Success:
16173  case OR_Deleted:
16174  break;
16175 
16176  case OR_No_Viable_Function:
16177  CandidateSet.NoteCandidates(
16178  PartialDiagnosticAt(UDSuffixLoc,
16179  PDiag(diag::err_ovl_no_viable_function_in_call)
16180  << R.getLookupName()),
16181  *this, OCD_AllCandidates, Args);
16182  return ExprError();
16183 
16184  case OR_Ambiguous:
16185  CandidateSet.NoteCandidates(
16186  PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16187  << R.getLookupName()),
16188  *this, OCD_AmbiguousCandidates, Args);
16189  return ExprError();
16190  }
16191 
16192  FunctionDecl *FD = Best->Function;
16193  ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16194  nullptr, HadMultipleCandidates,
16195  SuffixInfo.getLoc(),
16196  SuffixInfo.getInfo());
16197  if (Fn.isInvalid())
16198  return true;
16199 
16200  // Check the argument types. This should almost always be a no-op, except
16201  // that array-to-pointer decay is applied to string literals.
16202  Expr *ConvArgs[2];
16203  for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16206  SourceLocation(), Args[ArgIdx]);
16207  if (InputInit.isInvalid())
16208  return true;
16209  ConvArgs[ArgIdx] = InputInit.get();
16210  }
16211 
16212  QualType ResultTy = FD->getReturnType();
16214  ResultTy = ResultTy.getNonLValueExprType(Context);
16215 
16217  Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16218  LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16219 
16220  if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16221  return ExprError();
16222 
16223  if (CheckFunctionCall(FD, UDL, nullptr))
16224  return ExprError();
16225 
16227 }
16228 
16229 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
16230 /// given LookupResult is non-empty, it is assumed to describe a member which
16231 /// will be invoked. Otherwise, the function will be found via argument
16232 /// dependent lookup.
16233 /// CallExpr is set to a valid expression and FRS_Success returned on success,
16234 /// otherwise CallExpr is set to ExprError() and some non-success value
16235 /// is returned.
16238  SourceLocation RangeLoc,
16239  const DeclarationNameInfo &NameInfo,
16240  LookupResult &MemberLookup,
16241  OverloadCandidateSet *CandidateSet,
16242  Expr *Range, ExprResult *CallExpr) {
16243  Scope *S = nullptr;
16244 
16245  CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
16246  if (!MemberLookup.empty()) {
16247  ExprResult MemberRef =
16248  BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16249  /*IsPtr=*/false, CXXScopeSpec(),
16250  /*TemplateKWLoc=*/SourceLocation(),
16251  /*FirstQualifierInScope=*/nullptr,
16252  MemberLookup,
16253  /*TemplateArgs=*/nullptr, S);
16254  if (MemberRef.isInvalid()) {
16255  *CallExpr = ExprError();
16256  return FRS_DiagnosticIssued;
16257  }
16258  *CallExpr =
16259  BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
16260  if (CallExpr->isInvalid()) {
16261  *CallExpr = ExprError();
16262  return FRS_DiagnosticIssued;
16263  }
16264  } else {
16265  ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16267  NameInfo, UnresolvedSet<0>());
16268  if (FnR.isInvalid())
16269  return FRS_DiagnosticIssued;
16270  UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16271 
16272  bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16273  CandidateSet, CallExpr);
16274  if (CandidateSet->empty() || CandidateSetError) {
16275  *CallExpr = ExprError();
16276  return FRS_NoViableFunction;
16277  }
16279  OverloadingResult OverloadResult =
16280  CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16281 
16282  if (OverloadResult == OR_No_Viable_Function) {
16283  *CallExpr = ExprError();
16284  return FRS_NoViableFunction;
16285  }
16286  *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16287  Loc, nullptr, CandidateSet, &Best,
16288  OverloadResult,
16289  /*AllowTypoCorrection=*/false);
16290  if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16291  *CallExpr = ExprError();
16292  return FRS_DiagnosticIssued;
16293  }
16294  }
16295  return FRS_Success;
16296 }
16297 
16298 
16299 /// FixOverloadedFunctionReference - E is an expression that refers to
16300 /// a C++ overloaded function (possibly with some parentheses and
16301 /// perhaps a '&' around it). We have resolved the overloaded function
16302 /// to the function declaration Fn, so patch up the expression E to
16303 /// refer (possibly indirectly) to Fn. Returns the new expr.
16305  FunctionDecl *Fn) {
16306  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16307  ExprResult SubExpr =
16308  FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16309  if (SubExpr.isInvalid())
16310  return ExprError();
16311  if (SubExpr.get() == PE->getSubExpr())
16312  return PE;
16313 
16314  return new (Context)
16315  ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16316  }
16317 
16318  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16319  ExprResult SubExpr =
16320  FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16321  if (SubExpr.isInvalid())
16322  return ExprError();
16323  assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16324  SubExpr.get()->getType()) &&
16325  "Implicit cast type cannot be determined from overload");
16326  assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16327  if (SubExpr.get() == ICE->getSubExpr())
16328  return ICE;
16329 
16330  return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16331  SubExpr.get(), nullptr, ICE->getValueKind(),
16333  }
16334 
16335  if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16336  if (!GSE->isResultDependent()) {
16337  ExprResult SubExpr =
16338  FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16339  if (SubExpr.isInvalid())
16340  return ExprError();
16341  if (SubExpr.get() == GSE->getResultExpr())
16342  return GSE;
16343 
16344  // Replace the resulting type information before rebuilding the generic
16345  // selection expression.
16346  ArrayRef<Expr *> A = GSE->getAssocExprs();
16347  SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
16348  unsigned ResultIdx = GSE->getResultIndex();
16349  AssocExprs[ResultIdx] = SubExpr.get();
16350 
16351  if (GSE->isExprPredicate())
16353  Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16354  GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16355  GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16356  ResultIdx);
16358  Context, GSE->getGenericLoc(), GSE->getControllingType(),
16359  GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16360  GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16361  ResultIdx);
16362  }
16363  // Rather than fall through to the unreachable, return the original generic
16364  // selection expression.
16365  return GSE;
16366  }
16367 
16368  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16369  assert(UnOp->getOpcode() == UO_AddrOf &&
16370  "Can only take the address of an overloaded function");
16371  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16372  if (Method->isStatic()) {
16373  // Do nothing: static member functions aren't any different
16374  // from non-member functions.
16375  } else {
16376  // Fix the subexpression, which really has to be an
16377  // UnresolvedLookupExpr holding an overloaded member function
16378  // or template.
16379  ExprResult SubExpr =
16380  FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16381  if (SubExpr.isInvalid())
16382  return ExprError();
16383  if (SubExpr.get() == UnOp->getSubExpr())
16384  return UnOp;
16385 
16386  if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16387  SubExpr.get(), Method))
16388  return ExprError();
16389 
16390  assert(isa<DeclRefExpr>(SubExpr.get()) &&
16391  "fixed to something other than a decl ref");
16392  assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16393  "fixed to a member ref with no nested name qualifier");
16394 
16395  // We have taken the address of a pointer to member
16396  // function. Perform the computation here so that we get the
16397  // appropriate pointer to member type.
16398  QualType ClassType
16399  = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16400  QualType MemPtrType
16401  = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16402  // Under the MS ABI, lock down the inheritance model now.
16404  (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16405 
16406  return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16407  MemPtrType, VK_PRValue, OK_Ordinary,
16408  UnOp->getOperatorLoc(), false,
16410  }
16411  }
16412  ExprResult SubExpr =
16413  FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16414  if (SubExpr.isInvalid())
16415  return ExprError();
16416  if (SubExpr.get() == UnOp->getSubExpr())
16417  return UnOp;
16418 
16419  return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16420  SubExpr.get());
16421  }
16422 
16423  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16424  // FIXME: avoid copy.
16425  TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16426  if (ULE->hasExplicitTemplateArgs()) {
16427  ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16428  TemplateArgs = &TemplateArgsBuffer;
16429  }
16430 
16431  QualType Type = Fn->getType();
16432  ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
16433 
16434  // FIXME: Duplicated from BuildDeclarationNameExpr.
16435  if (unsigned BID = Fn->getBuiltinID()) {
16438  ValueKind = VK_PRValue;
16439  }
16440  }
16441 
16443  Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16444  Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16445  DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16446  return DRE;
16447  }
16448 
16449  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16450  // FIXME: avoid copy.
16451  TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16452  if (MemExpr->hasExplicitTemplateArgs()) {
16453  MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16454  TemplateArgs = &TemplateArgsBuffer;
16455  }
16456 
16457  Expr *Base;
16458 
16459  // If we're filling in a static method where we used to have an
16460  // implicit member access, rewrite to a simple decl ref.
16461  if (MemExpr->isImplicitAccess()) {
16462  if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16464  Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16465  MemExpr->getQualifierLoc(), Found.getDecl(),
16466  MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16467  DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16468  return DRE;
16469  } else {
16470  SourceLocation Loc = MemExpr->getMemberLoc();
16471  if (MemExpr->getQualifier())
16472  Loc = MemExpr->getQualifierLoc().getBeginLoc();
16473  Base =
16474  BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16475  }
16476  } else
16477  Base = MemExpr->getBase();
16478 
16479  ExprValueKind valueKind;
16480  QualType type;
16481  if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16482  valueKind = VK_LValue;
16483  type = Fn->getType();
16484  } else {
16485  valueKind = VK_PRValue;
16487  }
16488 
16489  return BuildMemberExpr(
16490  Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16491  MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16492  /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16493  type, valueKind, OK_Ordinary, TemplateArgs);
16494  }
16495 
16496  llvm_unreachable("Invalid reference to overloaded function");
16497 }
16498 
16500  DeclAccessPair Found,
16501  FunctionDecl *Fn) {
16502  return FixOverloadedFunctionReference(E.get(), Found, Fn);
16503 }
16504 
16505 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16506  FunctionDecl *Function) {
16507  if (!PartialOverloading || !Function)
16508  return true;
16509  if (Function->isVariadic())
16510  return false;
16511  if (const auto *Proto =
16512  dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16513  if (Proto->isTemplateVariadic())
16514  return false;
16515  if (auto *Pattern = Function->getTemplateInstantiationPattern())
16516  if (const auto *Proto =
16517  dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16518  if (Proto->isTemplateVariadic())
16519  return false;
16520  return true;
16521 }
16522 
16524  DeclarationName Name,
16525  OverloadCandidateSet &CandidateSet,
16526  FunctionDecl *Fn, MultiExprArg Args,
16527  bool IsMember) {
16528  StringLiteral *Msg = Fn->getDeletedMessage();
16529  CandidateSet.NoteCandidates(
16530  PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16531  << IsMember << Name << (Msg != nullptr)
16532  << (Msg ? Msg->getString() : StringRef())
16533  << Range),
16534  *this, OCD_AllCandidates, Args);
16535 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3299
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
llvm::APSInt APSInt
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
unsigned Offset
Definition: Format.cpp:2978
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:143
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs)
General arity mismatch diagnosis over a candidate in a candidate set.
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static ImplicitConversionSequence TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
Tries a user-defined conversion from From to ToType.
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static ImplicitConversionSequence::CompareKind HLSLCompareFloatingRank(QualType LHS, QualType RHS)
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs)
Additional arity mismatch diagnosis specific to a function overload candidates.
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
This file declares semantic analysis for SYCL constructs.
Defines the SourceManager interface.
const char * Data
Allows QualTypes to be sorted and hence used in maps and sets.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__device__ __2f16 b
__device__ int
A class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APFloat & getFloat()
Definition: APValue.h:437
bool isAbsent() const
Definition: APValue.h:397
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
Definition: ASTContext.h:1103
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1103
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:651
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1106
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2589
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2605
CanQualType DoubleTy
Definition: ASTContext.h:1106
CanQualType LongDoubleTy
Definition: ASTContext.h:1106
CanQualType Char16Ty
Definition: ASTContext.h:1101
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1122
CanQualType NullPtrTy
Definition: ASTContext.h:1121
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1605
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:649
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2782
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1106
const LangOptions & getLangOpts() const
Definition: ASTContext.h:778
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2286
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1095
CanQualType Float128Ty
Definition: ASTContext.h:1106
CanQualType UnsignedLongTy
Definition: ASTContext.h:1104
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1293
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1122
CanQualType CharTy
Definition: ASTContext.h:1096
CanQualType IntTy
Definition: ASTContext.h:1103
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2171
CanQualType SignedCharTy
Definition: ASTContext.h:1103
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1122
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2078
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2632
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1105
CanQualType BuiltinFnTy
Definition: ASTContext.h:1124
CanQualType VoidTy
Definition: ASTContext.h:1094
CanQualType UnsignedCharTy
Definition: ASTContext.h:1104
CanQualType UnsignedIntTy
Definition: ASTContext.h:1104
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1302
CanQualType UnknownAnyTy
Definition: ASTContext.h:1123
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1105
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1104
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1583
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
CanQualType ShortTy
Definition: ASTContext.h:1103
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
CanQualType Char32Ty
Definition: ASTContext.h:1102
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2166
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:761
CanQualType LongLongTy
Definition: ASTContext.h:1103
CanQualType WCharTy
Definition: ASTContext.h:1097
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1100
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3530
QualType getElementType() const
Definition: Type.h:3542
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7201
Attr - This represents one attribute.
Definition: Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3892
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2236
StringRef getOpcodeStr() const
Definition: Expr.h:3957
bool isCompoundAssignmentOp() const
Definition: Expr.h:4035
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4843
Pointer to a block type.
Definition: Type.h:3361
This class is used for builtin types like 'int'.
Definition: Type.h:2989
Kind getKind() const
Definition: Type.h:3035
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2898
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:626
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2455
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
unsigned getNumExplicitParams() const
Definition: DeclCXX.h:2214
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2576
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2565
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isStatic() const
Definition: DeclCXX.cpp:2186
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:562
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1833
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1549
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3194
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1563
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3042
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isAtLeastAsQualifiedAs(CanQual< T > Other) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
bool isVolatileQualified() const
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition: Type.h:3098
QualType getElementType() const
Definition: Type.h:3108
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4865
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3568
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1956
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2059
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition: Expr.h:1447
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:239
bool isTemplateDecl() const
returns true if this declaration is a template
Definition: DeclBase.cpp:235
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:575
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1132
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:570
bool hasAttr() const
Definition: DeclBase.h:583
T * getAttr() const
Definition: DeclBase.h:579
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
NameKind getNameKind() const
Determine what kind of name this is.
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:829
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1577
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:752
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:737
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:728
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3870
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4075
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5587
EnumDecl * getDecl() const
Definition: Type.h:5594
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1921
const Expr * getExpr() const
Definition: DeclCXX.h:1906
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2144
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiably lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3116
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3107
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3331
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4141
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3980
ConstantExprKind
Definition: Expr.h:748
@ ClassTemplateArgument
A class template argument. Such a value is used for code generation.
@ Normal
An integer constant expression (an array bound, enumerator, case value, bit-field width,...
@ NonClassTemplateArgument
A non-class template argument.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
Represents a member of a struct/union/class.
Definition: Decl.h:3060
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
Represents a function declaration or definition.
Definition: Decl.h:1972
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2602
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3717
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4046
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3636
param_iterator param_end()
Definition: Decl.h:2699
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3540
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3735
QualType getReturnType() const
Definition: Decl.h:2757
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3580
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4117
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3744
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4166
param_iterator param_begin()
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4241
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2505
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4182
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3318
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4110
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3739
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2670
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2435
bool isDeletedAsWritten() const
Definition: Decl.h:2509
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3310
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3576
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2350
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4399
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4270
bool isConsteval() const
Definition: Decl.h:2447
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3584
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2774
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3589
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3893
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2598
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
ArrayRef< QualType > param_types() const
Definition: Type.h:5056
unsigned getNumParams() const
Definition: Type.h:4901
Qualifiers getMethodQuals() const
Definition: Type.h:5042
QualType getParamType(unsigned i) const
Definition: Type.h:4903
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5024
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4379
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4453
bool getNoReturn() const
Definition: Type.h:4427
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4268
ExtInfo getExtInfo() const
Definition: Type.h:4597
CallingConv getCallConv() const
Definition: Type.h:4596
QualType getReturnType() const
Definition: Type.h:4585
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4609
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4532
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3707
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2129
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:691
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition: Overload.h:742
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:602
bool hasInitializerListContainerType() const
Definition: Overload.h:724
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:655
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:731
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:606
QualType getInitializerListContainerType() const
Definition: Overload.h:734
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4888
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:4995
unsigned getNumInits() const
Definition: Expr.h:4918
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2518
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4934
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2536
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3436
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:666
Represents the results of name lookup.
Definition: Lookup.h:46
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:488
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3224
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3413
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3307
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3321
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3335
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3442
Expr * getBase() const
Definition: Expr.h:3301
void setBase(Expr *E)
Definition: Expr.h:3300
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1853
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3419
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3311
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3502
QualType getPointeeType() const
Definition: Type.h:3488
Describes a module or submodule.
Definition: Module.h:105
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:463
std::string getQualifiedNameAsString(bool WithGlobalNsPrefix=false) const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:548
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6964
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
Represents a pointer to an Objective C object.
Definition: Type.h:7020
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7109
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7078
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7032
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1798
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7084
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7072
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1137
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1164
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1130
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1001
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:996
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition: Overload.h:1145
SourceLocation getLocation() const
Definition: Overload.h:1128
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions=std::nullopt)
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1178
CandidateSetKind getKind() const
Definition: Overload.h:1129
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2978
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3129
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3038
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3090
decls_iterator decls_begin() const
Definition: ExprCXX.h:3070
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3081
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3093
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3103
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3099
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3149
decls_iterator decls_end() const
Definition: ExprCXX.h:3073
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3087
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2182
Represents a parameter to a function.
Definition: Decl.h:1762
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2942
void EmitToString(DiagnosticsEngine &Diags, SmallVectorImpl< char > &Buf) const
StringRef getStringArg(unsigned I)
Retrieve the string argument at the given index.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3151
QualType getPointeeType() const
Definition: Type.h:3161
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4937
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7455
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:7449
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7460
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3493
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7553
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7371
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7497
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7411
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7572
QualType getCanonicalType() const
Definition: Type.h:7423
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7465
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1092
bool isMoreQualifiedThan(QualType Other) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: Type.h:7543
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7444
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7492
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7417
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7403
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7311
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7318
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4311
bool hasAtomic() const
Definition: Type.h:844
bool hasRestrict() const
Definition: Type.h:843
QualifiersAndAtomic withVolatile()
Definition: Type.h:856
QualifiersAndAtomic withAtomic()
Definition: Type.h:863
bool hasVolatile() const
Definition: Type.h:841
The collection of all-type qualifiers we support.
Definition: Type.h:318
unsigned getCVRQualifiers() const
Definition: Type.h:474
GC getObjCGCAttr() const
Definition: Type.h:505
bool hasOnlyConst() const
Definition: Type.h:444
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
void removeObjCLifetime()
Definition: Type.h:537
bool hasConst() const
Definition: Type.h:443
void addRestrict()
Definition: Type.h:466
bool hasRestrict() const
Definition: Type.h:463
void removeObjCGCAttr()
Definition: Type.h:509
void removeUnaligned()
Definition: Type.h:501
void removeAddressSpace()
Definition: Type.h:582
void addConst()
Definition: Type.h:446
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
bool hasVolatile() const
Definition: Type.h:453
bool hasObjCGCAttr() const
Definition: Type.h:504
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
std::string getAsString() const
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
LangAS getAddressSpace() const
Definition: Type.h:557
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:754
void addVolatile()
Definition: Type.h:456
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3454
Represents a struct/union/class.
Definition: Decl.h:4171
field_range fields() const
Definition: Decl.h:4377
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
RecordDecl * getDecl() const
Definition: Type.h:5571
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3392
QualType getPointeeType() const
Definition: Type.h:3410
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
@ Sycl
SYCL specific diagnostic.
Sema & SemaRef
Definition: SemaBase.h:40
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:176
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:447
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * >> &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition: SemaCUDA.cpp:395
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:389
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:253
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1314
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID, DeviceDiagnosticReason Reason=DeviceDiagnosticReason::Sycl|DeviceDiagnosticReason::Esimd)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition: SemaSYCL.cpp:5361
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:8176
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4823
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4852
RAII class to control scope of DeferDiags.
Definition: Sema.h:8027
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9610
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9640
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
SemaObjC & ObjC()
Definition: Sema.h:1012
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2547
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:8043
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15448
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7487
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:7499
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:493
@ VariadicDoesNotApply
Definition: Sema.h:2036
@ VariadicMethod
Definition: Sema.h:2034
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:168
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17315
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition: Sema.h:8259
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:8262
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8268
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:8266
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1449
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1547
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1117
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:857
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:6387
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition: Sema.cpp:615
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:833
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17740
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:678
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ForRangeStatus
Definition: Sema.h:8476
@ FRS_Success
Definition: Sema.h:8477
@ FRS_DiagnosticIssued
Definition: Sema.h:8479
@ FRS_NoViableFunction
Definition: Sema.h:8478
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition: Sema.h:2663
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:8069
@ None
Allow no explicit functions to be used.
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:774
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2277
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9368
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:68
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6548
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14136
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
const LangOptions & LangOpts
Definition: Sema.h:855
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
const LangOptions & getLangOpts() const
Definition: Sema.h:519
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:6816
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17436
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition: Sema.h:8287
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9745
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:721
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3301
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:11812
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition: Sema.h:5370
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:995
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8529
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
SemaSYCL & SYCL()
Definition: Sema.h:1037
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6215
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6254
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6233
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6217
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6250
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19898
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20867
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10604
AssignmentAction
Definition: Sema.h:5355
@ AA_Converting
Definition: Sema.h:5359
@ AA_Passing
Definition: Sema.h:5357
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:8892
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5588
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7662
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7708
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:229
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11787
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3335
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:8146
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:8151
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:8152
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:8150
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8149
ASTContext & getASTContext() const
Definition: Sema.h:526
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
OverloadKind
Definition: Sema.h:8045
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:122
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5237
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20151
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8923
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:860
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2485
DiagnosticsEngine & Diags
Definition: Sema.h:859
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:597
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10678
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21065
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3081
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14759
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:10663
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:392
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:523
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:5891
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
SemaCUDA & CUDA()
Definition: Sema.h:1002
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6848
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:267
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:357
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:355
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:327
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
QualType getFromType() const
Definition: Overload.h:370
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:332
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:294
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:354
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:304
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:337
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:288
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:299
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:284
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition: Overload.h:347
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition: Overload.h:319
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:323
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:314
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
void setAllToTypes(QualType T)
Definition: Overload.h:364
QualType getToType(unsigned Idx) const
Definition: Overload.h:374
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
StringRef getString() const
Definition: Expr.h:1850
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:655
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:708
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:693
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
Represents a template argument.
Definition: TemplateBase.h:61
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
Definition: TemplateName.h:219
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6101
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3417
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2400
bool isBlockPointerType() const
Definition: Type.h:7632
bool isVoidType() const
Definition: Type.h:7939
bool isBooleanType() const
Definition: Type.h:8067
bool isObjCBuiltinType() const
Definition: Type.h:7811
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2166
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1898
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:7698
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2145
bool isFloat16Type() const
Definition: Type.h:7948
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2070
bool isRValueReferenceType() const
Definition: Type.h:7644
bool isConstantArrayType() const
Definition: Type.h:7694
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8097
bool isArrayType() const
Definition: Type.h:7690
bool isCharType() const
Definition: Type.cpp:2088
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8004
bool isArithmeticType() const
Definition: Type.cpp:2280
bool isPointerType() const
Definition: Type.h:7624
bool isArrayParameterType() const
Definition: Type.h:7706
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7979
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2479
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isReferenceType() const
Definition: Type.h:7636
bool isEnumeralType() const
Definition: Type.h:7722
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2057
bool isObjCQualifiedIdType() const
Definition: Type.h:7781
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8054
bool isExtVectorType() const
Definition: Type.h:7734
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2124
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7768
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2669
bool isLValueReferenceType() const
Definition: Type.h:7640
bool isBitIntType() const
Definition: Type.h:7874
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2661
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2337
bool isAnyComplexType() const
Definition: Type.h:7726
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7992
bool isHalfType() const
Definition: Type.h:7943
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7921
bool isQueueT() const
Definition: Type.h:7845
bool isMemberPointerType() const
Definition: Type.h:7672
bool isObjCIdType() const
Definition: Type.h:7793
bool isMatrixType() const
Definition: Type.h:7748
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8073
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
bool isEventT() const
Definition: Type.h:7837
bool isBFloat16Type() const
Definition: Type.h:7960
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2361
bool isFunctionType() const
Definition: Type.h:7620
bool isObjCObjectPointerType() const
Definition: Type.h:7760
bool isVectorType() const
Definition: Type.h:7730
bool isObjCClassType() const
Definition: Type.h:7799
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2265
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2493
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2195
bool isAnyPointerType() const
Definition: Type.h:7628
TypeClass getTypeClass() const
Definition: Type.h:2300
bool isSamplerT() const
Definition: Type.h:7833
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool isNullPtrType() const
Definition: Type.h:7972
bool isRecordType() const
Definition: Type.h:7718
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2235
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1484
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4900
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1460
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3197
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:3273
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3265
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3936
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4044
QualType getBaseType() const
Definition: ExprCXX.h:4018
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4028
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4009
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4054
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4048
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
unsigned size() const
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:900
QualType getType() const
Definition: Decl.h:718
Represents a GCC generic vector type.
Definition: Type.h:3981
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Definition: AttrIterator.h:33
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
constexpr XRayInstrMask All
Definition: XRayInstr.h:43
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ After
Like System, but searched after the system directories.
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: Integral.h:29
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:218
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1903
CharSourceRange getSourceRange(const SourceRange &Range)
Returns the token CharSourceRange corresponding to Range.
Definition: FixIt.h:32
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
CUDAFunctionTarget
Definition: Cuda.h:132
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:774
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:802
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:811
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:794
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:798
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition: Overload.h:839
@ ovl_fail_too_few_arguments
Definition: Overload.h:776
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:818
@ ovl_fail_too_many_arguments
Definition: Overload.h:775
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:826
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:835
@ ovl_fail_bad_conversion
Definition: Overload.h:777
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:807
@ ovl_fail_bad_deduction
Definition: Overload.h:778
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:822
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:831
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:815
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:783
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:212
@ ICR_Conversion
Conversion.
Definition: Overload.h:220
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:229
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:232
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:223
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:226
@ ICR_Promotion
Promotion.
Definition: Overload.h:217
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:214
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:236
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition: Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition: Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition: Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition: Overload.h:94
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:205
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:429
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:243
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:371
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1241
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
unsigned long uint64_t
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:443
ConversionSet::const_iterator const_iterator
Definition: Overload.h:479
ConversionSet & conversions()
Definition: Overload.h:462
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:470
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:528
QualType getFromType() const
Definition: Overload.h:527
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Extra information about a function prototype.
Definition: Type.h:4747
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:4755
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1006
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1019
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1055
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1028
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1045
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:903
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:945
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:933
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:891
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:862
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:900
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:858
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:853
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:877
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:907
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:874
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:924
unsigned getNumParams() const
Definition: Overload.h:958
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:915
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:911
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:871
DeductionFailureInfo DeductionFailure
Definition: Overload.h:918
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:886
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:866
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:929
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9920
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:10008
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:10040
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8276
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6499
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:398
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:410
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:432
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:423
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:418
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:437
void dump() const
dump - Print this user-defined conversion sequence to standard error.