xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision 8a4dda33d67586ca2624f2a38417baa03a533a7f)
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"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/OperatorKinds.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/Support/Casting.h"
42 #include <algorithm>
43 #include <cstdlib>
44 #include <optional>
45 
46 using namespace clang;
47 using namespace sema;
48 
49 using AllowedExplicit = Sema::AllowedExplicit;
50 
51 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
52   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
53     return P->hasAttr<PassObjectSizeAttr>();
54   });
55 }
56 
57 /// A convenience routine for creating a decayed reference to a function.
58 static ExprResult CreateFunctionRefExpr(
59     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
60     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
61     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
62   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
63     return ExprError();
64   // If FoundDecl is different from Fn (such as if one is a template
65   // and the other a specialization), make sure DiagnoseUseOfDecl is
66   // called on both.
67   // FIXME: This would be more comprehensively addressed by modifying
68   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
69   // being used.
70   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
71     return ExprError();
72   DeclRefExpr *DRE = new (S.Context)
73       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
74   if (HadMultipleCandidates)
75     DRE->setHadMultipleCandidates(true);
76 
77   S.MarkDeclRefReferenced(DRE, Base);
78   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
79     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
80       S.ResolveExceptionSpec(Loc, FPT);
81       DRE->setType(Fn->getType());
82     }
83   }
84   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
85                              CK_FunctionToPointerDecay);
86 }
87 
88 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
89                                  bool InOverloadResolution,
90                                  StandardConversionSequence &SCS,
91                                  bool CStyle,
92                                  bool AllowObjCWritebackConversion);
93 
94 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
95                                                  QualType &ToType,
96                                                  bool InOverloadResolution,
97                                                  StandardConversionSequence &SCS,
98                                                  bool CStyle);
99 static OverloadingResult
100 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
101                         UserDefinedConversionSequence& User,
102                         OverloadCandidateSet& Conversions,
103                         AllowedExplicit AllowExplicit,
104                         bool AllowObjCConversionOnExplicit);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
108                                    const StandardConversionSequence& SCS1,
109                                    const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareQualificationConversions(Sema &S,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 static ImplicitConversionSequence::CompareKind
117 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
118                                 const StandardConversionSequence& SCS1,
119                                 const StandardConversionSequence& SCS2);
120 
121 /// GetConversionRank - Retrieve the implicit conversion rank
122 /// corresponding to the given implicit conversion kind.
123 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
124   static const ImplicitConversionRank
125     Rank[] = {
126     ICR_Exact_Match,
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Promotion,
133     ICR_Promotion,
134     ICR_Promotion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_OCL_Scalar_Widening,
148     ICR_Complex_Real_Conversion,
149     ICR_Conversion,
150     ICR_Conversion,
151     ICR_Writeback_Conversion,
152     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
153                      // it was omitted by the patch that added
154                      // ICK_Zero_Event_Conversion
155     ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
156                      // it was omitted by the patch that added
157                      // ICK_Zero_Queue_Conversion
158     ICR_C_Conversion,
159     ICR_C_Conversion_Extension
160   };
161   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
162   return Rank[(int)Kind];
163 }
164 
165 /// GetImplicitConversionName - Return the name of this kind of
166 /// implicit conversion.
167 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
168   static const char* const Name[] = {
169     "No conversion",
170     "Lvalue-to-rvalue",
171     "Array-to-pointer",
172     "Function-to-pointer",
173     "Function pointer conversion",
174     "Qualification",
175     "Integral promotion",
176     "Floating point promotion",
177     "Complex promotion",
178     "Integral conversion",
179     "Floating conversion",
180     "Complex conversion",
181     "Floating-integral conversion",
182     "Pointer conversion",
183     "Pointer-to-member conversion",
184     "Boolean conversion",
185     "Compatible-types conversion",
186     "Derived-to-base conversion",
187     "Vector conversion",
188     "SVE Vector conversion",
189     "RVV Vector conversion",
190     "Vector splat",
191     "Complex-real conversion",
192     "Block Pointer conversion",
193     "Transparent Union Conversion",
194     "Writeback conversion",
195     "OpenCL Zero Event Conversion",
196     "OpenCL Zero Queue Conversion",
197     "C specific type conversion",
198     "Incompatible pointer conversion"
199   };
200   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
201   return Name[Kind];
202 }
203 
204 /// StandardConversionSequence - Set the standard conversion
205 /// sequence to the identity conversion.
206 void StandardConversionSequence::setAsIdentityConversion() {
207   First = ICK_Identity;
208   Second = ICK_Identity;
209   Third = ICK_Identity;
210   DeprecatedStringLiteralToCharPtr = false;
211   QualificationIncludesObjCLifetime = false;
212   ReferenceBinding = false;
213   DirectBinding = false;
214   IsLvalueReference = true;
215   BindsToFunctionLvalue = false;
216   BindsToRvalue = false;
217   BindsImplicitObjectArgumentWithoutRefQualifier = false;
218   ObjCLifetimeConversionBinding = false;
219   CopyConstructor = nullptr;
220 }
221 
222 /// getRank - Retrieve the rank of this standard conversion sequence
223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224 /// implicit conversions.
225 ImplicitConversionRank StandardConversionSequence::getRank() const {
226   ImplicitConversionRank Rank = ICR_Exact_Match;
227   if  (GetConversionRank(First) > Rank)
228     Rank = GetConversionRank(First);
229   if  (GetConversionRank(Second) > Rank)
230     Rank = GetConversionRank(Second);
231   if  (GetConversionRank(Third) > Rank)
232     Rank = GetConversionRank(Third);
233   return Rank;
234 }
235 
236 /// isPointerConversionToBool - Determines whether this conversion is
237 /// a conversion of a pointer or pointer-to-member to bool. This is
238 /// used as part of the ranking of standard conversion sequences
239 /// (C++ 13.3.3.2p4).
240 bool StandardConversionSequence::isPointerConversionToBool() const {
241   // Note that FromType has not necessarily been transformed by the
242   // array-to-pointer or function-to-pointer implicit conversions, so
243   // check for their presence as well as checking whether FromType is
244   // a pointer.
245   if (getToType(1)->isBooleanType() &&
246       (getFromType()->isPointerType() ||
247        getFromType()->isMemberPointerType() ||
248        getFromType()->isObjCObjectPointerType() ||
249        getFromType()->isBlockPointerType() ||
250        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251     return true;
252 
253   return false;
254 }
255 
256 /// isPointerConversionToVoidPointer - Determines whether this
257 /// conversion is a conversion of a pointer to a void pointer. This is
258 /// used as part of the ranking of standard conversion sequences (C++
259 /// 13.3.3.2p4).
260 bool
261 StandardConversionSequence::
262 isPointerConversionToVoidPointer(ASTContext& Context) const {
263   QualType FromType = getFromType();
264   QualType ToType = getToType(1);
265 
266   // Note that FromType has not necessarily been transformed by the
267   // array-to-pointer implicit conversion, so check for its presence
268   // and redo the conversion to get a pointer.
269   if (First == ICK_Array_To_Pointer)
270     FromType = Context.getArrayDecayedType(FromType);
271 
272   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
273     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
274       return ToPtrType->getPointeeType()->isVoidType();
275 
276   return false;
277 }
278 
279 /// Skip any implicit casts which could be either part of a narrowing conversion
280 /// or after one in an implicit conversion.
281 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
282                                              const Expr *Converted) {
283   // We can have cleanups wrapping the converted expression; these need to be
284   // preserved so that destructors run if necessary.
285   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
286     Expr *Inner =
287         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
288     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
289                                     EWC->getObjects());
290   }
291 
292   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
293     switch (ICE->getCastKind()) {
294     case CK_NoOp:
295     case CK_IntegralCast:
296     case CK_IntegralToBoolean:
297     case CK_IntegralToFloating:
298     case CK_BooleanToSignedIntegral:
299     case CK_FloatingToIntegral:
300     case CK_FloatingToBoolean:
301     case CK_FloatingCast:
302       Converted = ICE->getSubExpr();
303       continue;
304 
305     default:
306       return Converted;
307     }
308   }
309 
310   return Converted;
311 }
312 
313 /// Check if this standard conversion sequence represents a narrowing
314 /// conversion, according to C++11 [dcl.init.list]p7.
315 ///
316 /// \param Ctx  The AST context.
317 /// \param Converted  The result of applying this standard conversion sequence.
318 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
319 ///        value of the expression prior to the narrowing conversion.
320 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
321 ///        type of the expression prior to the narrowing conversion.
322 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
323 ///        from floating point types to integral types should be ignored.
324 NarrowingKind StandardConversionSequence::getNarrowingKind(
325     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
326     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
327   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
328 
329   // C++11 [dcl.init.list]p7:
330   //   A narrowing conversion is an implicit conversion ...
331   QualType FromType = getToType(0);
332   QualType ToType = getToType(1);
333 
334   // A conversion to an enumeration type is narrowing if the conversion to
335   // the underlying type is narrowing. This only arises for expressions of
336   // the form 'Enum{init}'.
337   if (auto *ET = ToType->getAs<EnumType>())
338     ToType = ET->getDecl()->getIntegerType();
339 
340   switch (Second) {
341   // 'bool' is an integral type; dispatch to the right place to handle it.
342   case ICK_Boolean_Conversion:
343     if (FromType->isRealFloatingType())
344       goto FloatingIntegralConversion;
345     if (FromType->isIntegralOrUnscopedEnumerationType())
346       goto IntegralConversion;
347     // -- from a pointer type or pointer-to-member type to bool, or
348     return NK_Type_Narrowing;
349 
350   // -- from a floating-point type to an integer type, or
351   //
352   // -- from an integer type or unscoped enumeration type to a floating-point
353   //    type, except where the source is a constant expression and the actual
354   //    value after conversion will fit into the target type and will produce
355   //    the original value when converted back to the original type, or
356   case ICK_Floating_Integral:
357   FloatingIntegralConversion:
358     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
359       return NK_Type_Narrowing;
360     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
361                ToType->isRealFloatingType()) {
362       if (IgnoreFloatToIntegralConversion)
363         return NK_Not_Narrowing;
364       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
365       assert(Initializer && "Unknown conversion expression");
366 
367       // If it's value-dependent, we can't tell whether it's narrowing.
368       if (Initializer->isValueDependent())
369         return NK_Dependent_Narrowing;
370 
371       if (std::optional<llvm::APSInt> IntConstantValue =
372               Initializer->getIntegerConstantExpr(Ctx)) {
373         // Convert the integer to the floating type.
374         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
375         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
376                                 llvm::APFloat::rmNearestTiesToEven);
377         // And back.
378         llvm::APSInt ConvertedValue = *IntConstantValue;
379         bool ignored;
380         Result.convertToInteger(ConvertedValue,
381                                 llvm::APFloat::rmTowardZero, &ignored);
382         // If the resulting value is different, this was a narrowing conversion.
383         if (*IntConstantValue != ConvertedValue) {
384           ConstantValue = APValue(*IntConstantValue);
385           ConstantType = Initializer->getType();
386           return NK_Constant_Narrowing;
387         }
388       } else {
389         // Variables are always narrowings.
390         return NK_Variable_Narrowing;
391       }
392     }
393     return NK_Not_Narrowing;
394 
395   // -- from long double to double or float, or from double to float, except
396   //    where the source is a constant expression and the actual value after
397   //    conversion is within the range of values that can be represented (even
398   //    if it cannot be represented exactly), or
399   case ICK_Floating_Conversion:
400     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
401         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
402       // FromType is larger than ToType.
403       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 
405       // If it's value-dependent, we can't tell whether it's narrowing.
406       if (Initializer->isValueDependent())
407         return NK_Dependent_Narrowing;
408 
409       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
410         // Constant!
411         assert(ConstantValue.isFloat());
412         llvm::APFloat FloatVal = ConstantValue.getFloat();
413         // Convert the source value into the target type.
414         bool ignored;
415         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
416           Ctx.getFloatTypeSemantics(ToType),
417           llvm::APFloat::rmNearestTiesToEven, &ignored);
418         // If there was no overflow, the source value is within the range of
419         // values that can be represented.
420         if (ConvertStatus & llvm::APFloat::opOverflow) {
421           ConstantType = Initializer->getType();
422           return NK_Constant_Narrowing;
423         }
424       } else {
425         return NK_Variable_Narrowing;
426       }
427     }
428     return NK_Not_Narrowing;
429 
430   // -- from an integer type or unscoped enumeration type to an integer type
431   //    that cannot represent all the values of the original type, except where
432   //    the source is a constant expression and the actual value after
433   //    conversion will fit into the target type and will produce the original
434   //    value when converted back to the original type.
435   case ICK_Integral_Conversion:
436   IntegralConversion: {
437     assert(FromType->isIntegralOrUnscopedEnumerationType());
438     assert(ToType->isIntegralOrUnscopedEnumerationType());
439     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
440     const unsigned FromWidth = Ctx.getIntWidth(FromType);
441     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
442     const unsigned ToWidth = Ctx.getIntWidth(ToType);
443 
444     if (FromWidth > ToWidth ||
445         (FromWidth == ToWidth && FromSigned != ToSigned) ||
446         (FromSigned && !ToSigned)) {
447       // Not all values of FromType can be represented in ToType.
448       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
449 
450       // If it's value-dependent, we can't tell whether it's narrowing.
451       if (Initializer->isValueDependent())
452         return NK_Dependent_Narrowing;
453 
454       std::optional<llvm::APSInt> OptInitializerValue;
455       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
456         // Such conversions on variables are always narrowing.
457         return NK_Variable_Narrowing;
458       }
459       llvm::APSInt &InitializerValue = *OptInitializerValue;
460       bool Narrowing = false;
461       if (FromWidth < ToWidth) {
462         // Negative -> unsigned is narrowing. Otherwise, more bits is never
463         // narrowing.
464         if (InitializerValue.isSigned() && InitializerValue.isNegative())
465           Narrowing = true;
466       } else {
467         // Add a bit to the InitializerValue so we don't have to worry about
468         // signed vs. unsigned comparisons.
469         InitializerValue = InitializerValue.extend(
470           InitializerValue.getBitWidth() + 1);
471         // Convert the initializer to and from the target width and signed-ness.
472         llvm::APSInt ConvertedValue = InitializerValue;
473         ConvertedValue = ConvertedValue.trunc(ToWidth);
474         ConvertedValue.setIsSigned(ToSigned);
475         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
476         ConvertedValue.setIsSigned(InitializerValue.isSigned());
477         // If the result is different, this was a narrowing conversion.
478         if (ConvertedValue != InitializerValue)
479           Narrowing = true;
480       }
481       if (Narrowing) {
482         ConstantType = Initializer->getType();
483         ConstantValue = APValue(InitializerValue);
484         return NK_Constant_Narrowing;
485       }
486     }
487     return NK_Not_Narrowing;
488   }
489 
490   default:
491     // Other kinds of conversions are not narrowings.
492     return NK_Not_Narrowing;
493   }
494 }
495 
496 /// dump - Print this standard conversion sequence to standard
497 /// error. Useful for debugging overloading issues.
498 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
499   raw_ostream &OS = llvm::errs();
500   bool PrintedSomething = false;
501   if (First != ICK_Identity) {
502     OS << GetImplicitConversionName(First);
503     PrintedSomething = true;
504   }
505 
506   if (Second != ICK_Identity) {
507     if (PrintedSomething) {
508       OS << " -> ";
509     }
510     OS << GetImplicitConversionName(Second);
511 
512     if (CopyConstructor) {
513       OS << " (by copy constructor)";
514     } else if (DirectBinding) {
515       OS << " (direct reference binding)";
516     } else if (ReferenceBinding) {
517       OS << " (reference binding)";
518     }
519     PrintedSomething = true;
520   }
521 
522   if (Third != ICK_Identity) {
523     if (PrintedSomething) {
524       OS << " -> ";
525     }
526     OS << GetImplicitConversionName(Third);
527     PrintedSomething = true;
528   }
529 
530   if (!PrintedSomething) {
531     OS << "No conversions required";
532   }
533 }
534 
535 /// dump - Print this user-defined conversion sequence to standard
536 /// error. Useful for debugging overloading issues.
537 void UserDefinedConversionSequence::dump() const {
538   raw_ostream &OS = llvm::errs();
539   if (Before.First || Before.Second || Before.Third) {
540     Before.dump();
541     OS << " -> ";
542   }
543   if (ConversionFunction)
544     OS << '\'' << *ConversionFunction << '\'';
545   else
546     OS << "aggregate initialization";
547   if (After.First || After.Second || After.Third) {
548     OS << " -> ";
549     After.dump();
550   }
551 }
552 
553 /// dump - Print this implicit conversion sequence to standard
554 /// error. Useful for debugging overloading issues.
555 void ImplicitConversionSequence::dump() const {
556   raw_ostream &OS = llvm::errs();
557   if (hasInitializerListContainerType())
558     OS << "Worst list element conversion: ";
559   switch (ConversionKind) {
560   case StandardConversion:
561     OS << "Standard conversion: ";
562     Standard.dump();
563     break;
564   case UserDefinedConversion:
565     OS << "User-defined conversion: ";
566     UserDefined.dump();
567     break;
568   case EllipsisConversion:
569     OS << "Ellipsis conversion";
570     break;
571   case AmbiguousConversion:
572     OS << "Ambiguous conversion";
573     break;
574   case BadConversion:
575     OS << "Bad conversion";
576     break;
577   }
578 
579   OS << "\n";
580 }
581 
582 void AmbiguousConversionSequence::construct() {
583   new (&conversions()) ConversionSet();
584 }
585 
586 void AmbiguousConversionSequence::destruct() {
587   conversions().~ConversionSet();
588 }
589 
590 void
591 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
592   FromTypePtr = O.FromTypePtr;
593   ToTypePtr = O.ToTypePtr;
594   new (&conversions()) ConversionSet(O.conversions());
595 }
596 
597 namespace {
598   // Structure used by DeductionFailureInfo to store
599   // template argument information.
600   struct DFIArguments {
601     TemplateArgument FirstArg;
602     TemplateArgument SecondArg;
603   };
604   // Structure used by DeductionFailureInfo to store
605   // template parameter and template argument information.
606   struct DFIParamWithArguments : DFIArguments {
607     TemplateParameter Param;
608   };
609   // Structure used by DeductionFailureInfo to store template argument
610   // information and the index of the problematic call argument.
611   struct DFIDeducedMismatchArgs : DFIArguments {
612     TemplateArgumentList *TemplateArgs;
613     unsigned CallArgIndex;
614   };
615   // Structure used by DeductionFailureInfo to store information about
616   // unsatisfied constraints.
617   struct CNSInfo {
618     TemplateArgumentList *TemplateArgs;
619     ConstraintSatisfaction Satisfaction;
620   };
621 }
622 
623 /// Convert from Sema's representation of template deduction information
624 /// to the form used in overload-candidate information.
625 DeductionFailureInfo
626 clang::MakeDeductionFailureInfo(ASTContext &Context,
627                                 Sema::TemplateDeductionResult TDK,
628                                 TemplateDeductionInfo &Info) {
629   DeductionFailureInfo Result;
630   Result.Result = static_cast<unsigned>(TDK);
631   Result.HasDiagnostic = false;
632   switch (TDK) {
633   case Sema::TDK_Invalid:
634   case Sema::TDK_InstantiationDepth:
635   case Sema::TDK_TooManyArguments:
636   case Sema::TDK_TooFewArguments:
637   case Sema::TDK_MiscellaneousDeductionFailure:
638   case Sema::TDK_CUDATargetMismatch:
639     Result.Data = nullptr;
640     break;
641 
642   case Sema::TDK_Incomplete:
643   case Sema::TDK_InvalidExplicitArguments:
644     Result.Data = Info.Param.getOpaqueValue();
645     break;
646 
647   case Sema::TDK_DeducedMismatch:
648   case Sema::TDK_DeducedMismatchNested: {
649     // FIXME: Should allocate from normal heap so that we can free this later.
650     auto *Saved = new (Context) DFIDeducedMismatchArgs;
651     Saved->FirstArg = Info.FirstArg;
652     Saved->SecondArg = Info.SecondArg;
653     Saved->TemplateArgs = Info.takeSugared();
654     Saved->CallArgIndex = Info.CallArgIndex;
655     Result.Data = Saved;
656     break;
657   }
658 
659   case Sema::TDK_NonDeducedMismatch: {
660     // FIXME: Should allocate from normal heap so that we can free this later.
661     DFIArguments *Saved = new (Context) DFIArguments;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_IncompletePack:
669     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified: {
672     // FIXME: Should allocate from normal heap so that we can free this later.
673     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
674     Saved->Param = Info.Param;
675     Saved->FirstArg = Info.FirstArg;
676     Saved->SecondArg = Info.SecondArg;
677     Result.Data = Saved;
678     break;
679   }
680 
681   case Sema::TDK_SubstitutionFailure:
682     Result.Data = Info.takeSugared();
683     if (Info.hasSFINAEDiagnostic()) {
684       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
685           SourceLocation(), PartialDiagnostic::NullDiagnostic());
686       Info.takeSFINAEDiagnostic(*Diag);
687       Result.HasDiagnostic = true;
688     }
689     break;
690 
691   case Sema::TDK_ConstraintsNotSatisfied: {
692     CNSInfo *Saved = new (Context) CNSInfo;
693     Saved->TemplateArgs = Info.takeSugared();
694     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
695     Result.Data = Saved;
696     break;
697   }
698 
699   case Sema::TDK_Success:
700   case Sema::TDK_NonDependentConversionFailure:
701   case Sema::TDK_AlreadyDiagnosed:
702     llvm_unreachable("not a deduction failure");
703   }
704 
705   return Result;
706 }
707 
708 void DeductionFailureInfo::Destroy() {
709   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
710   case Sema::TDK_Success:
711   case Sema::TDK_Invalid:
712   case Sema::TDK_InstantiationDepth:
713   case Sema::TDK_Incomplete:
714   case Sema::TDK_TooManyArguments:
715   case Sema::TDK_TooFewArguments:
716   case Sema::TDK_InvalidExplicitArguments:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     break;
720 
721   case Sema::TDK_IncompletePack:
722   case Sema::TDK_Inconsistent:
723   case Sema::TDK_Underqualified:
724   case Sema::TDK_DeducedMismatch:
725   case Sema::TDK_DeducedMismatchNested:
726   case Sema::TDK_NonDeducedMismatch:
727     // FIXME: Destroy the data?
728     Data = nullptr;
729     break;
730 
731   case Sema::TDK_SubstitutionFailure:
732     // FIXME: Destroy the template argument list?
733     Data = nullptr;
734     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
735       Diag->~PartialDiagnosticAt();
736       HasDiagnostic = false;
737     }
738     break;
739 
740   case Sema::TDK_ConstraintsNotSatisfied:
741     // FIXME: Destroy the template argument list?
742     Data = nullptr;
743     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
744       Diag->~PartialDiagnosticAt();
745       HasDiagnostic = false;
746     }
747     break;
748 
749   // Unhandled
750   case Sema::TDK_MiscellaneousDeductionFailure:
751   case Sema::TDK_AlreadyDiagnosed:
752     break;
753   }
754 }
755 
756 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
757   if (HasDiagnostic)
758     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
759   return nullptr;
760 }
761 
762 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_TooManyArguments:
768   case Sema::TDK_TooFewArguments:
769   case Sema::TDK_SubstitutionFailure:
770   case Sema::TDK_DeducedMismatch:
771   case Sema::TDK_DeducedMismatchNested:
772   case Sema::TDK_NonDeducedMismatch:
773   case Sema::TDK_CUDATargetMismatch:
774   case Sema::TDK_NonDependentConversionFailure:
775   case Sema::TDK_ConstraintsNotSatisfied:
776     return TemplateParameter();
777 
778   case Sema::TDK_Incomplete:
779   case Sema::TDK_InvalidExplicitArguments:
780     return TemplateParameter::getFromOpaqueValue(Data);
781 
782   case Sema::TDK_IncompletePack:
783   case Sema::TDK_Inconsistent:
784   case Sema::TDK_Underqualified:
785     return static_cast<DFIParamWithArguments*>(Data)->Param;
786 
787   // Unhandled
788   case Sema::TDK_MiscellaneousDeductionFailure:
789   case Sema::TDK_AlreadyDiagnosed:
790     break;
791   }
792 
793   return TemplateParameter();
794 }
795 
796 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
797   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
798   case Sema::TDK_Success:
799   case Sema::TDK_Invalid:
800   case Sema::TDK_InstantiationDepth:
801   case Sema::TDK_TooManyArguments:
802   case Sema::TDK_TooFewArguments:
803   case Sema::TDK_Incomplete:
804   case Sema::TDK_IncompletePack:
805   case Sema::TDK_InvalidExplicitArguments:
806   case Sema::TDK_Inconsistent:
807   case Sema::TDK_Underqualified:
808   case Sema::TDK_NonDeducedMismatch:
809   case Sema::TDK_CUDATargetMismatch:
810   case Sema::TDK_NonDependentConversionFailure:
811     return nullptr;
812 
813   case Sema::TDK_DeducedMismatch:
814   case Sema::TDK_DeducedMismatchNested:
815     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
816 
817   case Sema::TDK_SubstitutionFailure:
818     return static_cast<TemplateArgumentList*>(Data);
819 
820   case Sema::TDK_ConstraintsNotSatisfied:
821     return static_cast<CNSInfo*>(Data)->TemplateArgs;
822 
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825   case Sema::TDK_AlreadyDiagnosed:
826     break;
827   }
828 
829   return nullptr;
830 }
831 
832 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
833   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
834   case Sema::TDK_Success:
835   case Sema::TDK_Invalid:
836   case Sema::TDK_InstantiationDepth:
837   case Sema::TDK_Incomplete:
838   case Sema::TDK_TooManyArguments:
839   case Sema::TDK_TooFewArguments:
840   case Sema::TDK_InvalidExplicitArguments:
841   case Sema::TDK_SubstitutionFailure:
842   case Sema::TDK_CUDATargetMismatch:
843   case Sema::TDK_NonDependentConversionFailure:
844   case Sema::TDK_ConstraintsNotSatisfied:
845     return nullptr;
846 
847   case Sema::TDK_IncompletePack:
848   case Sema::TDK_Inconsistent:
849   case Sema::TDK_Underqualified:
850   case Sema::TDK_DeducedMismatch:
851   case Sema::TDK_DeducedMismatchNested:
852   case Sema::TDK_NonDeducedMismatch:
853     return &static_cast<DFIArguments*>(Data)->FirstArg;
854 
855   // Unhandled
856   case Sema::TDK_MiscellaneousDeductionFailure:
857   case Sema::TDK_AlreadyDiagnosed:
858     break;
859   }
860 
861   return nullptr;
862 }
863 
864 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
865   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
866   case Sema::TDK_Success:
867   case Sema::TDK_Invalid:
868   case Sema::TDK_InstantiationDepth:
869   case Sema::TDK_Incomplete:
870   case Sema::TDK_IncompletePack:
871   case Sema::TDK_TooManyArguments:
872   case Sema::TDK_TooFewArguments:
873   case Sema::TDK_InvalidExplicitArguments:
874   case Sema::TDK_SubstitutionFailure:
875   case Sema::TDK_CUDATargetMismatch:
876   case Sema::TDK_NonDependentConversionFailure:
877   case Sema::TDK_ConstraintsNotSatisfied:
878     return nullptr;
879 
880   case Sema::TDK_Inconsistent:
881   case Sema::TDK_Underqualified:
882   case Sema::TDK_DeducedMismatch:
883   case Sema::TDK_DeducedMismatchNested:
884   case Sema::TDK_NonDeducedMismatch:
885     return &static_cast<DFIArguments*>(Data)->SecondArg;
886 
887   // Unhandled
888   case Sema::TDK_MiscellaneousDeductionFailure:
889   case Sema::TDK_AlreadyDiagnosed:
890     break;
891   }
892 
893   return nullptr;
894 }
895 
896 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
897   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
898   case Sema::TDK_DeducedMismatch:
899   case Sema::TDK_DeducedMismatchNested:
900     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
901 
902   default:
903     return std::nullopt;
904   }
905 }
906 
907 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
908                                 const FunctionDecl *Y) {
909   if (!X || !Y)
910     return false;
911   if (X->getNumParams() != Y->getNumParams())
912     return false;
913   for (unsigned I = 0; I < X->getNumParams(); ++I)
914     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
915                                     Y->getParamDecl(I)->getType()))
916       return false;
917   if (auto *FTX = X->getDescribedFunctionTemplate()) {
918     auto *FTY = Y->getDescribedFunctionTemplate();
919     if (!FTY)
920       return false;
921     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
922                                          FTY->getTemplateParameters()))
923       return false;
924   }
925   return true;
926 }
927 
928 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
929                                   Expr *FirstOperand, FunctionDecl *EqFD) {
930   assert(EqFD->getOverloadedOperator() ==
931          OverloadedOperatorKind::OO_EqualEqual);
932   // C++2a [over.match.oper]p4:
933   // A non-template function or function template F named operator== is a
934   // rewrite target with first operand o unless a search for the name operator!=
935   // in the scope S from the instantiation context of the operator expression
936   // finds a function or function template that would correspond
937   // ([basic.scope.scope]) to F if its name were operator==, where S is the
938   // scope of the class type of o if F is a class member, and the namespace
939   // scope of which F is a member otherwise. A function template specialization
940   // named operator== is a rewrite target if its function template is a rewrite
941   // target.
942   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
943       OverloadedOperatorKind::OO_ExclaimEqual);
944   if (isa<CXXMethodDecl>(EqFD)) {
945     // If F is a class member, search scope is class type of first operand.
946     QualType RHS = FirstOperand->getType();
947     auto *RHSRec = RHS->getAs<RecordType>();
948     if (!RHSRec)
949       return true;
950     LookupResult Members(S, NotEqOp, OpLoc,
951                          Sema::LookupNameKind::LookupMemberName);
952     S.LookupQualifiedName(Members, RHSRec->getDecl());
953     Members.suppressDiagnostics();
954     for (NamedDecl *Op : Members)
955       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
956         return false;
957     return true;
958   }
959   // Otherwise the search scope is the namespace scope of which F is a member.
960   LookupResult NonMembers(S, NotEqOp, OpLoc,
961                           Sema::LookupNameKind::LookupOperatorName);
962   S.LookupName(NonMembers,
963                S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
964   NonMembers.suppressDiagnostics();
965   for (NamedDecl *Op : NonMembers) {
966     auto *FD = Op->getAsFunction();
967     if(auto* UD = dyn_cast<UsingShadowDecl>(Op))
968       FD = UD->getUnderlyingDecl()->getAsFunction();
969     if (FunctionsCorrespond(S.Context, EqFD, FD) &&
970         declaresSameEntity(cast<Decl>(EqFD->getDeclContext()),
971                            cast<Decl>(Op->getDeclContext())))
972       return false;
973   }
974   return true;
975 }
976 
977 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
978     OverloadedOperatorKind Op) {
979   if (!AllowRewrittenCandidates)
980     return false;
981   return Op == OO_EqualEqual || Op == OO_Spaceship;
982 }
983 
984 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
985     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
986   auto Op = FD->getOverloadedOperator();
987   if (!allowsReversed(Op))
988     return false;
989   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
990     assert(OriginalArgs.size() == 2);
991     if (!shouldAddReversedEqEq(
992             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
993       return false;
994   }
995   // Don't bother adding a reversed candidate that can never be a better
996   // match than the non-reversed version.
997   return FD->getNumParams() != 2 ||
998          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
999                                            FD->getParamDecl(1)->getType()) ||
1000          FD->hasAttr<EnableIfAttr>();
1001 }
1002 
1003 void OverloadCandidateSet::destroyCandidates() {
1004   for (iterator i = begin(), e = end(); i != e; ++i) {
1005     for (auto &C : i->Conversions)
1006       C.~ImplicitConversionSequence();
1007     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1008       i->DeductionFailure.Destroy();
1009   }
1010 }
1011 
1012 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1013   destroyCandidates();
1014   SlabAllocator.Reset();
1015   NumInlineBytesUsed = 0;
1016   Candidates.clear();
1017   Functions.clear();
1018   Kind = CSK;
1019 }
1020 
1021 namespace {
1022   class UnbridgedCastsSet {
1023     struct Entry {
1024       Expr **Addr;
1025       Expr *Saved;
1026     };
1027     SmallVector<Entry, 2> Entries;
1028 
1029   public:
1030     void save(Sema &S, Expr *&E) {
1031       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1032       Entry entry = { &E, E };
1033       Entries.push_back(entry);
1034       E = S.stripARCUnbridgedCast(E);
1035     }
1036 
1037     void restore() {
1038       for (SmallVectorImpl<Entry>::iterator
1039              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1040         *i->Addr = i->Saved;
1041     }
1042   };
1043 }
1044 
1045 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1046 /// preprocessing on the given expression.
1047 ///
1048 /// \param unbridgedCasts a collection to which to add unbridged casts;
1049 ///   without this, they will be immediately diagnosed as errors
1050 ///
1051 /// Return true on unrecoverable error.
1052 static bool
1053 checkPlaceholderForOverload(Sema &S, Expr *&E,
1054                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1055   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1056     // We can't handle overloaded expressions here because overload
1057     // resolution might reasonably tweak them.
1058     if (placeholder->getKind() == BuiltinType::Overload) return false;
1059 
1060     // If the context potentially accepts unbridged ARC casts, strip
1061     // the unbridged cast and add it to the collection for later restoration.
1062     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1063         unbridgedCasts) {
1064       unbridgedCasts->save(S, E);
1065       return false;
1066     }
1067 
1068     // Go ahead and check everything else.
1069     ExprResult result = S.CheckPlaceholderExpr(E);
1070     if (result.isInvalid())
1071       return true;
1072 
1073     E = result.get();
1074     return false;
1075   }
1076 
1077   // Nothing to do.
1078   return false;
1079 }
1080 
1081 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1082 /// placeholders.
1083 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1084                                             UnbridgedCastsSet &unbridged) {
1085   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1086     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1087       return true;
1088 
1089   return false;
1090 }
1091 
1092 /// Determine whether the given New declaration is an overload of the
1093 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1094 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1095 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1096 /// functions (or function templates) at all. When it does return Ovl_Match or
1097 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1098 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1099 /// declaration.
1100 ///
1101 /// Example: Given the following input:
1102 ///
1103 ///   void f(int, float); // #1
1104 ///   void f(int, int); // #2
1105 ///   int f(int, int); // #3
1106 ///
1107 /// When we process #1, there is no previous declaration of "f", so IsOverload
1108 /// will not be used.
1109 ///
1110 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1111 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1112 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1113 /// unchanged.
1114 ///
1115 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1116 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1117 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1118 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1119 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1120 ///
1121 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1122 /// by a using declaration. The rules for whether to hide shadow declarations
1123 /// ignore some properties which otherwise figure into a function template's
1124 /// signature.
1125 Sema::OverloadKind
1126 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1127                     NamedDecl *&Match, bool NewIsUsingDecl) {
1128   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1129          I != E; ++I) {
1130     NamedDecl *OldD = *I;
1131 
1132     bool OldIsUsingDecl = false;
1133     if (isa<UsingShadowDecl>(OldD)) {
1134       OldIsUsingDecl = true;
1135 
1136       // We can always introduce two using declarations into the same
1137       // context, even if they have identical signatures.
1138       if (NewIsUsingDecl) continue;
1139 
1140       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1141     }
1142 
1143     // A using-declaration does not conflict with another declaration
1144     // if one of them is hidden.
1145     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1146       continue;
1147 
1148     // If either declaration was introduced by a using declaration,
1149     // we'll need to use slightly different rules for matching.
1150     // Essentially, these rules are the normal rules, except that
1151     // function templates hide function templates with different
1152     // return types or template parameter lists.
1153     bool UseMemberUsingDeclRules =
1154       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1155       !New->getFriendObjectKind();
1156 
1157     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1158       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1159         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1160           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1161           continue;
1162         }
1163 
1164         if (!isa<FunctionTemplateDecl>(OldD) &&
1165             !shouldLinkPossiblyHiddenDecl(*I, New))
1166           continue;
1167 
1168         Match = *I;
1169         return Ovl_Match;
1170       }
1171 
1172       // Builtins that have custom typechecking or have a reference should
1173       // not be overloadable or redeclarable.
1174       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1175         Match = *I;
1176         return Ovl_NonFunction;
1177       }
1178     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1179       // We can overload with these, which can show up when doing
1180       // redeclaration checks for UsingDecls.
1181       assert(Old.getLookupKind() == LookupUsingDeclName);
1182     } else if (isa<TagDecl>(OldD)) {
1183       // We can always overload with tags by hiding them.
1184     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1185       // Optimistically assume that an unresolved using decl will
1186       // overload; if it doesn't, we'll have to diagnose during
1187       // template instantiation.
1188       //
1189       // Exception: if the scope is dependent and this is not a class
1190       // member, the using declaration can only introduce an enumerator.
1191       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1192         Match = *I;
1193         return Ovl_NonFunction;
1194       }
1195     } else {
1196       // (C++ 13p1):
1197       //   Only function declarations can be overloaded; object and type
1198       //   declarations cannot be overloaded.
1199       Match = *I;
1200       return Ovl_NonFunction;
1201     }
1202   }
1203 
1204   // C++ [temp.friend]p1:
1205   //   For a friend function declaration that is not a template declaration:
1206   //    -- if the name of the friend is a qualified or unqualified template-id,
1207   //       [...], otherwise
1208   //    -- if the name of the friend is a qualified-id and a matching
1209   //       non-template function is found in the specified class or namespace,
1210   //       the friend declaration refers to that function, otherwise,
1211   //    -- if the name of the friend is a qualified-id and a matching function
1212   //       template is found in the specified class or namespace, the friend
1213   //       declaration refers to the deduced specialization of that function
1214   //       template, otherwise
1215   //    -- the name shall be an unqualified-id [...]
1216   // If we get here for a qualified friend declaration, we've just reached the
1217   // third bullet. If the type of the friend is dependent, skip this lookup
1218   // until instantiation.
1219   if (New->getFriendObjectKind() && New->getQualifier() &&
1220       !New->getDescribedFunctionTemplate() &&
1221       !New->getDependentSpecializationInfo() &&
1222       !New->getType()->isDependentType()) {
1223     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1224     TemplateSpecResult.addAllDecls(Old);
1225     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1226                                             /*QualifiedFriend*/true)) {
1227       New->setInvalidDecl();
1228       return Ovl_Overload;
1229     }
1230 
1231     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1232     return Ovl_Match;
1233   }
1234 
1235   return Ovl_Overload;
1236 }
1237 
1238 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1239                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1240                       bool ConsiderRequiresClauses) {
1241   // C++ [basic.start.main]p2: This function shall not be overloaded.
1242   if (New->isMain())
1243     return false;
1244 
1245   // MSVCRT user defined entry points cannot be overloaded.
1246   if (New->isMSVCRTEntryPoint())
1247     return false;
1248 
1249   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1250   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1251 
1252   // C++ [temp.fct]p2:
1253   //   A function template can be overloaded with other function templates
1254   //   and with normal (non-template) functions.
1255   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1256     return true;
1257 
1258   // Is the function New an overload of the function Old?
1259   QualType OldQType = Context.getCanonicalType(Old->getType());
1260   QualType NewQType = Context.getCanonicalType(New->getType());
1261 
1262   // Compare the signatures (C++ 1.3.10) of the two functions to
1263   // determine whether they are overloads. If we find any mismatch
1264   // in the signature, they are overloads.
1265 
1266   // If either of these functions is a K&R-style function (no
1267   // prototype), then we consider them to have matching signatures.
1268   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1269       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1270     return false;
1271 
1272   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1273   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1274 
1275   // The signature of a function includes the types of its
1276   // parameters (C++ 1.3.10), which includes the presence or absence
1277   // of the ellipsis; see C++ DR 357).
1278   if (OldQType != NewQType &&
1279       (OldType->getNumParams() != NewType->getNumParams() ||
1280        OldType->isVariadic() != NewType->isVariadic() ||
1281        !FunctionParamTypesAreEqual(OldType, NewType)))
1282     return true;
1283 
1284   // For member-like friends, the enclosing class is part of the signature.
1285   if ((New->isMemberLikeConstrainedFriend() ||
1286        Old->isMemberLikeConstrainedFriend()) &&
1287       !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1288     return true;
1289 
1290   if (NewTemplate) {
1291     // C++ [temp.over.link]p4:
1292     //   The signature of a function template consists of its function
1293     //   signature, its return type and its template parameter list. The names
1294     //   of the template parameters are significant only for establishing the
1295     //   relationship between the template parameters and the rest of the
1296     //   signature.
1297     //
1298     // We check the return type and template parameter lists for function
1299     // templates first; the remaining checks follow.
1300     bool SameTemplateParameterList = TemplateParameterListsAreEqual(
1301         NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1302         OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
1303     bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
1304                                               New->getDeclaredReturnType());
1305     // FIXME(GH58571): Match template parameter list even for non-constrained
1306     // template heads. This currently ensures that the code prior to C++20 is
1307     // not newly broken.
1308     bool ConstraintsInTemplateHead =
1309         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1310         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1311     // C++ [namespace.udecl]p11:
1312     //   The set of declarations named by a using-declarator that inhabits a
1313     //   class C does not include member functions and member function
1314     //   templates of a base class that "correspond" to (and thus would
1315     //   conflict with) a declaration of a function or function template in
1316     //   C.
1317     // Comparing return types is not required for the "correspond" check to
1318     // decide whether a member introduced by a shadow declaration is hidden.
1319     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1320         !SameTemplateParameterList)
1321       return true;
1322     if (!UseMemberUsingDeclRules &&
1323         (!SameTemplateParameterList || !SameReturnType))
1324       return true;
1325   }
1326 
1327   if (ConsiderRequiresClauses) {
1328     Expr *NewRC = New->getTrailingRequiresClause(),
1329          *OldRC = Old->getTrailingRequiresClause();
1330     if ((NewRC != nullptr) != (OldRC != nullptr))
1331       return true;
1332 
1333     if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1334         return true;
1335   }
1336 
1337   // If the function is a class member, its signature includes the
1338   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1339   //
1340   // As part of this, also check whether one of the member functions
1341   // is static, in which case they are not overloads (C++
1342   // 13.1p2). While not part of the definition of the signature,
1343   // this check is important to determine whether these functions
1344   // can be overloaded.
1345   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1346   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1347   if (OldMethod && NewMethod &&
1348       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1349     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1350       if (!UseMemberUsingDeclRules &&
1351           (OldMethod->getRefQualifier() == RQ_None ||
1352            NewMethod->getRefQualifier() == RQ_None)) {
1353         // C++20 [over.load]p2:
1354         //   - Member function declarations with the same name, the same
1355         //     parameter-type-list, and the same trailing requires-clause (if
1356         //     any), as well as member function template declarations with the
1357         //     same name, the same parameter-type-list, the same trailing
1358         //     requires-clause (if any), and the same template-head, cannot be
1359         //     overloaded if any of them, but not all, have a ref-qualifier.
1360         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1361             << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1362         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1363       }
1364       return true;
1365     }
1366 
1367     // We may not have applied the implicit const for a constexpr member
1368     // function yet (because we haven't yet resolved whether this is a static
1369     // or non-static member function). Add it now, on the assumption that this
1370     // is a redeclaration of OldMethod.
1371     auto OldQuals = OldMethod->getMethodQualifiers();
1372     auto NewQuals = NewMethod->getMethodQualifiers();
1373     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1374         !isa<CXXConstructorDecl>(NewMethod))
1375       NewQuals.addConst();
1376     // We do not allow overloading based off of '__restrict'.
1377     OldQuals.removeRestrict();
1378     NewQuals.removeRestrict();
1379     if (OldQuals != NewQuals)
1380       return true;
1381   }
1382 
1383   // Though pass_object_size is placed on parameters and takes an argument, we
1384   // consider it to be a function-level modifier for the sake of function
1385   // identity. Either the function has one or more parameters with
1386   // pass_object_size or it doesn't.
1387   if (functionHasPassObjectSizeParams(New) !=
1388       functionHasPassObjectSizeParams(Old))
1389     return true;
1390 
1391   // enable_if attributes are an order-sensitive part of the signature.
1392   for (specific_attr_iterator<EnableIfAttr>
1393          NewI = New->specific_attr_begin<EnableIfAttr>(),
1394          NewE = New->specific_attr_end<EnableIfAttr>(),
1395          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1396          OldE = Old->specific_attr_end<EnableIfAttr>();
1397        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1398     if (NewI == NewE || OldI == OldE)
1399       return true;
1400     llvm::FoldingSetNodeID NewID, OldID;
1401     NewI->getCond()->Profile(NewID, Context, true);
1402     OldI->getCond()->Profile(OldID, Context, true);
1403     if (NewID != OldID)
1404       return true;
1405   }
1406 
1407   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1408     // Don't allow overloading of destructors.  (In theory we could, but it
1409     // would be a giant change to clang.)
1410     if (!isa<CXXDestructorDecl>(New)) {
1411       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1412                          OldTarget = IdentifyCUDATarget(Old);
1413       if (NewTarget != CFT_InvalidTarget) {
1414         assert((OldTarget != CFT_InvalidTarget) &&
1415                "Unexpected invalid target.");
1416 
1417         // Allow overloading of functions with same signature and different CUDA
1418         // target attributes.
1419         if (NewTarget != OldTarget)
1420           return true;
1421       }
1422     }
1423   }
1424 
1425   // The signatures match; this is not an overload.
1426   return false;
1427 }
1428 
1429 /// Tries a user-defined conversion from From to ToType.
1430 ///
1431 /// Produces an implicit conversion sequence for when a standard conversion
1432 /// is not an option. See TryImplicitConversion for more information.
1433 static ImplicitConversionSequence
1434 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1435                          bool SuppressUserConversions,
1436                          AllowedExplicit AllowExplicit,
1437                          bool InOverloadResolution,
1438                          bool CStyle,
1439                          bool AllowObjCWritebackConversion,
1440                          bool AllowObjCConversionOnExplicit) {
1441   ImplicitConversionSequence ICS;
1442 
1443   if (SuppressUserConversions) {
1444     // We're not in the case above, so there is no conversion that
1445     // we can perform.
1446     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1447     return ICS;
1448   }
1449 
1450   // Attempt user-defined conversion.
1451   OverloadCandidateSet Conversions(From->getExprLoc(),
1452                                    OverloadCandidateSet::CSK_Normal);
1453   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1454                                   Conversions, AllowExplicit,
1455                                   AllowObjCConversionOnExplicit)) {
1456   case OR_Success:
1457   case OR_Deleted:
1458     ICS.setUserDefined();
1459     // C++ [over.ics.user]p4:
1460     //   A conversion of an expression of class type to the same class
1461     //   type is given Exact Match rank, and a conversion of an
1462     //   expression of class type to a base class of that type is
1463     //   given Conversion rank, in spite of the fact that a copy
1464     //   constructor (i.e., a user-defined conversion function) is
1465     //   called for those cases.
1466     if (CXXConstructorDecl *Constructor
1467           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1468       QualType FromCanon
1469         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1470       QualType ToCanon
1471         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1472       if (Constructor->isCopyConstructor() &&
1473           (FromCanon == ToCanon ||
1474            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1475         // Turn this into a "standard" conversion sequence, so that it
1476         // gets ranked with standard conversion sequences.
1477         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1478         ICS.setStandard();
1479         ICS.Standard.setAsIdentityConversion();
1480         ICS.Standard.setFromType(From->getType());
1481         ICS.Standard.setAllToTypes(ToType);
1482         ICS.Standard.CopyConstructor = Constructor;
1483         ICS.Standard.FoundCopyConstructor = Found;
1484         if (ToCanon != FromCanon)
1485           ICS.Standard.Second = ICK_Derived_To_Base;
1486       }
1487     }
1488     break;
1489 
1490   case OR_Ambiguous:
1491     ICS.setAmbiguous();
1492     ICS.Ambiguous.setFromType(From->getType());
1493     ICS.Ambiguous.setToType(ToType);
1494     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1495          Cand != Conversions.end(); ++Cand)
1496       if (Cand->Best)
1497         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1498     break;
1499 
1500     // Fall through.
1501   case OR_No_Viable_Function:
1502     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1503     break;
1504   }
1505 
1506   return ICS;
1507 }
1508 
1509 /// TryImplicitConversion - Attempt to perform an implicit conversion
1510 /// from the given expression (Expr) to the given type (ToType). This
1511 /// function returns an implicit conversion sequence that can be used
1512 /// to perform the initialization. Given
1513 ///
1514 ///   void f(float f);
1515 ///   void g(int i) { f(i); }
1516 ///
1517 /// this routine would produce an implicit conversion sequence to
1518 /// describe the initialization of f from i, which will be a standard
1519 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1520 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1521 //
1522 /// Note that this routine only determines how the conversion can be
1523 /// performed; it does not actually perform the conversion. As such,
1524 /// it will not produce any diagnostics if no conversion is available,
1525 /// but will instead return an implicit conversion sequence of kind
1526 /// "BadConversion".
1527 ///
1528 /// If @p SuppressUserConversions, then user-defined conversions are
1529 /// not permitted.
1530 /// If @p AllowExplicit, then explicit user-defined conversions are
1531 /// permitted.
1532 ///
1533 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1534 /// writeback conversion, which allows __autoreleasing id* parameters to
1535 /// be initialized with __strong id* or __weak id* arguments.
1536 static ImplicitConversionSequence
1537 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1538                       bool SuppressUserConversions,
1539                       AllowedExplicit AllowExplicit,
1540                       bool InOverloadResolution,
1541                       bool CStyle,
1542                       bool AllowObjCWritebackConversion,
1543                       bool AllowObjCConversionOnExplicit) {
1544   ImplicitConversionSequence ICS;
1545   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1546                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1547     ICS.setStandard();
1548     return ICS;
1549   }
1550 
1551   if (!S.getLangOpts().CPlusPlus) {
1552     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1553     return ICS;
1554   }
1555 
1556   // C++ [over.ics.user]p4:
1557   //   A conversion of an expression of class type to the same class
1558   //   type is given Exact Match rank, and a conversion of an
1559   //   expression of class type to a base class of that type is
1560   //   given Conversion rank, in spite of the fact that a copy/move
1561   //   constructor (i.e., a user-defined conversion function) is
1562   //   called for those cases.
1563   QualType FromType = From->getType();
1564   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1565       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1566        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1567     ICS.setStandard();
1568     ICS.Standard.setAsIdentityConversion();
1569     ICS.Standard.setFromType(FromType);
1570     ICS.Standard.setAllToTypes(ToType);
1571 
1572     // We don't actually check at this point whether there is a valid
1573     // copy/move constructor, since overloading just assumes that it
1574     // exists. When we actually perform initialization, we'll find the
1575     // appropriate constructor to copy the returned object, if needed.
1576     ICS.Standard.CopyConstructor = nullptr;
1577 
1578     // Determine whether this is considered a derived-to-base conversion.
1579     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1580       ICS.Standard.Second = ICK_Derived_To_Base;
1581 
1582     return ICS;
1583   }
1584 
1585   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1586                                   AllowExplicit, InOverloadResolution, CStyle,
1587                                   AllowObjCWritebackConversion,
1588                                   AllowObjCConversionOnExplicit);
1589 }
1590 
1591 ImplicitConversionSequence
1592 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1593                             bool SuppressUserConversions,
1594                             AllowedExplicit AllowExplicit,
1595                             bool InOverloadResolution,
1596                             bool CStyle,
1597                             bool AllowObjCWritebackConversion) {
1598   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1599                                  AllowExplicit, InOverloadResolution, CStyle,
1600                                  AllowObjCWritebackConversion,
1601                                  /*AllowObjCConversionOnExplicit=*/false);
1602 }
1603 
1604 /// PerformImplicitConversion - Perform an implicit conversion of the
1605 /// expression From to the type ToType. Returns the
1606 /// converted expression. Flavor is the kind of conversion we're
1607 /// performing, used in the error message. If @p AllowExplicit,
1608 /// explicit user-defined conversions are permitted.
1609 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1610                                            AssignmentAction Action,
1611                                            bool AllowExplicit) {
1612   if (checkPlaceholderForOverload(*this, From))
1613     return ExprError();
1614 
1615   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1616   bool AllowObjCWritebackConversion
1617     = getLangOpts().ObjCAutoRefCount &&
1618       (Action == AA_Passing || Action == AA_Sending);
1619   if (getLangOpts().ObjC)
1620     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1621                                       From->getType(), From);
1622   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1623       *this, From, ToType,
1624       /*SuppressUserConversions=*/false,
1625       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1626       /*InOverloadResolution=*/false,
1627       /*CStyle=*/false, AllowObjCWritebackConversion,
1628       /*AllowObjCConversionOnExplicit=*/false);
1629   return PerformImplicitConversion(From, ToType, ICS, Action);
1630 }
1631 
1632 /// Determine whether the conversion from FromType to ToType is a valid
1633 /// conversion that strips "noexcept" or "noreturn" off the nested function
1634 /// type.
1635 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1636                                 QualType &ResultTy) {
1637   if (Context.hasSameUnqualifiedType(FromType, ToType))
1638     return false;
1639 
1640   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1641   //                    or F(t noexcept) -> F(t)
1642   // where F adds one of the following at most once:
1643   //   - a pointer
1644   //   - a member pointer
1645   //   - a block pointer
1646   // Changes here need matching changes in FindCompositePointerType.
1647   CanQualType CanTo = Context.getCanonicalType(ToType);
1648   CanQualType CanFrom = Context.getCanonicalType(FromType);
1649   Type::TypeClass TyClass = CanTo->getTypeClass();
1650   if (TyClass != CanFrom->getTypeClass()) return false;
1651   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1652     if (TyClass == Type::Pointer) {
1653       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1654       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1655     } else if (TyClass == Type::BlockPointer) {
1656       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1657       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1658     } else if (TyClass == Type::MemberPointer) {
1659       auto ToMPT = CanTo.castAs<MemberPointerType>();
1660       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1661       // A function pointer conversion cannot change the class of the function.
1662       if (ToMPT->getClass() != FromMPT->getClass())
1663         return false;
1664       CanTo = ToMPT->getPointeeType();
1665       CanFrom = FromMPT->getPointeeType();
1666     } else {
1667       return false;
1668     }
1669 
1670     TyClass = CanTo->getTypeClass();
1671     if (TyClass != CanFrom->getTypeClass()) return false;
1672     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1673       return false;
1674   }
1675 
1676   const auto *FromFn = cast<FunctionType>(CanFrom);
1677   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1678 
1679   const auto *ToFn = cast<FunctionType>(CanTo);
1680   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1681 
1682   bool Changed = false;
1683 
1684   // Drop 'noreturn' if not present in target type.
1685   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1686     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1687     Changed = true;
1688   }
1689 
1690   // Drop 'noexcept' if not present in target type.
1691   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1692     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1693     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1694       FromFn = cast<FunctionType>(
1695           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1696                                                    EST_None)
1697                  .getTypePtr());
1698       Changed = true;
1699     }
1700 
1701     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1702     // only if the ExtParameterInfo lists of the two function prototypes can be
1703     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1704     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1705     bool CanUseToFPT, CanUseFromFPT;
1706     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1707                                       CanUseFromFPT, NewParamInfos) &&
1708         CanUseToFPT && !CanUseFromFPT) {
1709       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1710       ExtInfo.ExtParameterInfos =
1711           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1712       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1713                                             FromFPT->getParamTypes(), ExtInfo);
1714       FromFn = QT->getAs<FunctionType>();
1715       Changed = true;
1716     }
1717   }
1718 
1719   if (!Changed)
1720     return false;
1721 
1722   assert(QualType(FromFn, 0).isCanonical());
1723   if (QualType(FromFn, 0) != CanTo) return false;
1724 
1725   ResultTy = ToType;
1726   return true;
1727 }
1728 
1729 /// Determine whether the conversion from FromType to ToType is a valid
1730 /// vector conversion.
1731 ///
1732 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1733 /// conversion.
1734 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1735                                ImplicitConversionKind &ICK, Expr *From,
1736                                bool InOverloadResolution, bool CStyle) {
1737   // We need at least one of these types to be a vector type to have a vector
1738   // conversion.
1739   if (!ToType->isVectorType() && !FromType->isVectorType())
1740     return false;
1741 
1742   // Identical types require no conversions.
1743   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1744     return false;
1745 
1746   // There are no conversions between extended vector types, only identity.
1747   if (ToType->isExtVectorType()) {
1748     // There are no conversions between extended vector types other than the
1749     // identity conversion.
1750     if (FromType->isExtVectorType())
1751       return false;
1752 
1753     // Vector splat from any arithmetic type to a vector.
1754     if (FromType->isArithmeticType()) {
1755       ICK = ICK_Vector_Splat;
1756       return true;
1757     }
1758   }
1759 
1760   if (ToType->isSVESizelessBuiltinType() ||
1761       FromType->isSVESizelessBuiltinType())
1762     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1763         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1764       ICK = ICK_SVE_Vector_Conversion;
1765       return true;
1766     }
1767 
1768   if (ToType->isRVVSizelessBuiltinType() ||
1769       FromType->isRVVSizelessBuiltinType())
1770     if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
1771         S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
1772       ICK = ICK_RVV_Vector_Conversion;
1773       return true;
1774     }
1775 
1776   // We can perform the conversion between vector types in the following cases:
1777   // 1)vector types are equivalent AltiVec and GCC vector types
1778   // 2)lax vector conversions are permitted and the vector types are of the
1779   //   same size
1780   // 3)the destination type does not have the ARM MVE strict-polymorphism
1781   //   attribute, which inhibits lax vector conversion for overload resolution
1782   //   only
1783   if (ToType->isVectorType() && FromType->isVectorType()) {
1784     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1785         (S.isLaxVectorConversion(FromType, ToType) &&
1786          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1787       if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
1788           S.isLaxVectorConversion(FromType, ToType) &&
1789           S.anyAltivecTypes(FromType, ToType) &&
1790           !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
1791           !InOverloadResolution && !CStyle) {
1792         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1793             << FromType << ToType;
1794       }
1795       ICK = ICK_Vector_Conversion;
1796       return true;
1797     }
1798   }
1799 
1800   return false;
1801 }
1802 
1803 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1804                                 bool InOverloadResolution,
1805                                 StandardConversionSequence &SCS,
1806                                 bool CStyle);
1807 
1808 /// IsStandardConversion - Determines whether there is a standard
1809 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1810 /// expression From to the type ToType. Standard conversion sequences
1811 /// only consider non-class types; for conversions that involve class
1812 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1813 /// contain the standard conversion sequence required to perform this
1814 /// conversion and this routine will return true. Otherwise, this
1815 /// routine will return false and the value of SCS is unspecified.
1816 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1817                                  bool InOverloadResolution,
1818                                  StandardConversionSequence &SCS,
1819                                  bool CStyle,
1820                                  bool AllowObjCWritebackConversion) {
1821   QualType FromType = From->getType();
1822 
1823   // Standard conversions (C++ [conv])
1824   SCS.setAsIdentityConversion();
1825   SCS.IncompatibleObjC = false;
1826   SCS.setFromType(FromType);
1827   SCS.CopyConstructor = nullptr;
1828 
1829   // There are no standard conversions for class types in C++, so
1830   // abort early. When overloading in C, however, we do permit them.
1831   if (S.getLangOpts().CPlusPlus &&
1832       (FromType->isRecordType() || ToType->isRecordType()))
1833     return false;
1834 
1835   // The first conversion can be an lvalue-to-rvalue conversion,
1836   // array-to-pointer conversion, or function-to-pointer conversion
1837   // (C++ 4p1).
1838 
1839   if (FromType == S.Context.OverloadTy) {
1840     DeclAccessPair AccessPair;
1841     if (FunctionDecl *Fn
1842           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1843                                                  AccessPair)) {
1844       // We were able to resolve the address of the overloaded function,
1845       // so we can convert to the type of that function.
1846       FromType = Fn->getType();
1847       SCS.setFromType(FromType);
1848 
1849       // we can sometimes resolve &foo<int> regardless of ToType, so check
1850       // if the type matches (identity) or we are converting to bool
1851       if (!S.Context.hasSameUnqualifiedType(
1852                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1853         QualType resultTy;
1854         // if the function type matches except for [[noreturn]], it's ok
1855         if (!S.IsFunctionConversion(FromType,
1856               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1857           // otherwise, only a boolean conversion is standard
1858           if (!ToType->isBooleanType())
1859             return false;
1860       }
1861 
1862       // Check if the "from" expression is taking the address of an overloaded
1863       // function and recompute the FromType accordingly. Take advantage of the
1864       // fact that non-static member functions *must* have such an address-of
1865       // expression.
1866       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1867       if (Method && !Method->isStatic()) {
1868         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1869                "Non-unary operator on non-static member address");
1870         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1871                == UO_AddrOf &&
1872                "Non-address-of operator on non-static member address");
1873         const Type *ClassType
1874           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1875         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1876       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1877         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1878                UO_AddrOf &&
1879                "Non-address-of operator for overloaded function expression");
1880         FromType = S.Context.getPointerType(FromType);
1881       }
1882     } else {
1883       return false;
1884     }
1885   }
1886   // Lvalue-to-rvalue conversion (C++11 4.1):
1887   //   A glvalue (3.10) of a non-function, non-array type T can
1888   //   be converted to a prvalue.
1889   bool argIsLValue = From->isGLValue();
1890   if (argIsLValue &&
1891       !FromType->isFunctionType() && !FromType->isArrayType() &&
1892       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1893     SCS.First = ICK_Lvalue_To_Rvalue;
1894 
1895     // C11 6.3.2.1p2:
1896     //   ... if the lvalue has atomic type, the value has the non-atomic version
1897     //   of the type of the lvalue ...
1898     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1899       FromType = Atomic->getValueType();
1900 
1901     // If T is a non-class type, the type of the rvalue is the
1902     // cv-unqualified version of T. Otherwise, the type of the rvalue
1903     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1904     // just strip the qualifiers because they don't matter.
1905     FromType = FromType.getUnqualifiedType();
1906   } else if (FromType->isArrayType()) {
1907     // Array-to-pointer conversion (C++ 4.2)
1908     SCS.First = ICK_Array_To_Pointer;
1909 
1910     // An lvalue or rvalue of type "array of N T" or "array of unknown
1911     // bound of T" can be converted to an rvalue of type "pointer to
1912     // T" (C++ 4.2p1).
1913     FromType = S.Context.getArrayDecayedType(FromType);
1914 
1915     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1916       // This conversion is deprecated in C++03 (D.4)
1917       SCS.DeprecatedStringLiteralToCharPtr = true;
1918 
1919       // For the purpose of ranking in overload resolution
1920       // (13.3.3.1.1), this conversion is considered an
1921       // array-to-pointer conversion followed by a qualification
1922       // conversion (4.4). (C++ 4.2p2)
1923       SCS.Second = ICK_Identity;
1924       SCS.Third = ICK_Qualification;
1925       SCS.QualificationIncludesObjCLifetime = false;
1926       SCS.setAllToTypes(FromType);
1927       return true;
1928     }
1929   } else if (FromType->isFunctionType() && argIsLValue) {
1930     // Function-to-pointer conversion (C++ 4.3).
1931     SCS.First = ICK_Function_To_Pointer;
1932 
1933     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1934       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1935         if (!S.checkAddressOfFunctionIsAvailable(FD))
1936           return false;
1937 
1938     // An lvalue of function type T can be converted to an rvalue of
1939     // type "pointer to T." The result is a pointer to the
1940     // function. (C++ 4.3p1).
1941     FromType = S.Context.getPointerType(FromType);
1942   } else {
1943     // We don't require any conversions for the first step.
1944     SCS.First = ICK_Identity;
1945   }
1946   SCS.setToType(0, FromType);
1947 
1948   // The second conversion can be an integral promotion, floating
1949   // point promotion, integral conversion, floating point conversion,
1950   // floating-integral conversion, pointer conversion,
1951   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1952   // For overloading in C, this can also be a "compatible-type"
1953   // conversion.
1954   bool IncompatibleObjC = false;
1955   ImplicitConversionKind SecondICK = ICK_Identity;
1956   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1957     // The unqualified versions of the types are the same: there's no
1958     // conversion to do.
1959     SCS.Second = ICK_Identity;
1960   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1961     // Integral promotion (C++ 4.5).
1962     SCS.Second = ICK_Integral_Promotion;
1963     FromType = ToType.getUnqualifiedType();
1964   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1965     // Floating point promotion (C++ 4.6).
1966     SCS.Second = ICK_Floating_Promotion;
1967     FromType = ToType.getUnqualifiedType();
1968   } else if (S.IsComplexPromotion(FromType, ToType)) {
1969     // Complex promotion (Clang extension)
1970     SCS.Second = ICK_Complex_Promotion;
1971     FromType = ToType.getUnqualifiedType();
1972   } else if (ToType->isBooleanType() &&
1973              (FromType->isArithmeticType() ||
1974               FromType->isAnyPointerType() ||
1975               FromType->isBlockPointerType() ||
1976               FromType->isMemberPointerType())) {
1977     // Boolean conversions (C++ 4.12).
1978     SCS.Second = ICK_Boolean_Conversion;
1979     FromType = S.Context.BoolTy;
1980   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1981              ToType->isIntegralType(S.Context)) {
1982     // Integral conversions (C++ 4.7).
1983     SCS.Second = ICK_Integral_Conversion;
1984     FromType = ToType.getUnqualifiedType();
1985   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1986     // Complex conversions (C99 6.3.1.6)
1987     SCS.Second = ICK_Complex_Conversion;
1988     FromType = ToType.getUnqualifiedType();
1989   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1990              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1991     // Complex-real conversions (C99 6.3.1.7)
1992     SCS.Second = ICK_Complex_Real;
1993     FromType = ToType.getUnqualifiedType();
1994   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1995     // FIXME: disable conversions between long double, __ibm128 and __float128
1996     // if their representation is different until there is back end support
1997     // We of course allow this conversion if long double is really double.
1998 
1999     // Conversions between bfloat16 and float16 are currently not supported.
2000     if ((FromType->isBFloat16Type() &&
2001          (ToType->isFloat16Type() || ToType->isHalfType())) ||
2002         (ToType->isBFloat16Type() &&
2003          (FromType->isFloat16Type() || FromType->isHalfType())))
2004       return false;
2005 
2006     // Conversions between IEEE-quad and IBM-extended semantics are not
2007     // permitted.
2008     const llvm::fltSemantics &FromSem =
2009         S.Context.getFloatTypeSemantics(FromType);
2010     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2011     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2012          &ToSem == &llvm::APFloat::IEEEquad()) ||
2013         (&FromSem == &llvm::APFloat::IEEEquad() &&
2014          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2015       return false;
2016 
2017     // Floating point conversions (C++ 4.8).
2018     SCS.Second = ICK_Floating_Conversion;
2019     FromType = ToType.getUnqualifiedType();
2020   } else if ((FromType->isRealFloatingType() &&
2021               ToType->isIntegralType(S.Context)) ||
2022              (FromType->isIntegralOrUnscopedEnumerationType() &&
2023               ToType->isRealFloatingType())) {
2024 
2025     // Floating-integral conversions (C++ 4.9).
2026     SCS.Second = ICK_Floating_Integral;
2027     FromType = ToType.getUnqualifiedType();
2028   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2029     SCS.Second = ICK_Block_Pointer_Conversion;
2030   } else if (AllowObjCWritebackConversion &&
2031              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2032     SCS.Second = ICK_Writeback_Conversion;
2033   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2034                                    FromType, IncompatibleObjC)) {
2035     // Pointer conversions (C++ 4.10).
2036     SCS.Second = ICK_Pointer_Conversion;
2037     SCS.IncompatibleObjC = IncompatibleObjC;
2038     FromType = FromType.getUnqualifiedType();
2039   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2040                                          InOverloadResolution, FromType)) {
2041     // Pointer to member conversions (4.11).
2042     SCS.Second = ICK_Pointer_Member;
2043   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2044                                 InOverloadResolution, CStyle)) {
2045     SCS.Second = SecondICK;
2046     FromType = ToType.getUnqualifiedType();
2047   } else if (!S.getLangOpts().CPlusPlus &&
2048              S.Context.typesAreCompatible(ToType, FromType)) {
2049     // Compatible conversions (Clang extension for C function overloading)
2050     SCS.Second = ICK_Compatible_Conversion;
2051     FromType = ToType.getUnqualifiedType();
2052   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2053                                              InOverloadResolution,
2054                                              SCS, CStyle)) {
2055     SCS.Second = ICK_TransparentUnionConversion;
2056     FromType = ToType;
2057   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2058                                  CStyle)) {
2059     // tryAtomicConversion has updated the standard conversion sequence
2060     // appropriately.
2061     return true;
2062   } else if (ToType->isEventT() &&
2063              From->isIntegerConstantExpr(S.getASTContext()) &&
2064              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2065     SCS.Second = ICK_Zero_Event_Conversion;
2066     FromType = ToType;
2067   } else if (ToType->isQueueT() &&
2068              From->isIntegerConstantExpr(S.getASTContext()) &&
2069              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2070     SCS.Second = ICK_Zero_Queue_Conversion;
2071     FromType = ToType;
2072   } else if (ToType->isSamplerT() &&
2073              From->isIntegerConstantExpr(S.getASTContext())) {
2074     SCS.Second = ICK_Compatible_Conversion;
2075     FromType = ToType;
2076   } else {
2077     // No second conversion required.
2078     SCS.Second = ICK_Identity;
2079   }
2080   SCS.setToType(1, FromType);
2081 
2082   // The third conversion can be a function pointer conversion or a
2083   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2084   bool ObjCLifetimeConversion;
2085   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2086     // Function pointer conversions (removing 'noexcept') including removal of
2087     // 'noreturn' (Clang extension).
2088     SCS.Third = ICK_Function_Conversion;
2089   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2090                                          ObjCLifetimeConversion)) {
2091     SCS.Third = ICK_Qualification;
2092     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2093     FromType = ToType;
2094   } else {
2095     // No conversion required
2096     SCS.Third = ICK_Identity;
2097   }
2098 
2099   // C++ [over.best.ics]p6:
2100   //   [...] Any difference in top-level cv-qualification is
2101   //   subsumed by the initialization itself and does not constitute
2102   //   a conversion. [...]
2103   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2104   QualType CanonTo = S.Context.getCanonicalType(ToType);
2105   if (CanonFrom.getLocalUnqualifiedType()
2106                                      == CanonTo.getLocalUnqualifiedType() &&
2107       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2108     FromType = ToType;
2109     CanonFrom = CanonTo;
2110   }
2111 
2112   SCS.setToType(2, FromType);
2113 
2114   if (CanonFrom == CanonTo)
2115     return true;
2116 
2117   // If we have not converted the argument type to the parameter type,
2118   // this is a bad conversion sequence, unless we're resolving an overload in C.
2119   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2120     return false;
2121 
2122   ExprResult ER = ExprResult{From};
2123   Sema::AssignConvertType Conv =
2124       S.CheckSingleAssignmentConstraints(ToType, ER,
2125                                          /*Diagnose=*/false,
2126                                          /*DiagnoseCFAudited=*/false,
2127                                          /*ConvertRHS=*/false);
2128   ImplicitConversionKind SecondConv;
2129   switch (Conv) {
2130   case Sema::Compatible:
2131     SecondConv = ICK_C_Only_Conversion;
2132     break;
2133   // For our purposes, discarding qualifiers is just as bad as using an
2134   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2135   // qualifiers, as well.
2136   case Sema::CompatiblePointerDiscardsQualifiers:
2137   case Sema::IncompatiblePointer:
2138   case Sema::IncompatiblePointerSign:
2139     SecondConv = ICK_Incompatible_Pointer_Conversion;
2140     break;
2141   default:
2142     return false;
2143   }
2144 
2145   // First can only be an lvalue conversion, so we pretend that this was the
2146   // second conversion. First should already be valid from earlier in the
2147   // function.
2148   SCS.Second = SecondConv;
2149   SCS.setToType(1, ToType);
2150 
2151   // Third is Identity, because Second should rank us worse than any other
2152   // conversion. This could also be ICK_Qualification, but it's simpler to just
2153   // lump everything in with the second conversion, and we don't gain anything
2154   // from making this ICK_Qualification.
2155   SCS.Third = ICK_Identity;
2156   SCS.setToType(2, ToType);
2157   return true;
2158 }
2159 
2160 static bool
2161 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2162                                      QualType &ToType,
2163                                      bool InOverloadResolution,
2164                                      StandardConversionSequence &SCS,
2165                                      bool CStyle) {
2166 
2167   const RecordType *UT = ToType->getAsUnionType();
2168   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2169     return false;
2170   // The field to initialize within the transparent union.
2171   RecordDecl *UD = UT->getDecl();
2172   // It's compatible if the expression matches any of the fields.
2173   for (const auto *it : UD->fields()) {
2174     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2175                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2176       ToType = it->getType();
2177       return true;
2178     }
2179   }
2180   return false;
2181 }
2182 
2183 /// IsIntegralPromotion - Determines whether the conversion from the
2184 /// expression From (whose potentially-adjusted type is FromType) to
2185 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2186 /// sets PromotedType to the promoted type.
2187 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2188   const BuiltinType *To = ToType->getAs<BuiltinType>();
2189   // All integers are built-in.
2190   if (!To) {
2191     return false;
2192   }
2193 
2194   // An rvalue of type char, signed char, unsigned char, short int, or
2195   // unsigned short int can be converted to an rvalue of type int if
2196   // int can represent all the values of the source type; otherwise,
2197   // the source rvalue can be converted to an rvalue of type unsigned
2198   // int (C++ 4.5p1).
2199   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2200       !FromType->isEnumeralType()) {
2201     if ( // We can promote any signed, promotable integer type to an int
2202         (FromType->isSignedIntegerType() ||
2203          // We can promote any unsigned integer type whose size is
2204          // less than int to an int.
2205          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2206       return To->getKind() == BuiltinType::Int;
2207     }
2208 
2209     return To->getKind() == BuiltinType::UInt;
2210   }
2211 
2212   // C++11 [conv.prom]p3:
2213   //   A prvalue of an unscoped enumeration type whose underlying type is not
2214   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2215   //   following types that can represent all the values of the enumeration
2216   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2217   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2218   //   long long int. If none of the types in that list can represent all the
2219   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2220   //   type can be converted to an rvalue a prvalue of the extended integer type
2221   //   with lowest integer conversion rank (4.13) greater than the rank of long
2222   //   long in which all the values of the enumeration can be represented. If
2223   //   there are two such extended types, the signed one is chosen.
2224   // C++11 [conv.prom]p4:
2225   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2226   //   can be converted to a prvalue of its underlying type. Moreover, if
2227   //   integral promotion can be applied to its underlying type, a prvalue of an
2228   //   unscoped enumeration type whose underlying type is fixed can also be
2229   //   converted to a prvalue of the promoted underlying type.
2230   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2231     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2232     // provided for a scoped enumeration.
2233     if (FromEnumType->getDecl()->isScoped())
2234       return false;
2235 
2236     // We can perform an integral promotion to the underlying type of the enum,
2237     // even if that's not the promoted type. Note that the check for promoting
2238     // the underlying type is based on the type alone, and does not consider
2239     // the bitfield-ness of the actual source expression.
2240     if (FromEnumType->getDecl()->isFixed()) {
2241       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2242       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2243              IsIntegralPromotion(nullptr, Underlying, ToType);
2244     }
2245 
2246     // We have already pre-calculated the promotion type, so this is trivial.
2247     if (ToType->isIntegerType() &&
2248         isCompleteType(From->getBeginLoc(), FromType))
2249       return Context.hasSameUnqualifiedType(
2250           ToType, FromEnumType->getDecl()->getPromotionType());
2251 
2252     // C++ [conv.prom]p5:
2253     //   If the bit-field has an enumerated type, it is treated as any other
2254     //   value of that type for promotion purposes.
2255     //
2256     // ... so do not fall through into the bit-field checks below in C++.
2257     if (getLangOpts().CPlusPlus)
2258       return false;
2259   }
2260 
2261   // C++0x [conv.prom]p2:
2262   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2263   //   to an rvalue a prvalue of the first of the following types that can
2264   //   represent all the values of its underlying type: int, unsigned int,
2265   //   long int, unsigned long int, long long int, or unsigned long long int.
2266   //   If none of the types in that list can represent all the values of its
2267   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2268   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2269   //   type.
2270   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2271       ToType->isIntegerType()) {
2272     // Determine whether the type we're converting from is signed or
2273     // unsigned.
2274     bool FromIsSigned = FromType->isSignedIntegerType();
2275     uint64_t FromSize = Context.getTypeSize(FromType);
2276 
2277     // The types we'll try to promote to, in the appropriate
2278     // order. Try each of these types.
2279     QualType PromoteTypes[6] = {
2280       Context.IntTy, Context.UnsignedIntTy,
2281       Context.LongTy, Context.UnsignedLongTy ,
2282       Context.LongLongTy, Context.UnsignedLongLongTy
2283     };
2284     for (int Idx = 0; Idx < 6; ++Idx) {
2285       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2286       if (FromSize < ToSize ||
2287           (FromSize == ToSize &&
2288            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2289         // We found the type that we can promote to. If this is the
2290         // type we wanted, we have a promotion. Otherwise, no
2291         // promotion.
2292         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2293       }
2294     }
2295   }
2296 
2297   // An rvalue for an integral bit-field (9.6) can be converted to an
2298   // rvalue of type int if int can represent all the values of the
2299   // bit-field; otherwise, it can be converted to unsigned int if
2300   // unsigned int can represent all the values of the bit-field. If
2301   // the bit-field is larger yet, no integral promotion applies to
2302   // it. If the bit-field has an enumerated type, it is treated as any
2303   // other value of that type for promotion purposes (C++ 4.5p3).
2304   // FIXME: We should delay checking of bit-fields until we actually perform the
2305   // conversion.
2306   //
2307   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2308   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2309   // bit-fields and those whose underlying type is larger than int) for GCC
2310   // compatibility.
2311   if (From) {
2312     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2313       std::optional<llvm::APSInt> BitWidth;
2314       if (FromType->isIntegralType(Context) &&
2315           (BitWidth =
2316                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2317         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2318         ToSize = Context.getTypeSize(ToType);
2319 
2320         // Are we promoting to an int from a bitfield that fits in an int?
2321         if (*BitWidth < ToSize ||
2322             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2323           return To->getKind() == BuiltinType::Int;
2324         }
2325 
2326         // Are we promoting to an unsigned int from an unsigned bitfield
2327         // that fits into an unsigned int?
2328         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2329           return To->getKind() == BuiltinType::UInt;
2330         }
2331 
2332         return false;
2333       }
2334     }
2335   }
2336 
2337   // An rvalue of type bool can be converted to an rvalue of type int,
2338   // with false becoming zero and true becoming one (C++ 4.5p4).
2339   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2340     return true;
2341   }
2342 
2343   return false;
2344 }
2345 
2346 /// IsFloatingPointPromotion - Determines whether the conversion from
2347 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2348 /// returns true and sets PromotedType to the promoted type.
2349 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2350   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2351     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2352       /// An rvalue of type float can be converted to an rvalue of type
2353       /// double. (C++ 4.6p1).
2354       if (FromBuiltin->getKind() == BuiltinType::Float &&
2355           ToBuiltin->getKind() == BuiltinType::Double)
2356         return true;
2357 
2358       // C99 6.3.1.5p1:
2359       //   When a float is promoted to double or long double, or a
2360       //   double is promoted to long double [...].
2361       if (!getLangOpts().CPlusPlus &&
2362           (FromBuiltin->getKind() == BuiltinType::Float ||
2363            FromBuiltin->getKind() == BuiltinType::Double) &&
2364           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2365            ToBuiltin->getKind() == BuiltinType::Float128 ||
2366            ToBuiltin->getKind() == BuiltinType::Ibm128))
2367         return true;
2368 
2369       // Half can be promoted to float.
2370       if (!getLangOpts().NativeHalfType &&
2371            FromBuiltin->getKind() == BuiltinType::Half &&
2372           ToBuiltin->getKind() == BuiltinType::Float)
2373         return true;
2374     }
2375 
2376   return false;
2377 }
2378 
2379 /// Determine if a conversion is a complex promotion.
2380 ///
2381 /// A complex promotion is defined as a complex -> complex conversion
2382 /// where the conversion between the underlying real types is a
2383 /// floating-point or integral promotion.
2384 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2385   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2386   if (!FromComplex)
2387     return false;
2388 
2389   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2390   if (!ToComplex)
2391     return false;
2392 
2393   return IsFloatingPointPromotion(FromComplex->getElementType(),
2394                                   ToComplex->getElementType()) ||
2395     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2396                         ToComplex->getElementType());
2397 }
2398 
2399 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2400 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2401 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2402 /// if non-empty, will be a pointer to ToType that may or may not have
2403 /// the right set of qualifiers on its pointee.
2404 ///
2405 static QualType
2406 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2407                                    QualType ToPointee, QualType ToType,
2408                                    ASTContext &Context,
2409                                    bool StripObjCLifetime = false) {
2410   assert((FromPtr->getTypeClass() == Type::Pointer ||
2411           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2412          "Invalid similarly-qualified pointer type");
2413 
2414   /// Conversions to 'id' subsume cv-qualifier conversions.
2415   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2416     return ToType.getUnqualifiedType();
2417 
2418   QualType CanonFromPointee
2419     = Context.getCanonicalType(FromPtr->getPointeeType());
2420   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2421   Qualifiers Quals = CanonFromPointee.getQualifiers();
2422 
2423   if (StripObjCLifetime)
2424     Quals.removeObjCLifetime();
2425 
2426   // Exact qualifier match -> return the pointer type we're converting to.
2427   if (CanonToPointee.getLocalQualifiers() == Quals) {
2428     // ToType is exactly what we need. Return it.
2429     if (!ToType.isNull())
2430       return ToType.getUnqualifiedType();
2431 
2432     // Build a pointer to ToPointee. It has the right qualifiers
2433     // already.
2434     if (isa<ObjCObjectPointerType>(ToType))
2435       return Context.getObjCObjectPointerType(ToPointee);
2436     return Context.getPointerType(ToPointee);
2437   }
2438 
2439   // Just build a canonical type that has the right qualifiers.
2440   QualType QualifiedCanonToPointee
2441     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2442 
2443   if (isa<ObjCObjectPointerType>(ToType))
2444     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2445   return Context.getPointerType(QualifiedCanonToPointee);
2446 }
2447 
2448 static bool isNullPointerConstantForConversion(Expr *Expr,
2449                                                bool InOverloadResolution,
2450                                                ASTContext &Context) {
2451   // Handle value-dependent integral null pointer constants correctly.
2452   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2453   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2454       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2455     return !InOverloadResolution;
2456 
2457   return Expr->isNullPointerConstant(Context,
2458                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2459                                         : Expr::NPC_ValueDependentIsNull);
2460 }
2461 
2462 /// IsPointerConversion - Determines whether the conversion of the
2463 /// expression From, which has the (possibly adjusted) type FromType,
2464 /// can be converted to the type ToType via a pointer conversion (C++
2465 /// 4.10). If so, returns true and places the converted type (that
2466 /// might differ from ToType in its cv-qualifiers at some level) into
2467 /// ConvertedType.
2468 ///
2469 /// This routine also supports conversions to and from block pointers
2470 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2471 /// pointers to interfaces. FIXME: Once we've determined the
2472 /// appropriate overloading rules for Objective-C, we may want to
2473 /// split the Objective-C checks into a different routine; however,
2474 /// GCC seems to consider all of these conversions to be pointer
2475 /// conversions, so for now they live here. IncompatibleObjC will be
2476 /// set if the conversion is an allowed Objective-C conversion that
2477 /// should result in a warning.
2478 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2479                                bool InOverloadResolution,
2480                                QualType& ConvertedType,
2481                                bool &IncompatibleObjC) {
2482   IncompatibleObjC = false;
2483   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2484                               IncompatibleObjC))
2485     return true;
2486 
2487   // Conversion from a null pointer constant to any Objective-C pointer type.
2488   if (ToType->isObjCObjectPointerType() &&
2489       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2490     ConvertedType = ToType;
2491     return true;
2492   }
2493 
2494   // Blocks: Block pointers can be converted to void*.
2495   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2496       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2497     ConvertedType = ToType;
2498     return true;
2499   }
2500   // Blocks: A null pointer constant can be converted to a block
2501   // pointer type.
2502   if (ToType->isBlockPointerType() &&
2503       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2504     ConvertedType = ToType;
2505     return true;
2506   }
2507 
2508   // If the left-hand-side is nullptr_t, the right side can be a null
2509   // pointer constant.
2510   if (ToType->isNullPtrType() &&
2511       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2512     ConvertedType = ToType;
2513     return true;
2514   }
2515 
2516   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2517   if (!ToTypePtr)
2518     return false;
2519 
2520   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2521   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2522     ConvertedType = ToType;
2523     return true;
2524   }
2525 
2526   // Beyond this point, both types need to be pointers
2527   // , including objective-c pointers.
2528   QualType ToPointeeType = ToTypePtr->getPointeeType();
2529   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2530       !getLangOpts().ObjCAutoRefCount) {
2531     ConvertedType = BuildSimilarlyQualifiedPointerType(
2532         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2533         Context);
2534     return true;
2535   }
2536   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2537   if (!FromTypePtr)
2538     return false;
2539 
2540   QualType FromPointeeType = FromTypePtr->getPointeeType();
2541 
2542   // If the unqualified pointee types are the same, this can't be a
2543   // pointer conversion, so don't do all of the work below.
2544   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2545     return false;
2546 
2547   // An rvalue of type "pointer to cv T," where T is an object type,
2548   // can be converted to an rvalue of type "pointer to cv void" (C++
2549   // 4.10p2).
2550   if (FromPointeeType->isIncompleteOrObjectType() &&
2551       ToPointeeType->isVoidType()) {
2552     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2553                                                        ToPointeeType,
2554                                                        ToType, Context,
2555                                                    /*StripObjCLifetime=*/true);
2556     return true;
2557   }
2558 
2559   // MSVC allows implicit function to void* type conversion.
2560   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2561       ToPointeeType->isVoidType()) {
2562     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2563                                                        ToPointeeType,
2564                                                        ToType, Context);
2565     return true;
2566   }
2567 
2568   // When we're overloading in C, we allow a special kind of pointer
2569   // conversion for compatible-but-not-identical pointee types.
2570   if (!getLangOpts().CPlusPlus &&
2571       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2572     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2573                                                        ToPointeeType,
2574                                                        ToType, Context);
2575     return true;
2576   }
2577 
2578   // C++ [conv.ptr]p3:
2579   //
2580   //   An rvalue of type "pointer to cv D," where D is a class type,
2581   //   can be converted to an rvalue of type "pointer to cv B," where
2582   //   B is a base class (clause 10) of D. If B is an inaccessible
2583   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2584   //   necessitates this conversion is ill-formed. The result of the
2585   //   conversion is a pointer to the base class sub-object of the
2586   //   derived class object. The null pointer value is converted to
2587   //   the null pointer value of the destination type.
2588   //
2589   // Note that we do not check for ambiguity or inaccessibility
2590   // here. That is handled by CheckPointerConversion.
2591   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2592       ToPointeeType->isRecordType() &&
2593       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2594       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2595     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2596                                                        ToPointeeType,
2597                                                        ToType, Context);
2598     return true;
2599   }
2600 
2601   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2602       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2603     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2604                                                        ToPointeeType,
2605                                                        ToType, Context);
2606     return true;
2607   }
2608 
2609   return false;
2610 }
2611 
2612 /// Adopt the given qualifiers for the given type.
2613 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2614   Qualifiers TQs = T.getQualifiers();
2615 
2616   // Check whether qualifiers already match.
2617   if (TQs == Qs)
2618     return T;
2619 
2620   if (Qs.compatiblyIncludes(TQs))
2621     return Context.getQualifiedType(T, Qs);
2622 
2623   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2624 }
2625 
2626 /// isObjCPointerConversion - Determines whether this is an
2627 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2628 /// with the same arguments and return values.
2629 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2630                                    QualType& ConvertedType,
2631                                    bool &IncompatibleObjC) {
2632   if (!getLangOpts().ObjC)
2633     return false;
2634 
2635   // The set of qualifiers on the type we're converting from.
2636   Qualifiers FromQualifiers = FromType.getQualifiers();
2637 
2638   // First, we handle all conversions on ObjC object pointer types.
2639   const ObjCObjectPointerType* ToObjCPtr =
2640     ToType->getAs<ObjCObjectPointerType>();
2641   const ObjCObjectPointerType *FromObjCPtr =
2642     FromType->getAs<ObjCObjectPointerType>();
2643 
2644   if (ToObjCPtr && FromObjCPtr) {
2645     // If the pointee types are the same (ignoring qualifications),
2646     // then this is not a pointer conversion.
2647     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2648                                        FromObjCPtr->getPointeeType()))
2649       return false;
2650 
2651     // Conversion between Objective-C pointers.
2652     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2653       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2654       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2655       if (getLangOpts().CPlusPlus && LHS && RHS &&
2656           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2657                                                 FromObjCPtr->getPointeeType()))
2658         return false;
2659       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2660                                                    ToObjCPtr->getPointeeType(),
2661                                                          ToType, Context);
2662       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2663       return true;
2664     }
2665 
2666     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2667       // Okay: this is some kind of implicit downcast of Objective-C
2668       // interfaces, which is permitted. However, we're going to
2669       // complain about it.
2670       IncompatibleObjC = true;
2671       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2672                                                    ToObjCPtr->getPointeeType(),
2673                                                          ToType, Context);
2674       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2675       return true;
2676     }
2677   }
2678   // Beyond this point, both types need to be C pointers or block pointers.
2679   QualType ToPointeeType;
2680   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2681     ToPointeeType = ToCPtr->getPointeeType();
2682   else if (const BlockPointerType *ToBlockPtr =
2683             ToType->getAs<BlockPointerType>()) {
2684     // Objective C++: We're able to convert from a pointer to any object
2685     // to a block pointer type.
2686     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2687       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2688       return true;
2689     }
2690     ToPointeeType = ToBlockPtr->getPointeeType();
2691   }
2692   else if (FromType->getAs<BlockPointerType>() &&
2693            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2694     // Objective C++: We're able to convert from a block pointer type to a
2695     // pointer to any object.
2696     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2697     return true;
2698   }
2699   else
2700     return false;
2701 
2702   QualType FromPointeeType;
2703   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2704     FromPointeeType = FromCPtr->getPointeeType();
2705   else if (const BlockPointerType *FromBlockPtr =
2706            FromType->getAs<BlockPointerType>())
2707     FromPointeeType = FromBlockPtr->getPointeeType();
2708   else
2709     return false;
2710 
2711   // If we have pointers to pointers, recursively check whether this
2712   // is an Objective-C conversion.
2713   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2714       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2715                               IncompatibleObjC)) {
2716     // We always complain about this conversion.
2717     IncompatibleObjC = true;
2718     ConvertedType = Context.getPointerType(ConvertedType);
2719     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2720     return true;
2721   }
2722   // Allow conversion of pointee being objective-c pointer to another one;
2723   // as in I* to id.
2724   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2725       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2726       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2727                               IncompatibleObjC)) {
2728 
2729     ConvertedType = Context.getPointerType(ConvertedType);
2730     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2731     return true;
2732   }
2733 
2734   // If we have pointers to functions or blocks, check whether the only
2735   // differences in the argument and result types are in Objective-C
2736   // pointer conversions. If so, we permit the conversion (but
2737   // complain about it).
2738   const FunctionProtoType *FromFunctionType
2739     = FromPointeeType->getAs<FunctionProtoType>();
2740   const FunctionProtoType *ToFunctionType
2741     = ToPointeeType->getAs<FunctionProtoType>();
2742   if (FromFunctionType && ToFunctionType) {
2743     // If the function types are exactly the same, this isn't an
2744     // Objective-C pointer conversion.
2745     if (Context.getCanonicalType(FromPointeeType)
2746           == Context.getCanonicalType(ToPointeeType))
2747       return false;
2748 
2749     // Perform the quick checks that will tell us whether these
2750     // function types are obviously different.
2751     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2752         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2753         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2754       return false;
2755 
2756     bool HasObjCConversion = false;
2757     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2758         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2759       // Okay, the types match exactly. Nothing to do.
2760     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2761                                        ToFunctionType->getReturnType(),
2762                                        ConvertedType, IncompatibleObjC)) {
2763       // Okay, we have an Objective-C pointer conversion.
2764       HasObjCConversion = true;
2765     } else {
2766       // Function types are too different. Abort.
2767       return false;
2768     }
2769 
2770     // Check argument types.
2771     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2772          ArgIdx != NumArgs; ++ArgIdx) {
2773       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2774       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2775       if (Context.getCanonicalType(FromArgType)
2776             == Context.getCanonicalType(ToArgType)) {
2777         // Okay, the types match exactly. Nothing to do.
2778       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2779                                          ConvertedType, IncompatibleObjC)) {
2780         // Okay, we have an Objective-C pointer conversion.
2781         HasObjCConversion = true;
2782       } else {
2783         // Argument types are too different. Abort.
2784         return false;
2785       }
2786     }
2787 
2788     if (HasObjCConversion) {
2789       // We had an Objective-C conversion. Allow this pointer
2790       // conversion, but complain about it.
2791       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2792       IncompatibleObjC = true;
2793       return true;
2794     }
2795   }
2796 
2797   return false;
2798 }
2799 
2800 /// Determine whether this is an Objective-C writeback conversion,
2801 /// used for parameter passing when performing automatic reference counting.
2802 ///
2803 /// \param FromType The type we're converting form.
2804 ///
2805 /// \param ToType The type we're converting to.
2806 ///
2807 /// \param ConvertedType The type that will be produced after applying
2808 /// this conversion.
2809 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2810                                      QualType &ConvertedType) {
2811   if (!getLangOpts().ObjCAutoRefCount ||
2812       Context.hasSameUnqualifiedType(FromType, ToType))
2813     return false;
2814 
2815   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2816   QualType ToPointee;
2817   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2818     ToPointee = ToPointer->getPointeeType();
2819   else
2820     return false;
2821 
2822   Qualifiers ToQuals = ToPointee.getQualifiers();
2823   if (!ToPointee->isObjCLifetimeType() ||
2824       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2825       !ToQuals.withoutObjCLifetime().empty())
2826     return false;
2827 
2828   // Argument must be a pointer to __strong to __weak.
2829   QualType FromPointee;
2830   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2831     FromPointee = FromPointer->getPointeeType();
2832   else
2833     return false;
2834 
2835   Qualifiers FromQuals = FromPointee.getQualifiers();
2836   if (!FromPointee->isObjCLifetimeType() ||
2837       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2838        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2839     return false;
2840 
2841   // Make sure that we have compatible qualifiers.
2842   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2843   if (!ToQuals.compatiblyIncludes(FromQuals))
2844     return false;
2845 
2846   // Remove qualifiers from the pointee type we're converting from; they
2847   // aren't used in the compatibility check belong, and we'll be adding back
2848   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2849   FromPointee = FromPointee.getUnqualifiedType();
2850 
2851   // The unqualified form of the pointee types must be compatible.
2852   ToPointee = ToPointee.getUnqualifiedType();
2853   bool IncompatibleObjC;
2854   if (Context.typesAreCompatible(FromPointee, ToPointee))
2855     FromPointee = ToPointee;
2856   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2857                                     IncompatibleObjC))
2858     return false;
2859 
2860   /// Construct the type we're converting to, which is a pointer to
2861   /// __autoreleasing pointee.
2862   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2863   ConvertedType = Context.getPointerType(FromPointee);
2864   return true;
2865 }
2866 
2867 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2868                                     QualType& ConvertedType) {
2869   QualType ToPointeeType;
2870   if (const BlockPointerType *ToBlockPtr =
2871         ToType->getAs<BlockPointerType>())
2872     ToPointeeType = ToBlockPtr->getPointeeType();
2873   else
2874     return false;
2875 
2876   QualType FromPointeeType;
2877   if (const BlockPointerType *FromBlockPtr =
2878       FromType->getAs<BlockPointerType>())
2879     FromPointeeType = FromBlockPtr->getPointeeType();
2880   else
2881     return false;
2882   // We have pointer to blocks, check whether the only
2883   // differences in the argument and result types are in Objective-C
2884   // pointer conversions. If so, we permit the conversion.
2885 
2886   const FunctionProtoType *FromFunctionType
2887     = FromPointeeType->getAs<FunctionProtoType>();
2888   const FunctionProtoType *ToFunctionType
2889     = ToPointeeType->getAs<FunctionProtoType>();
2890 
2891   if (!FromFunctionType || !ToFunctionType)
2892     return false;
2893 
2894   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2895     return true;
2896 
2897   // Perform the quick checks that will tell us whether these
2898   // function types are obviously different.
2899   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2900       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2901     return false;
2902 
2903   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2904   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2905   if (FromEInfo != ToEInfo)
2906     return false;
2907 
2908   bool IncompatibleObjC = false;
2909   if (Context.hasSameType(FromFunctionType->getReturnType(),
2910                           ToFunctionType->getReturnType())) {
2911     // Okay, the types match exactly. Nothing to do.
2912   } else {
2913     QualType RHS = FromFunctionType->getReturnType();
2914     QualType LHS = ToFunctionType->getReturnType();
2915     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2916         !RHS.hasQualifiers() && LHS.hasQualifiers())
2917        LHS = LHS.getUnqualifiedType();
2918 
2919      if (Context.hasSameType(RHS,LHS)) {
2920        // OK exact match.
2921      } else if (isObjCPointerConversion(RHS, LHS,
2922                                         ConvertedType, IncompatibleObjC)) {
2923      if (IncompatibleObjC)
2924        return false;
2925      // Okay, we have an Objective-C pointer conversion.
2926      }
2927      else
2928        return false;
2929    }
2930 
2931    // Check argument types.
2932    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2933         ArgIdx != NumArgs; ++ArgIdx) {
2934      IncompatibleObjC = false;
2935      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2936      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2937      if (Context.hasSameType(FromArgType, ToArgType)) {
2938        // Okay, the types match exactly. Nothing to do.
2939      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2940                                         ConvertedType, IncompatibleObjC)) {
2941        if (IncompatibleObjC)
2942          return false;
2943        // Okay, we have an Objective-C pointer conversion.
2944      } else
2945        // Argument types are too different. Abort.
2946        return false;
2947    }
2948 
2949    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2950    bool CanUseToFPT, CanUseFromFPT;
2951    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2952                                       CanUseToFPT, CanUseFromFPT,
2953                                       NewParamInfos))
2954      return false;
2955 
2956    ConvertedType = ToType;
2957    return true;
2958 }
2959 
2960 enum {
2961   ft_default,
2962   ft_different_class,
2963   ft_parameter_arity,
2964   ft_parameter_mismatch,
2965   ft_return_type,
2966   ft_qualifer_mismatch,
2967   ft_noexcept
2968 };
2969 
2970 /// Attempts to get the FunctionProtoType from a Type. Handles
2971 /// MemberFunctionPointers properly.
2972 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2973   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2974     return FPT;
2975 
2976   if (auto *MPT = FromType->getAs<MemberPointerType>())
2977     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2978 
2979   return nullptr;
2980 }
2981 
2982 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2983 /// function types.  Catches different number of parameter, mismatch in
2984 /// parameter types, and different return types.
2985 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2986                                       QualType FromType, QualType ToType) {
2987   // If either type is not valid, include no extra info.
2988   if (FromType.isNull() || ToType.isNull()) {
2989     PDiag << ft_default;
2990     return;
2991   }
2992 
2993   // Get the function type from the pointers.
2994   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2995     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2996                *ToMember = ToType->castAs<MemberPointerType>();
2997     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2998       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2999             << QualType(FromMember->getClass(), 0);
3000       return;
3001     }
3002     FromType = FromMember->getPointeeType();
3003     ToType = ToMember->getPointeeType();
3004   }
3005 
3006   if (FromType->isPointerType())
3007     FromType = FromType->getPointeeType();
3008   if (ToType->isPointerType())
3009     ToType = ToType->getPointeeType();
3010 
3011   // Remove references.
3012   FromType = FromType.getNonReferenceType();
3013   ToType = ToType.getNonReferenceType();
3014 
3015   // Don't print extra info for non-specialized template functions.
3016   if (FromType->isInstantiationDependentType() &&
3017       !FromType->getAs<TemplateSpecializationType>()) {
3018     PDiag << ft_default;
3019     return;
3020   }
3021 
3022   // No extra info for same types.
3023   if (Context.hasSameType(FromType, ToType)) {
3024     PDiag << ft_default;
3025     return;
3026   }
3027 
3028   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3029                           *ToFunction = tryGetFunctionProtoType(ToType);
3030 
3031   // Both types need to be function types.
3032   if (!FromFunction || !ToFunction) {
3033     PDiag << ft_default;
3034     return;
3035   }
3036 
3037   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3038     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3039           << FromFunction->getNumParams();
3040     return;
3041   }
3042 
3043   // Handle different parameter types.
3044   unsigned ArgPos;
3045   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3046     PDiag << ft_parameter_mismatch << ArgPos + 1
3047           << ToFunction->getParamType(ArgPos)
3048           << FromFunction->getParamType(ArgPos);
3049     return;
3050   }
3051 
3052   // Handle different return type.
3053   if (!Context.hasSameType(FromFunction->getReturnType(),
3054                            ToFunction->getReturnType())) {
3055     PDiag << ft_return_type << ToFunction->getReturnType()
3056           << FromFunction->getReturnType();
3057     return;
3058   }
3059 
3060   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3061     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3062           << FromFunction->getMethodQuals();
3063     return;
3064   }
3065 
3066   // Handle exception specification differences on canonical type (in C++17
3067   // onwards).
3068   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3069           ->isNothrow() !=
3070       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3071           ->isNothrow()) {
3072     PDiag << ft_noexcept;
3073     return;
3074   }
3075 
3076   // Unable to find a difference, so add no extra info.
3077   PDiag << ft_default;
3078 }
3079 
3080 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3081 /// for equality of their parameter types. Caller has already checked that
3082 /// they have same number of parameters.  If the parameters are different,
3083 /// ArgPos will have the parameter index of the first different parameter.
3084 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3085 /// reverse order. That's useful if one of the functions is being used as a C++20
3086 /// synthesized operator overload with a reversed parameter order.
3087 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3088                                       const FunctionProtoType *NewType,
3089                                       unsigned *ArgPos, bool Reversed) {
3090   assert(OldType->getNumParams() == NewType->getNumParams() &&
3091          "Can't compare parameters of functions with different number of "
3092          "parameters!");
3093   for (size_t I = 0; I < OldType->getNumParams(); I++) {
3094     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3095     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
3096 
3097     // Ignore address spaces in pointee type. This is to disallow overloading
3098     // on __ptr32/__ptr64 address spaces.
3099     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
3100     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
3101 
3102     if (!Context.hasSameType(Old, New)) {
3103       if (ArgPos)
3104         *ArgPos = I;
3105       return false;
3106     }
3107   }
3108   return true;
3109 }
3110 
3111 /// CheckPointerConversion - Check the pointer conversion from the
3112 /// expression From to the type ToType. This routine checks for
3113 /// ambiguous or inaccessible derived-to-base pointer
3114 /// conversions for which IsPointerConversion has already returned
3115 /// true. It returns true and produces a diagnostic if there was an
3116 /// error, or returns false otherwise.
3117 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3118                                   CastKind &Kind,
3119                                   CXXCastPath& BasePath,
3120                                   bool IgnoreBaseAccess,
3121                                   bool Diagnose) {
3122   QualType FromType = From->getType();
3123   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3124 
3125   Kind = CK_BitCast;
3126 
3127   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3128       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3129           Expr::NPCK_ZeroExpression) {
3130     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3131       DiagRuntimeBehavior(From->getExprLoc(), From,
3132                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3133                             << ToType << From->getSourceRange());
3134     else if (!isUnevaluatedContext())
3135       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3136         << ToType << From->getSourceRange();
3137   }
3138   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3139     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3140       QualType FromPointeeType = FromPtrType->getPointeeType(),
3141                ToPointeeType   = ToPtrType->getPointeeType();
3142 
3143       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3144           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3145         // We must have a derived-to-base conversion. Check an
3146         // ambiguous or inaccessible conversion.
3147         unsigned InaccessibleID = 0;
3148         unsigned AmbiguousID = 0;
3149         if (Diagnose) {
3150           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3151           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3152         }
3153         if (CheckDerivedToBaseConversion(
3154                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3155                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3156                 &BasePath, IgnoreBaseAccess))
3157           return true;
3158 
3159         // The conversion was successful.
3160         Kind = CK_DerivedToBase;
3161       }
3162 
3163       if (Diagnose && !IsCStyleOrFunctionalCast &&
3164           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3165         assert(getLangOpts().MSVCCompat &&
3166                "this should only be possible with MSVCCompat!");
3167         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3168             << From->getSourceRange();
3169       }
3170     }
3171   } else if (const ObjCObjectPointerType *ToPtrType =
3172                ToType->getAs<ObjCObjectPointerType>()) {
3173     if (const ObjCObjectPointerType *FromPtrType =
3174           FromType->getAs<ObjCObjectPointerType>()) {
3175       // Objective-C++ conversions are always okay.
3176       // FIXME: We should have a different class of conversions for the
3177       // Objective-C++ implicit conversions.
3178       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3179         return false;
3180     } else if (FromType->isBlockPointerType()) {
3181       Kind = CK_BlockPointerToObjCPointerCast;
3182     } else {
3183       Kind = CK_CPointerToObjCPointerCast;
3184     }
3185   } else if (ToType->isBlockPointerType()) {
3186     if (!FromType->isBlockPointerType())
3187       Kind = CK_AnyPointerToBlockPointerCast;
3188   }
3189 
3190   // We shouldn't fall into this case unless it's valid for other
3191   // reasons.
3192   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3193     Kind = CK_NullToPointer;
3194 
3195   return false;
3196 }
3197 
3198 /// IsMemberPointerConversion - Determines whether the conversion of the
3199 /// expression From, which has the (possibly adjusted) type FromType, can be
3200 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3201 /// If so, returns true and places the converted type (that might differ from
3202 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3203 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3204                                      QualType ToType,
3205                                      bool InOverloadResolution,
3206                                      QualType &ConvertedType) {
3207   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3208   if (!ToTypePtr)
3209     return false;
3210 
3211   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3212   if (From->isNullPointerConstant(Context,
3213                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3214                                         : Expr::NPC_ValueDependentIsNull)) {
3215     ConvertedType = ToType;
3216     return true;
3217   }
3218 
3219   // Otherwise, both types have to be member pointers.
3220   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3221   if (!FromTypePtr)
3222     return false;
3223 
3224   // A pointer to member of B can be converted to a pointer to member of D,
3225   // where D is derived from B (C++ 4.11p2).
3226   QualType FromClass(FromTypePtr->getClass(), 0);
3227   QualType ToClass(ToTypePtr->getClass(), 0);
3228 
3229   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3230       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3231     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3232                                                  ToClass.getTypePtr());
3233     return true;
3234   }
3235 
3236   return false;
3237 }
3238 
3239 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3240 /// expression From to the type ToType. This routine checks for ambiguous or
3241 /// virtual or inaccessible base-to-derived member pointer conversions
3242 /// for which IsMemberPointerConversion has already returned true. It returns
3243 /// true and produces a diagnostic if there was an error, or returns false
3244 /// otherwise.
3245 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3246                                         CastKind &Kind,
3247                                         CXXCastPath &BasePath,
3248                                         bool IgnoreBaseAccess) {
3249   QualType FromType = From->getType();
3250   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3251   if (!FromPtrType) {
3252     // This must be a null pointer to member pointer conversion
3253     assert(From->isNullPointerConstant(Context,
3254                                        Expr::NPC_ValueDependentIsNull) &&
3255            "Expr must be null pointer constant!");
3256     Kind = CK_NullToMemberPointer;
3257     return false;
3258   }
3259 
3260   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3261   assert(ToPtrType && "No member pointer cast has a target type "
3262                       "that is not a member pointer.");
3263 
3264   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3265   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3266 
3267   // FIXME: What about dependent types?
3268   assert(FromClass->isRecordType() && "Pointer into non-class.");
3269   assert(ToClass->isRecordType() && "Pointer into non-class.");
3270 
3271   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3272                      /*DetectVirtual=*/true);
3273   bool DerivationOkay =
3274       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3275   assert(DerivationOkay &&
3276          "Should not have been called if derivation isn't OK.");
3277   (void)DerivationOkay;
3278 
3279   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3280                                   getUnqualifiedType())) {
3281     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3282     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3283       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3284     return true;
3285   }
3286 
3287   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3288     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3289       << FromClass << ToClass << QualType(VBase, 0)
3290       << From->getSourceRange();
3291     return true;
3292   }
3293 
3294   if (!IgnoreBaseAccess)
3295     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3296                          Paths.front(),
3297                          diag::err_downcast_from_inaccessible_base);
3298 
3299   // Must be a base to derived member conversion.
3300   BuildBasePathArray(Paths, BasePath);
3301   Kind = CK_BaseToDerivedMemberPointer;
3302   return false;
3303 }
3304 
3305 /// Determine whether the lifetime conversion between the two given
3306 /// qualifiers sets is nontrivial.
3307 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3308                                                Qualifiers ToQuals) {
3309   // Converting anything to const __unsafe_unretained is trivial.
3310   if (ToQuals.hasConst() &&
3311       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3312     return false;
3313 
3314   return true;
3315 }
3316 
3317 /// Perform a single iteration of the loop for checking if a qualification
3318 /// conversion is valid.
3319 ///
3320 /// Specifically, check whether any change between the qualifiers of \p
3321 /// FromType and \p ToType is permissible, given knowledge about whether every
3322 /// outer layer is const-qualified.
3323 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3324                                           bool CStyle, bool IsTopLevel,
3325                                           bool &PreviousToQualsIncludeConst,
3326                                           bool &ObjCLifetimeConversion) {
3327   Qualifiers FromQuals = FromType.getQualifiers();
3328   Qualifiers ToQuals = ToType.getQualifiers();
3329 
3330   // Ignore __unaligned qualifier.
3331   FromQuals.removeUnaligned();
3332 
3333   // Objective-C ARC:
3334   //   Check Objective-C lifetime conversions.
3335   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3336     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3337       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3338         ObjCLifetimeConversion = true;
3339       FromQuals.removeObjCLifetime();
3340       ToQuals.removeObjCLifetime();
3341     } else {
3342       // Qualification conversions cannot cast between different
3343       // Objective-C lifetime qualifiers.
3344       return false;
3345     }
3346   }
3347 
3348   // Allow addition/removal of GC attributes but not changing GC attributes.
3349   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3350       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3351     FromQuals.removeObjCGCAttr();
3352     ToQuals.removeObjCGCAttr();
3353   }
3354 
3355   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3356   //      2,j, and similarly for volatile.
3357   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3358     return false;
3359 
3360   // If address spaces mismatch:
3361   //  - in top level it is only valid to convert to addr space that is a
3362   //    superset in all cases apart from C-style casts where we allow
3363   //    conversions between overlapping address spaces.
3364   //  - in non-top levels it is not a valid conversion.
3365   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3366       (!IsTopLevel ||
3367        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3368          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3369     return false;
3370 
3371   //   -- if the cv 1,j and cv 2,j are different, then const is in
3372   //      every cv for 0 < k < j.
3373   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3374       !PreviousToQualsIncludeConst)
3375     return false;
3376 
3377   // The following wording is from C++20, where the result of the conversion
3378   // is T3, not T2.
3379   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3380   //      "array of unknown bound of"
3381   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3382     return false;
3383 
3384   //   -- if the resulting P3,i is different from P1,i [...], then const is
3385   //      added to every cv 3_k for 0 < k < i.
3386   if (!CStyle && FromType->isConstantArrayType() &&
3387       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3388     return false;
3389 
3390   // Keep track of whether all prior cv-qualifiers in the "to" type
3391   // include const.
3392   PreviousToQualsIncludeConst =
3393       PreviousToQualsIncludeConst && ToQuals.hasConst();
3394   return true;
3395 }
3396 
3397 /// IsQualificationConversion - Determines whether the conversion from
3398 /// an rvalue of type FromType to ToType is a qualification conversion
3399 /// (C++ 4.4).
3400 ///
3401 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3402 /// when the qualification conversion involves a change in the Objective-C
3403 /// object lifetime.
3404 bool
3405 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3406                                 bool CStyle, bool &ObjCLifetimeConversion) {
3407   FromType = Context.getCanonicalType(FromType);
3408   ToType = Context.getCanonicalType(ToType);
3409   ObjCLifetimeConversion = false;
3410 
3411   // If FromType and ToType are the same type, this is not a
3412   // qualification conversion.
3413   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3414     return false;
3415 
3416   // (C++ 4.4p4):
3417   //   A conversion can add cv-qualifiers at levels other than the first
3418   //   in multi-level pointers, subject to the following rules: [...]
3419   bool PreviousToQualsIncludeConst = true;
3420   bool UnwrappedAnyPointer = false;
3421   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3422     if (!isQualificationConversionStep(
3423             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3424             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3425       return false;
3426     UnwrappedAnyPointer = true;
3427   }
3428 
3429   // We are left with FromType and ToType being the pointee types
3430   // after unwrapping the original FromType and ToType the same number
3431   // of times. If we unwrapped any pointers, and if FromType and
3432   // ToType have the same unqualified type (since we checked
3433   // qualifiers above), then this is a qualification conversion.
3434   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3435 }
3436 
3437 /// - Determine whether this is a conversion from a scalar type to an
3438 /// atomic type.
3439 ///
3440 /// If successful, updates \c SCS's second and third steps in the conversion
3441 /// sequence to finish the conversion.
3442 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3443                                 bool InOverloadResolution,
3444                                 StandardConversionSequence &SCS,
3445                                 bool CStyle) {
3446   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3447   if (!ToAtomic)
3448     return false;
3449 
3450   StandardConversionSequence InnerSCS;
3451   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3452                             InOverloadResolution, InnerSCS,
3453                             CStyle, /*AllowObjCWritebackConversion=*/false))
3454     return false;
3455 
3456   SCS.Second = InnerSCS.Second;
3457   SCS.setToType(1, InnerSCS.getToType(1));
3458   SCS.Third = InnerSCS.Third;
3459   SCS.QualificationIncludesObjCLifetime
3460     = InnerSCS.QualificationIncludesObjCLifetime;
3461   SCS.setToType(2, InnerSCS.getToType(2));
3462   return true;
3463 }
3464 
3465 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3466                                               CXXConstructorDecl *Constructor,
3467                                               QualType Type) {
3468   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3469   if (CtorType->getNumParams() > 0) {
3470     QualType FirstArg = CtorType->getParamType(0);
3471     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3472       return true;
3473   }
3474   return false;
3475 }
3476 
3477 static OverloadingResult
3478 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3479                                        CXXRecordDecl *To,
3480                                        UserDefinedConversionSequence &User,
3481                                        OverloadCandidateSet &CandidateSet,
3482                                        bool AllowExplicit) {
3483   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3484   for (auto *D : S.LookupConstructors(To)) {
3485     auto Info = getConstructorInfo(D);
3486     if (!Info)
3487       continue;
3488 
3489     bool Usable = !Info.Constructor->isInvalidDecl() &&
3490                   S.isInitListConstructor(Info.Constructor);
3491     if (Usable) {
3492       bool SuppressUserConversions = false;
3493       if (Info.ConstructorTmpl)
3494         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3495                                        /*ExplicitArgs*/ nullptr, From,
3496                                        CandidateSet, SuppressUserConversions,
3497                                        /*PartialOverloading*/ false,
3498                                        AllowExplicit);
3499       else
3500         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3501                                CandidateSet, SuppressUserConversions,
3502                                /*PartialOverloading*/ false, AllowExplicit);
3503     }
3504   }
3505 
3506   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3507 
3508   OverloadCandidateSet::iterator Best;
3509   switch (auto Result =
3510               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3511   case OR_Deleted:
3512   case OR_Success: {
3513     // Record the standard conversion we used and the conversion function.
3514     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3515     QualType ThisType = Constructor->getThisType();
3516     // Initializer lists don't have conversions as such.
3517     User.Before.setAsIdentityConversion();
3518     User.HadMultipleCandidates = HadMultipleCandidates;
3519     User.ConversionFunction = Constructor;
3520     User.FoundConversionFunction = Best->FoundDecl;
3521     User.After.setAsIdentityConversion();
3522     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3523     User.After.setAllToTypes(ToType);
3524     return Result;
3525   }
3526 
3527   case OR_No_Viable_Function:
3528     return OR_No_Viable_Function;
3529   case OR_Ambiguous:
3530     return OR_Ambiguous;
3531   }
3532 
3533   llvm_unreachable("Invalid OverloadResult!");
3534 }
3535 
3536 /// Determines whether there is a user-defined conversion sequence
3537 /// (C++ [over.ics.user]) that converts expression From to the type
3538 /// ToType. If such a conversion exists, User will contain the
3539 /// user-defined conversion sequence that performs such a conversion
3540 /// and this routine will return true. Otherwise, this routine returns
3541 /// false and User is unspecified.
3542 ///
3543 /// \param AllowExplicit  true if the conversion should consider C++0x
3544 /// "explicit" conversion functions as well as non-explicit conversion
3545 /// functions (C++0x [class.conv.fct]p2).
3546 ///
3547 /// \param AllowObjCConversionOnExplicit true if the conversion should
3548 /// allow an extra Objective-C pointer conversion on uses of explicit
3549 /// constructors. Requires \c AllowExplicit to also be set.
3550 static OverloadingResult
3551 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3552                         UserDefinedConversionSequence &User,
3553                         OverloadCandidateSet &CandidateSet,
3554                         AllowedExplicit AllowExplicit,
3555                         bool AllowObjCConversionOnExplicit) {
3556   assert(AllowExplicit != AllowedExplicit::None ||
3557          !AllowObjCConversionOnExplicit);
3558   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3559 
3560   // Whether we will only visit constructors.
3561   bool ConstructorsOnly = false;
3562 
3563   // If the type we are conversion to is a class type, enumerate its
3564   // constructors.
3565   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3566     // C++ [over.match.ctor]p1:
3567     //   When objects of class type are direct-initialized (8.5), or
3568     //   copy-initialized from an expression of the same or a
3569     //   derived class type (8.5), overload resolution selects the
3570     //   constructor. [...] For copy-initialization, the candidate
3571     //   functions are all the converting constructors (12.3.1) of
3572     //   that class. The argument list is the expression-list within
3573     //   the parentheses of the initializer.
3574     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3575         (From->getType()->getAs<RecordType>() &&
3576          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3577       ConstructorsOnly = true;
3578 
3579     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3580       // We're not going to find any constructors.
3581     } else if (CXXRecordDecl *ToRecordDecl
3582                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3583 
3584       Expr **Args = &From;
3585       unsigned NumArgs = 1;
3586       bool ListInitializing = false;
3587       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3588         // But first, see if there is an init-list-constructor that will work.
3589         OverloadingResult Result = IsInitializerListConstructorConversion(
3590             S, From, ToType, ToRecordDecl, User, CandidateSet,
3591             AllowExplicit == AllowedExplicit::All);
3592         if (Result != OR_No_Viable_Function)
3593           return Result;
3594         // Never mind.
3595         CandidateSet.clear(
3596             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3597 
3598         // If we're list-initializing, we pass the individual elements as
3599         // arguments, not the entire list.
3600         Args = InitList->getInits();
3601         NumArgs = InitList->getNumInits();
3602         ListInitializing = true;
3603       }
3604 
3605       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3606         auto Info = getConstructorInfo(D);
3607         if (!Info)
3608           continue;
3609 
3610         bool Usable = !Info.Constructor->isInvalidDecl();
3611         if (!ListInitializing)
3612           Usable = Usable && Info.Constructor->isConvertingConstructor(
3613                                  /*AllowExplicit*/ true);
3614         if (Usable) {
3615           bool SuppressUserConversions = !ConstructorsOnly;
3616           // C++20 [over.best.ics.general]/4.5:
3617           //   if the target is the first parameter of a constructor [of class
3618           //   X] and the constructor [...] is a candidate by [...] the second
3619           //   phase of [over.match.list] when the initializer list has exactly
3620           //   one element that is itself an initializer list, [...] and the
3621           //   conversion is to X or reference to cv X, user-defined conversion
3622           //   sequences are not cnosidered.
3623           if (SuppressUserConversions && ListInitializing) {
3624             SuppressUserConversions =
3625                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3626                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3627                                                   ToType);
3628           }
3629           if (Info.ConstructorTmpl)
3630             S.AddTemplateOverloadCandidate(
3631                 Info.ConstructorTmpl, Info.FoundDecl,
3632                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3633                 CandidateSet, SuppressUserConversions,
3634                 /*PartialOverloading*/ false,
3635                 AllowExplicit == AllowedExplicit::All);
3636           else
3637             // Allow one user-defined conversion when user specifies a
3638             // From->ToType conversion via an static cast (c-style, etc).
3639             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3640                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
3641                                    SuppressUserConversions,
3642                                    /*PartialOverloading*/ false,
3643                                    AllowExplicit == AllowedExplicit::All);
3644         }
3645       }
3646     }
3647   }
3648 
3649   // Enumerate conversion functions, if we're allowed to.
3650   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3651   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3652     // No conversion functions from incomplete types.
3653   } else if (const RecordType *FromRecordType =
3654                  From->getType()->getAs<RecordType>()) {
3655     if (CXXRecordDecl *FromRecordDecl
3656          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3657       // Add all of the conversion functions as candidates.
3658       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3659       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3660         DeclAccessPair FoundDecl = I.getPair();
3661         NamedDecl *D = FoundDecl.getDecl();
3662         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3663         if (isa<UsingShadowDecl>(D))
3664           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3665 
3666         CXXConversionDecl *Conv;
3667         FunctionTemplateDecl *ConvTemplate;
3668         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3669           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3670         else
3671           Conv = cast<CXXConversionDecl>(D);
3672 
3673         if (ConvTemplate)
3674           S.AddTemplateConversionCandidate(
3675               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3676               CandidateSet, AllowObjCConversionOnExplicit,
3677               AllowExplicit != AllowedExplicit::None);
3678         else
3679           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3680                                    CandidateSet, AllowObjCConversionOnExplicit,
3681                                    AllowExplicit != AllowedExplicit::None);
3682       }
3683     }
3684   }
3685 
3686   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3687 
3688   OverloadCandidateSet::iterator Best;
3689   switch (auto Result =
3690               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3691   case OR_Success:
3692   case OR_Deleted:
3693     // Record the standard conversion we used and the conversion function.
3694     if (CXXConstructorDecl *Constructor
3695           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3696       // C++ [over.ics.user]p1:
3697       //   If the user-defined conversion is specified by a
3698       //   constructor (12.3.1), the initial standard conversion
3699       //   sequence converts the source type to the type required by
3700       //   the argument of the constructor.
3701       //
3702       QualType ThisType = Constructor->getThisType();
3703       if (isa<InitListExpr>(From)) {
3704         // Initializer lists don't have conversions as such.
3705         User.Before.setAsIdentityConversion();
3706       } else {
3707         if (Best->Conversions[0].isEllipsis())
3708           User.EllipsisConversion = true;
3709         else {
3710           User.Before = Best->Conversions[0].Standard;
3711           User.EllipsisConversion = false;
3712         }
3713       }
3714       User.HadMultipleCandidates = HadMultipleCandidates;
3715       User.ConversionFunction = Constructor;
3716       User.FoundConversionFunction = Best->FoundDecl;
3717       User.After.setAsIdentityConversion();
3718       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3719       User.After.setAllToTypes(ToType);
3720       return Result;
3721     }
3722     if (CXXConversionDecl *Conversion
3723                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3724       // C++ [over.ics.user]p1:
3725       //
3726       //   [...] If the user-defined conversion is specified by a
3727       //   conversion function (12.3.2), the initial standard
3728       //   conversion sequence converts the source type to the
3729       //   implicit object parameter of the conversion function.
3730       User.Before = Best->Conversions[0].Standard;
3731       User.HadMultipleCandidates = HadMultipleCandidates;
3732       User.ConversionFunction = Conversion;
3733       User.FoundConversionFunction = Best->FoundDecl;
3734       User.EllipsisConversion = false;
3735 
3736       // C++ [over.ics.user]p2:
3737       //   The second standard conversion sequence converts the
3738       //   result of the user-defined conversion to the target type
3739       //   for the sequence. Since an implicit conversion sequence
3740       //   is an initialization, the special rules for
3741       //   initialization by user-defined conversion apply when
3742       //   selecting the best user-defined conversion for a
3743       //   user-defined conversion sequence (see 13.3.3 and
3744       //   13.3.3.1).
3745       User.After = Best->FinalConversion;
3746       return Result;
3747     }
3748     llvm_unreachable("Not a constructor or conversion function?");
3749 
3750   case OR_No_Viable_Function:
3751     return OR_No_Viable_Function;
3752 
3753   case OR_Ambiguous:
3754     return OR_Ambiguous;
3755   }
3756 
3757   llvm_unreachable("Invalid OverloadResult!");
3758 }
3759 
3760 bool
3761 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3762   ImplicitConversionSequence ICS;
3763   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3764                                     OverloadCandidateSet::CSK_Normal);
3765   OverloadingResult OvResult =
3766     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3767                             CandidateSet, AllowedExplicit::None, false);
3768 
3769   if (!(OvResult == OR_Ambiguous ||
3770         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3771     return false;
3772 
3773   auto Cands = CandidateSet.CompleteCandidates(
3774       *this,
3775       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3776       From);
3777   if (OvResult == OR_Ambiguous)
3778     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3779         << From->getType() << ToType << From->getSourceRange();
3780   else { // OR_No_Viable_Function && !CandidateSet.empty()
3781     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3782                              diag::err_typecheck_nonviable_condition_incomplete,
3783                              From->getType(), From->getSourceRange()))
3784       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3785           << false << From->getType() << From->getSourceRange() << ToType;
3786   }
3787 
3788   CandidateSet.NoteCandidates(
3789                               *this, From, Cands);
3790   return true;
3791 }
3792 
3793 // Helper for compareConversionFunctions that gets the FunctionType that the
3794 // conversion-operator return  value 'points' to, or nullptr.
3795 static const FunctionType *
3796 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3797   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3798   const PointerType *RetPtrTy =
3799       ConvFuncTy->getReturnType()->getAs<PointerType>();
3800 
3801   if (!RetPtrTy)
3802     return nullptr;
3803 
3804   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3805 }
3806 
3807 /// Compare the user-defined conversion functions or constructors
3808 /// of two user-defined conversion sequences to determine whether any ordering
3809 /// is possible.
3810 static ImplicitConversionSequence::CompareKind
3811 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3812                            FunctionDecl *Function2) {
3813   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3814   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3815   if (!Conv1 || !Conv2)
3816     return ImplicitConversionSequence::Indistinguishable;
3817 
3818   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3819     return ImplicitConversionSequence::Indistinguishable;
3820 
3821   // Objective-C++:
3822   //   If both conversion functions are implicitly-declared conversions from
3823   //   a lambda closure type to a function pointer and a block pointer,
3824   //   respectively, always prefer the conversion to a function pointer,
3825   //   because the function pointer is more lightweight and is more likely
3826   //   to keep code working.
3827   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3828     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3829     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3830     if (Block1 != Block2)
3831       return Block1 ? ImplicitConversionSequence::Worse
3832                     : ImplicitConversionSequence::Better;
3833   }
3834 
3835   // In order to support multiple calling conventions for the lambda conversion
3836   // operator (such as when the free and member function calling convention is
3837   // different), prefer the 'free' mechanism, followed by the calling-convention
3838   // of operator(). The latter is in place to support the MSVC-like solution of
3839   // defining ALL of the possible conversions in regards to calling-convention.
3840   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3841   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3842 
3843   if (Conv1FuncRet && Conv2FuncRet &&
3844       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3845     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3846     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3847 
3848     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3849     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3850 
3851     CallingConv CallOpCC =
3852         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3853     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3854         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3855     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3856         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3857 
3858     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3859     for (CallingConv CC : PrefOrder) {
3860       if (Conv1CC == CC)
3861         return ImplicitConversionSequence::Better;
3862       if (Conv2CC == CC)
3863         return ImplicitConversionSequence::Worse;
3864     }
3865   }
3866 
3867   return ImplicitConversionSequence::Indistinguishable;
3868 }
3869 
3870 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3871     const ImplicitConversionSequence &ICS) {
3872   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3873          (ICS.isUserDefined() &&
3874           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3875 }
3876 
3877 /// CompareImplicitConversionSequences - Compare two implicit
3878 /// conversion sequences to determine whether one is better than the
3879 /// other or if they are indistinguishable (C++ 13.3.3.2).
3880 static ImplicitConversionSequence::CompareKind
3881 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3882                                    const ImplicitConversionSequence& ICS1,
3883                                    const ImplicitConversionSequence& ICS2)
3884 {
3885   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3886   // conversion sequences (as defined in 13.3.3.1)
3887   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3888   //      conversion sequence than a user-defined conversion sequence or
3889   //      an ellipsis conversion sequence, and
3890   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3891   //      conversion sequence than an ellipsis conversion sequence
3892   //      (13.3.3.1.3).
3893   //
3894   // C++0x [over.best.ics]p10:
3895   //   For the purpose of ranking implicit conversion sequences as
3896   //   described in 13.3.3.2, the ambiguous conversion sequence is
3897   //   treated as a user-defined sequence that is indistinguishable
3898   //   from any other user-defined conversion sequence.
3899 
3900   // String literal to 'char *' conversion has been deprecated in C++03. It has
3901   // been removed from C++11. We still accept this conversion, if it happens at
3902   // the best viable function. Otherwise, this conversion is considered worse
3903   // than ellipsis conversion. Consider this as an extension; this is not in the
3904   // standard. For example:
3905   //
3906   // int &f(...);    // #1
3907   // void f(char*);  // #2
3908   // void g() { int &r = f("foo"); }
3909   //
3910   // In C++03, we pick #2 as the best viable function.
3911   // In C++11, we pick #1 as the best viable function, because ellipsis
3912   // conversion is better than string-literal to char* conversion (since there
3913   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3914   // convert arguments, #2 would be the best viable function in C++11.
3915   // If the best viable function has this conversion, a warning will be issued
3916   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3917 
3918   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3919       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3920           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3921       // Ill-formedness must not differ
3922       ICS1.isBad() == ICS2.isBad())
3923     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3924                ? ImplicitConversionSequence::Worse
3925                : ImplicitConversionSequence::Better;
3926 
3927   if (ICS1.getKindRank() < ICS2.getKindRank())
3928     return ImplicitConversionSequence::Better;
3929   if (ICS2.getKindRank() < ICS1.getKindRank())
3930     return ImplicitConversionSequence::Worse;
3931 
3932   // The following checks require both conversion sequences to be of
3933   // the same kind.
3934   if (ICS1.getKind() != ICS2.getKind())
3935     return ImplicitConversionSequence::Indistinguishable;
3936 
3937   ImplicitConversionSequence::CompareKind Result =
3938       ImplicitConversionSequence::Indistinguishable;
3939 
3940   // Two implicit conversion sequences of the same form are
3941   // indistinguishable conversion sequences unless one of the
3942   // following rules apply: (C++ 13.3.3.2p3):
3943 
3944   // List-initialization sequence L1 is a better conversion sequence than
3945   // list-initialization sequence L2 if:
3946   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3947   //   if not that,
3948   // — L1 and L2 convert to arrays of the same element type, and either the
3949   //   number of elements n_1 initialized by L1 is less than the number of
3950   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3951   //   an array of unknown bound and L1 does not,
3952   // even if one of the other rules in this paragraph would otherwise apply.
3953   if (!ICS1.isBad()) {
3954     bool StdInit1 = false, StdInit2 = false;
3955     if (ICS1.hasInitializerListContainerType())
3956       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3957                                         nullptr);
3958     if (ICS2.hasInitializerListContainerType())
3959       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3960                                         nullptr);
3961     if (StdInit1 != StdInit2)
3962       return StdInit1 ? ImplicitConversionSequence::Better
3963                       : ImplicitConversionSequence::Worse;
3964 
3965     if (ICS1.hasInitializerListContainerType() &&
3966         ICS2.hasInitializerListContainerType())
3967       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3968               ICS1.getInitializerListContainerType()))
3969         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3970                 ICS2.getInitializerListContainerType())) {
3971           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3972                                                CAT2->getElementType())) {
3973             // Both to arrays of the same element type
3974             if (CAT1->getSize() != CAT2->getSize())
3975               // Different sized, the smaller wins
3976               return CAT1->getSize().ult(CAT2->getSize())
3977                          ? ImplicitConversionSequence::Better
3978                          : ImplicitConversionSequence::Worse;
3979             if (ICS1.isInitializerListOfIncompleteArray() !=
3980                 ICS2.isInitializerListOfIncompleteArray())
3981               // One is incomplete, it loses
3982               return ICS2.isInitializerListOfIncompleteArray()
3983                          ? ImplicitConversionSequence::Better
3984                          : ImplicitConversionSequence::Worse;
3985           }
3986         }
3987   }
3988 
3989   if (ICS1.isStandard())
3990     // Standard conversion sequence S1 is a better conversion sequence than
3991     // standard conversion sequence S2 if [...]
3992     Result = CompareStandardConversionSequences(S, Loc,
3993                                                 ICS1.Standard, ICS2.Standard);
3994   else if (ICS1.isUserDefined()) {
3995     // User-defined conversion sequence U1 is a better conversion
3996     // sequence than another user-defined conversion sequence U2 if
3997     // they contain the same user-defined conversion function or
3998     // constructor and if the second standard conversion sequence of
3999     // U1 is better than the second standard conversion sequence of
4000     // U2 (C++ 13.3.3.2p3).
4001     if (ICS1.UserDefined.ConversionFunction ==
4002           ICS2.UserDefined.ConversionFunction)
4003       Result = CompareStandardConversionSequences(S, Loc,
4004                                                   ICS1.UserDefined.After,
4005                                                   ICS2.UserDefined.After);
4006     else
4007       Result = compareConversionFunctions(S,
4008                                           ICS1.UserDefined.ConversionFunction,
4009                                           ICS2.UserDefined.ConversionFunction);
4010   }
4011 
4012   return Result;
4013 }
4014 
4015 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4016 // determine if one is a proper subset of the other.
4017 static ImplicitConversionSequence::CompareKind
4018 compareStandardConversionSubsets(ASTContext &Context,
4019                                  const StandardConversionSequence& SCS1,
4020                                  const StandardConversionSequence& SCS2) {
4021   ImplicitConversionSequence::CompareKind Result
4022     = ImplicitConversionSequence::Indistinguishable;
4023 
4024   // the identity conversion sequence is considered to be a subsequence of
4025   // any non-identity conversion sequence
4026   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4027     return ImplicitConversionSequence::Better;
4028   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4029     return ImplicitConversionSequence::Worse;
4030 
4031   if (SCS1.Second != SCS2.Second) {
4032     if (SCS1.Second == ICK_Identity)
4033       Result = ImplicitConversionSequence::Better;
4034     else if (SCS2.Second == ICK_Identity)
4035       Result = ImplicitConversionSequence::Worse;
4036     else
4037       return ImplicitConversionSequence::Indistinguishable;
4038   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4039     return ImplicitConversionSequence::Indistinguishable;
4040 
4041   if (SCS1.Third == SCS2.Third) {
4042     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4043                              : ImplicitConversionSequence::Indistinguishable;
4044   }
4045 
4046   if (SCS1.Third == ICK_Identity)
4047     return Result == ImplicitConversionSequence::Worse
4048              ? ImplicitConversionSequence::Indistinguishable
4049              : ImplicitConversionSequence::Better;
4050 
4051   if (SCS2.Third == ICK_Identity)
4052     return Result == ImplicitConversionSequence::Better
4053              ? ImplicitConversionSequence::Indistinguishable
4054              : ImplicitConversionSequence::Worse;
4055 
4056   return ImplicitConversionSequence::Indistinguishable;
4057 }
4058 
4059 /// Determine whether one of the given reference bindings is better
4060 /// than the other based on what kind of bindings they are.
4061 static bool
4062 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4063                              const StandardConversionSequence &SCS2) {
4064   // C++0x [over.ics.rank]p3b4:
4065   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4066   //      implicit object parameter of a non-static member function declared
4067   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4068   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4069   //      lvalue reference to a function lvalue and S2 binds an rvalue
4070   //      reference*.
4071   //
4072   // FIXME: Rvalue references. We're going rogue with the above edits,
4073   // because the semantics in the current C++0x working paper (N3225 at the
4074   // time of this writing) break the standard definition of std::forward
4075   // and std::reference_wrapper when dealing with references to functions.
4076   // Proposed wording changes submitted to CWG for consideration.
4077   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4078       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4079     return false;
4080 
4081   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4082           SCS2.IsLvalueReference) ||
4083          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4084           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4085 }
4086 
4087 enum class FixedEnumPromotion {
4088   None,
4089   ToUnderlyingType,
4090   ToPromotedUnderlyingType
4091 };
4092 
4093 /// Returns kind of fixed enum promotion the \a SCS uses.
4094 static FixedEnumPromotion
4095 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4096 
4097   if (SCS.Second != ICK_Integral_Promotion)
4098     return FixedEnumPromotion::None;
4099 
4100   QualType FromType = SCS.getFromType();
4101   if (!FromType->isEnumeralType())
4102     return FixedEnumPromotion::None;
4103 
4104   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4105   if (!Enum->isFixed())
4106     return FixedEnumPromotion::None;
4107 
4108   QualType UnderlyingType = Enum->getIntegerType();
4109   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4110     return FixedEnumPromotion::ToUnderlyingType;
4111 
4112   return FixedEnumPromotion::ToPromotedUnderlyingType;
4113 }
4114 
4115 /// CompareStandardConversionSequences - Compare two standard
4116 /// conversion sequences to determine whether one is better than the
4117 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4118 static ImplicitConversionSequence::CompareKind
4119 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4120                                    const StandardConversionSequence& SCS1,
4121                                    const StandardConversionSequence& SCS2)
4122 {
4123   // Standard conversion sequence S1 is a better conversion sequence
4124   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4125 
4126   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4127   //     sequences in the canonical form defined by 13.3.3.1.1,
4128   //     excluding any Lvalue Transformation; the identity conversion
4129   //     sequence is considered to be a subsequence of any
4130   //     non-identity conversion sequence) or, if not that,
4131   if (ImplicitConversionSequence::CompareKind CK
4132         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4133     return CK;
4134 
4135   //  -- the rank of S1 is better than the rank of S2 (by the rules
4136   //     defined below), or, if not that,
4137   ImplicitConversionRank Rank1 = SCS1.getRank();
4138   ImplicitConversionRank Rank2 = SCS2.getRank();
4139   if (Rank1 < Rank2)
4140     return ImplicitConversionSequence::Better;
4141   else if (Rank2 < Rank1)
4142     return ImplicitConversionSequence::Worse;
4143 
4144   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4145   // are indistinguishable unless one of the following rules
4146   // applies:
4147 
4148   //   A conversion that is not a conversion of a pointer, or
4149   //   pointer to member, to bool is better than another conversion
4150   //   that is such a conversion.
4151   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4152     return SCS2.isPointerConversionToBool()
4153              ? ImplicitConversionSequence::Better
4154              : ImplicitConversionSequence::Worse;
4155 
4156   // C++14 [over.ics.rank]p4b2:
4157   // This is retroactively applied to C++11 by CWG 1601.
4158   //
4159   //   A conversion that promotes an enumeration whose underlying type is fixed
4160   //   to its underlying type is better than one that promotes to the promoted
4161   //   underlying type, if the two are different.
4162   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4163   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4164   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4165       FEP1 != FEP2)
4166     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4167                ? ImplicitConversionSequence::Better
4168                : ImplicitConversionSequence::Worse;
4169 
4170   // C++ [over.ics.rank]p4b2:
4171   //
4172   //   If class B is derived directly or indirectly from class A,
4173   //   conversion of B* to A* is better than conversion of B* to
4174   //   void*, and conversion of A* to void* is better than conversion
4175   //   of B* to void*.
4176   bool SCS1ConvertsToVoid
4177     = SCS1.isPointerConversionToVoidPointer(S.Context);
4178   bool SCS2ConvertsToVoid
4179     = SCS2.isPointerConversionToVoidPointer(S.Context);
4180   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4181     // Exactly one of the conversion sequences is a conversion to
4182     // a void pointer; it's the worse conversion.
4183     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4184                               : ImplicitConversionSequence::Worse;
4185   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4186     // Neither conversion sequence converts to a void pointer; compare
4187     // their derived-to-base conversions.
4188     if (ImplicitConversionSequence::CompareKind DerivedCK
4189           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4190       return DerivedCK;
4191   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4192              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4193     // Both conversion sequences are conversions to void
4194     // pointers. Compare the source types to determine if there's an
4195     // inheritance relationship in their sources.
4196     QualType FromType1 = SCS1.getFromType();
4197     QualType FromType2 = SCS2.getFromType();
4198 
4199     // Adjust the types we're converting from via the array-to-pointer
4200     // conversion, if we need to.
4201     if (SCS1.First == ICK_Array_To_Pointer)
4202       FromType1 = S.Context.getArrayDecayedType(FromType1);
4203     if (SCS2.First == ICK_Array_To_Pointer)
4204       FromType2 = S.Context.getArrayDecayedType(FromType2);
4205 
4206     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4207     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4208 
4209     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4210       return ImplicitConversionSequence::Better;
4211     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4212       return ImplicitConversionSequence::Worse;
4213 
4214     // Objective-C++: If one interface is more specific than the
4215     // other, it is the better one.
4216     const ObjCObjectPointerType* FromObjCPtr1
4217       = FromType1->getAs<ObjCObjectPointerType>();
4218     const ObjCObjectPointerType* FromObjCPtr2
4219       = FromType2->getAs<ObjCObjectPointerType>();
4220     if (FromObjCPtr1 && FromObjCPtr2) {
4221       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4222                                                           FromObjCPtr2);
4223       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4224                                                            FromObjCPtr1);
4225       if (AssignLeft != AssignRight) {
4226         return AssignLeft? ImplicitConversionSequence::Better
4227                          : ImplicitConversionSequence::Worse;
4228       }
4229     }
4230   }
4231 
4232   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4233     // Check for a better reference binding based on the kind of bindings.
4234     if (isBetterReferenceBindingKind(SCS1, SCS2))
4235       return ImplicitConversionSequence::Better;
4236     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4237       return ImplicitConversionSequence::Worse;
4238   }
4239 
4240   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4241   // bullet 3).
4242   if (ImplicitConversionSequence::CompareKind QualCK
4243         = CompareQualificationConversions(S, SCS1, SCS2))
4244     return QualCK;
4245 
4246   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4247     // C++ [over.ics.rank]p3b4:
4248     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4249     //      which the references refer are the same type except for
4250     //      top-level cv-qualifiers, and the type to which the reference
4251     //      initialized by S2 refers is more cv-qualified than the type
4252     //      to which the reference initialized by S1 refers.
4253     QualType T1 = SCS1.getToType(2);
4254     QualType T2 = SCS2.getToType(2);
4255     T1 = S.Context.getCanonicalType(T1);
4256     T2 = S.Context.getCanonicalType(T2);
4257     Qualifiers T1Quals, T2Quals;
4258     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4259     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4260     if (UnqualT1 == UnqualT2) {
4261       // Objective-C++ ARC: If the references refer to objects with different
4262       // lifetimes, prefer bindings that don't change lifetime.
4263       if (SCS1.ObjCLifetimeConversionBinding !=
4264                                           SCS2.ObjCLifetimeConversionBinding) {
4265         return SCS1.ObjCLifetimeConversionBinding
4266                                            ? ImplicitConversionSequence::Worse
4267                                            : ImplicitConversionSequence::Better;
4268       }
4269 
4270       // If the type is an array type, promote the element qualifiers to the
4271       // type for comparison.
4272       if (isa<ArrayType>(T1) && T1Quals)
4273         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4274       if (isa<ArrayType>(T2) && T2Quals)
4275         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4276       if (T2.isMoreQualifiedThan(T1))
4277         return ImplicitConversionSequence::Better;
4278       if (T1.isMoreQualifiedThan(T2))
4279         return ImplicitConversionSequence::Worse;
4280     }
4281   }
4282 
4283   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4284   // floating-to-integral conversion if the integral conversion
4285   // is between types of the same size.
4286   // For example:
4287   // void f(float);
4288   // void f(int);
4289   // int main {
4290   //    long a;
4291   //    f(a);
4292   // }
4293   // Here, MSVC will call f(int) instead of generating a compile error
4294   // as clang will do in standard mode.
4295   if (S.getLangOpts().MSVCCompat &&
4296       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4297       SCS1.Second == ICK_Integral_Conversion &&
4298       SCS2.Second == ICK_Floating_Integral &&
4299       S.Context.getTypeSize(SCS1.getFromType()) ==
4300           S.Context.getTypeSize(SCS1.getToType(2)))
4301     return ImplicitConversionSequence::Better;
4302 
4303   // Prefer a compatible vector conversion over a lax vector conversion
4304   // For example:
4305   //
4306   // typedef float __v4sf __attribute__((__vector_size__(16)));
4307   // void f(vector float);
4308   // void f(vector signed int);
4309   // int main() {
4310   //   __v4sf a;
4311   //   f(a);
4312   // }
4313   // Here, we'd like to choose f(vector float) and not
4314   // report an ambiguous call error
4315   if (SCS1.Second == ICK_Vector_Conversion &&
4316       SCS2.Second == ICK_Vector_Conversion) {
4317     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4318         SCS1.getFromType(), SCS1.getToType(2));
4319     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4320         SCS2.getFromType(), SCS2.getToType(2));
4321 
4322     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4323       return SCS1IsCompatibleVectorConversion
4324                  ? ImplicitConversionSequence::Better
4325                  : ImplicitConversionSequence::Worse;
4326   }
4327 
4328   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4329       SCS2.Second == ICK_SVE_Vector_Conversion) {
4330     bool SCS1IsCompatibleSVEVectorConversion =
4331         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4332     bool SCS2IsCompatibleSVEVectorConversion =
4333         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4334 
4335     if (SCS1IsCompatibleSVEVectorConversion !=
4336         SCS2IsCompatibleSVEVectorConversion)
4337       return SCS1IsCompatibleSVEVectorConversion
4338                  ? ImplicitConversionSequence::Better
4339                  : ImplicitConversionSequence::Worse;
4340   }
4341 
4342   if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4343       SCS2.Second == ICK_RVV_Vector_Conversion) {
4344     bool SCS1IsCompatibleRVVVectorConversion =
4345         S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4346     bool SCS2IsCompatibleRVVVectorConversion =
4347         S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4348 
4349     if (SCS1IsCompatibleRVVVectorConversion !=
4350         SCS2IsCompatibleRVVVectorConversion)
4351       return SCS1IsCompatibleRVVVectorConversion
4352                  ? ImplicitConversionSequence::Better
4353                  : ImplicitConversionSequence::Worse;
4354   }
4355 
4356   return ImplicitConversionSequence::Indistinguishable;
4357 }
4358 
4359 /// CompareQualificationConversions - Compares two standard conversion
4360 /// sequences to determine whether they can be ranked based on their
4361 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4362 static ImplicitConversionSequence::CompareKind
4363 CompareQualificationConversions(Sema &S,
4364                                 const StandardConversionSequence& SCS1,
4365                                 const StandardConversionSequence& SCS2) {
4366   // C++ [over.ics.rank]p3:
4367   //  -- S1 and S2 differ only in their qualification conversion and
4368   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4369   // [C++98]
4370   //     [...] and the cv-qualification signature of type T1 is a proper subset
4371   //     of the cv-qualification signature of type T2, and S1 is not the
4372   //     deprecated string literal array-to-pointer conversion (4.2).
4373   // [C++2a]
4374   //     [...] where T1 can be converted to T2 by a qualification conversion.
4375   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4376       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4377     return ImplicitConversionSequence::Indistinguishable;
4378 
4379   // FIXME: the example in the standard doesn't use a qualification
4380   // conversion (!)
4381   QualType T1 = SCS1.getToType(2);
4382   QualType T2 = SCS2.getToType(2);
4383   T1 = S.Context.getCanonicalType(T1);
4384   T2 = S.Context.getCanonicalType(T2);
4385   assert(!T1->isReferenceType() && !T2->isReferenceType());
4386   Qualifiers T1Quals, T2Quals;
4387   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4388   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4389 
4390   // If the types are the same, we won't learn anything by unwrapping
4391   // them.
4392   if (UnqualT1 == UnqualT2)
4393     return ImplicitConversionSequence::Indistinguishable;
4394 
4395   // Don't ever prefer a standard conversion sequence that uses the deprecated
4396   // string literal array to pointer conversion.
4397   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4398   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4399 
4400   // Objective-C++ ARC:
4401   //   Prefer qualification conversions not involving a change in lifetime
4402   //   to qualification conversions that do change lifetime.
4403   if (SCS1.QualificationIncludesObjCLifetime &&
4404       !SCS2.QualificationIncludesObjCLifetime)
4405     CanPick1 = false;
4406   if (SCS2.QualificationIncludesObjCLifetime &&
4407       !SCS1.QualificationIncludesObjCLifetime)
4408     CanPick2 = false;
4409 
4410   bool ObjCLifetimeConversion;
4411   if (CanPick1 &&
4412       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4413     CanPick1 = false;
4414   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4415   // directions, so we can't short-cut this second check in general.
4416   if (CanPick2 &&
4417       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4418     CanPick2 = false;
4419 
4420   if (CanPick1 != CanPick2)
4421     return CanPick1 ? ImplicitConversionSequence::Better
4422                     : ImplicitConversionSequence::Worse;
4423   return ImplicitConversionSequence::Indistinguishable;
4424 }
4425 
4426 /// CompareDerivedToBaseConversions - Compares two standard conversion
4427 /// sequences to determine whether they can be ranked based on their
4428 /// various kinds of derived-to-base conversions (C++
4429 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4430 /// conversions between Objective-C interface types.
4431 static ImplicitConversionSequence::CompareKind
4432 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4433                                 const StandardConversionSequence& SCS1,
4434                                 const StandardConversionSequence& SCS2) {
4435   QualType FromType1 = SCS1.getFromType();
4436   QualType ToType1 = SCS1.getToType(1);
4437   QualType FromType2 = SCS2.getFromType();
4438   QualType ToType2 = SCS2.getToType(1);
4439 
4440   // Adjust the types we're converting from via the array-to-pointer
4441   // conversion, if we need to.
4442   if (SCS1.First == ICK_Array_To_Pointer)
4443     FromType1 = S.Context.getArrayDecayedType(FromType1);
4444   if (SCS2.First == ICK_Array_To_Pointer)
4445     FromType2 = S.Context.getArrayDecayedType(FromType2);
4446 
4447   // Canonicalize all of the types.
4448   FromType1 = S.Context.getCanonicalType(FromType1);
4449   ToType1 = S.Context.getCanonicalType(ToType1);
4450   FromType2 = S.Context.getCanonicalType(FromType2);
4451   ToType2 = S.Context.getCanonicalType(ToType2);
4452 
4453   // C++ [over.ics.rank]p4b3:
4454   //
4455   //   If class B is derived directly or indirectly from class A and
4456   //   class C is derived directly or indirectly from B,
4457   //
4458   // Compare based on pointer conversions.
4459   if (SCS1.Second == ICK_Pointer_Conversion &&
4460       SCS2.Second == ICK_Pointer_Conversion &&
4461       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4462       FromType1->isPointerType() && FromType2->isPointerType() &&
4463       ToType1->isPointerType() && ToType2->isPointerType()) {
4464     QualType FromPointee1 =
4465         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4466     QualType ToPointee1 =
4467         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4468     QualType FromPointee2 =
4469         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4470     QualType ToPointee2 =
4471         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4472 
4473     //   -- conversion of C* to B* is better than conversion of C* to A*,
4474     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4475       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4476         return ImplicitConversionSequence::Better;
4477       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4478         return ImplicitConversionSequence::Worse;
4479     }
4480 
4481     //   -- conversion of B* to A* is better than conversion of C* to A*,
4482     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4483       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4484         return ImplicitConversionSequence::Better;
4485       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4486         return ImplicitConversionSequence::Worse;
4487     }
4488   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4489              SCS2.Second == ICK_Pointer_Conversion) {
4490     const ObjCObjectPointerType *FromPtr1
4491       = FromType1->getAs<ObjCObjectPointerType>();
4492     const ObjCObjectPointerType *FromPtr2
4493       = FromType2->getAs<ObjCObjectPointerType>();
4494     const ObjCObjectPointerType *ToPtr1
4495       = ToType1->getAs<ObjCObjectPointerType>();
4496     const ObjCObjectPointerType *ToPtr2
4497       = ToType2->getAs<ObjCObjectPointerType>();
4498 
4499     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4500       // Apply the same conversion ranking rules for Objective-C pointer types
4501       // that we do for C++ pointers to class types. However, we employ the
4502       // Objective-C pseudo-subtyping relationship used for assignment of
4503       // Objective-C pointer types.
4504       bool FromAssignLeft
4505         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4506       bool FromAssignRight
4507         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4508       bool ToAssignLeft
4509         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4510       bool ToAssignRight
4511         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4512 
4513       // A conversion to an a non-id object pointer type or qualified 'id'
4514       // type is better than a conversion to 'id'.
4515       if (ToPtr1->isObjCIdType() &&
4516           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4517         return ImplicitConversionSequence::Worse;
4518       if (ToPtr2->isObjCIdType() &&
4519           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4520         return ImplicitConversionSequence::Better;
4521 
4522       // A conversion to a non-id object pointer type is better than a
4523       // conversion to a qualified 'id' type
4524       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4525         return ImplicitConversionSequence::Worse;
4526       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4527         return ImplicitConversionSequence::Better;
4528 
4529       // A conversion to an a non-Class object pointer type or qualified 'Class'
4530       // type is better than a conversion to 'Class'.
4531       if (ToPtr1->isObjCClassType() &&
4532           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4533         return ImplicitConversionSequence::Worse;
4534       if (ToPtr2->isObjCClassType() &&
4535           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4536         return ImplicitConversionSequence::Better;
4537 
4538       // A conversion to a non-Class object pointer type is better than a
4539       // conversion to a qualified 'Class' type.
4540       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4541         return ImplicitConversionSequence::Worse;
4542       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4543         return ImplicitConversionSequence::Better;
4544 
4545       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4546       if (S.Context.hasSameType(FromType1, FromType2) &&
4547           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4548           (ToAssignLeft != ToAssignRight)) {
4549         if (FromPtr1->isSpecialized()) {
4550           // "conversion of B<A> * to B * is better than conversion of B * to
4551           // C *.
4552           bool IsFirstSame =
4553               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4554           bool IsSecondSame =
4555               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4556           if (IsFirstSame) {
4557             if (!IsSecondSame)
4558               return ImplicitConversionSequence::Better;
4559           } else if (IsSecondSame)
4560             return ImplicitConversionSequence::Worse;
4561         }
4562         return ToAssignLeft? ImplicitConversionSequence::Worse
4563                            : ImplicitConversionSequence::Better;
4564       }
4565 
4566       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4567       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4568           (FromAssignLeft != FromAssignRight))
4569         return FromAssignLeft? ImplicitConversionSequence::Better
4570         : ImplicitConversionSequence::Worse;
4571     }
4572   }
4573 
4574   // Ranking of member-pointer types.
4575   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4576       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4577       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4578     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4579     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4580     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4581     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4582     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4583     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4584     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4585     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4586     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4587     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4588     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4589     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4590     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4591     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4592       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4593         return ImplicitConversionSequence::Worse;
4594       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4595         return ImplicitConversionSequence::Better;
4596     }
4597     // conversion of B::* to C::* is better than conversion of A::* to C::*
4598     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4599       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4600         return ImplicitConversionSequence::Better;
4601       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4602         return ImplicitConversionSequence::Worse;
4603     }
4604   }
4605 
4606   if (SCS1.Second == ICK_Derived_To_Base) {
4607     //   -- conversion of C to B is better than conversion of C to A,
4608     //   -- binding of an expression of type C to a reference of type
4609     //      B& is better than binding an expression of type C to a
4610     //      reference of type A&,
4611     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4612         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4613       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4614         return ImplicitConversionSequence::Better;
4615       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4616         return ImplicitConversionSequence::Worse;
4617     }
4618 
4619     //   -- conversion of B to A is better than conversion of C to A.
4620     //   -- binding of an expression of type B to a reference of type
4621     //      A& is better than binding an expression of type C to a
4622     //      reference of type A&,
4623     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4624         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4625       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4626         return ImplicitConversionSequence::Better;
4627       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4628         return ImplicitConversionSequence::Worse;
4629     }
4630   }
4631 
4632   return ImplicitConversionSequence::Indistinguishable;
4633 }
4634 
4635 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4636   if (!T.getQualifiers().hasUnaligned())
4637     return T;
4638 
4639   Qualifiers Q;
4640   T = Ctx.getUnqualifiedArrayType(T, Q);
4641   Q.removeUnaligned();
4642   return Ctx.getQualifiedType(T, Q);
4643 }
4644 
4645 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4646 /// determine whether they are reference-compatible,
4647 /// reference-related, or incompatible, for use in C++ initialization by
4648 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4649 /// type, and the first type (T1) is the pointee type of the reference
4650 /// type being initialized.
4651 Sema::ReferenceCompareResult
4652 Sema::CompareReferenceRelationship(SourceLocation Loc,
4653                                    QualType OrigT1, QualType OrigT2,
4654                                    ReferenceConversions *ConvOut) {
4655   assert(!OrigT1->isReferenceType() &&
4656     "T1 must be the pointee type of the reference type");
4657   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4658 
4659   QualType T1 = Context.getCanonicalType(OrigT1);
4660   QualType T2 = Context.getCanonicalType(OrigT2);
4661   Qualifiers T1Quals, T2Quals;
4662   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4663   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4664 
4665   ReferenceConversions ConvTmp;
4666   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4667   Conv = ReferenceConversions();
4668 
4669   // C++2a [dcl.init.ref]p4:
4670   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4671   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4672   //   T1 is a base class of T2.
4673   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4674   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4675   //   "pointer to cv1 T1" via a standard conversion sequence.
4676 
4677   // Check for standard conversions we can apply to pointers: derived-to-base
4678   // conversions, ObjC pointer conversions, and function pointer conversions.
4679   // (Qualification conversions are checked last.)
4680   QualType ConvertedT2;
4681   if (UnqualT1 == UnqualT2) {
4682     // Nothing to do.
4683   } else if (isCompleteType(Loc, OrigT2) &&
4684              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4685     Conv |= ReferenceConversions::DerivedToBase;
4686   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4687            UnqualT2->isObjCObjectOrInterfaceType() &&
4688            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4689     Conv |= ReferenceConversions::ObjC;
4690   else if (UnqualT2->isFunctionType() &&
4691            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4692     Conv |= ReferenceConversions::Function;
4693     // No need to check qualifiers; function types don't have them.
4694     return Ref_Compatible;
4695   }
4696   bool ConvertedReferent = Conv != 0;
4697 
4698   // We can have a qualification conversion. Compute whether the types are
4699   // similar at the same time.
4700   bool PreviousToQualsIncludeConst = true;
4701   bool TopLevel = true;
4702   do {
4703     if (T1 == T2)
4704       break;
4705 
4706     // We will need a qualification conversion.
4707     Conv |= ReferenceConversions::Qualification;
4708 
4709     // Track whether we performed a qualification conversion anywhere other
4710     // than the top level. This matters for ranking reference bindings in
4711     // overload resolution.
4712     if (!TopLevel)
4713       Conv |= ReferenceConversions::NestedQualification;
4714 
4715     // MS compiler ignores __unaligned qualifier for references; do the same.
4716     T1 = withoutUnaligned(Context, T1);
4717     T2 = withoutUnaligned(Context, T2);
4718 
4719     // If we find a qualifier mismatch, the types are not reference-compatible,
4720     // but are still be reference-related if they're similar.
4721     bool ObjCLifetimeConversion = false;
4722     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4723                                        PreviousToQualsIncludeConst,
4724                                        ObjCLifetimeConversion))
4725       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4726                  ? Ref_Related
4727                  : Ref_Incompatible;
4728 
4729     // FIXME: Should we track this for any level other than the first?
4730     if (ObjCLifetimeConversion)
4731       Conv |= ReferenceConversions::ObjCLifetime;
4732 
4733     TopLevel = false;
4734   } while (Context.UnwrapSimilarTypes(T1, T2));
4735 
4736   // At this point, if the types are reference-related, we must either have the
4737   // same inner type (ignoring qualifiers), or must have already worked out how
4738   // to convert the referent.
4739   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4740              ? Ref_Compatible
4741              : Ref_Incompatible;
4742 }
4743 
4744 /// Look for a user-defined conversion to a value reference-compatible
4745 ///        with DeclType. Return true if something definite is found.
4746 static bool
4747 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4748                          QualType DeclType, SourceLocation DeclLoc,
4749                          Expr *Init, QualType T2, bool AllowRvalues,
4750                          bool AllowExplicit) {
4751   assert(T2->isRecordType() && "Can only find conversions of record types.");
4752   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4753 
4754   OverloadCandidateSet CandidateSet(
4755       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4756   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4757   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4758     NamedDecl *D = *I;
4759     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4760     if (isa<UsingShadowDecl>(D))
4761       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4762 
4763     FunctionTemplateDecl *ConvTemplate
4764       = dyn_cast<FunctionTemplateDecl>(D);
4765     CXXConversionDecl *Conv;
4766     if (ConvTemplate)
4767       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4768     else
4769       Conv = cast<CXXConversionDecl>(D);
4770 
4771     if (AllowRvalues) {
4772       // If we are initializing an rvalue reference, don't permit conversion
4773       // functions that return lvalues.
4774       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4775         const ReferenceType *RefType
4776           = Conv->getConversionType()->getAs<LValueReferenceType>();
4777         if (RefType && !RefType->getPointeeType()->isFunctionType())
4778           continue;
4779       }
4780 
4781       if (!ConvTemplate &&
4782           S.CompareReferenceRelationship(
4783               DeclLoc,
4784               Conv->getConversionType()
4785                   .getNonReferenceType()
4786                   .getUnqualifiedType(),
4787               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4788               Sema::Ref_Incompatible)
4789         continue;
4790     } else {
4791       // If the conversion function doesn't return a reference type,
4792       // it can't be considered for this conversion. An rvalue reference
4793       // is only acceptable if its referencee is a function type.
4794 
4795       const ReferenceType *RefType =
4796         Conv->getConversionType()->getAs<ReferenceType>();
4797       if (!RefType ||
4798           (!RefType->isLValueReferenceType() &&
4799            !RefType->getPointeeType()->isFunctionType()))
4800         continue;
4801     }
4802 
4803     if (ConvTemplate)
4804       S.AddTemplateConversionCandidate(
4805           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4806           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4807     else
4808       S.AddConversionCandidate(
4809           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4810           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4811   }
4812 
4813   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4814 
4815   OverloadCandidateSet::iterator Best;
4816   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4817   case OR_Success:
4818     // C++ [over.ics.ref]p1:
4819     //
4820     //   [...] If the parameter binds directly to the result of
4821     //   applying a conversion function to the argument
4822     //   expression, the implicit conversion sequence is a
4823     //   user-defined conversion sequence (13.3.3.1.2), with the
4824     //   second standard conversion sequence either an identity
4825     //   conversion or, if the conversion function returns an
4826     //   entity of a type that is a derived class of the parameter
4827     //   type, a derived-to-base Conversion.
4828     if (!Best->FinalConversion.DirectBinding)
4829       return false;
4830 
4831     ICS.setUserDefined();
4832     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4833     ICS.UserDefined.After = Best->FinalConversion;
4834     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4835     ICS.UserDefined.ConversionFunction = Best->Function;
4836     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4837     ICS.UserDefined.EllipsisConversion = false;
4838     assert(ICS.UserDefined.After.ReferenceBinding &&
4839            ICS.UserDefined.After.DirectBinding &&
4840            "Expected a direct reference binding!");
4841     return true;
4842 
4843   case OR_Ambiguous:
4844     ICS.setAmbiguous();
4845     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4846          Cand != CandidateSet.end(); ++Cand)
4847       if (Cand->Best)
4848         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4849     return true;
4850 
4851   case OR_No_Viable_Function:
4852   case OR_Deleted:
4853     // There was no suitable conversion, or we found a deleted
4854     // conversion; continue with other checks.
4855     return false;
4856   }
4857 
4858   llvm_unreachable("Invalid OverloadResult!");
4859 }
4860 
4861 /// Compute an implicit conversion sequence for reference
4862 /// initialization.
4863 static ImplicitConversionSequence
4864 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4865                  SourceLocation DeclLoc,
4866                  bool SuppressUserConversions,
4867                  bool AllowExplicit) {
4868   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4869 
4870   // Most paths end in a failed conversion.
4871   ImplicitConversionSequence ICS;
4872   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4873 
4874   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4875   QualType T2 = Init->getType();
4876 
4877   // If the initializer is the address of an overloaded function, try
4878   // to resolve the overloaded function. If all goes well, T2 is the
4879   // type of the resulting function.
4880   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4881     DeclAccessPair Found;
4882     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4883                                                                 false, Found))
4884       T2 = Fn->getType();
4885   }
4886 
4887   // Compute some basic properties of the types and the initializer.
4888   bool isRValRef = DeclType->isRValueReferenceType();
4889   Expr::Classification InitCategory = Init->Classify(S.Context);
4890 
4891   Sema::ReferenceConversions RefConv;
4892   Sema::ReferenceCompareResult RefRelationship =
4893       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4894 
4895   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4896     ICS.setStandard();
4897     ICS.Standard.First = ICK_Identity;
4898     // FIXME: A reference binding can be a function conversion too. We should
4899     // consider that when ordering reference-to-function bindings.
4900     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4901                               ? ICK_Derived_To_Base
4902                               : (RefConv & Sema::ReferenceConversions::ObjC)
4903                                     ? ICK_Compatible_Conversion
4904                                     : ICK_Identity;
4905     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4906     // a reference binding that performs a non-top-level qualification
4907     // conversion as a qualification conversion, not as an identity conversion.
4908     ICS.Standard.Third = (RefConv &
4909                               Sema::ReferenceConversions::NestedQualification)
4910                              ? ICK_Qualification
4911                              : ICK_Identity;
4912     ICS.Standard.setFromType(T2);
4913     ICS.Standard.setToType(0, T2);
4914     ICS.Standard.setToType(1, T1);
4915     ICS.Standard.setToType(2, T1);
4916     ICS.Standard.ReferenceBinding = true;
4917     ICS.Standard.DirectBinding = BindsDirectly;
4918     ICS.Standard.IsLvalueReference = !isRValRef;
4919     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4920     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4921     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4922     ICS.Standard.ObjCLifetimeConversionBinding =
4923         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4924     ICS.Standard.CopyConstructor = nullptr;
4925     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4926   };
4927 
4928   // C++0x [dcl.init.ref]p5:
4929   //   A reference to type "cv1 T1" is initialized by an expression
4930   //   of type "cv2 T2" as follows:
4931 
4932   //     -- If reference is an lvalue reference and the initializer expression
4933   if (!isRValRef) {
4934     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4935     //        reference-compatible with "cv2 T2," or
4936     //
4937     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4938     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4939       // C++ [over.ics.ref]p1:
4940       //   When a parameter of reference type binds directly (8.5.3)
4941       //   to an argument expression, the implicit conversion sequence
4942       //   is the identity conversion, unless the argument expression
4943       //   has a type that is a derived class of the parameter type,
4944       //   in which case the implicit conversion sequence is a
4945       //   derived-to-base Conversion (13.3.3.1).
4946       SetAsReferenceBinding(/*BindsDirectly=*/true);
4947 
4948       // Nothing more to do: the inaccessibility/ambiguity check for
4949       // derived-to-base conversions is suppressed when we're
4950       // computing the implicit conversion sequence (C++
4951       // [over.best.ics]p2).
4952       return ICS;
4953     }
4954 
4955     //       -- has a class type (i.e., T2 is a class type), where T1 is
4956     //          not reference-related to T2, and can be implicitly
4957     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4958     //          is reference-compatible with "cv3 T3" 92) (this
4959     //          conversion is selected by enumerating the applicable
4960     //          conversion functions (13.3.1.6) and choosing the best
4961     //          one through overload resolution (13.3)),
4962     if (!SuppressUserConversions && T2->isRecordType() &&
4963         S.isCompleteType(DeclLoc, T2) &&
4964         RefRelationship == Sema::Ref_Incompatible) {
4965       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4966                                    Init, T2, /*AllowRvalues=*/false,
4967                                    AllowExplicit))
4968         return ICS;
4969     }
4970   }
4971 
4972   //     -- Otherwise, the reference shall be an lvalue reference to a
4973   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4974   //        shall be an rvalue reference.
4975   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4976     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4977       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4978     return ICS;
4979   }
4980 
4981   //       -- If the initializer expression
4982   //
4983   //            -- is an xvalue, class prvalue, array prvalue or function
4984   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4985   if (RefRelationship == Sema::Ref_Compatible &&
4986       (InitCategory.isXValue() ||
4987        (InitCategory.isPRValue() &&
4988           (T2->isRecordType() || T2->isArrayType())) ||
4989        (InitCategory.isLValue() && T2->isFunctionType()))) {
4990     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4991     // binding unless we're binding to a class prvalue.
4992     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4993     // allow the use of rvalue references in C++98/03 for the benefit of
4994     // standard library implementors; therefore, we need the xvalue check here.
4995     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4996                           !(InitCategory.isPRValue() || T2->isRecordType()));
4997     return ICS;
4998   }
4999 
5000   //            -- has a class type (i.e., T2 is a class type), where T1 is not
5001   //               reference-related to T2, and can be implicitly converted to
5002   //               an xvalue, class prvalue, or function lvalue of type
5003   //               "cv3 T3", where "cv1 T1" is reference-compatible with
5004   //               "cv3 T3",
5005   //
5006   //          then the reference is bound to the value of the initializer
5007   //          expression in the first case and to the result of the conversion
5008   //          in the second case (or, in either case, to an appropriate base
5009   //          class subobject).
5010   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5011       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5012       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5013                                Init, T2, /*AllowRvalues=*/true,
5014                                AllowExplicit)) {
5015     // In the second case, if the reference is an rvalue reference
5016     // and the second standard conversion sequence of the
5017     // user-defined conversion sequence includes an lvalue-to-rvalue
5018     // conversion, the program is ill-formed.
5019     if (ICS.isUserDefined() && isRValRef &&
5020         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5021       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5022 
5023     return ICS;
5024   }
5025 
5026   // A temporary of function type cannot be created; don't even try.
5027   if (T1->isFunctionType())
5028     return ICS;
5029 
5030   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5031   //          initialized from the initializer expression using the
5032   //          rules for a non-reference copy initialization (8.5). The
5033   //          reference is then bound to the temporary. If T1 is
5034   //          reference-related to T2, cv1 must be the same
5035   //          cv-qualification as, or greater cv-qualification than,
5036   //          cv2; otherwise, the program is ill-formed.
5037   if (RefRelationship == Sema::Ref_Related) {
5038     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5039     // we would be reference-compatible or reference-compatible with
5040     // added qualification. But that wasn't the case, so the reference
5041     // initialization fails.
5042     //
5043     // Note that we only want to check address spaces and cvr-qualifiers here.
5044     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5045     Qualifiers T1Quals = T1.getQualifiers();
5046     Qualifiers T2Quals = T2.getQualifiers();
5047     T1Quals.removeObjCGCAttr();
5048     T1Quals.removeObjCLifetime();
5049     T2Quals.removeObjCGCAttr();
5050     T2Quals.removeObjCLifetime();
5051     // MS compiler ignores __unaligned qualifier for references; do the same.
5052     T1Quals.removeUnaligned();
5053     T2Quals.removeUnaligned();
5054     if (!T1Quals.compatiblyIncludes(T2Quals))
5055       return ICS;
5056   }
5057 
5058   // If at least one of the types is a class type, the types are not
5059   // related, and we aren't allowed any user conversions, the
5060   // reference binding fails. This case is important for breaking
5061   // recursion, since TryImplicitConversion below will attempt to
5062   // create a temporary through the use of a copy constructor.
5063   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5064       (T1->isRecordType() || T2->isRecordType()))
5065     return ICS;
5066 
5067   // If T1 is reference-related to T2 and the reference is an rvalue
5068   // reference, the initializer expression shall not be an lvalue.
5069   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5070       Init->Classify(S.Context).isLValue()) {
5071     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5072     return ICS;
5073   }
5074 
5075   // C++ [over.ics.ref]p2:
5076   //   When a parameter of reference type is not bound directly to
5077   //   an argument expression, the conversion sequence is the one
5078   //   required to convert the argument expression to the
5079   //   underlying type of the reference according to
5080   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5081   //   to copy-initializing a temporary of the underlying type with
5082   //   the argument expression. Any difference in top-level
5083   //   cv-qualification is subsumed by the initialization itself
5084   //   and does not constitute a conversion.
5085   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5086                               AllowedExplicit::None,
5087                               /*InOverloadResolution=*/false,
5088                               /*CStyle=*/false,
5089                               /*AllowObjCWritebackConversion=*/false,
5090                               /*AllowObjCConversionOnExplicit=*/false);
5091 
5092   // Of course, that's still a reference binding.
5093   if (ICS.isStandard()) {
5094     ICS.Standard.ReferenceBinding = true;
5095     ICS.Standard.IsLvalueReference = !isRValRef;
5096     ICS.Standard.BindsToFunctionLvalue = false;
5097     ICS.Standard.BindsToRvalue = true;
5098     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5099     ICS.Standard.ObjCLifetimeConversionBinding = false;
5100   } else if (ICS.isUserDefined()) {
5101     const ReferenceType *LValRefType =
5102         ICS.UserDefined.ConversionFunction->getReturnType()
5103             ->getAs<LValueReferenceType>();
5104 
5105     // C++ [over.ics.ref]p3:
5106     //   Except for an implicit object parameter, for which see 13.3.1, a
5107     //   standard conversion sequence cannot be formed if it requires [...]
5108     //   binding an rvalue reference to an lvalue other than a function
5109     //   lvalue.
5110     // Note that the function case is not possible here.
5111     if (isRValRef && LValRefType) {
5112       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5113       return ICS;
5114     }
5115 
5116     ICS.UserDefined.After.ReferenceBinding = true;
5117     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5118     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5119     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5120     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5121     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5122   }
5123 
5124   return ICS;
5125 }
5126 
5127 static ImplicitConversionSequence
5128 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5129                       bool SuppressUserConversions,
5130                       bool InOverloadResolution,
5131                       bool AllowObjCWritebackConversion,
5132                       bool AllowExplicit = false);
5133 
5134 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5135 /// initializer list From.
5136 static ImplicitConversionSequence
5137 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5138                   bool SuppressUserConversions,
5139                   bool InOverloadResolution,
5140                   bool AllowObjCWritebackConversion) {
5141   // C++11 [over.ics.list]p1:
5142   //   When an argument is an initializer list, it is not an expression and
5143   //   special rules apply for converting it to a parameter type.
5144 
5145   ImplicitConversionSequence Result;
5146   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5147 
5148   // We need a complete type for what follows.  With one C++20 exception,
5149   // incomplete types can never be initialized from init lists.
5150   QualType InitTy = ToType;
5151   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5152   if (AT && S.getLangOpts().CPlusPlus20)
5153     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5154       // C++20 allows list initialization of an incomplete array type.
5155       InitTy = IAT->getElementType();
5156   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5157     return Result;
5158 
5159   // C++20 [over.ics.list]/2:
5160   //   If the initializer list is a designated-initializer-list, a conversion
5161   //   is only possible if the parameter has an aggregate type
5162   //
5163   // FIXME: The exception for reference initialization here is not part of the
5164   // language rules, but follow other compilers in adding it as a tentative DR
5165   // resolution.
5166   bool IsDesignatedInit = From->hasDesignatedInit();
5167   if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5168       IsDesignatedInit)
5169     return Result;
5170 
5171   // Per DR1467:
5172   //   If the parameter type is a class X and the initializer list has a single
5173   //   element of type cv U, where U is X or a class derived from X, the
5174   //   implicit conversion sequence is the one required to convert the element
5175   //   to the parameter type.
5176   //
5177   //   Otherwise, if the parameter type is a character array [... ]
5178   //   and the initializer list has a single element that is an
5179   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5180   //   implicit conversion sequence is the identity conversion.
5181   if (From->getNumInits() == 1 && !IsDesignatedInit) {
5182     if (ToType->isRecordType()) {
5183       QualType InitType = From->getInit(0)->getType();
5184       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5185           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5186         return TryCopyInitialization(S, From->getInit(0), ToType,
5187                                      SuppressUserConversions,
5188                                      InOverloadResolution,
5189                                      AllowObjCWritebackConversion);
5190     }
5191 
5192     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5193       InitializedEntity Entity =
5194           InitializedEntity::InitializeParameter(S.Context, ToType,
5195                                                  /*Consumed=*/false);
5196       if (S.CanPerformCopyInitialization(Entity, From)) {
5197         Result.setStandard();
5198         Result.Standard.setAsIdentityConversion();
5199         Result.Standard.setFromType(ToType);
5200         Result.Standard.setAllToTypes(ToType);
5201         return Result;
5202       }
5203     }
5204   }
5205 
5206   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5207   // C++11 [over.ics.list]p2:
5208   //   If the parameter type is std::initializer_list<X> or "array of X" and
5209   //   all the elements can be implicitly converted to X, the implicit
5210   //   conversion sequence is the worst conversion necessary to convert an
5211   //   element of the list to X.
5212   //
5213   // C++14 [over.ics.list]p3:
5214   //   Otherwise, if the parameter type is "array of N X", if the initializer
5215   //   list has exactly N elements or if it has fewer than N elements and X is
5216   //   default-constructible, and if all the elements of the initializer list
5217   //   can be implicitly converted to X, the implicit conversion sequence is
5218   //   the worst conversion necessary to convert an element of the list to X.
5219   if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5220     unsigned e = From->getNumInits();
5221     ImplicitConversionSequence DfltElt;
5222     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5223                    QualType());
5224     QualType ContTy = ToType;
5225     bool IsUnbounded = false;
5226     if (AT) {
5227       InitTy = AT->getElementType();
5228       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5229         if (CT->getSize().ult(e)) {
5230           // Too many inits, fatally bad
5231           Result.setBad(BadConversionSequence::too_many_initializers, From,
5232                         ToType);
5233           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5234           return Result;
5235         }
5236         if (CT->getSize().ugt(e)) {
5237           // Need an init from empty {}, is there one?
5238           InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5239                                  From->getEndLoc());
5240           EmptyList.setType(S.Context.VoidTy);
5241           DfltElt = TryListConversion(
5242               S, &EmptyList, InitTy, SuppressUserConversions,
5243               InOverloadResolution, AllowObjCWritebackConversion);
5244           if (DfltElt.isBad()) {
5245             // No {} init, fatally bad
5246             Result.setBad(BadConversionSequence::too_few_initializers, From,
5247                           ToType);
5248             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5249             return Result;
5250           }
5251         }
5252       } else {
5253         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5254         IsUnbounded = true;
5255         if (!e) {
5256           // Cannot convert to zero-sized.
5257           Result.setBad(BadConversionSequence::too_few_initializers, From,
5258                         ToType);
5259           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5260           return Result;
5261         }
5262         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5263         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5264                                                 ArrayType::Normal, 0);
5265       }
5266     }
5267 
5268     Result.setStandard();
5269     Result.Standard.setAsIdentityConversion();
5270     Result.Standard.setFromType(InitTy);
5271     Result.Standard.setAllToTypes(InitTy);
5272     for (unsigned i = 0; i < e; ++i) {
5273       Expr *Init = From->getInit(i);
5274       ImplicitConversionSequence ICS = TryCopyInitialization(
5275           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5276           AllowObjCWritebackConversion);
5277 
5278       // Keep the worse conversion seen so far.
5279       // FIXME: Sequences are not totally ordered, so 'worse' can be
5280       // ambiguous. CWG has been informed.
5281       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5282                                              Result) ==
5283           ImplicitConversionSequence::Worse) {
5284         Result = ICS;
5285         // Bail as soon as we find something unconvertible.
5286         if (Result.isBad()) {
5287           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5288           return Result;
5289         }
5290       }
5291     }
5292 
5293     // If we needed any implicit {} initialization, compare that now.
5294     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5295     // has been informed that this might not be the best thing.
5296     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5297                                 S, From->getEndLoc(), DfltElt, Result) ==
5298                                 ImplicitConversionSequence::Worse)
5299       Result = DfltElt;
5300     // Record the type being initialized so that we may compare sequences
5301     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5302     return Result;
5303   }
5304 
5305   // C++14 [over.ics.list]p4:
5306   // C++11 [over.ics.list]p3:
5307   //   Otherwise, if the parameter is a non-aggregate class X and overload
5308   //   resolution chooses a single best constructor [...] the implicit
5309   //   conversion sequence is a user-defined conversion sequence. If multiple
5310   //   constructors are viable but none is better than the others, the
5311   //   implicit conversion sequence is a user-defined conversion sequence.
5312   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5313     // This function can deal with initializer lists.
5314     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5315                                     AllowedExplicit::None,
5316                                     InOverloadResolution, /*CStyle=*/false,
5317                                     AllowObjCWritebackConversion,
5318                                     /*AllowObjCConversionOnExplicit=*/false);
5319   }
5320 
5321   // C++14 [over.ics.list]p5:
5322   // C++11 [over.ics.list]p4:
5323   //   Otherwise, if the parameter has an aggregate type which can be
5324   //   initialized from the initializer list [...] the implicit conversion
5325   //   sequence is a user-defined conversion sequence.
5326   if (ToType->isAggregateType()) {
5327     // Type is an aggregate, argument is an init list. At this point it comes
5328     // down to checking whether the initialization works.
5329     // FIXME: Find out whether this parameter is consumed or not.
5330     InitializedEntity Entity =
5331         InitializedEntity::InitializeParameter(S.Context, ToType,
5332                                                /*Consumed=*/false);
5333     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5334                                                                  From)) {
5335       Result.setUserDefined();
5336       Result.UserDefined.Before.setAsIdentityConversion();
5337       // Initializer lists don't have a type.
5338       Result.UserDefined.Before.setFromType(QualType());
5339       Result.UserDefined.Before.setAllToTypes(QualType());
5340 
5341       Result.UserDefined.After.setAsIdentityConversion();
5342       Result.UserDefined.After.setFromType(ToType);
5343       Result.UserDefined.After.setAllToTypes(ToType);
5344       Result.UserDefined.ConversionFunction = nullptr;
5345     }
5346     return Result;
5347   }
5348 
5349   // C++14 [over.ics.list]p6:
5350   // C++11 [over.ics.list]p5:
5351   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5352   if (ToType->isReferenceType()) {
5353     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5354     // mention initializer lists in any way. So we go by what list-
5355     // initialization would do and try to extrapolate from that.
5356 
5357     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5358 
5359     // If the initializer list has a single element that is reference-related
5360     // to the parameter type, we initialize the reference from that.
5361     if (From->getNumInits() == 1 && !IsDesignatedInit) {
5362       Expr *Init = From->getInit(0);
5363 
5364       QualType T2 = Init->getType();
5365 
5366       // If the initializer is the address of an overloaded function, try
5367       // to resolve the overloaded function. If all goes well, T2 is the
5368       // type of the resulting function.
5369       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5370         DeclAccessPair Found;
5371         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5372                                    Init, ToType, false, Found))
5373           T2 = Fn->getType();
5374       }
5375 
5376       // Compute some basic properties of the types and the initializer.
5377       Sema::ReferenceCompareResult RefRelationship =
5378           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5379 
5380       if (RefRelationship >= Sema::Ref_Related) {
5381         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5382                                 SuppressUserConversions,
5383                                 /*AllowExplicit=*/false);
5384       }
5385     }
5386 
5387     // Otherwise, we bind the reference to a temporary created from the
5388     // initializer list.
5389     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5390                                InOverloadResolution,
5391                                AllowObjCWritebackConversion);
5392     if (Result.isFailure())
5393       return Result;
5394     assert(!Result.isEllipsis() &&
5395            "Sub-initialization cannot result in ellipsis conversion.");
5396 
5397     // Can we even bind to a temporary?
5398     if (ToType->isRValueReferenceType() ||
5399         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5400       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5401                                             Result.UserDefined.After;
5402       SCS.ReferenceBinding = true;
5403       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5404       SCS.BindsToRvalue = true;
5405       SCS.BindsToFunctionLvalue = false;
5406       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5407       SCS.ObjCLifetimeConversionBinding = false;
5408     } else
5409       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5410                     From, ToType);
5411     return Result;
5412   }
5413 
5414   // C++14 [over.ics.list]p7:
5415   // C++11 [over.ics.list]p6:
5416   //   Otherwise, if the parameter type is not a class:
5417   if (!ToType->isRecordType()) {
5418     //    - if the initializer list has one element that is not itself an
5419     //      initializer list, the implicit conversion sequence is the one
5420     //      required to convert the element to the parameter type.
5421     unsigned NumInits = From->getNumInits();
5422     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5423       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5424                                      SuppressUserConversions,
5425                                      InOverloadResolution,
5426                                      AllowObjCWritebackConversion);
5427     //    - if the initializer list has no elements, the implicit conversion
5428     //      sequence is the identity conversion.
5429     else if (NumInits == 0) {
5430       Result.setStandard();
5431       Result.Standard.setAsIdentityConversion();
5432       Result.Standard.setFromType(ToType);
5433       Result.Standard.setAllToTypes(ToType);
5434     }
5435     return Result;
5436   }
5437 
5438   // C++14 [over.ics.list]p8:
5439   // C++11 [over.ics.list]p7:
5440   //   In all cases other than those enumerated above, no conversion is possible
5441   return Result;
5442 }
5443 
5444 /// TryCopyInitialization - Try to copy-initialize a value of type
5445 /// ToType from the expression From. Return the implicit conversion
5446 /// sequence required to pass this argument, which may be a bad
5447 /// conversion sequence (meaning that the argument cannot be passed to
5448 /// a parameter of this type). If @p SuppressUserConversions, then we
5449 /// do not permit any user-defined conversion sequences.
5450 static ImplicitConversionSequence
5451 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5452                       bool SuppressUserConversions,
5453                       bool InOverloadResolution,
5454                       bool AllowObjCWritebackConversion,
5455                       bool AllowExplicit) {
5456   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5457     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5458                              InOverloadResolution,AllowObjCWritebackConversion);
5459 
5460   if (ToType->isReferenceType())
5461     return TryReferenceInit(S, From, ToType,
5462                             /*FIXME:*/ From->getBeginLoc(),
5463                             SuppressUserConversions, AllowExplicit);
5464 
5465   return TryImplicitConversion(S, From, ToType,
5466                                SuppressUserConversions,
5467                                AllowedExplicit::None,
5468                                InOverloadResolution,
5469                                /*CStyle=*/false,
5470                                AllowObjCWritebackConversion,
5471                                /*AllowObjCConversionOnExplicit=*/false);
5472 }
5473 
5474 static bool TryCopyInitialization(const CanQualType FromQTy,
5475                                   const CanQualType ToQTy,
5476                                   Sema &S,
5477                                   SourceLocation Loc,
5478                                   ExprValueKind FromVK) {
5479   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5480   ImplicitConversionSequence ICS =
5481     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5482 
5483   return !ICS.isBad();
5484 }
5485 
5486 /// TryObjectArgumentInitialization - Try to initialize the object
5487 /// parameter of the given member function (@c Method) from the
5488 /// expression @p From.
5489 static ImplicitConversionSequence
5490 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5491                                 Expr::Classification FromClassification,
5492                                 CXXMethodDecl *Method,
5493                                 CXXRecordDecl *ActingContext) {
5494   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5495   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5496   //                 const volatile object.
5497   Qualifiers Quals = Method->getMethodQualifiers();
5498   if (isa<CXXDestructorDecl>(Method)) {
5499     Quals.addConst();
5500     Quals.addVolatile();
5501   }
5502 
5503   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5504 
5505   // Set up the conversion sequence as a "bad" conversion, to allow us
5506   // to exit early.
5507   ImplicitConversionSequence ICS;
5508 
5509   // We need to have an object of class type.
5510   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5511     FromType = PT->getPointeeType();
5512 
5513     // When we had a pointer, it's implicitly dereferenced, so we
5514     // better have an lvalue.
5515     assert(FromClassification.isLValue());
5516   }
5517 
5518   assert(FromType->isRecordType());
5519 
5520   // C++0x [over.match.funcs]p4:
5521   //   For non-static member functions, the type of the implicit object
5522   //   parameter is
5523   //
5524   //     - "lvalue reference to cv X" for functions declared without a
5525   //        ref-qualifier or with the & ref-qualifier
5526   //     - "rvalue reference to cv X" for functions declared with the &&
5527   //        ref-qualifier
5528   //
5529   // where X is the class of which the function is a member and cv is the
5530   // cv-qualification on the member function declaration.
5531   //
5532   // However, when finding an implicit conversion sequence for the argument, we
5533   // are not allowed to perform user-defined conversions
5534   // (C++ [over.match.funcs]p5). We perform a simplified version of
5535   // reference binding here, that allows class rvalues to bind to
5536   // non-constant references.
5537 
5538   // First check the qualifiers.
5539   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5540   if (ImplicitParamType.getCVRQualifiers()
5541                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5542       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5543     ICS.setBad(BadConversionSequence::bad_qualifiers,
5544                FromType, ImplicitParamType);
5545     return ICS;
5546   }
5547 
5548   if (FromTypeCanon.hasAddressSpace()) {
5549     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5550     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5551     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5552       ICS.setBad(BadConversionSequence::bad_qualifiers,
5553                  FromType, ImplicitParamType);
5554       return ICS;
5555     }
5556   }
5557 
5558   // Check that we have either the same type or a derived type. It
5559   // affects the conversion rank.
5560   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5561   ImplicitConversionKind SecondKind;
5562   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5563     SecondKind = ICK_Identity;
5564   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5565     SecondKind = ICK_Derived_To_Base;
5566   else {
5567     ICS.setBad(BadConversionSequence::unrelated_class,
5568                FromType, ImplicitParamType);
5569     return ICS;
5570   }
5571 
5572   // Check the ref-qualifier.
5573   switch (Method->getRefQualifier()) {
5574   case RQ_None:
5575     // Do nothing; we don't care about lvalueness or rvalueness.
5576     break;
5577 
5578   case RQ_LValue:
5579     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5580       // non-const lvalue reference cannot bind to an rvalue
5581       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5582                  ImplicitParamType);
5583       return ICS;
5584     }
5585     break;
5586 
5587   case RQ_RValue:
5588     if (!FromClassification.isRValue()) {
5589       // rvalue reference cannot bind to an lvalue
5590       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5591                  ImplicitParamType);
5592       return ICS;
5593     }
5594     break;
5595   }
5596 
5597   // Success. Mark this as a reference binding.
5598   ICS.setStandard();
5599   ICS.Standard.setAsIdentityConversion();
5600   ICS.Standard.Second = SecondKind;
5601   ICS.Standard.setFromType(FromType);
5602   ICS.Standard.setAllToTypes(ImplicitParamType);
5603   ICS.Standard.ReferenceBinding = true;
5604   ICS.Standard.DirectBinding = true;
5605   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5606   ICS.Standard.BindsToFunctionLvalue = false;
5607   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5608   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5609     = (Method->getRefQualifier() == RQ_None);
5610   return ICS;
5611 }
5612 
5613 /// PerformObjectArgumentInitialization - Perform initialization of
5614 /// the implicit object parameter for the given Method with the given
5615 /// expression.
5616 ExprResult
5617 Sema::PerformObjectArgumentInitialization(Expr *From,
5618                                           NestedNameSpecifier *Qualifier,
5619                                           NamedDecl *FoundDecl,
5620                                           CXXMethodDecl *Method) {
5621   QualType FromRecordType, DestType;
5622   QualType ImplicitParamRecordType  =
5623     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5624 
5625   Expr::Classification FromClassification;
5626   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5627     FromRecordType = PT->getPointeeType();
5628     DestType = Method->getThisType();
5629     FromClassification = Expr::Classification::makeSimpleLValue();
5630   } else {
5631     FromRecordType = From->getType();
5632     DestType = ImplicitParamRecordType;
5633     FromClassification = From->Classify(Context);
5634 
5635     // When performing member access on a prvalue, materialize a temporary.
5636     if (From->isPRValue()) {
5637       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5638                                             Method->getRefQualifier() !=
5639                                                 RefQualifierKind::RQ_RValue);
5640     }
5641   }
5642 
5643   // Note that we always use the true parent context when performing
5644   // the actual argument initialization.
5645   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5646       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5647       Method->getParent());
5648   if (ICS.isBad()) {
5649     switch (ICS.Bad.Kind) {
5650     case BadConversionSequence::bad_qualifiers: {
5651       Qualifiers FromQs = FromRecordType.getQualifiers();
5652       Qualifiers ToQs = DestType.getQualifiers();
5653       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5654       if (CVR) {
5655         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5656             << Method->getDeclName() << FromRecordType << (CVR - 1)
5657             << From->getSourceRange();
5658         Diag(Method->getLocation(), diag::note_previous_decl)
5659           << Method->getDeclName();
5660         return ExprError();
5661       }
5662       break;
5663     }
5664 
5665     case BadConversionSequence::lvalue_ref_to_rvalue:
5666     case BadConversionSequence::rvalue_ref_to_lvalue: {
5667       bool IsRValueQualified =
5668         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5669       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5670           << Method->getDeclName() << FromClassification.isRValue()
5671           << IsRValueQualified;
5672       Diag(Method->getLocation(), diag::note_previous_decl)
5673         << Method->getDeclName();
5674       return ExprError();
5675     }
5676 
5677     case BadConversionSequence::no_conversion:
5678     case BadConversionSequence::unrelated_class:
5679       break;
5680 
5681     case BadConversionSequence::too_few_initializers:
5682     case BadConversionSequence::too_many_initializers:
5683       llvm_unreachable("Lists are not objects");
5684     }
5685 
5686     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5687            << ImplicitParamRecordType << FromRecordType
5688            << From->getSourceRange();
5689   }
5690 
5691   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5692     ExprResult FromRes =
5693       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5694     if (FromRes.isInvalid())
5695       return ExprError();
5696     From = FromRes.get();
5697   }
5698 
5699   if (!Context.hasSameType(From->getType(), DestType)) {
5700     CastKind CK;
5701     QualType PteeTy = DestType->getPointeeType();
5702     LangAS DestAS =
5703         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5704     if (FromRecordType.getAddressSpace() != DestAS)
5705       CK = CK_AddressSpaceConversion;
5706     else
5707       CK = CK_NoOp;
5708     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5709   }
5710   return From;
5711 }
5712 
5713 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5714 /// expression From to bool (C++0x [conv]p3).
5715 static ImplicitConversionSequence
5716 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5717   // C++ [dcl.init]/17.8:
5718   //   - Otherwise, if the initialization is direct-initialization, the source
5719   //     type is std::nullptr_t, and the destination type is bool, the initial
5720   //     value of the object being initialized is false.
5721   if (From->getType()->isNullPtrType())
5722     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5723                                                         S.Context.BoolTy,
5724                                                         From->isGLValue());
5725 
5726   // All other direct-initialization of bool is equivalent to an implicit
5727   // conversion to bool in which explicit conversions are permitted.
5728   return TryImplicitConversion(S, From, S.Context.BoolTy,
5729                                /*SuppressUserConversions=*/false,
5730                                AllowedExplicit::Conversions,
5731                                /*InOverloadResolution=*/false,
5732                                /*CStyle=*/false,
5733                                /*AllowObjCWritebackConversion=*/false,
5734                                /*AllowObjCConversionOnExplicit=*/false);
5735 }
5736 
5737 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5738 /// of the expression From to bool (C++0x [conv]p3).
5739 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5740   if (checkPlaceholderForOverload(*this, From))
5741     return ExprError();
5742 
5743   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5744   if (!ICS.isBad())
5745     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5746 
5747   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5748     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5749            << From->getType() << From->getSourceRange();
5750   return ExprError();
5751 }
5752 
5753 /// Check that the specified conversion is permitted in a converted constant
5754 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5755 /// is acceptable.
5756 static bool CheckConvertedConstantConversions(Sema &S,
5757                                               StandardConversionSequence &SCS) {
5758   // Since we know that the target type is an integral or unscoped enumeration
5759   // type, most conversion kinds are impossible. All possible First and Third
5760   // conversions are fine.
5761   switch (SCS.Second) {
5762   case ICK_Identity:
5763   case ICK_Integral_Promotion:
5764   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5765   case ICK_Zero_Queue_Conversion:
5766     return true;
5767 
5768   case ICK_Boolean_Conversion:
5769     // Conversion from an integral or unscoped enumeration type to bool is
5770     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5771     // conversion, so we allow it in a converted constant expression.
5772     //
5773     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5774     // a lot of popular code. We should at least add a warning for this
5775     // (non-conforming) extension.
5776     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5777            SCS.getToType(2)->isBooleanType();
5778 
5779   case ICK_Pointer_Conversion:
5780   case ICK_Pointer_Member:
5781     // C++1z: null pointer conversions and null member pointer conversions are
5782     // only permitted if the source type is std::nullptr_t.
5783     return SCS.getFromType()->isNullPtrType();
5784 
5785   case ICK_Floating_Promotion:
5786   case ICK_Complex_Promotion:
5787   case ICK_Floating_Conversion:
5788   case ICK_Complex_Conversion:
5789   case ICK_Floating_Integral:
5790   case ICK_Compatible_Conversion:
5791   case ICK_Derived_To_Base:
5792   case ICK_Vector_Conversion:
5793   case ICK_SVE_Vector_Conversion:
5794   case ICK_RVV_Vector_Conversion:
5795   case ICK_Vector_Splat:
5796   case ICK_Complex_Real:
5797   case ICK_Block_Pointer_Conversion:
5798   case ICK_TransparentUnionConversion:
5799   case ICK_Writeback_Conversion:
5800   case ICK_Zero_Event_Conversion:
5801   case ICK_C_Only_Conversion:
5802   case ICK_Incompatible_Pointer_Conversion:
5803     return false;
5804 
5805   case ICK_Lvalue_To_Rvalue:
5806   case ICK_Array_To_Pointer:
5807   case ICK_Function_To_Pointer:
5808     llvm_unreachable("found a first conversion kind in Second");
5809 
5810   case ICK_Function_Conversion:
5811   case ICK_Qualification:
5812     llvm_unreachable("found a third conversion kind in Second");
5813 
5814   case ICK_Num_Conversion_Kinds:
5815     break;
5816   }
5817 
5818   llvm_unreachable("unknown conversion kind");
5819 }
5820 
5821 /// BuildConvertedConstantExpression - Check that the expression From is a
5822 /// converted constant expression of type T, perform the conversion but
5823 /// does not evaluate the expression
5824 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
5825                                                    QualType T,
5826                                                    Sema::CCEKind CCE,
5827                                                    NamedDecl *Dest,
5828                                                    APValue &PreNarrowingValue) {
5829   assert(S.getLangOpts().CPlusPlus11 &&
5830          "converted constant expression outside C++11");
5831 
5832   if (checkPlaceholderForOverload(S, From))
5833     return ExprError();
5834 
5835   // C++1z [expr.const]p3:
5836   //  A converted constant expression of type T is an expression,
5837   //  implicitly converted to type T, where the converted
5838   //  expression is a constant expression and the implicit conversion
5839   //  sequence contains only [... list of conversions ...].
5840   ImplicitConversionSequence ICS =
5841       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5842           ? TryContextuallyConvertToBool(S, From)
5843           : TryCopyInitialization(S, From, T,
5844                                   /*SuppressUserConversions=*/false,
5845                                   /*InOverloadResolution=*/false,
5846                                   /*AllowObjCWritebackConversion=*/false,
5847                                   /*AllowExplicit=*/false);
5848   StandardConversionSequence *SCS = nullptr;
5849   switch (ICS.getKind()) {
5850   case ImplicitConversionSequence::StandardConversion:
5851     SCS = &ICS.Standard;
5852     break;
5853   case ImplicitConversionSequence::UserDefinedConversion:
5854     if (T->isRecordType())
5855       SCS = &ICS.UserDefined.Before;
5856     else
5857       SCS = &ICS.UserDefined.After;
5858     break;
5859   case ImplicitConversionSequence::AmbiguousConversion:
5860   case ImplicitConversionSequence::BadConversion:
5861     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5862       return S.Diag(From->getBeginLoc(),
5863                     diag::err_typecheck_converted_constant_expression)
5864              << From->getType() << From->getSourceRange() << T;
5865     return ExprError();
5866 
5867   case ImplicitConversionSequence::EllipsisConversion:
5868   case ImplicitConversionSequence::StaticObjectArgumentConversion:
5869     llvm_unreachable("bad conversion in converted constant expression");
5870   }
5871 
5872   // Check that we would only use permitted conversions.
5873   if (!CheckConvertedConstantConversions(S, *SCS)) {
5874     return S.Diag(From->getBeginLoc(),
5875                   diag::err_typecheck_converted_constant_expression_disallowed)
5876            << From->getType() << From->getSourceRange() << T;
5877   }
5878   // [...] and where the reference binding (if any) binds directly.
5879   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5880     return S.Diag(From->getBeginLoc(),
5881                   diag::err_typecheck_converted_constant_expression_indirect)
5882            << From->getType() << From->getSourceRange() << T;
5883   }
5884 
5885   // Usually we can simply apply the ImplicitConversionSequence we formed
5886   // earlier, but that's not guaranteed to work when initializing an object of
5887   // class type.
5888   ExprResult Result;
5889   if (T->isRecordType()) {
5890     assert(CCE == Sema::CCEK_TemplateArg &&
5891            "unexpected class type converted constant expr");
5892     Result = S.PerformCopyInitialization(
5893         InitializedEntity::InitializeTemplateParameter(
5894             T, cast<NonTypeTemplateParmDecl>(Dest)),
5895         SourceLocation(), From);
5896   } else {
5897     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5898   }
5899   if (Result.isInvalid())
5900     return Result;
5901 
5902   // C++2a [intro.execution]p5:
5903   //   A full-expression is [...] a constant-expression [...]
5904   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5905                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
5906                                  CCE == Sema::CCEKind::CCEK_TemplateArg);
5907   if (Result.isInvalid())
5908     return Result;
5909 
5910   // Check for a narrowing implicit conversion.
5911   bool ReturnPreNarrowingValue = false;
5912   QualType PreNarrowingType;
5913   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5914                                 PreNarrowingType)) {
5915   case NK_Dependent_Narrowing:
5916     // Implicit conversion to a narrower type, but the expression is
5917     // value-dependent so we can't tell whether it's actually narrowing.
5918   case NK_Variable_Narrowing:
5919     // Implicit conversion to a narrower type, and the value is not a constant
5920     // expression. We'll diagnose this in a moment.
5921   case NK_Not_Narrowing:
5922     break;
5923 
5924   case NK_Constant_Narrowing:
5925     if (CCE == Sema::CCEK_ArrayBound &&
5926         PreNarrowingType->isIntegralOrEnumerationType() &&
5927         PreNarrowingValue.isInt()) {
5928       // Don't diagnose array bound narrowing here; we produce more precise
5929       // errors by allowing the un-narrowed value through.
5930       ReturnPreNarrowingValue = true;
5931       break;
5932     }
5933     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5934         << CCE << /*Constant*/ 1
5935         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5936     break;
5937 
5938   case NK_Type_Narrowing:
5939     // FIXME: It would be better to diagnose that the expression is not a
5940     // constant expression.
5941     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5942         << CCE << /*Constant*/ 0 << From->getType() << T;
5943     break;
5944   }
5945   if (!ReturnPreNarrowingValue)
5946     PreNarrowingValue = {};
5947 
5948   return Result;
5949 }
5950 
5951 /// EvaluateConvertedConstantExpression - Evaluate an Expression
5952 /// That is a converted constant expression
5953 /// (which was built with BuildConvertedConstantExpression)
5954 static ExprResult EvaluateConvertedConstantExpression(
5955     Sema &S, Expr *E, QualType T, APValue &Value, Sema::CCEKind CCE,
5956     bool RequireInt, const APValue &PreNarrowingValue) {
5957   ExprResult Result = E;
5958   // Check the expression is a constant expression.
5959   SmallVector<PartialDiagnosticAt, 8> Notes;
5960   Expr::EvalResult Eval;
5961   Eval.Diag = &Notes;
5962 
5963   ConstantExprKind Kind;
5964   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5965     Kind = ConstantExprKind::ClassTemplateArgument;
5966   else if (CCE == Sema::CCEK_TemplateArg)
5967     Kind = ConstantExprKind::NonClassTemplateArgument;
5968   else
5969     Kind = ConstantExprKind::Normal;
5970 
5971   if (!E->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5972       (RequireInt && !Eval.Val.isInt())) {
5973     // The expression can't be folded, so we can't keep it at this position in
5974     // the AST.
5975     Result = ExprError();
5976   } else {
5977     Value = Eval.Val;
5978 
5979     if (Notes.empty()) {
5980       // It's a constant expression.
5981       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5982       if (!PreNarrowingValue.isAbsent())
5983         Value = std::move(PreNarrowingValue);
5984       return E;
5985     }
5986   }
5987 
5988   // It's not a constant expression. Produce an appropriate diagnostic.
5989   if (Notes.size() == 1 &&
5990       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5991     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5992   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5993                                    diag::note_constexpr_invalid_template_arg) {
5994     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5995     for (unsigned I = 0; I < Notes.size(); ++I)
5996       S.Diag(Notes[I].first, Notes[I].second);
5997   } else {
5998     S.Diag(E->getBeginLoc(), diag::err_expr_not_cce)
5999         << CCE << E->getSourceRange();
6000     for (unsigned I = 0; I < Notes.size(); ++I)
6001       S.Diag(Notes[I].first, Notes[I].second);
6002   }
6003   return ExprError();
6004 }
6005 
6006 /// CheckConvertedConstantExpression - Check that the expression From is a
6007 /// converted constant expression of type T, perform the conversion and produce
6008 /// the converted expression, per C++11 [expr.const]p3.
6009 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6010                                                    QualType T, APValue &Value,
6011                                                    Sema::CCEKind CCE,
6012                                                    bool RequireInt,
6013                                                    NamedDecl *Dest) {
6014 
6015   APValue PreNarrowingValue;
6016   ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6017                                                        PreNarrowingValue);
6018   if (Result.isInvalid() || Result.get()->isValueDependent()) {
6019     Value = APValue();
6020     return Result;
6021   }
6022   return EvaluateConvertedConstantExpression(S, Result.get(), T, Value, CCE,
6023                                              RequireInt, PreNarrowingValue);
6024 }
6025 
6026 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6027                                                   CCEKind CCE,
6028                                                   NamedDecl *Dest) {
6029   APValue PreNarrowingValue;
6030   return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6031                                             PreNarrowingValue);
6032 }
6033 
6034 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6035                                                   APValue &Value, CCEKind CCE,
6036                                                   NamedDecl *Dest) {
6037   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6038                                             Dest);
6039 }
6040 
6041 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6042                                                   llvm::APSInt &Value,
6043                                                   CCEKind CCE) {
6044   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6045 
6046   APValue V;
6047   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6048                                               /*Dest=*/nullptr);
6049   if (!R.isInvalid() && !R.get()->isValueDependent())
6050     Value = V.getInt();
6051   return R;
6052 }
6053 
6054 
6055 /// dropPointerConversions - If the given standard conversion sequence
6056 /// involves any pointer conversions, remove them.  This may change
6057 /// the result type of the conversion sequence.
6058 static void dropPointerConversion(StandardConversionSequence &SCS) {
6059   if (SCS.Second == ICK_Pointer_Conversion) {
6060     SCS.Second = ICK_Identity;
6061     SCS.Third = ICK_Identity;
6062     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6063   }
6064 }
6065 
6066 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6067 /// convert the expression From to an Objective-C pointer type.
6068 static ImplicitConversionSequence
6069 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6070   // Do an implicit conversion to 'id'.
6071   QualType Ty = S.Context.getObjCIdType();
6072   ImplicitConversionSequence ICS
6073     = TryImplicitConversion(S, From, Ty,
6074                             // FIXME: Are these flags correct?
6075                             /*SuppressUserConversions=*/false,
6076                             AllowedExplicit::Conversions,
6077                             /*InOverloadResolution=*/false,
6078                             /*CStyle=*/false,
6079                             /*AllowObjCWritebackConversion=*/false,
6080                             /*AllowObjCConversionOnExplicit=*/true);
6081 
6082   // Strip off any final conversions to 'id'.
6083   switch (ICS.getKind()) {
6084   case ImplicitConversionSequence::BadConversion:
6085   case ImplicitConversionSequence::AmbiguousConversion:
6086   case ImplicitConversionSequence::EllipsisConversion:
6087   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6088     break;
6089 
6090   case ImplicitConversionSequence::UserDefinedConversion:
6091     dropPointerConversion(ICS.UserDefined.After);
6092     break;
6093 
6094   case ImplicitConversionSequence::StandardConversion:
6095     dropPointerConversion(ICS.Standard);
6096     break;
6097   }
6098 
6099   return ICS;
6100 }
6101 
6102 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6103 /// conversion of the expression From to an Objective-C pointer type.
6104 /// Returns a valid but null ExprResult if no conversion sequence exists.
6105 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6106   if (checkPlaceholderForOverload(*this, From))
6107     return ExprError();
6108 
6109   QualType Ty = Context.getObjCIdType();
6110   ImplicitConversionSequence ICS =
6111     TryContextuallyConvertToObjCPointer(*this, From);
6112   if (!ICS.isBad())
6113     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6114   return ExprResult();
6115 }
6116 
6117 /// Determine whether the provided type is an integral type, or an enumeration
6118 /// type of a permitted flavor.
6119 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6120   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6121                                  : T->isIntegralOrUnscopedEnumerationType();
6122 }
6123 
6124 static ExprResult
6125 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6126                             Sema::ContextualImplicitConverter &Converter,
6127                             QualType T, UnresolvedSetImpl &ViableConversions) {
6128 
6129   if (Converter.Suppress)
6130     return ExprError();
6131 
6132   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6133   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6134     CXXConversionDecl *Conv =
6135         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6136     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6137     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6138   }
6139   return From;
6140 }
6141 
6142 static bool
6143 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6144                            Sema::ContextualImplicitConverter &Converter,
6145                            QualType T, bool HadMultipleCandidates,
6146                            UnresolvedSetImpl &ExplicitConversions) {
6147   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6148     DeclAccessPair Found = ExplicitConversions[0];
6149     CXXConversionDecl *Conversion =
6150         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6151 
6152     // The user probably meant to invoke the given explicit
6153     // conversion; use it.
6154     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6155     std::string TypeStr;
6156     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6157 
6158     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6159         << FixItHint::CreateInsertion(From->getBeginLoc(),
6160                                       "static_cast<" + TypeStr + ">(")
6161         << FixItHint::CreateInsertion(
6162                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6163     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6164 
6165     // If we aren't in a SFINAE context, build a call to the
6166     // explicit conversion function.
6167     if (SemaRef.isSFINAEContext())
6168       return true;
6169 
6170     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6171     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6172                                                        HadMultipleCandidates);
6173     if (Result.isInvalid())
6174       return true;
6175     // Record usage of conversion in an implicit cast.
6176     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6177                                     CK_UserDefinedConversion, Result.get(),
6178                                     nullptr, Result.get()->getValueKind(),
6179                                     SemaRef.CurFPFeatureOverrides());
6180   }
6181   return false;
6182 }
6183 
6184 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6185                              Sema::ContextualImplicitConverter &Converter,
6186                              QualType T, bool HadMultipleCandidates,
6187                              DeclAccessPair &Found) {
6188   CXXConversionDecl *Conversion =
6189       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6190   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6191 
6192   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6193   if (!Converter.SuppressConversion) {
6194     if (SemaRef.isSFINAEContext())
6195       return true;
6196 
6197     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6198         << From->getSourceRange();
6199   }
6200 
6201   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6202                                                      HadMultipleCandidates);
6203   if (Result.isInvalid())
6204     return true;
6205   // Record usage of conversion in an implicit cast.
6206   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6207                                   CK_UserDefinedConversion, Result.get(),
6208                                   nullptr, Result.get()->getValueKind(),
6209                                   SemaRef.CurFPFeatureOverrides());
6210   return false;
6211 }
6212 
6213 static ExprResult finishContextualImplicitConversion(
6214     Sema &SemaRef, SourceLocation Loc, Expr *From,
6215     Sema::ContextualImplicitConverter &Converter) {
6216   if (!Converter.match(From->getType()) && !Converter.Suppress)
6217     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6218         << From->getSourceRange();
6219 
6220   return SemaRef.DefaultLvalueConversion(From);
6221 }
6222 
6223 static void
6224 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6225                                   UnresolvedSetImpl &ViableConversions,
6226                                   OverloadCandidateSet &CandidateSet) {
6227   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6228     DeclAccessPair FoundDecl = ViableConversions[I];
6229     NamedDecl *D = FoundDecl.getDecl();
6230     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6231     if (isa<UsingShadowDecl>(D))
6232       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6233 
6234     CXXConversionDecl *Conv;
6235     FunctionTemplateDecl *ConvTemplate;
6236     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6237       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6238     else
6239       Conv = cast<CXXConversionDecl>(D);
6240 
6241     if (ConvTemplate)
6242       SemaRef.AddTemplateConversionCandidate(
6243           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6244           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6245     else
6246       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6247                                      ToType, CandidateSet,
6248                                      /*AllowObjCConversionOnExplicit=*/false,
6249                                      /*AllowExplicit*/ true);
6250   }
6251 }
6252 
6253 /// Attempt to convert the given expression to a type which is accepted
6254 /// by the given converter.
6255 ///
6256 /// This routine will attempt to convert an expression of class type to a
6257 /// type accepted by the specified converter. In C++11 and before, the class
6258 /// must have a single non-explicit conversion function converting to a matching
6259 /// type. In C++1y, there can be multiple such conversion functions, but only
6260 /// one target type.
6261 ///
6262 /// \param Loc The source location of the construct that requires the
6263 /// conversion.
6264 ///
6265 /// \param From The expression we're converting from.
6266 ///
6267 /// \param Converter Used to control and diagnose the conversion process.
6268 ///
6269 /// \returns The expression, converted to an integral or enumeration type if
6270 /// successful.
6271 ExprResult Sema::PerformContextualImplicitConversion(
6272     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6273   // We can't perform any more checking for type-dependent expressions.
6274   if (From->isTypeDependent())
6275     return From;
6276 
6277   // Process placeholders immediately.
6278   if (From->hasPlaceholderType()) {
6279     ExprResult result = CheckPlaceholderExpr(From);
6280     if (result.isInvalid())
6281       return result;
6282     From = result.get();
6283   }
6284 
6285   // If the expression already has a matching type, we're golden.
6286   QualType T = From->getType();
6287   if (Converter.match(T))
6288     return DefaultLvalueConversion(From);
6289 
6290   // FIXME: Check for missing '()' if T is a function type?
6291 
6292   // We can only perform contextual implicit conversions on objects of class
6293   // type.
6294   const RecordType *RecordTy = T->getAs<RecordType>();
6295   if (!RecordTy || !getLangOpts().CPlusPlus) {
6296     if (!Converter.Suppress)
6297       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6298     return From;
6299   }
6300 
6301   // We must have a complete class type.
6302   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6303     ContextualImplicitConverter &Converter;
6304     Expr *From;
6305 
6306     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6307         : Converter(Converter), From(From) {}
6308 
6309     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6310       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6311     }
6312   } IncompleteDiagnoser(Converter, From);
6313 
6314   if (Converter.Suppress ? !isCompleteType(Loc, T)
6315                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6316     return From;
6317 
6318   // Look for a conversion to an integral or enumeration type.
6319   UnresolvedSet<4>
6320       ViableConversions; // These are *potentially* viable in C++1y.
6321   UnresolvedSet<4> ExplicitConversions;
6322   const auto &Conversions =
6323       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6324 
6325   bool HadMultipleCandidates =
6326       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6327 
6328   // To check that there is only one target type, in C++1y:
6329   QualType ToType;
6330   bool HasUniqueTargetType = true;
6331 
6332   // Collect explicit or viable (potentially in C++1y) conversions.
6333   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6334     NamedDecl *D = (*I)->getUnderlyingDecl();
6335     CXXConversionDecl *Conversion;
6336     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6337     if (ConvTemplate) {
6338       if (getLangOpts().CPlusPlus14)
6339         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6340       else
6341         continue; // C++11 does not consider conversion operator templates(?).
6342     } else
6343       Conversion = cast<CXXConversionDecl>(D);
6344 
6345     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6346            "Conversion operator templates are considered potentially "
6347            "viable in C++1y");
6348 
6349     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6350     if (Converter.match(CurToType) || ConvTemplate) {
6351 
6352       if (Conversion->isExplicit()) {
6353         // FIXME: For C++1y, do we need this restriction?
6354         // cf. diagnoseNoViableConversion()
6355         if (!ConvTemplate)
6356           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6357       } else {
6358         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6359           if (ToType.isNull())
6360             ToType = CurToType.getUnqualifiedType();
6361           else if (HasUniqueTargetType &&
6362                    (CurToType.getUnqualifiedType() != ToType))
6363             HasUniqueTargetType = false;
6364         }
6365         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6366       }
6367     }
6368   }
6369 
6370   if (getLangOpts().CPlusPlus14) {
6371     // C++1y [conv]p6:
6372     // ... An expression e of class type E appearing in such a context
6373     // is said to be contextually implicitly converted to a specified
6374     // type T and is well-formed if and only if e can be implicitly
6375     // converted to a type T that is determined as follows: E is searched
6376     // for conversion functions whose return type is cv T or reference to
6377     // cv T such that T is allowed by the context. There shall be
6378     // exactly one such T.
6379 
6380     // If no unique T is found:
6381     if (ToType.isNull()) {
6382       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6383                                      HadMultipleCandidates,
6384                                      ExplicitConversions))
6385         return ExprError();
6386       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6387     }
6388 
6389     // If more than one unique Ts are found:
6390     if (!HasUniqueTargetType)
6391       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6392                                          ViableConversions);
6393 
6394     // If one unique T is found:
6395     // First, build a candidate set from the previously recorded
6396     // potentially viable conversions.
6397     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6398     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6399                                       CandidateSet);
6400 
6401     // Then, perform overload resolution over the candidate set.
6402     OverloadCandidateSet::iterator Best;
6403     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6404     case OR_Success: {
6405       // Apply this conversion.
6406       DeclAccessPair Found =
6407           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6408       if (recordConversion(*this, Loc, From, Converter, T,
6409                            HadMultipleCandidates, Found))
6410         return ExprError();
6411       break;
6412     }
6413     case OR_Ambiguous:
6414       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6415                                          ViableConversions);
6416     case OR_No_Viable_Function:
6417       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6418                                      HadMultipleCandidates,
6419                                      ExplicitConversions))
6420         return ExprError();
6421       [[fallthrough]];
6422     case OR_Deleted:
6423       // We'll complain below about a non-integral condition type.
6424       break;
6425     }
6426   } else {
6427     switch (ViableConversions.size()) {
6428     case 0: {
6429       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6430                                      HadMultipleCandidates,
6431                                      ExplicitConversions))
6432         return ExprError();
6433 
6434       // We'll complain below about a non-integral condition type.
6435       break;
6436     }
6437     case 1: {
6438       // Apply this conversion.
6439       DeclAccessPair Found = ViableConversions[0];
6440       if (recordConversion(*this, Loc, From, Converter, T,
6441                            HadMultipleCandidates, Found))
6442         return ExprError();
6443       break;
6444     }
6445     default:
6446       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6447                                          ViableConversions);
6448     }
6449   }
6450 
6451   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6452 }
6453 
6454 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6455 /// an acceptable non-member overloaded operator for a call whose
6456 /// arguments have types T1 (and, if non-empty, T2). This routine
6457 /// implements the check in C++ [over.match.oper]p3b2 concerning
6458 /// enumeration types.
6459 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6460                                                    FunctionDecl *Fn,
6461                                                    ArrayRef<Expr *> Args) {
6462   QualType T1 = Args[0]->getType();
6463   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6464 
6465   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6466     return true;
6467 
6468   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6469     return true;
6470 
6471   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6472   if (Proto->getNumParams() < 1)
6473     return false;
6474 
6475   if (T1->isEnumeralType()) {
6476     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6477     if (Context.hasSameUnqualifiedType(T1, ArgType))
6478       return true;
6479   }
6480 
6481   if (Proto->getNumParams() < 2)
6482     return false;
6483 
6484   if (!T2.isNull() && T2->isEnumeralType()) {
6485     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6486     if (Context.hasSameUnqualifiedType(T2, ArgType))
6487       return true;
6488   }
6489 
6490   return false;
6491 }
6492 
6493 /// AddOverloadCandidate - Adds the given function to the set of
6494 /// candidate functions, using the given function call arguments.  If
6495 /// @p SuppressUserConversions, then don't allow user-defined
6496 /// conversions via constructors or conversion operators.
6497 ///
6498 /// \param PartialOverloading true if we are performing "partial" overloading
6499 /// based on an incomplete set of function arguments. This feature is used by
6500 /// code completion.
6501 void Sema::AddOverloadCandidate(
6502     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6503     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6504     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6505     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6506     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6507   const FunctionProtoType *Proto
6508     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6509   assert(Proto && "Functions without a prototype cannot be overloaded");
6510   assert(!Function->getDescribedFunctionTemplate() &&
6511          "Use AddTemplateOverloadCandidate for function templates");
6512 
6513   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6514     if (!isa<CXXConstructorDecl>(Method)) {
6515       // If we get here, it's because we're calling a member function
6516       // that is named without a member access expression (e.g.,
6517       // "this->f") that was either written explicitly or created
6518       // implicitly. This can happen with a qualified call to a member
6519       // function, e.g., X::f(). We use an empty type for the implied
6520       // object argument (C++ [over.call.func]p3), and the acting context
6521       // is irrelevant.
6522       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6523                          Expr::Classification::makeSimpleLValue(), Args,
6524                          CandidateSet, SuppressUserConversions,
6525                          PartialOverloading, EarlyConversions, PO);
6526       return;
6527     }
6528     // We treat a constructor like a non-member function, since its object
6529     // argument doesn't participate in overload resolution.
6530   }
6531 
6532   if (!CandidateSet.isNewCandidate(Function, PO))
6533     return;
6534 
6535   // C++11 [class.copy]p11: [DR1402]
6536   //   A defaulted move constructor that is defined as deleted is ignored by
6537   //   overload resolution.
6538   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6539   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6540       Constructor->isMoveConstructor())
6541     return;
6542 
6543   // Overload resolution is always an unevaluated context.
6544   EnterExpressionEvaluationContext Unevaluated(
6545       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6546 
6547   // C++ [over.match.oper]p3:
6548   //   if no operand has a class type, only those non-member functions in the
6549   //   lookup set that have a first parameter of type T1 or "reference to
6550   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6551   //   is a right operand) a second parameter of type T2 or "reference to
6552   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6553   //   candidate functions.
6554   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6555       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6556     return;
6557 
6558   // Add this candidate
6559   OverloadCandidate &Candidate =
6560       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6561   Candidate.FoundDecl = FoundDecl;
6562   Candidate.Function = Function;
6563   Candidate.Viable = true;
6564   Candidate.RewriteKind =
6565       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6566   Candidate.IsSurrogate = false;
6567   Candidate.IsADLCandidate = IsADLCandidate;
6568   Candidate.IgnoreObjectArgument = false;
6569   Candidate.ExplicitCallArguments = Args.size();
6570 
6571   // Explicit functions are not actually candidates at all if we're not
6572   // allowing them in this context, but keep them around so we can point
6573   // to them in diagnostics.
6574   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6575     Candidate.Viable = false;
6576     Candidate.FailureKind = ovl_fail_explicit;
6577     return;
6578   }
6579 
6580   // Functions with internal linkage are only viable in the same module unit.
6581   if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6582     /// FIXME: Currently, the semantics of linkage in clang is slightly
6583     /// different from the semantics in C++ spec. In C++ spec, only names
6584     /// have linkage. So that all entities of the same should share one
6585     /// linkage. But in clang, different entities of the same could have
6586     /// different linkage.
6587     NamedDecl *ND = Function;
6588     if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6589       ND = SpecInfo->getTemplate();
6590 
6591     if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6592       Candidate.Viable = false;
6593       Candidate.FailureKind = ovl_fail_module_mismatched;
6594       return;
6595     }
6596   }
6597 
6598   if (Function->isMultiVersion() &&
6599       ((Function->hasAttr<TargetAttr>() &&
6600         !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6601        (Function->hasAttr<TargetVersionAttr>() &&
6602         !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6603     Candidate.Viable = false;
6604     Candidate.FailureKind = ovl_non_default_multiversion_function;
6605     return;
6606   }
6607 
6608   if (Constructor) {
6609     // C++ [class.copy]p3:
6610     //   A member function template is never instantiated to perform the copy
6611     //   of a class object to an object of its class type.
6612     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6613     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6614         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6615          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6616                        ClassType))) {
6617       Candidate.Viable = false;
6618       Candidate.FailureKind = ovl_fail_illegal_constructor;
6619       return;
6620     }
6621 
6622     // C++ [over.match.funcs]p8: (proposed DR resolution)
6623     //   A constructor inherited from class type C that has a first parameter
6624     //   of type "reference to P" (including such a constructor instantiated
6625     //   from a template) is excluded from the set of candidate functions when
6626     //   constructing an object of type cv D if the argument list has exactly
6627     //   one argument and D is reference-related to P and P is reference-related
6628     //   to C.
6629     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6630     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6631         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6632       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6633       QualType C = Context.getRecordType(Constructor->getParent());
6634       QualType D = Context.getRecordType(Shadow->getParent());
6635       SourceLocation Loc = Args.front()->getExprLoc();
6636       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6637           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6638         Candidate.Viable = false;
6639         Candidate.FailureKind = ovl_fail_inhctor_slice;
6640         return;
6641       }
6642     }
6643 
6644     // Check that the constructor is capable of constructing an object in the
6645     // destination address space.
6646     if (!Qualifiers::isAddressSpaceSupersetOf(
6647             Constructor->getMethodQualifiers().getAddressSpace(),
6648             CandidateSet.getDestAS())) {
6649       Candidate.Viable = false;
6650       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6651     }
6652   }
6653 
6654   unsigned NumParams = Proto->getNumParams();
6655 
6656   // (C++ 13.3.2p2): A candidate function having fewer than m
6657   // parameters is viable only if it has an ellipsis in its parameter
6658   // list (8.3.5).
6659   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6660       !Proto->isVariadic() &&
6661       shouldEnforceArgLimit(PartialOverloading, Function)) {
6662     Candidate.Viable = false;
6663     Candidate.FailureKind = ovl_fail_too_many_arguments;
6664     return;
6665   }
6666 
6667   // (C++ 13.3.2p2): A candidate function having more than m parameters
6668   // is viable only if the (m+1)st parameter has a default argument
6669   // (8.3.6). For the purposes of overload resolution, the
6670   // parameter list is truncated on the right, so that there are
6671   // exactly m parameters.
6672   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6673   if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6674       !PartialOverloading) {
6675     // Not enough arguments.
6676     Candidate.Viable = false;
6677     Candidate.FailureKind = ovl_fail_too_few_arguments;
6678     return;
6679   }
6680 
6681   // (CUDA B.1): Check for invalid calls between targets.
6682   if (getLangOpts().CUDA)
6683     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6684       // Skip the check for callers that are implicit members, because in this
6685       // case we may not yet know what the member's target is; the target is
6686       // inferred for the member automatically, based on the bases and fields of
6687       // the class.
6688       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6689         Candidate.Viable = false;
6690         Candidate.FailureKind = ovl_fail_bad_target;
6691         return;
6692       }
6693 
6694   if (Function->getTrailingRequiresClause()) {
6695     ConstraintSatisfaction Satisfaction;
6696     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6697                                  /*ForOverloadResolution*/ true) ||
6698         !Satisfaction.IsSatisfied) {
6699       Candidate.Viable = false;
6700       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6701       return;
6702     }
6703   }
6704 
6705   // Determine the implicit conversion sequences for each of the
6706   // arguments.
6707   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6708     unsigned ConvIdx =
6709         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6710     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6711       // We already formed a conversion sequence for this parameter during
6712       // template argument deduction.
6713     } else if (ArgIdx < NumParams) {
6714       // (C++ 13.3.2p3): for F to be a viable function, there shall
6715       // exist for each argument an implicit conversion sequence
6716       // (13.3.3.1) that converts that argument to the corresponding
6717       // parameter of F.
6718       QualType ParamType = Proto->getParamType(ArgIdx);
6719       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6720           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6721           /*InOverloadResolution=*/true,
6722           /*AllowObjCWritebackConversion=*/
6723           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6724       if (Candidate.Conversions[ConvIdx].isBad()) {
6725         Candidate.Viable = false;
6726         Candidate.FailureKind = ovl_fail_bad_conversion;
6727         return;
6728       }
6729     } else {
6730       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6731       // argument for which there is no corresponding parameter is
6732       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6733       Candidate.Conversions[ConvIdx].setEllipsis();
6734     }
6735   }
6736 
6737   if (EnableIfAttr *FailedAttr =
6738           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6739     Candidate.Viable = false;
6740     Candidate.FailureKind = ovl_fail_enable_if;
6741     Candidate.DeductionFailure.Data = FailedAttr;
6742     return;
6743   }
6744 }
6745 
6746 ObjCMethodDecl *
6747 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6748                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6749   if (Methods.size() <= 1)
6750     return nullptr;
6751 
6752   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6753     bool Match = true;
6754     ObjCMethodDecl *Method = Methods[b];
6755     unsigned NumNamedArgs = Sel.getNumArgs();
6756     // Method might have more arguments than selector indicates. This is due
6757     // to addition of c-style arguments in method.
6758     if (Method->param_size() > NumNamedArgs)
6759       NumNamedArgs = Method->param_size();
6760     if (Args.size() < NumNamedArgs)
6761       continue;
6762 
6763     for (unsigned i = 0; i < NumNamedArgs; i++) {
6764       // We can't do any type-checking on a type-dependent argument.
6765       if (Args[i]->isTypeDependent()) {
6766         Match = false;
6767         break;
6768       }
6769 
6770       ParmVarDecl *param = Method->parameters()[i];
6771       Expr *argExpr = Args[i];
6772       assert(argExpr && "SelectBestMethod(): missing expression");
6773 
6774       // Strip the unbridged-cast placeholder expression off unless it's
6775       // a consumed argument.
6776       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6777           !param->hasAttr<CFConsumedAttr>())
6778         argExpr = stripARCUnbridgedCast(argExpr);
6779 
6780       // If the parameter is __unknown_anytype, move on to the next method.
6781       if (param->getType() == Context.UnknownAnyTy) {
6782         Match = false;
6783         break;
6784       }
6785 
6786       ImplicitConversionSequence ConversionState
6787         = TryCopyInitialization(*this, argExpr, param->getType(),
6788                                 /*SuppressUserConversions*/false,
6789                                 /*InOverloadResolution=*/true,
6790                                 /*AllowObjCWritebackConversion=*/
6791                                 getLangOpts().ObjCAutoRefCount,
6792                                 /*AllowExplicit*/false);
6793       // This function looks for a reasonably-exact match, so we consider
6794       // incompatible pointer conversions to be a failure here.
6795       if (ConversionState.isBad() ||
6796           (ConversionState.isStandard() &&
6797            ConversionState.Standard.Second ==
6798                ICK_Incompatible_Pointer_Conversion)) {
6799         Match = false;
6800         break;
6801       }
6802     }
6803     // Promote additional arguments to variadic methods.
6804     if (Match && Method->isVariadic()) {
6805       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6806         if (Args[i]->isTypeDependent()) {
6807           Match = false;
6808           break;
6809         }
6810         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6811                                                           nullptr);
6812         if (Arg.isInvalid()) {
6813           Match = false;
6814           break;
6815         }
6816       }
6817     } else {
6818       // Check for extra arguments to non-variadic methods.
6819       if (Args.size() != NumNamedArgs)
6820         Match = false;
6821       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6822         // Special case when selectors have no argument. In this case, select
6823         // one with the most general result type of 'id'.
6824         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6825           QualType ReturnT = Methods[b]->getReturnType();
6826           if (ReturnT->isObjCIdType())
6827             return Methods[b];
6828         }
6829       }
6830     }
6831 
6832     if (Match)
6833       return Method;
6834   }
6835   return nullptr;
6836 }
6837 
6838 static bool convertArgsForAvailabilityChecks(
6839     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6840     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6841     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6842   if (ThisArg) {
6843     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6844     assert(!isa<CXXConstructorDecl>(Method) &&
6845            "Shouldn't have `this` for ctors!");
6846     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6847     ExprResult R = S.PerformObjectArgumentInitialization(
6848         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6849     if (R.isInvalid())
6850       return false;
6851     ConvertedThis = R.get();
6852   } else {
6853     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6854       (void)MD;
6855       assert((MissingImplicitThis || MD->isStatic() ||
6856               isa<CXXConstructorDecl>(MD)) &&
6857              "Expected `this` for non-ctor instance methods");
6858     }
6859     ConvertedThis = nullptr;
6860   }
6861 
6862   // Ignore any variadic arguments. Converting them is pointless, since the
6863   // user can't refer to them in the function condition.
6864   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6865 
6866   // Convert the arguments.
6867   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6868     ExprResult R;
6869     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6870                                         S.Context, Function->getParamDecl(I)),
6871                                     SourceLocation(), Args[I]);
6872 
6873     if (R.isInvalid())
6874       return false;
6875 
6876     ConvertedArgs.push_back(R.get());
6877   }
6878 
6879   if (Trap.hasErrorOccurred())
6880     return false;
6881 
6882   // Push default arguments if needed.
6883   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6884     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6885       ParmVarDecl *P = Function->getParamDecl(i);
6886       if (!P->hasDefaultArg())
6887         return false;
6888       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6889       if (R.isInvalid())
6890         return false;
6891       ConvertedArgs.push_back(R.get());
6892     }
6893 
6894     if (Trap.hasErrorOccurred())
6895       return false;
6896   }
6897   return true;
6898 }
6899 
6900 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6901                                   SourceLocation CallLoc,
6902                                   ArrayRef<Expr *> Args,
6903                                   bool MissingImplicitThis) {
6904   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6905   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6906     return nullptr;
6907 
6908   SFINAETrap Trap(*this);
6909   SmallVector<Expr *, 16> ConvertedArgs;
6910   // FIXME: We should look into making enable_if late-parsed.
6911   Expr *DiscardedThis;
6912   if (!convertArgsForAvailabilityChecks(
6913           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6914           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6915     return *EnableIfAttrs.begin();
6916 
6917   for (auto *EIA : EnableIfAttrs) {
6918     APValue Result;
6919     // FIXME: This doesn't consider value-dependent cases, because doing so is
6920     // very difficult. Ideally, we should handle them more gracefully.
6921     if (EIA->getCond()->isValueDependent() ||
6922         !EIA->getCond()->EvaluateWithSubstitution(
6923             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
6924       return EIA;
6925 
6926     if (!Result.isInt() || !Result.getInt().getBoolValue())
6927       return EIA;
6928   }
6929   return nullptr;
6930 }
6931 
6932 template <typename CheckFn>
6933 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6934                                         bool ArgDependent, SourceLocation Loc,
6935                                         CheckFn &&IsSuccessful) {
6936   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6937   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6938     if (ArgDependent == DIA->getArgDependent())
6939       Attrs.push_back(DIA);
6940   }
6941 
6942   // Common case: No diagnose_if attributes, so we can quit early.
6943   if (Attrs.empty())
6944     return false;
6945 
6946   auto WarningBegin = std::stable_partition(
6947       Attrs.begin(), Attrs.end(),
6948       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6949 
6950   // Note that diagnose_if attributes are late-parsed, so they appear in the
6951   // correct order (unlike enable_if attributes).
6952   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6953                                IsSuccessful);
6954   if (ErrAttr != WarningBegin) {
6955     const DiagnoseIfAttr *DIA = *ErrAttr;
6956     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6957     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6958         << DIA->getParent() << DIA->getCond()->getSourceRange();
6959     return true;
6960   }
6961 
6962   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6963     if (IsSuccessful(DIA)) {
6964       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6965       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6966           << DIA->getParent() << DIA->getCond()->getSourceRange();
6967     }
6968 
6969   return false;
6970 }
6971 
6972 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6973                                                const Expr *ThisArg,
6974                                                ArrayRef<const Expr *> Args,
6975                                                SourceLocation Loc) {
6976   return diagnoseDiagnoseIfAttrsWith(
6977       *this, Function, /*ArgDependent=*/true, Loc,
6978       [&](const DiagnoseIfAttr *DIA) {
6979         APValue Result;
6980         // It's sane to use the same Args for any redecl of this function, since
6981         // EvaluateWithSubstitution only cares about the position of each
6982         // argument in the arg list, not the ParmVarDecl* it maps to.
6983         if (!DIA->getCond()->EvaluateWithSubstitution(
6984                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6985           return false;
6986         return Result.isInt() && Result.getInt().getBoolValue();
6987       });
6988 }
6989 
6990 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6991                                                  SourceLocation Loc) {
6992   return diagnoseDiagnoseIfAttrsWith(
6993       *this, ND, /*ArgDependent=*/false, Loc,
6994       [&](const DiagnoseIfAttr *DIA) {
6995         bool Result;
6996         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6997                Result;
6998       });
6999 }
7000 
7001 /// Add all of the function declarations in the given function set to
7002 /// the overload candidate set.
7003 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7004                                  ArrayRef<Expr *> Args,
7005                                  OverloadCandidateSet &CandidateSet,
7006                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7007                                  bool SuppressUserConversions,
7008                                  bool PartialOverloading,
7009                                  bool FirstArgumentIsBase) {
7010   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7011     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7012     ArrayRef<Expr *> FunctionArgs = Args;
7013 
7014     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7015     FunctionDecl *FD =
7016         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7017 
7018     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7019       QualType ObjectType;
7020       Expr::Classification ObjectClassification;
7021       if (Args.size() > 0) {
7022         if (Expr *E = Args[0]) {
7023           // Use the explicit base to restrict the lookup:
7024           ObjectType = E->getType();
7025           // Pointers in the object arguments are implicitly dereferenced, so we
7026           // always classify them as l-values.
7027           if (!ObjectType.isNull() && ObjectType->isPointerType())
7028             ObjectClassification = Expr::Classification::makeSimpleLValue();
7029           else
7030             ObjectClassification = E->Classify(Context);
7031         } // .. else there is an implicit base.
7032         FunctionArgs = Args.slice(1);
7033       }
7034       if (FunTmpl) {
7035         AddMethodTemplateCandidate(
7036             FunTmpl, F.getPair(),
7037             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7038             ExplicitTemplateArgs, ObjectType, ObjectClassification,
7039             FunctionArgs, CandidateSet, SuppressUserConversions,
7040             PartialOverloading);
7041       } else {
7042         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7043                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7044                            ObjectClassification, FunctionArgs, CandidateSet,
7045                            SuppressUserConversions, PartialOverloading);
7046       }
7047     } else {
7048       // This branch handles both standalone functions and static methods.
7049 
7050       // Slice the first argument (which is the base) when we access
7051       // static method as non-static.
7052       if (Args.size() > 0 &&
7053           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7054                         !isa<CXXConstructorDecl>(FD)))) {
7055         assert(cast<CXXMethodDecl>(FD)->isStatic());
7056         FunctionArgs = Args.slice(1);
7057       }
7058       if (FunTmpl) {
7059         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7060                                      ExplicitTemplateArgs, FunctionArgs,
7061                                      CandidateSet, SuppressUserConversions,
7062                                      PartialOverloading);
7063       } else {
7064         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7065                              SuppressUserConversions, PartialOverloading);
7066       }
7067     }
7068   }
7069 }
7070 
7071 /// AddMethodCandidate - Adds a named decl (which is some kind of
7072 /// method) as a method candidate to the given overload set.
7073 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7074                               Expr::Classification ObjectClassification,
7075                               ArrayRef<Expr *> Args,
7076                               OverloadCandidateSet &CandidateSet,
7077                               bool SuppressUserConversions,
7078                               OverloadCandidateParamOrder PO) {
7079   NamedDecl *Decl = FoundDecl.getDecl();
7080   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7081 
7082   if (isa<UsingShadowDecl>(Decl))
7083     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7084 
7085   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7086     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7087            "Expected a member function template");
7088     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7089                                /*ExplicitArgs*/ nullptr, ObjectType,
7090                                ObjectClassification, Args, CandidateSet,
7091                                SuppressUserConversions, false, PO);
7092   } else {
7093     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7094                        ObjectType, ObjectClassification, Args, CandidateSet,
7095                        SuppressUserConversions, false, std::nullopt, PO);
7096   }
7097 }
7098 
7099 /// AddMethodCandidate - Adds the given C++ member function to the set
7100 /// of candidate functions, using the given function call arguments
7101 /// and the object argument (@c Object). For example, in a call
7102 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7103 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7104 /// allow user-defined conversions via constructors or conversion
7105 /// operators.
7106 void
7107 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7108                          CXXRecordDecl *ActingContext, QualType ObjectType,
7109                          Expr::Classification ObjectClassification,
7110                          ArrayRef<Expr *> Args,
7111                          OverloadCandidateSet &CandidateSet,
7112                          bool SuppressUserConversions,
7113                          bool PartialOverloading,
7114                          ConversionSequenceList EarlyConversions,
7115                          OverloadCandidateParamOrder PO) {
7116   const FunctionProtoType *Proto
7117     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7118   assert(Proto && "Methods without a prototype cannot be overloaded");
7119   assert(!isa<CXXConstructorDecl>(Method) &&
7120          "Use AddOverloadCandidate for constructors");
7121 
7122   if (!CandidateSet.isNewCandidate(Method, PO))
7123     return;
7124 
7125   // C++11 [class.copy]p23: [DR1402]
7126   //   A defaulted move assignment operator that is defined as deleted is
7127   //   ignored by overload resolution.
7128   if (Method->isDefaulted() && Method->isDeleted() &&
7129       Method->isMoveAssignmentOperator())
7130     return;
7131 
7132   // Overload resolution is always an unevaluated context.
7133   EnterExpressionEvaluationContext Unevaluated(
7134       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7135 
7136   // Add this candidate
7137   OverloadCandidate &Candidate =
7138       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7139   Candidate.FoundDecl = FoundDecl;
7140   Candidate.Function = Method;
7141   Candidate.RewriteKind =
7142       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7143   Candidate.IsSurrogate = false;
7144   Candidate.IgnoreObjectArgument = false;
7145   Candidate.ExplicitCallArguments = Args.size();
7146 
7147   unsigned NumParams = Proto->getNumParams();
7148 
7149   // (C++ 13.3.2p2): A candidate function having fewer than m
7150   // parameters is viable only if it has an ellipsis in its parameter
7151   // list (8.3.5).
7152   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7153       !Proto->isVariadic() &&
7154       shouldEnforceArgLimit(PartialOverloading, Method)) {
7155     Candidate.Viable = false;
7156     Candidate.FailureKind = ovl_fail_too_many_arguments;
7157     return;
7158   }
7159 
7160   // (C++ 13.3.2p2): A candidate function having more than m parameters
7161   // is viable only if the (m+1)st parameter has a default argument
7162   // (8.3.6). For the purposes of overload resolution, the
7163   // parameter list is truncated on the right, so that there are
7164   // exactly m parameters.
7165   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
7166   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7167     // Not enough arguments.
7168     Candidate.Viable = false;
7169     Candidate.FailureKind = ovl_fail_too_few_arguments;
7170     return;
7171   }
7172 
7173   Candidate.Viable = true;
7174 
7175   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7176   if (ObjectType.isNull())
7177     Candidate.IgnoreObjectArgument = true;
7178   else if (Method->isStatic()) {
7179     // [over.best.ics.general]p8
7180     // When the parameter is the implicit object parameter of a static member
7181     // function, the implicit conversion sequence is a standard conversion
7182     // sequence that is neither better nor worse than any other standard
7183     // conversion sequence.
7184     //
7185     // This is a rule that was introduced in C++23 to support static lambdas. We
7186     // apply it retroactively because we want to support static lambdas as an
7187     // extension and it doesn't hurt previous code.
7188     Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7189   } else {
7190     // Determine the implicit conversion sequence for the object
7191     // parameter.
7192     Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7193         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7194         Method, ActingContext);
7195     if (Candidate.Conversions[FirstConvIdx].isBad()) {
7196       Candidate.Viable = false;
7197       Candidate.FailureKind = ovl_fail_bad_conversion;
7198       return;
7199     }
7200   }
7201 
7202   // (CUDA B.1): Check for invalid calls between targets.
7203   if (getLangOpts().CUDA)
7204     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7205       if (!IsAllowedCUDACall(Caller, Method)) {
7206         Candidate.Viable = false;
7207         Candidate.FailureKind = ovl_fail_bad_target;
7208         return;
7209       }
7210 
7211   if (Method->getTrailingRequiresClause()) {
7212     ConstraintSatisfaction Satisfaction;
7213     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7214                                  /*ForOverloadResolution*/ true) ||
7215         !Satisfaction.IsSatisfied) {
7216       Candidate.Viable = false;
7217       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7218       return;
7219     }
7220   }
7221 
7222   // Determine the implicit conversion sequences for each of the
7223   // arguments.
7224   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7225     unsigned ConvIdx =
7226         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7227     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7228       // We already formed a conversion sequence for this parameter during
7229       // template argument deduction.
7230     } else if (ArgIdx < NumParams) {
7231       // (C++ 13.3.2p3): for F to be a viable function, there shall
7232       // exist for each argument an implicit conversion sequence
7233       // (13.3.3.1) that converts that argument to the corresponding
7234       // parameter of F.
7235       QualType ParamType = Proto->getParamType(ArgIdx);
7236       Candidate.Conversions[ConvIdx]
7237         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7238                                 SuppressUserConversions,
7239                                 /*InOverloadResolution=*/true,
7240                                 /*AllowObjCWritebackConversion=*/
7241                                   getLangOpts().ObjCAutoRefCount);
7242       if (Candidate.Conversions[ConvIdx].isBad()) {
7243         Candidate.Viable = false;
7244         Candidate.FailureKind = ovl_fail_bad_conversion;
7245         return;
7246       }
7247     } else {
7248       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7249       // argument for which there is no corresponding parameter is
7250       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7251       Candidate.Conversions[ConvIdx].setEllipsis();
7252     }
7253   }
7254 
7255   if (EnableIfAttr *FailedAttr =
7256           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7257     Candidate.Viable = false;
7258     Candidate.FailureKind = ovl_fail_enable_if;
7259     Candidate.DeductionFailure.Data = FailedAttr;
7260     return;
7261   }
7262 
7263   if (Method->isMultiVersion() &&
7264       ((Method->hasAttr<TargetAttr>() &&
7265         !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7266        (Method->hasAttr<TargetVersionAttr>() &&
7267         !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7268     Candidate.Viable = false;
7269     Candidate.FailureKind = ovl_non_default_multiversion_function;
7270   }
7271 }
7272 
7273 /// Add a C++ member function template as a candidate to the candidate
7274 /// set, using template argument deduction to produce an appropriate member
7275 /// function template specialization.
7276 void Sema::AddMethodTemplateCandidate(
7277     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7278     CXXRecordDecl *ActingContext,
7279     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7280     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7281     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7282     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7283   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7284     return;
7285 
7286   // C++ [over.match.funcs]p7:
7287   //   In each case where a candidate is a function template, candidate
7288   //   function template specializations are generated using template argument
7289   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7290   //   candidate functions in the usual way.113) A given name can refer to one
7291   //   or more function templates and also to a set of overloaded non-template
7292   //   functions. In such a case, the candidate functions generated from each
7293   //   function template are combined with the set of non-template candidate
7294   //   functions.
7295   TemplateDeductionInfo Info(CandidateSet.getLocation());
7296   FunctionDecl *Specialization = nullptr;
7297   ConversionSequenceList Conversions;
7298   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7299           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7300           PartialOverloading, /*AggregateDeductionCandidate=*/false,
7301           [&](ArrayRef<QualType> ParamTypes) {
7302             return CheckNonDependentConversions(
7303                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7304                 SuppressUserConversions, ActingContext, ObjectType,
7305                 ObjectClassification, PO);
7306           })) {
7307     OverloadCandidate &Candidate =
7308         CandidateSet.addCandidate(Conversions.size(), Conversions);
7309     Candidate.FoundDecl = FoundDecl;
7310     Candidate.Function = MethodTmpl->getTemplatedDecl();
7311     Candidate.Viable = false;
7312     Candidate.RewriteKind =
7313       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7314     Candidate.IsSurrogate = false;
7315     Candidate.IgnoreObjectArgument =
7316         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7317         ObjectType.isNull();
7318     Candidate.ExplicitCallArguments = Args.size();
7319     if (Result == TDK_NonDependentConversionFailure)
7320       Candidate.FailureKind = ovl_fail_bad_conversion;
7321     else {
7322       Candidate.FailureKind = ovl_fail_bad_deduction;
7323       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7324                                                             Info);
7325     }
7326     return;
7327   }
7328 
7329   // Add the function template specialization produced by template argument
7330   // deduction as a candidate.
7331   assert(Specialization && "Missing member function template specialization?");
7332   assert(isa<CXXMethodDecl>(Specialization) &&
7333          "Specialization is not a member function?");
7334   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7335                      ActingContext, ObjectType, ObjectClassification, Args,
7336                      CandidateSet, SuppressUserConversions, PartialOverloading,
7337                      Conversions, PO);
7338 }
7339 
7340 /// Determine whether a given function template has a simple explicit specifier
7341 /// or a non-value-dependent explicit-specification that evaluates to true.
7342 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7343   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7344 }
7345 
7346 /// Add a C++ function template specialization as a candidate
7347 /// in the candidate set, using template argument deduction to produce
7348 /// an appropriate function template specialization.
7349 void Sema::AddTemplateOverloadCandidate(
7350     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7351     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7352     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7353     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7354     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7355   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7356     return;
7357 
7358   // If the function template has a non-dependent explicit specification,
7359   // exclude it now if appropriate; we are not permitted to perform deduction
7360   // and substitution in this case.
7361   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7362     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7363     Candidate.FoundDecl = FoundDecl;
7364     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7365     Candidate.Viable = false;
7366     Candidate.FailureKind = ovl_fail_explicit;
7367     return;
7368   }
7369 
7370   // C++ [over.match.funcs]p7:
7371   //   In each case where a candidate is a function template, candidate
7372   //   function template specializations are generated using template argument
7373   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7374   //   candidate functions in the usual way.113) A given name can refer to one
7375   //   or more function templates and also to a set of overloaded non-template
7376   //   functions. In such a case, the candidate functions generated from each
7377   //   function template are combined with the set of non-template candidate
7378   //   functions.
7379   TemplateDeductionInfo Info(CandidateSet.getLocation());
7380   FunctionDecl *Specialization = nullptr;
7381   ConversionSequenceList Conversions;
7382   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7383           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7384           PartialOverloading, AggregateCandidateDeduction,
7385           [&](ArrayRef<QualType> ParamTypes) {
7386             return CheckNonDependentConversions(
7387                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7388                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7389           })) {
7390     OverloadCandidate &Candidate =
7391         CandidateSet.addCandidate(Conversions.size(), Conversions);
7392     Candidate.FoundDecl = FoundDecl;
7393     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7394     Candidate.Viable = false;
7395     Candidate.RewriteKind =
7396       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7397     Candidate.IsSurrogate = false;
7398     Candidate.IsADLCandidate = IsADLCandidate;
7399     // Ignore the object argument if there is one, since we don't have an object
7400     // type.
7401     Candidate.IgnoreObjectArgument =
7402         isa<CXXMethodDecl>(Candidate.Function) &&
7403         !isa<CXXConstructorDecl>(Candidate.Function);
7404     Candidate.ExplicitCallArguments = Args.size();
7405     if (Result == TDK_NonDependentConversionFailure)
7406       Candidate.FailureKind = ovl_fail_bad_conversion;
7407     else {
7408       Candidate.FailureKind = ovl_fail_bad_deduction;
7409       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7410                                                             Info);
7411     }
7412     return;
7413   }
7414 
7415   // Add the function template specialization produced by template argument
7416   // deduction as a candidate.
7417   assert(Specialization && "Missing function template specialization?");
7418   AddOverloadCandidate(
7419       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7420       PartialOverloading, AllowExplicit,
7421       /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7422       Info.AggregateDeductionCandidateHasMismatchedArity);
7423 }
7424 
7425 /// Check that implicit conversion sequences can be formed for each argument
7426 /// whose corresponding parameter has a non-dependent type, per DR1391's
7427 /// [temp.deduct.call]p10.
7428 bool Sema::CheckNonDependentConversions(
7429     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7430     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7431     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7432     CXXRecordDecl *ActingContext, QualType ObjectType,
7433     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7434   // FIXME: The cases in which we allow explicit conversions for constructor
7435   // arguments never consider calling a constructor template. It's not clear
7436   // that is correct.
7437   const bool AllowExplicit = false;
7438 
7439   auto *FD = FunctionTemplate->getTemplatedDecl();
7440   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7441   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7442   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7443 
7444   Conversions =
7445       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7446 
7447   // Overload resolution is always an unevaluated context.
7448   EnterExpressionEvaluationContext Unevaluated(
7449       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7450 
7451   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7452   // require that, but this check should never result in a hard error, and
7453   // overload resolution is permitted to sidestep instantiations.
7454   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7455       !ObjectType.isNull()) {
7456     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7457     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7458         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7459         Method, ActingContext);
7460     if (Conversions[ConvIdx].isBad())
7461       return true;
7462   }
7463 
7464   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7465        ++I) {
7466     QualType ParamType = ParamTypes[I];
7467     if (!ParamType->isDependentType()) {
7468       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7469                              ? 0
7470                              : (ThisConversions + I);
7471       Conversions[ConvIdx]
7472         = TryCopyInitialization(*this, Args[I], ParamType,
7473                                 SuppressUserConversions,
7474                                 /*InOverloadResolution=*/true,
7475                                 /*AllowObjCWritebackConversion=*/
7476                                   getLangOpts().ObjCAutoRefCount,
7477                                 AllowExplicit);
7478       if (Conversions[ConvIdx].isBad())
7479         return true;
7480     }
7481   }
7482 
7483   return false;
7484 }
7485 
7486 /// Determine whether this is an allowable conversion from the result
7487 /// of an explicit conversion operator to the expected type, per C++
7488 /// [over.match.conv]p1 and [over.match.ref]p1.
7489 ///
7490 /// \param ConvType The return type of the conversion function.
7491 ///
7492 /// \param ToType The type we are converting to.
7493 ///
7494 /// \param AllowObjCPointerConversion Allow a conversion from one
7495 /// Objective-C pointer to another.
7496 ///
7497 /// \returns true if the conversion is allowable, false otherwise.
7498 static bool isAllowableExplicitConversion(Sema &S,
7499                                           QualType ConvType, QualType ToType,
7500                                           bool AllowObjCPointerConversion) {
7501   QualType ToNonRefType = ToType.getNonReferenceType();
7502 
7503   // Easy case: the types are the same.
7504   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7505     return true;
7506 
7507   // Allow qualification conversions.
7508   bool ObjCLifetimeConversion;
7509   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7510                                   ObjCLifetimeConversion))
7511     return true;
7512 
7513   // If we're not allowed to consider Objective-C pointer conversions,
7514   // we're done.
7515   if (!AllowObjCPointerConversion)
7516     return false;
7517 
7518   // Is this an Objective-C pointer conversion?
7519   bool IncompatibleObjC = false;
7520   QualType ConvertedType;
7521   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7522                                    IncompatibleObjC);
7523 }
7524 
7525 /// AddConversionCandidate - Add a C++ conversion function as a
7526 /// candidate in the candidate set (C++ [over.match.conv],
7527 /// C++ [over.match.copy]). From is the expression we're converting from,
7528 /// and ToType is the type that we're eventually trying to convert to
7529 /// (which may or may not be the same type as the type that the
7530 /// conversion function produces).
7531 void Sema::AddConversionCandidate(
7532     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7533     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7534     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7535     bool AllowExplicit, bool AllowResultConversion) {
7536   assert(!Conversion->getDescribedFunctionTemplate() &&
7537          "Conversion function templates use AddTemplateConversionCandidate");
7538   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7539   if (!CandidateSet.isNewCandidate(Conversion))
7540     return;
7541 
7542   // If the conversion function has an undeduced return type, trigger its
7543   // deduction now.
7544   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7545     if (DeduceReturnType(Conversion, From->getExprLoc()))
7546       return;
7547     ConvType = Conversion->getConversionType().getNonReferenceType();
7548   }
7549 
7550   // If we don't allow any conversion of the result type, ignore conversion
7551   // functions that don't convert to exactly (possibly cv-qualified) T.
7552   if (!AllowResultConversion &&
7553       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7554     return;
7555 
7556   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7557   // operator is only a candidate if its return type is the target type or
7558   // can be converted to the target type with a qualification conversion.
7559   //
7560   // FIXME: Include such functions in the candidate list and explain why we
7561   // can't select them.
7562   if (Conversion->isExplicit() &&
7563       !isAllowableExplicitConversion(*this, ConvType, ToType,
7564                                      AllowObjCConversionOnExplicit))
7565     return;
7566 
7567   // Overload resolution is always an unevaluated context.
7568   EnterExpressionEvaluationContext Unevaluated(
7569       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7570 
7571   // Add this candidate
7572   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7573   Candidate.FoundDecl = FoundDecl;
7574   Candidate.Function = Conversion;
7575   Candidate.IsSurrogate = false;
7576   Candidate.IgnoreObjectArgument = false;
7577   Candidate.FinalConversion.setAsIdentityConversion();
7578   Candidate.FinalConversion.setFromType(ConvType);
7579   Candidate.FinalConversion.setAllToTypes(ToType);
7580   Candidate.Viable = true;
7581   Candidate.ExplicitCallArguments = 1;
7582 
7583   // Explicit functions are not actually candidates at all if we're not
7584   // allowing them in this context, but keep them around so we can point
7585   // to them in diagnostics.
7586   if (!AllowExplicit && Conversion->isExplicit()) {
7587     Candidate.Viable = false;
7588     Candidate.FailureKind = ovl_fail_explicit;
7589     return;
7590   }
7591 
7592   // C++ [over.match.funcs]p4:
7593   //   For conversion functions, the function is considered to be a member of
7594   //   the class of the implicit implied object argument for the purpose of
7595   //   defining the type of the implicit object parameter.
7596   //
7597   // Determine the implicit conversion sequence for the implicit
7598   // object parameter.
7599   QualType ImplicitParamType = From->getType();
7600   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7601     ImplicitParamType = FromPtrType->getPointeeType();
7602   CXXRecordDecl *ConversionContext
7603     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7604 
7605   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7606       *this, CandidateSet.getLocation(), From->getType(),
7607       From->Classify(Context), Conversion, ConversionContext);
7608 
7609   if (Candidate.Conversions[0].isBad()) {
7610     Candidate.Viable = false;
7611     Candidate.FailureKind = ovl_fail_bad_conversion;
7612     return;
7613   }
7614 
7615   if (Conversion->getTrailingRequiresClause()) {
7616     ConstraintSatisfaction Satisfaction;
7617     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7618         !Satisfaction.IsSatisfied) {
7619       Candidate.Viable = false;
7620       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7621       return;
7622     }
7623   }
7624 
7625   // We won't go through a user-defined type conversion function to convert a
7626   // derived to base as such conversions are given Conversion Rank. They only
7627   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7628   QualType FromCanon
7629     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7630   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7631   if (FromCanon == ToCanon ||
7632       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7633     Candidate.Viable = false;
7634     Candidate.FailureKind = ovl_fail_trivial_conversion;
7635     return;
7636   }
7637 
7638   // To determine what the conversion from the result of calling the
7639   // conversion function to the type we're eventually trying to
7640   // convert to (ToType), we need to synthesize a call to the
7641   // conversion function and attempt copy initialization from it. This
7642   // makes sure that we get the right semantics with respect to
7643   // lvalues/rvalues and the type. Fortunately, we can allocate this
7644   // call on the stack and we don't need its arguments to be
7645   // well-formed.
7646   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7647                             VK_LValue, From->getBeginLoc());
7648   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7649                                 Context.getPointerType(Conversion->getType()),
7650                                 CK_FunctionToPointerDecay, &ConversionRef,
7651                                 VK_PRValue, FPOptionsOverride());
7652 
7653   QualType ConversionType = Conversion->getConversionType();
7654   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7655     Candidate.Viable = false;
7656     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7657     return;
7658   }
7659 
7660   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7661 
7662   // Note that it is safe to allocate CallExpr on the stack here because
7663   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7664   // allocator).
7665   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7666 
7667   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7668   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7669       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7670 
7671   ImplicitConversionSequence ICS =
7672       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7673                             /*SuppressUserConversions=*/true,
7674                             /*InOverloadResolution=*/false,
7675                             /*AllowObjCWritebackConversion=*/false);
7676 
7677   switch (ICS.getKind()) {
7678   case ImplicitConversionSequence::StandardConversion:
7679     Candidate.FinalConversion = ICS.Standard;
7680 
7681     // C++ [over.ics.user]p3:
7682     //   If the user-defined conversion is specified by a specialization of a
7683     //   conversion function template, the second standard conversion sequence
7684     //   shall have exact match rank.
7685     if (Conversion->getPrimaryTemplate() &&
7686         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7687       Candidate.Viable = false;
7688       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7689       return;
7690     }
7691 
7692     // C++0x [dcl.init.ref]p5:
7693     //    In the second case, if the reference is an rvalue reference and
7694     //    the second standard conversion sequence of the user-defined
7695     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7696     //    program is ill-formed.
7697     if (ToType->isRValueReferenceType() &&
7698         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7699       Candidate.Viable = false;
7700       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7701       return;
7702     }
7703     break;
7704 
7705   case ImplicitConversionSequence::BadConversion:
7706     Candidate.Viable = false;
7707     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7708     return;
7709 
7710   default:
7711     llvm_unreachable(
7712            "Can only end up with a standard conversion sequence or failure");
7713   }
7714 
7715   if (EnableIfAttr *FailedAttr =
7716           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7717     Candidate.Viable = false;
7718     Candidate.FailureKind = ovl_fail_enable_if;
7719     Candidate.DeductionFailure.Data = FailedAttr;
7720     return;
7721   }
7722 
7723   if (Conversion->isMultiVersion() &&
7724       ((Conversion->hasAttr<TargetAttr>() &&
7725         !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
7726        (Conversion->hasAttr<TargetVersionAttr>() &&
7727         !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7728     Candidate.Viable = false;
7729     Candidate.FailureKind = ovl_non_default_multiversion_function;
7730   }
7731 }
7732 
7733 /// Adds a conversion function template specialization
7734 /// candidate to the overload set, using template argument deduction
7735 /// to deduce the template arguments of the conversion function
7736 /// template from the type that we are converting to (C++
7737 /// [temp.deduct.conv]).
7738 void Sema::AddTemplateConversionCandidate(
7739     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7740     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7741     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7742     bool AllowExplicit, bool AllowResultConversion) {
7743   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7744          "Only conversion function templates permitted here");
7745 
7746   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7747     return;
7748 
7749   // If the function template has a non-dependent explicit specification,
7750   // exclude it now if appropriate; we are not permitted to perform deduction
7751   // and substitution in this case.
7752   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7753     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7754     Candidate.FoundDecl = FoundDecl;
7755     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7756     Candidate.Viable = false;
7757     Candidate.FailureKind = ovl_fail_explicit;
7758     return;
7759   }
7760 
7761   TemplateDeductionInfo Info(CandidateSet.getLocation());
7762   CXXConversionDecl *Specialization = nullptr;
7763   if (TemplateDeductionResult Result
7764         = DeduceTemplateArguments(FunctionTemplate, ToType,
7765                                   Specialization, Info)) {
7766     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7767     Candidate.FoundDecl = FoundDecl;
7768     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7769     Candidate.Viable = false;
7770     Candidate.FailureKind = ovl_fail_bad_deduction;
7771     Candidate.IsSurrogate = false;
7772     Candidate.IgnoreObjectArgument = false;
7773     Candidate.ExplicitCallArguments = 1;
7774     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7775                                                           Info);
7776     return;
7777   }
7778 
7779   // Add the conversion function template specialization produced by
7780   // template argument deduction as a candidate.
7781   assert(Specialization && "Missing function template specialization?");
7782   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7783                          CandidateSet, AllowObjCConversionOnExplicit,
7784                          AllowExplicit, AllowResultConversion);
7785 }
7786 
7787 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7788 /// converts the given @c Object to a function pointer via the
7789 /// conversion function @c Conversion, and then attempts to call it
7790 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7791 /// the type of function that we'll eventually be calling.
7792 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7793                                  DeclAccessPair FoundDecl,
7794                                  CXXRecordDecl *ActingContext,
7795                                  const FunctionProtoType *Proto,
7796                                  Expr *Object,
7797                                  ArrayRef<Expr *> Args,
7798                                  OverloadCandidateSet& CandidateSet) {
7799   if (!CandidateSet.isNewCandidate(Conversion))
7800     return;
7801 
7802   // Overload resolution is always an unevaluated context.
7803   EnterExpressionEvaluationContext Unevaluated(
7804       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7805 
7806   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7807   Candidate.FoundDecl = FoundDecl;
7808   Candidate.Function = nullptr;
7809   Candidate.Surrogate = Conversion;
7810   Candidate.Viable = true;
7811   Candidate.IsSurrogate = true;
7812   Candidate.IgnoreObjectArgument = false;
7813   Candidate.ExplicitCallArguments = Args.size();
7814 
7815   // Determine the implicit conversion sequence for the implicit
7816   // object parameter.
7817   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7818       *this, CandidateSet.getLocation(), Object->getType(),
7819       Object->Classify(Context), Conversion, ActingContext);
7820   if (ObjectInit.isBad()) {
7821     Candidate.Viable = false;
7822     Candidate.FailureKind = ovl_fail_bad_conversion;
7823     Candidate.Conversions[0] = ObjectInit;
7824     return;
7825   }
7826 
7827   // The first conversion is actually a user-defined conversion whose
7828   // first conversion is ObjectInit's standard conversion (which is
7829   // effectively a reference binding). Record it as such.
7830   Candidate.Conversions[0].setUserDefined();
7831   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7832   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7833   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7834   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7835   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7836   Candidate.Conversions[0].UserDefined.After
7837     = Candidate.Conversions[0].UserDefined.Before;
7838   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7839 
7840   // Find the
7841   unsigned NumParams = Proto->getNumParams();
7842 
7843   // (C++ 13.3.2p2): A candidate function having fewer than m
7844   // parameters is viable only if it has an ellipsis in its parameter
7845   // list (8.3.5).
7846   if (Args.size() > NumParams && !Proto->isVariadic()) {
7847     Candidate.Viable = false;
7848     Candidate.FailureKind = ovl_fail_too_many_arguments;
7849     return;
7850   }
7851 
7852   // Function types don't have any default arguments, so just check if
7853   // we have enough arguments.
7854   if (Args.size() < NumParams) {
7855     // Not enough arguments.
7856     Candidate.Viable = false;
7857     Candidate.FailureKind = ovl_fail_too_few_arguments;
7858     return;
7859   }
7860 
7861   // Determine the implicit conversion sequences for each of the
7862   // arguments.
7863   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7864     if (ArgIdx < NumParams) {
7865       // (C++ 13.3.2p3): for F to be a viable function, there shall
7866       // exist for each argument an implicit conversion sequence
7867       // (13.3.3.1) that converts that argument to the corresponding
7868       // parameter of F.
7869       QualType ParamType = Proto->getParamType(ArgIdx);
7870       Candidate.Conversions[ArgIdx + 1]
7871         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7872                                 /*SuppressUserConversions=*/false,
7873                                 /*InOverloadResolution=*/false,
7874                                 /*AllowObjCWritebackConversion=*/
7875                                   getLangOpts().ObjCAutoRefCount);
7876       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7877         Candidate.Viable = false;
7878         Candidate.FailureKind = ovl_fail_bad_conversion;
7879         return;
7880       }
7881     } else {
7882       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7883       // argument for which there is no corresponding parameter is
7884       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7885       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7886     }
7887   }
7888 
7889   if (Conversion->getTrailingRequiresClause()) {
7890     ConstraintSatisfaction Satisfaction;
7891     if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
7892                                  /*ForOverloadResolution*/ true) ||
7893         !Satisfaction.IsSatisfied) {
7894       Candidate.Viable = false;
7895       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7896       return;
7897     }
7898   }
7899 
7900   if (EnableIfAttr *FailedAttr =
7901           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7902     Candidate.Viable = false;
7903     Candidate.FailureKind = ovl_fail_enable_if;
7904     Candidate.DeductionFailure.Data = FailedAttr;
7905     return;
7906   }
7907 }
7908 
7909 /// Add all of the non-member operator function declarations in the given
7910 /// function set to the overload candidate set.
7911 void Sema::AddNonMemberOperatorCandidates(
7912     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7913     OverloadCandidateSet &CandidateSet,
7914     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7915   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7916     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7917     ArrayRef<Expr *> FunctionArgs = Args;
7918 
7919     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7920     FunctionDecl *FD =
7921         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7922 
7923     // Don't consider rewritten functions if we're not rewriting.
7924     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7925       continue;
7926 
7927     assert(!isa<CXXMethodDecl>(FD) &&
7928            "unqualified operator lookup found a member function");
7929 
7930     if (FunTmpl) {
7931       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7932                                    FunctionArgs, CandidateSet);
7933       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7934         AddTemplateOverloadCandidate(
7935             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7936             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7937             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7938     } else {
7939       if (ExplicitTemplateArgs)
7940         continue;
7941       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7942       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7943         AddOverloadCandidate(
7944             FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7945             false, false, true, false, ADLCallKind::NotADL, std::nullopt,
7946             OverloadCandidateParamOrder::Reversed);
7947     }
7948   }
7949 }
7950 
7951 /// Add overload candidates for overloaded operators that are
7952 /// member functions.
7953 ///
7954 /// Add the overloaded operator candidates that are member functions
7955 /// for the operator Op that was used in an operator expression such
7956 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7957 /// CandidateSet will store the added overload candidates. (C++
7958 /// [over.match.oper]).
7959 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7960                                        SourceLocation OpLoc,
7961                                        ArrayRef<Expr *> Args,
7962                                        OverloadCandidateSet &CandidateSet,
7963                                        OverloadCandidateParamOrder PO) {
7964   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7965 
7966   // C++ [over.match.oper]p3:
7967   //   For a unary operator @ with an operand of a type whose
7968   //   cv-unqualified version is T1, and for a binary operator @ with
7969   //   a left operand of a type whose cv-unqualified version is T1 and
7970   //   a right operand of a type whose cv-unqualified version is T2,
7971   //   three sets of candidate functions, designated member
7972   //   candidates, non-member candidates and built-in candidates, are
7973   //   constructed as follows:
7974   QualType T1 = Args[0]->getType();
7975 
7976   //     -- If T1 is a complete class type or a class currently being
7977   //        defined, the set of member candidates is the result of the
7978   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7979   //        the set of member candidates is empty.
7980   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7981     // Complete the type if it can be completed.
7982     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7983       return;
7984     // If the type is neither complete nor being defined, bail out now.
7985     if (!T1Rec->getDecl()->getDefinition())
7986       return;
7987 
7988     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7989     LookupQualifiedName(Operators, T1Rec->getDecl());
7990     Operators.suppressDiagnostics();
7991 
7992     for (LookupResult::iterator Oper = Operators.begin(),
7993                                 OperEnd = Operators.end();
7994          Oper != OperEnd; ++Oper) {
7995       if (Oper->getAsFunction() &&
7996           PO == OverloadCandidateParamOrder::Reversed &&
7997           !CandidateSet.getRewriteInfo().shouldAddReversed(
7998               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
7999         continue;
8000       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8001                          Args[0]->Classify(Context), Args.slice(1),
8002                          CandidateSet, /*SuppressUserConversion=*/false, PO);
8003     }
8004   }
8005 }
8006 
8007 /// AddBuiltinCandidate - Add a candidate for a built-in
8008 /// operator. ResultTy and ParamTys are the result and parameter types
8009 /// of the built-in candidate, respectively. Args and NumArgs are the
8010 /// arguments being passed to the candidate. IsAssignmentOperator
8011 /// should be true when this built-in candidate is an assignment
8012 /// operator. NumContextualBoolArguments is the number of arguments
8013 /// (at the beginning of the argument list) that will be contextually
8014 /// converted to bool.
8015 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8016                                OverloadCandidateSet& CandidateSet,
8017                                bool IsAssignmentOperator,
8018                                unsigned NumContextualBoolArguments) {
8019   // Overload resolution is always an unevaluated context.
8020   EnterExpressionEvaluationContext Unevaluated(
8021       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8022 
8023   // Add this candidate
8024   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8025   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8026   Candidate.Function = nullptr;
8027   Candidate.IsSurrogate = false;
8028   Candidate.IgnoreObjectArgument = false;
8029   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8030 
8031   // Determine the implicit conversion sequences for each of the
8032   // arguments.
8033   Candidate.Viable = true;
8034   Candidate.ExplicitCallArguments = Args.size();
8035   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8036     // C++ [over.match.oper]p4:
8037     //   For the built-in assignment operators, conversions of the
8038     //   left operand are restricted as follows:
8039     //     -- no temporaries are introduced to hold the left operand, and
8040     //     -- no user-defined conversions are applied to the left
8041     //        operand to achieve a type match with the left-most
8042     //        parameter of a built-in candidate.
8043     //
8044     // We block these conversions by turning off user-defined
8045     // conversions, since that is the only way that initialization of
8046     // a reference to a non-class type can occur from something that
8047     // is not of the same type.
8048     if (ArgIdx < NumContextualBoolArguments) {
8049       assert(ParamTys[ArgIdx] == Context.BoolTy &&
8050              "Contextual conversion to bool requires bool type");
8051       Candidate.Conversions[ArgIdx]
8052         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8053     } else {
8054       Candidate.Conversions[ArgIdx]
8055         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8056                                 ArgIdx == 0 && IsAssignmentOperator,
8057                                 /*InOverloadResolution=*/false,
8058                                 /*AllowObjCWritebackConversion=*/
8059                                   getLangOpts().ObjCAutoRefCount);
8060     }
8061     if (Candidate.Conversions[ArgIdx].isBad()) {
8062       Candidate.Viable = false;
8063       Candidate.FailureKind = ovl_fail_bad_conversion;
8064       break;
8065     }
8066   }
8067 }
8068 
8069 namespace {
8070 
8071 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8072 /// candidate operator functions for built-in operators (C++
8073 /// [over.built]). The types are separated into pointer types and
8074 /// enumeration types.
8075 class BuiltinCandidateTypeSet  {
8076   /// TypeSet - A set of types.
8077   typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8078 
8079   /// PointerTypes - The set of pointer types that will be used in the
8080   /// built-in candidates.
8081   TypeSet PointerTypes;
8082 
8083   /// MemberPointerTypes - The set of member pointer types that will be
8084   /// used in the built-in candidates.
8085   TypeSet MemberPointerTypes;
8086 
8087   /// EnumerationTypes - The set of enumeration types that will be
8088   /// used in the built-in candidates.
8089   TypeSet EnumerationTypes;
8090 
8091   /// The set of vector types that will be used in the built-in
8092   /// candidates.
8093   TypeSet VectorTypes;
8094 
8095   /// The set of matrix types that will be used in the built-in
8096   /// candidates.
8097   TypeSet MatrixTypes;
8098 
8099   /// A flag indicating non-record types are viable candidates
8100   bool HasNonRecordTypes;
8101 
8102   /// A flag indicating whether either arithmetic or enumeration types
8103   /// were present in the candidate set.
8104   bool HasArithmeticOrEnumeralTypes;
8105 
8106   /// A flag indicating whether the nullptr type was present in the
8107   /// candidate set.
8108   bool HasNullPtrType;
8109 
8110   /// Sema - The semantic analysis instance where we are building the
8111   /// candidate type set.
8112   Sema &SemaRef;
8113 
8114   /// Context - The AST context in which we will build the type sets.
8115   ASTContext &Context;
8116 
8117   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8118                                                const Qualifiers &VisibleQuals);
8119   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8120 
8121 public:
8122   /// iterator - Iterates through the types that are part of the set.
8123   typedef TypeSet::iterator iterator;
8124 
8125   BuiltinCandidateTypeSet(Sema &SemaRef)
8126     : HasNonRecordTypes(false),
8127       HasArithmeticOrEnumeralTypes(false),
8128       HasNullPtrType(false),
8129       SemaRef(SemaRef),
8130       Context(SemaRef.Context) { }
8131 
8132   void AddTypesConvertedFrom(QualType Ty,
8133                              SourceLocation Loc,
8134                              bool AllowUserConversions,
8135                              bool AllowExplicitConversions,
8136                              const Qualifiers &VisibleTypeConversionsQuals);
8137 
8138   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8139   llvm::iterator_range<iterator> member_pointer_types() {
8140     return MemberPointerTypes;
8141   }
8142   llvm::iterator_range<iterator> enumeration_types() {
8143     return EnumerationTypes;
8144   }
8145   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8146   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8147 
8148   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8149   bool hasNonRecordTypes() { return HasNonRecordTypes; }
8150   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8151   bool hasNullPtrType() const { return HasNullPtrType; }
8152 };
8153 
8154 } // end anonymous namespace
8155 
8156 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8157 /// the set of pointer types along with any more-qualified variants of
8158 /// that type. For example, if @p Ty is "int const *", this routine
8159 /// will add "int const *", "int const volatile *", "int const
8160 /// restrict *", and "int const volatile restrict *" to the set of
8161 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8162 /// false otherwise.
8163 ///
8164 /// FIXME: what to do about extended qualifiers?
8165 bool
8166 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8167                                              const Qualifiers &VisibleQuals) {
8168 
8169   // Insert this type.
8170   if (!PointerTypes.insert(Ty))
8171     return false;
8172 
8173   QualType PointeeTy;
8174   const PointerType *PointerTy = Ty->getAs<PointerType>();
8175   bool buildObjCPtr = false;
8176   if (!PointerTy) {
8177     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8178     PointeeTy = PTy->getPointeeType();
8179     buildObjCPtr = true;
8180   } else {
8181     PointeeTy = PointerTy->getPointeeType();
8182   }
8183 
8184   // Don't add qualified variants of arrays. For one, they're not allowed
8185   // (the qualifier would sink to the element type), and for another, the
8186   // only overload situation where it matters is subscript or pointer +- int,
8187   // and those shouldn't have qualifier variants anyway.
8188   if (PointeeTy->isArrayType())
8189     return true;
8190 
8191   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8192   bool hasVolatile = VisibleQuals.hasVolatile();
8193   bool hasRestrict = VisibleQuals.hasRestrict();
8194 
8195   // Iterate through all strict supersets of BaseCVR.
8196   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8197     if ((CVR | BaseCVR) != CVR) continue;
8198     // Skip over volatile if no volatile found anywhere in the types.
8199     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8200 
8201     // Skip over restrict if no restrict found anywhere in the types, or if
8202     // the type cannot be restrict-qualified.
8203     if ((CVR & Qualifiers::Restrict) &&
8204         (!hasRestrict ||
8205          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8206       continue;
8207 
8208     // Build qualified pointee type.
8209     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8210 
8211     // Build qualified pointer type.
8212     QualType QPointerTy;
8213     if (!buildObjCPtr)
8214       QPointerTy = Context.getPointerType(QPointeeTy);
8215     else
8216       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8217 
8218     // Insert qualified pointer type.
8219     PointerTypes.insert(QPointerTy);
8220   }
8221 
8222   return true;
8223 }
8224 
8225 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8226 /// to the set of pointer types along with any more-qualified variants of
8227 /// that type. For example, if @p Ty is "int const *", this routine
8228 /// will add "int const *", "int const volatile *", "int const
8229 /// restrict *", and "int const volatile restrict *" to the set of
8230 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8231 /// false otherwise.
8232 ///
8233 /// FIXME: what to do about extended qualifiers?
8234 bool
8235 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8236     QualType Ty) {
8237   // Insert this type.
8238   if (!MemberPointerTypes.insert(Ty))
8239     return false;
8240 
8241   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8242   assert(PointerTy && "type was not a member pointer type!");
8243 
8244   QualType PointeeTy = PointerTy->getPointeeType();
8245   // Don't add qualified variants of arrays. For one, they're not allowed
8246   // (the qualifier would sink to the element type), and for another, the
8247   // only overload situation where it matters is subscript or pointer +- int,
8248   // and those shouldn't have qualifier variants anyway.
8249   if (PointeeTy->isArrayType())
8250     return true;
8251   const Type *ClassTy = PointerTy->getClass();
8252 
8253   // Iterate through all strict supersets of the pointee type's CVR
8254   // qualifiers.
8255   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8256   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8257     if ((CVR | BaseCVR) != CVR) continue;
8258 
8259     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8260     MemberPointerTypes.insert(
8261       Context.getMemberPointerType(QPointeeTy, ClassTy));
8262   }
8263 
8264   return true;
8265 }
8266 
8267 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8268 /// Ty can be implicit converted to the given set of @p Types. We're
8269 /// primarily interested in pointer types and enumeration types. We also
8270 /// take member pointer types, for the conditional operator.
8271 /// AllowUserConversions is true if we should look at the conversion
8272 /// functions of a class type, and AllowExplicitConversions if we
8273 /// should also include the explicit conversion functions of a class
8274 /// type.
8275 void
8276 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8277                                                SourceLocation Loc,
8278                                                bool AllowUserConversions,
8279                                                bool AllowExplicitConversions,
8280                                                const Qualifiers &VisibleQuals) {
8281   // Only deal with canonical types.
8282   Ty = Context.getCanonicalType(Ty);
8283 
8284   // Look through reference types; they aren't part of the type of an
8285   // expression for the purposes of conversions.
8286   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8287     Ty = RefTy->getPointeeType();
8288 
8289   // If we're dealing with an array type, decay to the pointer.
8290   if (Ty->isArrayType())
8291     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8292 
8293   // Otherwise, we don't care about qualifiers on the type.
8294   Ty = Ty.getLocalUnqualifiedType();
8295 
8296   // Flag if we ever add a non-record type.
8297   const RecordType *TyRec = Ty->getAs<RecordType>();
8298   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8299 
8300   // Flag if we encounter an arithmetic type.
8301   HasArithmeticOrEnumeralTypes =
8302     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8303 
8304   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8305     PointerTypes.insert(Ty);
8306   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8307     // Insert our type, and its more-qualified variants, into the set
8308     // of types.
8309     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8310       return;
8311   } else if (Ty->isMemberPointerType()) {
8312     // Member pointers are far easier, since the pointee can't be converted.
8313     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8314       return;
8315   } else if (Ty->isEnumeralType()) {
8316     HasArithmeticOrEnumeralTypes = true;
8317     EnumerationTypes.insert(Ty);
8318   } else if (Ty->isVectorType()) {
8319     // We treat vector types as arithmetic types in many contexts as an
8320     // extension.
8321     HasArithmeticOrEnumeralTypes = true;
8322     VectorTypes.insert(Ty);
8323   } else if (Ty->isMatrixType()) {
8324     // Similar to vector types, we treat vector types as arithmetic types in
8325     // many contexts as an extension.
8326     HasArithmeticOrEnumeralTypes = true;
8327     MatrixTypes.insert(Ty);
8328   } else if (Ty->isNullPtrType()) {
8329     HasNullPtrType = true;
8330   } else if (AllowUserConversions && TyRec) {
8331     // No conversion functions in incomplete types.
8332     if (!SemaRef.isCompleteType(Loc, Ty))
8333       return;
8334 
8335     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8336     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8337       if (isa<UsingShadowDecl>(D))
8338         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8339 
8340       // Skip conversion function templates; they don't tell us anything
8341       // about which builtin types we can convert to.
8342       if (isa<FunctionTemplateDecl>(D))
8343         continue;
8344 
8345       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8346       if (AllowExplicitConversions || !Conv->isExplicit()) {
8347         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8348                               VisibleQuals);
8349       }
8350     }
8351   }
8352 }
8353 /// Helper function for adjusting address spaces for the pointer or reference
8354 /// operands of builtin operators depending on the argument.
8355 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8356                                                         Expr *Arg) {
8357   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8358 }
8359 
8360 /// Helper function for AddBuiltinOperatorCandidates() that adds
8361 /// the volatile- and non-volatile-qualified assignment operators for the
8362 /// given type to the candidate set.
8363 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8364                                                    QualType T,
8365                                                    ArrayRef<Expr *> Args,
8366                                     OverloadCandidateSet &CandidateSet) {
8367   QualType ParamTypes[2];
8368 
8369   // T& operator=(T&, T)
8370   ParamTypes[0] = S.Context.getLValueReferenceType(
8371       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8372   ParamTypes[1] = T;
8373   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8374                         /*IsAssignmentOperator=*/true);
8375 
8376   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8377     // volatile T& operator=(volatile T&, T)
8378     ParamTypes[0] = S.Context.getLValueReferenceType(
8379         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8380                                                 Args[0]));
8381     ParamTypes[1] = T;
8382     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8383                           /*IsAssignmentOperator=*/true);
8384   }
8385 }
8386 
8387 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8388 /// if any, found in visible type conversion functions found in ArgExpr's type.
8389 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8390     Qualifiers VRQuals;
8391     const RecordType *TyRec;
8392     if (const MemberPointerType *RHSMPType =
8393         ArgExpr->getType()->getAs<MemberPointerType>())
8394       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8395     else
8396       TyRec = ArgExpr->getType()->getAs<RecordType>();
8397     if (!TyRec) {
8398       // Just to be safe, assume the worst case.
8399       VRQuals.addVolatile();
8400       VRQuals.addRestrict();
8401       return VRQuals;
8402     }
8403 
8404     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8405     if (!ClassDecl->hasDefinition())
8406       return VRQuals;
8407 
8408     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8409       if (isa<UsingShadowDecl>(D))
8410         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8411       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8412         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8413         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8414           CanTy = ResTypeRef->getPointeeType();
8415         // Need to go down the pointer/mempointer chain and add qualifiers
8416         // as see them.
8417         bool done = false;
8418         while (!done) {
8419           if (CanTy.isRestrictQualified())
8420             VRQuals.addRestrict();
8421           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8422             CanTy = ResTypePtr->getPointeeType();
8423           else if (const MemberPointerType *ResTypeMPtr =
8424                 CanTy->getAs<MemberPointerType>())
8425             CanTy = ResTypeMPtr->getPointeeType();
8426           else
8427             done = true;
8428           if (CanTy.isVolatileQualified())
8429             VRQuals.addVolatile();
8430           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8431             return VRQuals;
8432         }
8433       }
8434     }
8435     return VRQuals;
8436 }
8437 
8438 // Note: We're currently only handling qualifiers that are meaningful for the
8439 // LHS of compound assignment overloading.
8440 static void forAllQualifierCombinationsImpl(
8441     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8442     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8443   // _Atomic
8444   if (Available.hasAtomic()) {
8445     Available.removeAtomic();
8446     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8447     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8448     return;
8449   }
8450 
8451   // volatile
8452   if (Available.hasVolatile()) {
8453     Available.removeVolatile();
8454     assert(!Applied.hasVolatile());
8455     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8456                                     Callback);
8457     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8458     return;
8459   }
8460 
8461   Callback(Applied);
8462 }
8463 
8464 static void forAllQualifierCombinations(
8465     QualifiersAndAtomic Quals,
8466     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8467   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8468                                          Callback);
8469 }
8470 
8471 static QualType makeQualifiedLValueReferenceType(QualType Base,
8472                                                  QualifiersAndAtomic Quals,
8473                                                  Sema &S) {
8474   if (Quals.hasAtomic())
8475     Base = S.Context.getAtomicType(Base);
8476   if (Quals.hasVolatile())
8477     Base = S.Context.getVolatileType(Base);
8478   return S.Context.getLValueReferenceType(Base);
8479 }
8480 
8481 namespace {
8482 
8483 /// Helper class to manage the addition of builtin operator overload
8484 /// candidates. It provides shared state and utility methods used throughout
8485 /// the process, as well as a helper method to add each group of builtin
8486 /// operator overloads from the standard to a candidate set.
8487 class BuiltinOperatorOverloadBuilder {
8488   // Common instance state available to all overload candidate addition methods.
8489   Sema &S;
8490   ArrayRef<Expr *> Args;
8491   QualifiersAndAtomic VisibleTypeConversionsQuals;
8492   bool HasArithmeticOrEnumeralCandidateType;
8493   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8494   OverloadCandidateSet &CandidateSet;
8495 
8496   static constexpr int ArithmeticTypesCap = 24;
8497   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8498 
8499   // Define some indices used to iterate over the arithmetic types in
8500   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8501   // types are that preserved by promotion (C++ [over.built]p2).
8502   unsigned FirstIntegralType,
8503            LastIntegralType;
8504   unsigned FirstPromotedIntegralType,
8505            LastPromotedIntegralType;
8506   unsigned FirstPromotedArithmeticType,
8507            LastPromotedArithmeticType;
8508   unsigned NumArithmeticTypes;
8509 
8510   void InitArithmeticTypes() {
8511     // Start of promoted types.
8512     FirstPromotedArithmeticType = 0;
8513     ArithmeticTypes.push_back(S.Context.FloatTy);
8514     ArithmeticTypes.push_back(S.Context.DoubleTy);
8515     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8516     if (S.Context.getTargetInfo().hasFloat128Type())
8517       ArithmeticTypes.push_back(S.Context.Float128Ty);
8518     if (S.Context.getTargetInfo().hasIbm128Type())
8519       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8520 
8521     // Start of integral types.
8522     FirstIntegralType = ArithmeticTypes.size();
8523     FirstPromotedIntegralType = ArithmeticTypes.size();
8524     ArithmeticTypes.push_back(S.Context.IntTy);
8525     ArithmeticTypes.push_back(S.Context.LongTy);
8526     ArithmeticTypes.push_back(S.Context.LongLongTy);
8527     if (S.Context.getTargetInfo().hasInt128Type() ||
8528         (S.Context.getAuxTargetInfo() &&
8529          S.Context.getAuxTargetInfo()->hasInt128Type()))
8530       ArithmeticTypes.push_back(S.Context.Int128Ty);
8531     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8532     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8533     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8534     if (S.Context.getTargetInfo().hasInt128Type() ||
8535         (S.Context.getAuxTargetInfo() &&
8536          S.Context.getAuxTargetInfo()->hasInt128Type()))
8537       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8538     LastPromotedIntegralType = ArithmeticTypes.size();
8539     LastPromotedArithmeticType = ArithmeticTypes.size();
8540     // End of promoted types.
8541 
8542     ArithmeticTypes.push_back(S.Context.BoolTy);
8543     ArithmeticTypes.push_back(S.Context.CharTy);
8544     ArithmeticTypes.push_back(S.Context.WCharTy);
8545     if (S.Context.getLangOpts().Char8)
8546       ArithmeticTypes.push_back(S.Context.Char8Ty);
8547     ArithmeticTypes.push_back(S.Context.Char16Ty);
8548     ArithmeticTypes.push_back(S.Context.Char32Ty);
8549     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8550     ArithmeticTypes.push_back(S.Context.ShortTy);
8551     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8552     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8553     LastIntegralType = ArithmeticTypes.size();
8554     NumArithmeticTypes = ArithmeticTypes.size();
8555     // End of integral types.
8556     // FIXME: What about complex? What about half?
8557 
8558     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8559            "Enough inline storage for all arithmetic types.");
8560   }
8561 
8562   /// Helper method to factor out the common pattern of adding overloads
8563   /// for '++' and '--' builtin operators.
8564   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8565                                            bool HasVolatile,
8566                                            bool HasRestrict) {
8567     QualType ParamTypes[2] = {
8568       S.Context.getLValueReferenceType(CandidateTy),
8569       S.Context.IntTy
8570     };
8571 
8572     // Non-volatile version.
8573     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8574 
8575     // Use a heuristic to reduce number of builtin candidates in the set:
8576     // add volatile version only if there are conversions to a volatile type.
8577     if (HasVolatile) {
8578       ParamTypes[0] =
8579         S.Context.getLValueReferenceType(
8580           S.Context.getVolatileType(CandidateTy));
8581       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8582     }
8583 
8584     // Add restrict version only if there are conversions to a restrict type
8585     // and our candidate type is a non-restrict-qualified pointer.
8586     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8587         !CandidateTy.isRestrictQualified()) {
8588       ParamTypes[0]
8589         = S.Context.getLValueReferenceType(
8590             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8591       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8592 
8593       if (HasVolatile) {
8594         ParamTypes[0]
8595           = S.Context.getLValueReferenceType(
8596               S.Context.getCVRQualifiedType(CandidateTy,
8597                                             (Qualifiers::Volatile |
8598                                              Qualifiers::Restrict)));
8599         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8600       }
8601     }
8602 
8603   }
8604 
8605   /// Helper to add an overload candidate for a binary builtin with types \p L
8606   /// and \p R.
8607   void AddCandidate(QualType L, QualType R) {
8608     QualType LandR[2] = {L, R};
8609     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8610   }
8611 
8612 public:
8613   BuiltinOperatorOverloadBuilder(
8614     Sema &S, ArrayRef<Expr *> Args,
8615     QualifiersAndAtomic VisibleTypeConversionsQuals,
8616     bool HasArithmeticOrEnumeralCandidateType,
8617     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8618     OverloadCandidateSet &CandidateSet)
8619     : S(S), Args(Args),
8620       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8621       HasArithmeticOrEnumeralCandidateType(
8622         HasArithmeticOrEnumeralCandidateType),
8623       CandidateTypes(CandidateTypes),
8624       CandidateSet(CandidateSet) {
8625 
8626     InitArithmeticTypes();
8627   }
8628 
8629   // Increment is deprecated for bool since C++17.
8630   //
8631   // C++ [over.built]p3:
8632   //
8633   //   For every pair (T, VQ), where T is an arithmetic type other
8634   //   than bool, and VQ is either volatile or empty, there exist
8635   //   candidate operator functions of the form
8636   //
8637   //       VQ T&      operator++(VQ T&);
8638   //       T          operator++(VQ T&, int);
8639   //
8640   // C++ [over.built]p4:
8641   //
8642   //   For every pair (T, VQ), where T is an arithmetic type other
8643   //   than bool, and VQ is either volatile or empty, there exist
8644   //   candidate operator functions of the form
8645   //
8646   //       VQ T&      operator--(VQ T&);
8647   //       T          operator--(VQ T&, int);
8648   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8649     if (!HasArithmeticOrEnumeralCandidateType)
8650       return;
8651 
8652     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8653       const auto TypeOfT = ArithmeticTypes[Arith];
8654       if (TypeOfT == S.Context.BoolTy) {
8655         if (Op == OO_MinusMinus)
8656           continue;
8657         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8658           continue;
8659       }
8660       addPlusPlusMinusMinusStyleOverloads(
8661         TypeOfT,
8662         VisibleTypeConversionsQuals.hasVolatile(),
8663         VisibleTypeConversionsQuals.hasRestrict());
8664     }
8665   }
8666 
8667   // C++ [over.built]p5:
8668   //
8669   //   For every pair (T, VQ), where T is a cv-qualified or
8670   //   cv-unqualified object type, and VQ is either volatile or
8671   //   empty, there exist candidate operator functions of the form
8672   //
8673   //       T*VQ&      operator++(T*VQ&);
8674   //       T*VQ&      operator--(T*VQ&);
8675   //       T*         operator++(T*VQ&, int);
8676   //       T*         operator--(T*VQ&, int);
8677   void addPlusPlusMinusMinusPointerOverloads() {
8678     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8679       // Skip pointer types that aren't pointers to object types.
8680       if (!PtrTy->getPointeeType()->isObjectType())
8681         continue;
8682 
8683       addPlusPlusMinusMinusStyleOverloads(
8684           PtrTy,
8685           (!PtrTy.isVolatileQualified() &&
8686            VisibleTypeConversionsQuals.hasVolatile()),
8687           (!PtrTy.isRestrictQualified() &&
8688            VisibleTypeConversionsQuals.hasRestrict()));
8689     }
8690   }
8691 
8692   // C++ [over.built]p6:
8693   //   For every cv-qualified or cv-unqualified object type T, there
8694   //   exist candidate operator functions of the form
8695   //
8696   //       T&         operator*(T*);
8697   //
8698   // C++ [over.built]p7:
8699   //   For every function type T that does not have cv-qualifiers or a
8700   //   ref-qualifier, there exist candidate operator functions of the form
8701   //       T&         operator*(T*);
8702   void addUnaryStarPointerOverloads() {
8703     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8704       QualType PointeeTy = ParamTy->getPointeeType();
8705       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8706         continue;
8707 
8708       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8709         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8710           continue;
8711 
8712       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8713     }
8714   }
8715 
8716   // C++ [over.built]p9:
8717   //  For every promoted arithmetic type T, there exist candidate
8718   //  operator functions of the form
8719   //
8720   //       T         operator+(T);
8721   //       T         operator-(T);
8722   void addUnaryPlusOrMinusArithmeticOverloads() {
8723     if (!HasArithmeticOrEnumeralCandidateType)
8724       return;
8725 
8726     for (unsigned Arith = FirstPromotedArithmeticType;
8727          Arith < LastPromotedArithmeticType; ++Arith) {
8728       QualType ArithTy = ArithmeticTypes[Arith];
8729       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8730     }
8731 
8732     // Extension: We also add these operators for vector types.
8733     for (QualType VecTy : CandidateTypes[0].vector_types())
8734       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8735   }
8736 
8737   // C++ [over.built]p8:
8738   //   For every type T, there exist candidate operator functions of
8739   //   the form
8740   //
8741   //       T*         operator+(T*);
8742   void addUnaryPlusPointerOverloads() {
8743     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8744       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8745   }
8746 
8747   // C++ [over.built]p10:
8748   //   For every promoted integral type T, there exist candidate
8749   //   operator functions of the form
8750   //
8751   //        T         operator~(T);
8752   void addUnaryTildePromotedIntegralOverloads() {
8753     if (!HasArithmeticOrEnumeralCandidateType)
8754       return;
8755 
8756     for (unsigned Int = FirstPromotedIntegralType;
8757          Int < LastPromotedIntegralType; ++Int) {
8758       QualType IntTy = ArithmeticTypes[Int];
8759       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8760     }
8761 
8762     // Extension: We also add this operator for vector types.
8763     for (QualType VecTy : CandidateTypes[0].vector_types())
8764       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8765   }
8766 
8767   // C++ [over.match.oper]p16:
8768   //   For every pointer to member type T or type std::nullptr_t, there
8769   //   exist candidate operator functions of the form
8770   //
8771   //        bool operator==(T,T);
8772   //        bool operator!=(T,T);
8773   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8774     /// Set of (canonical) types that we've already handled.
8775     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8776 
8777     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8778       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8779         // Don't add the same builtin candidate twice.
8780         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8781           continue;
8782 
8783         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8784         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8785       }
8786 
8787       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8788         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8789         if (AddedTypes.insert(NullPtrTy).second) {
8790           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8791           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8792         }
8793       }
8794     }
8795   }
8796 
8797   // C++ [over.built]p15:
8798   //
8799   //   For every T, where T is an enumeration type or a pointer type,
8800   //   there exist candidate operator functions of the form
8801   //
8802   //        bool       operator<(T, T);
8803   //        bool       operator>(T, T);
8804   //        bool       operator<=(T, T);
8805   //        bool       operator>=(T, T);
8806   //        bool       operator==(T, T);
8807   //        bool       operator!=(T, T);
8808   //           R       operator<=>(T, T)
8809   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8810     // C++ [over.match.oper]p3:
8811     //   [...]the built-in candidates include all of the candidate operator
8812     //   functions defined in 13.6 that, compared to the given operator, [...]
8813     //   do not have the same parameter-type-list as any non-template non-member
8814     //   candidate.
8815     //
8816     // Note that in practice, this only affects enumeration types because there
8817     // aren't any built-in candidates of record type, and a user-defined operator
8818     // must have an operand of record or enumeration type. Also, the only other
8819     // overloaded operator with enumeration arguments, operator=,
8820     // cannot be overloaded for enumeration types, so this is the only place
8821     // where we must suppress candidates like this.
8822     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8823       UserDefinedBinaryOperators;
8824 
8825     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8826       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8827         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8828                                          CEnd = CandidateSet.end();
8829              C != CEnd; ++C) {
8830           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8831             continue;
8832 
8833           if (C->Function->isFunctionTemplateSpecialization())
8834             continue;
8835 
8836           // We interpret "same parameter-type-list" as applying to the
8837           // "synthesized candidate, with the order of the two parameters
8838           // reversed", not to the original function.
8839           bool Reversed = C->isReversed();
8840           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8841                                         ->getType()
8842                                         .getUnqualifiedType();
8843           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8844                                          ->getType()
8845                                          .getUnqualifiedType();
8846 
8847           // Skip if either parameter isn't of enumeral type.
8848           if (!FirstParamType->isEnumeralType() ||
8849               !SecondParamType->isEnumeralType())
8850             continue;
8851 
8852           // Add this operator to the set of known user-defined operators.
8853           UserDefinedBinaryOperators.insert(
8854             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8855                            S.Context.getCanonicalType(SecondParamType)));
8856         }
8857       }
8858     }
8859 
8860     /// Set of (canonical) types that we've already handled.
8861     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8862 
8863     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8864       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8865         // Don't add the same builtin candidate twice.
8866         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8867           continue;
8868         if (IsSpaceship && PtrTy->isFunctionPointerType())
8869           continue;
8870 
8871         QualType ParamTypes[2] = {PtrTy, PtrTy};
8872         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8873       }
8874       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8875         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8876 
8877         // Don't add the same builtin candidate twice, or if a user defined
8878         // candidate exists.
8879         if (!AddedTypes.insert(CanonType).second ||
8880             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8881                                                             CanonType)))
8882           continue;
8883         QualType ParamTypes[2] = {EnumTy, EnumTy};
8884         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8885       }
8886     }
8887   }
8888 
8889   // C++ [over.built]p13:
8890   //
8891   //   For every cv-qualified or cv-unqualified object type T
8892   //   there exist candidate operator functions of the form
8893   //
8894   //      T*         operator+(T*, ptrdiff_t);
8895   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8896   //      T*         operator-(T*, ptrdiff_t);
8897   //      T*         operator+(ptrdiff_t, T*);
8898   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8899   //
8900   // C++ [over.built]p14:
8901   //
8902   //   For every T, where T is a pointer to object type, there
8903   //   exist candidate operator functions of the form
8904   //
8905   //      ptrdiff_t  operator-(T, T);
8906   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8907     /// Set of (canonical) types that we've already handled.
8908     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8909 
8910     for (int Arg = 0; Arg < 2; ++Arg) {
8911       QualType AsymmetricParamTypes[2] = {
8912         S.Context.getPointerDiffType(),
8913         S.Context.getPointerDiffType(),
8914       };
8915       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8916         QualType PointeeTy = PtrTy->getPointeeType();
8917         if (!PointeeTy->isObjectType())
8918           continue;
8919 
8920         AsymmetricParamTypes[Arg] = PtrTy;
8921         if (Arg == 0 || Op == OO_Plus) {
8922           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8923           // T* operator+(ptrdiff_t, T*);
8924           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8925         }
8926         if (Op == OO_Minus) {
8927           // ptrdiff_t operator-(T, T);
8928           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8929             continue;
8930 
8931           QualType ParamTypes[2] = {PtrTy, PtrTy};
8932           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8933         }
8934       }
8935     }
8936   }
8937 
8938   // C++ [over.built]p12:
8939   //
8940   //   For every pair of promoted arithmetic types L and R, there
8941   //   exist candidate operator functions of the form
8942   //
8943   //        LR         operator*(L, R);
8944   //        LR         operator/(L, R);
8945   //        LR         operator+(L, R);
8946   //        LR         operator-(L, R);
8947   //        bool       operator<(L, R);
8948   //        bool       operator>(L, R);
8949   //        bool       operator<=(L, R);
8950   //        bool       operator>=(L, R);
8951   //        bool       operator==(L, R);
8952   //        bool       operator!=(L, R);
8953   //
8954   //   where LR is the result of the usual arithmetic conversions
8955   //   between types L and R.
8956   //
8957   // C++ [over.built]p24:
8958   //
8959   //   For every pair of promoted arithmetic types L and R, there exist
8960   //   candidate operator functions of the form
8961   //
8962   //        LR       operator?(bool, L, R);
8963   //
8964   //   where LR is the result of the usual arithmetic conversions
8965   //   between types L and R.
8966   // Our candidates ignore the first parameter.
8967   void addGenericBinaryArithmeticOverloads() {
8968     if (!HasArithmeticOrEnumeralCandidateType)
8969       return;
8970 
8971     for (unsigned Left = FirstPromotedArithmeticType;
8972          Left < LastPromotedArithmeticType; ++Left) {
8973       for (unsigned Right = FirstPromotedArithmeticType;
8974            Right < LastPromotedArithmeticType; ++Right) {
8975         QualType LandR[2] = { ArithmeticTypes[Left],
8976                               ArithmeticTypes[Right] };
8977         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8978       }
8979     }
8980 
8981     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8982     // conditional operator for vector types.
8983     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8984       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8985         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8986         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8987       }
8988   }
8989 
8990   /// Add binary operator overloads for each candidate matrix type M1, M2:
8991   ///  * (M1, M1) -> M1
8992   ///  * (M1, M1.getElementType()) -> M1
8993   ///  * (M2.getElementType(), M2) -> M2
8994   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8995   void addMatrixBinaryArithmeticOverloads() {
8996     if (!HasArithmeticOrEnumeralCandidateType)
8997       return;
8998 
8999     for (QualType M1 : CandidateTypes[0].matrix_types()) {
9000       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9001       AddCandidate(M1, M1);
9002     }
9003 
9004     for (QualType M2 : CandidateTypes[1].matrix_types()) {
9005       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9006       if (!CandidateTypes[0].containsMatrixType(M2))
9007         AddCandidate(M2, M2);
9008     }
9009   }
9010 
9011   // C++2a [over.built]p14:
9012   //
9013   //   For every integral type T there exists a candidate operator function
9014   //   of the form
9015   //
9016   //        std::strong_ordering operator<=>(T, T)
9017   //
9018   // C++2a [over.built]p15:
9019   //
9020   //   For every pair of floating-point types L and R, there exists a candidate
9021   //   operator function of the form
9022   //
9023   //       std::partial_ordering operator<=>(L, R);
9024   //
9025   // FIXME: The current specification for integral types doesn't play nice with
9026   // the direction of p0946r0, which allows mixed integral and unscoped-enum
9027   // comparisons. Under the current spec this can lead to ambiguity during
9028   // overload resolution. For example:
9029   //
9030   //   enum A : int {a};
9031   //   auto x = (a <=> (long)42);
9032   //
9033   //   error: call is ambiguous for arguments 'A' and 'long'.
9034   //   note: candidate operator<=>(int, int)
9035   //   note: candidate operator<=>(long, long)
9036   //
9037   // To avoid this error, this function deviates from the specification and adds
9038   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9039   // arithmetic types (the same as the generic relational overloads).
9040   //
9041   // For now this function acts as a placeholder.
9042   void addThreeWayArithmeticOverloads() {
9043     addGenericBinaryArithmeticOverloads();
9044   }
9045 
9046   // C++ [over.built]p17:
9047   //
9048   //   For every pair of promoted integral types L and R, there
9049   //   exist candidate operator functions of the form
9050   //
9051   //      LR         operator%(L, R);
9052   //      LR         operator&(L, R);
9053   //      LR         operator^(L, R);
9054   //      LR         operator|(L, R);
9055   //      L          operator<<(L, R);
9056   //      L          operator>>(L, R);
9057   //
9058   //   where LR is the result of the usual arithmetic conversions
9059   //   between types L and R.
9060   void addBinaryBitwiseArithmeticOverloads() {
9061     if (!HasArithmeticOrEnumeralCandidateType)
9062       return;
9063 
9064     for (unsigned Left = FirstPromotedIntegralType;
9065          Left < LastPromotedIntegralType; ++Left) {
9066       for (unsigned Right = FirstPromotedIntegralType;
9067            Right < LastPromotedIntegralType; ++Right) {
9068         QualType LandR[2] = { ArithmeticTypes[Left],
9069                               ArithmeticTypes[Right] };
9070         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9071       }
9072     }
9073   }
9074 
9075   // C++ [over.built]p20:
9076   //
9077   //   For every pair (T, VQ), where T is an enumeration or
9078   //   pointer to member type and VQ is either volatile or
9079   //   empty, there exist candidate operator functions of the form
9080   //
9081   //        VQ T&      operator=(VQ T&, T);
9082   void addAssignmentMemberPointerOrEnumeralOverloads() {
9083     /// Set of (canonical) types that we've already handled.
9084     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9085 
9086     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9087       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9088         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9089           continue;
9090 
9091         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9092       }
9093 
9094       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9095         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9096           continue;
9097 
9098         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9099       }
9100     }
9101   }
9102 
9103   // C++ [over.built]p19:
9104   //
9105   //   For every pair (T, VQ), where T is any type and VQ is either
9106   //   volatile or empty, there exist candidate operator functions
9107   //   of the form
9108   //
9109   //        T*VQ&      operator=(T*VQ&, T*);
9110   //
9111   // C++ [over.built]p21:
9112   //
9113   //   For every pair (T, VQ), where T is a cv-qualified or
9114   //   cv-unqualified object type and VQ is either volatile or
9115   //   empty, there exist candidate operator functions of the form
9116   //
9117   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9118   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
9119   void addAssignmentPointerOverloads(bool isEqualOp) {
9120     /// Set of (canonical) types that we've already handled.
9121     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9122 
9123     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9124       // If this is operator=, keep track of the builtin candidates we added.
9125       if (isEqualOp)
9126         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9127       else if (!PtrTy->getPointeeType()->isObjectType())
9128         continue;
9129 
9130       // non-volatile version
9131       QualType ParamTypes[2] = {
9132           S.Context.getLValueReferenceType(PtrTy),
9133           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9134       };
9135       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9136                             /*IsAssignmentOperator=*/ isEqualOp);
9137 
9138       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9139                           VisibleTypeConversionsQuals.hasVolatile();
9140       if (NeedVolatile) {
9141         // volatile version
9142         ParamTypes[0] =
9143             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9144         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9145                               /*IsAssignmentOperator=*/isEqualOp);
9146       }
9147 
9148       if (!PtrTy.isRestrictQualified() &&
9149           VisibleTypeConversionsQuals.hasRestrict()) {
9150         // restrict version
9151         ParamTypes[0] =
9152             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9153         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9154                               /*IsAssignmentOperator=*/isEqualOp);
9155 
9156         if (NeedVolatile) {
9157           // volatile restrict version
9158           ParamTypes[0] =
9159               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9160                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9161           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9162                                 /*IsAssignmentOperator=*/isEqualOp);
9163         }
9164       }
9165     }
9166 
9167     if (isEqualOp) {
9168       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9169         // Make sure we don't add the same candidate twice.
9170         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9171           continue;
9172 
9173         QualType ParamTypes[2] = {
9174             S.Context.getLValueReferenceType(PtrTy),
9175             PtrTy,
9176         };
9177 
9178         // non-volatile version
9179         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9180                               /*IsAssignmentOperator=*/true);
9181 
9182         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9183                             VisibleTypeConversionsQuals.hasVolatile();
9184         if (NeedVolatile) {
9185           // volatile version
9186           ParamTypes[0] = S.Context.getLValueReferenceType(
9187               S.Context.getVolatileType(PtrTy));
9188           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9189                                 /*IsAssignmentOperator=*/true);
9190         }
9191 
9192         if (!PtrTy.isRestrictQualified() &&
9193             VisibleTypeConversionsQuals.hasRestrict()) {
9194           // restrict version
9195           ParamTypes[0] = S.Context.getLValueReferenceType(
9196               S.Context.getRestrictType(PtrTy));
9197           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9198                                 /*IsAssignmentOperator=*/true);
9199 
9200           if (NeedVolatile) {
9201             // volatile restrict version
9202             ParamTypes[0] =
9203                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9204                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9205             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9206                                   /*IsAssignmentOperator=*/true);
9207           }
9208         }
9209       }
9210     }
9211   }
9212 
9213   // C++ [over.built]p18:
9214   //
9215   //   For every triple (L, VQ, R), where L is an arithmetic type,
9216   //   VQ is either volatile or empty, and R is a promoted
9217   //   arithmetic type, there exist candidate operator functions of
9218   //   the form
9219   //
9220   //        VQ L&      operator=(VQ L&, R);
9221   //        VQ L&      operator*=(VQ L&, R);
9222   //        VQ L&      operator/=(VQ L&, R);
9223   //        VQ L&      operator+=(VQ L&, R);
9224   //        VQ L&      operator-=(VQ L&, R);
9225   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9226     if (!HasArithmeticOrEnumeralCandidateType)
9227       return;
9228 
9229     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9230       for (unsigned Right = FirstPromotedArithmeticType;
9231            Right < LastPromotedArithmeticType; ++Right) {
9232         QualType ParamTypes[2];
9233         ParamTypes[1] = ArithmeticTypes[Right];
9234         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9235             S, ArithmeticTypes[Left], Args[0]);
9236 
9237         forAllQualifierCombinations(
9238             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9239               ParamTypes[0] =
9240                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9241               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9242                                     /*IsAssignmentOperator=*/isEqualOp);
9243             });
9244       }
9245     }
9246 
9247     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9248     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9249       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9250         QualType ParamTypes[2];
9251         ParamTypes[1] = Vec2Ty;
9252         // Add this built-in operator as a candidate (VQ is empty).
9253         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9254         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9255                               /*IsAssignmentOperator=*/isEqualOp);
9256 
9257         // Add this built-in operator as a candidate (VQ is 'volatile').
9258         if (VisibleTypeConversionsQuals.hasVolatile()) {
9259           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9260           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9261           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9262                                 /*IsAssignmentOperator=*/isEqualOp);
9263         }
9264       }
9265   }
9266 
9267   // C++ [over.built]p22:
9268   //
9269   //   For every triple (L, VQ, R), where L is an integral type, VQ
9270   //   is either volatile or empty, and R is a promoted integral
9271   //   type, there exist candidate operator functions of the form
9272   //
9273   //        VQ L&       operator%=(VQ L&, R);
9274   //        VQ L&       operator<<=(VQ L&, R);
9275   //        VQ L&       operator>>=(VQ L&, R);
9276   //        VQ L&       operator&=(VQ L&, R);
9277   //        VQ L&       operator^=(VQ L&, R);
9278   //        VQ L&       operator|=(VQ L&, R);
9279   void addAssignmentIntegralOverloads() {
9280     if (!HasArithmeticOrEnumeralCandidateType)
9281       return;
9282 
9283     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9284       for (unsigned Right = FirstPromotedIntegralType;
9285            Right < LastPromotedIntegralType; ++Right) {
9286         QualType ParamTypes[2];
9287         ParamTypes[1] = ArithmeticTypes[Right];
9288         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9289             S, ArithmeticTypes[Left], Args[0]);
9290 
9291         forAllQualifierCombinations(
9292             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9293               ParamTypes[0] =
9294                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9295               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9296             });
9297       }
9298     }
9299   }
9300 
9301   // C++ [over.operator]p23:
9302   //
9303   //   There also exist candidate operator functions of the form
9304   //
9305   //        bool        operator!(bool);
9306   //        bool        operator&&(bool, bool);
9307   //        bool        operator||(bool, bool);
9308   void addExclaimOverload() {
9309     QualType ParamTy = S.Context.BoolTy;
9310     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9311                           /*IsAssignmentOperator=*/false,
9312                           /*NumContextualBoolArguments=*/1);
9313   }
9314   void addAmpAmpOrPipePipeOverload() {
9315     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9316     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9317                           /*IsAssignmentOperator=*/false,
9318                           /*NumContextualBoolArguments=*/2);
9319   }
9320 
9321   // C++ [over.built]p13:
9322   //
9323   //   For every cv-qualified or cv-unqualified object type T there
9324   //   exist candidate operator functions of the form
9325   //
9326   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9327   //        T&         operator[](T*, ptrdiff_t);
9328   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9329   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9330   //        T&         operator[](ptrdiff_t, T*);
9331   void addSubscriptOverloads() {
9332     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9333       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9334       QualType PointeeType = PtrTy->getPointeeType();
9335       if (!PointeeType->isObjectType())
9336         continue;
9337 
9338       // T& operator[](T*, ptrdiff_t)
9339       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9340     }
9341 
9342     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9343       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9344       QualType PointeeType = PtrTy->getPointeeType();
9345       if (!PointeeType->isObjectType())
9346         continue;
9347 
9348       // T& operator[](ptrdiff_t, T*)
9349       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9350     }
9351   }
9352 
9353   // C++ [over.built]p11:
9354   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9355   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9356   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9357   //    there exist candidate operator functions of the form
9358   //
9359   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9360   //
9361   //    where CV12 is the union of CV1 and CV2.
9362   void addArrowStarOverloads() {
9363     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9364       QualType C1Ty = PtrTy;
9365       QualType C1;
9366       QualifierCollector Q1;
9367       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9368       if (!isa<RecordType>(C1))
9369         continue;
9370       // heuristic to reduce number of builtin candidates in the set.
9371       // Add volatile/restrict version only if there are conversions to a
9372       // volatile/restrict type.
9373       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9374         continue;
9375       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9376         continue;
9377       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9378         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9379         QualType C2 = QualType(mptr->getClass(), 0);
9380         C2 = C2.getUnqualifiedType();
9381         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9382           break;
9383         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9384         // build CV12 T&
9385         QualType T = mptr->getPointeeType();
9386         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9387             T.isVolatileQualified())
9388           continue;
9389         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9390             T.isRestrictQualified())
9391           continue;
9392         T = Q1.apply(S.Context, T);
9393         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9394       }
9395     }
9396   }
9397 
9398   // Note that we don't consider the first argument, since it has been
9399   // contextually converted to bool long ago. The candidates below are
9400   // therefore added as binary.
9401   //
9402   // C++ [over.built]p25:
9403   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9404   //   enumeration type, there exist candidate operator functions of the form
9405   //
9406   //        T        operator?(bool, T, T);
9407   //
9408   void addConditionalOperatorOverloads() {
9409     /// Set of (canonical) types that we've already handled.
9410     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9411 
9412     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9413       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9414         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9415           continue;
9416 
9417         QualType ParamTypes[2] = {PtrTy, PtrTy};
9418         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9419       }
9420 
9421       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9422         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9423           continue;
9424 
9425         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9426         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9427       }
9428 
9429       if (S.getLangOpts().CPlusPlus11) {
9430         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9431           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9432             continue;
9433 
9434           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9435             continue;
9436 
9437           QualType ParamTypes[2] = {EnumTy, EnumTy};
9438           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9439         }
9440       }
9441     }
9442   }
9443 };
9444 
9445 } // end anonymous namespace
9446 
9447 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9448 /// operator overloads to the candidate set (C++ [over.built]), based
9449 /// on the operator @p Op and the arguments given. For example, if the
9450 /// operator is a binary '+', this routine might add "int
9451 /// operator+(int, int)" to cover integer addition.
9452 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9453                                         SourceLocation OpLoc,
9454                                         ArrayRef<Expr *> Args,
9455                                         OverloadCandidateSet &CandidateSet) {
9456   // Find all of the types that the arguments can convert to, but only
9457   // if the operator we're looking at has built-in operator candidates
9458   // that make use of these types. Also record whether we encounter non-record
9459   // candidate types or either arithmetic or enumeral candidate types.
9460   QualifiersAndAtomic VisibleTypeConversionsQuals;
9461   VisibleTypeConversionsQuals.addConst();
9462   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9463     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9464     if (Args[ArgIdx]->getType()->isAtomicType())
9465       VisibleTypeConversionsQuals.addAtomic();
9466   }
9467 
9468   bool HasNonRecordCandidateType = false;
9469   bool HasArithmeticOrEnumeralCandidateType = false;
9470   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9471   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9472     CandidateTypes.emplace_back(*this);
9473     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9474                                                  OpLoc,
9475                                                  true,
9476                                                  (Op == OO_Exclaim ||
9477                                                   Op == OO_AmpAmp ||
9478                                                   Op == OO_PipePipe),
9479                                                  VisibleTypeConversionsQuals);
9480     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9481         CandidateTypes[ArgIdx].hasNonRecordTypes();
9482     HasArithmeticOrEnumeralCandidateType =
9483         HasArithmeticOrEnumeralCandidateType ||
9484         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9485   }
9486 
9487   // Exit early when no non-record types have been added to the candidate set
9488   // for any of the arguments to the operator.
9489   //
9490   // We can't exit early for !, ||, or &&, since there we have always have
9491   // 'bool' overloads.
9492   if (!HasNonRecordCandidateType &&
9493       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9494     return;
9495 
9496   // Setup an object to manage the common state for building overloads.
9497   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9498                                            VisibleTypeConversionsQuals,
9499                                            HasArithmeticOrEnumeralCandidateType,
9500                                            CandidateTypes, CandidateSet);
9501 
9502   // Dispatch over the operation to add in only those overloads which apply.
9503   switch (Op) {
9504   case OO_None:
9505   case NUM_OVERLOADED_OPERATORS:
9506     llvm_unreachable("Expected an overloaded operator");
9507 
9508   case OO_New:
9509   case OO_Delete:
9510   case OO_Array_New:
9511   case OO_Array_Delete:
9512   case OO_Call:
9513     llvm_unreachable(
9514                     "Special operators don't use AddBuiltinOperatorCandidates");
9515 
9516   case OO_Comma:
9517   case OO_Arrow:
9518   case OO_Coawait:
9519     // C++ [over.match.oper]p3:
9520     //   -- For the operator ',', the unary operator '&', the
9521     //      operator '->', or the operator 'co_await', the
9522     //      built-in candidates set is empty.
9523     break;
9524 
9525   case OO_Plus: // '+' is either unary or binary
9526     if (Args.size() == 1)
9527       OpBuilder.addUnaryPlusPointerOverloads();
9528     [[fallthrough]];
9529 
9530   case OO_Minus: // '-' is either unary or binary
9531     if (Args.size() == 1) {
9532       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9533     } else {
9534       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9535       OpBuilder.addGenericBinaryArithmeticOverloads();
9536       OpBuilder.addMatrixBinaryArithmeticOverloads();
9537     }
9538     break;
9539 
9540   case OO_Star: // '*' is either unary or binary
9541     if (Args.size() == 1)
9542       OpBuilder.addUnaryStarPointerOverloads();
9543     else {
9544       OpBuilder.addGenericBinaryArithmeticOverloads();
9545       OpBuilder.addMatrixBinaryArithmeticOverloads();
9546     }
9547     break;
9548 
9549   case OO_Slash:
9550     OpBuilder.addGenericBinaryArithmeticOverloads();
9551     break;
9552 
9553   case OO_PlusPlus:
9554   case OO_MinusMinus:
9555     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9556     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9557     break;
9558 
9559   case OO_EqualEqual:
9560   case OO_ExclaimEqual:
9561     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9562     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9563     OpBuilder.addGenericBinaryArithmeticOverloads();
9564     break;
9565 
9566   case OO_Less:
9567   case OO_Greater:
9568   case OO_LessEqual:
9569   case OO_GreaterEqual:
9570     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9571     OpBuilder.addGenericBinaryArithmeticOverloads();
9572     break;
9573 
9574   case OO_Spaceship:
9575     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9576     OpBuilder.addThreeWayArithmeticOverloads();
9577     break;
9578 
9579   case OO_Percent:
9580   case OO_Caret:
9581   case OO_Pipe:
9582   case OO_LessLess:
9583   case OO_GreaterGreater:
9584     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9585     break;
9586 
9587   case OO_Amp: // '&' is either unary or binary
9588     if (Args.size() == 1)
9589       // C++ [over.match.oper]p3:
9590       //   -- For the operator ',', the unary operator '&', or the
9591       //      operator '->', the built-in candidates set is empty.
9592       break;
9593 
9594     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9595     break;
9596 
9597   case OO_Tilde:
9598     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9599     break;
9600 
9601   case OO_Equal:
9602     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9603     [[fallthrough]];
9604 
9605   case OO_PlusEqual:
9606   case OO_MinusEqual:
9607     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9608     [[fallthrough]];
9609 
9610   case OO_StarEqual:
9611   case OO_SlashEqual:
9612     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9613     break;
9614 
9615   case OO_PercentEqual:
9616   case OO_LessLessEqual:
9617   case OO_GreaterGreaterEqual:
9618   case OO_AmpEqual:
9619   case OO_CaretEqual:
9620   case OO_PipeEqual:
9621     OpBuilder.addAssignmentIntegralOverloads();
9622     break;
9623 
9624   case OO_Exclaim:
9625     OpBuilder.addExclaimOverload();
9626     break;
9627 
9628   case OO_AmpAmp:
9629   case OO_PipePipe:
9630     OpBuilder.addAmpAmpOrPipePipeOverload();
9631     break;
9632 
9633   case OO_Subscript:
9634     if (Args.size() == 2)
9635       OpBuilder.addSubscriptOverloads();
9636     break;
9637 
9638   case OO_ArrowStar:
9639     OpBuilder.addArrowStarOverloads();
9640     break;
9641 
9642   case OO_Conditional:
9643     OpBuilder.addConditionalOperatorOverloads();
9644     OpBuilder.addGenericBinaryArithmeticOverloads();
9645     break;
9646   }
9647 }
9648 
9649 /// Add function candidates found via argument-dependent lookup
9650 /// to the set of overloading candidates.
9651 ///
9652 /// This routine performs argument-dependent name lookup based on the
9653 /// given function name (which may also be an operator name) and adds
9654 /// all of the overload candidates found by ADL to the overload
9655 /// candidate set (C++ [basic.lookup.argdep]).
9656 void
9657 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9658                                            SourceLocation Loc,
9659                                            ArrayRef<Expr *> Args,
9660                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9661                                            OverloadCandidateSet& CandidateSet,
9662                                            bool PartialOverloading) {
9663   ADLResult Fns;
9664 
9665   // FIXME: This approach for uniquing ADL results (and removing
9666   // redundant candidates from the set) relies on pointer-equality,
9667   // which means we need to key off the canonical decl.  However,
9668   // always going back to the canonical decl might not get us the
9669   // right set of default arguments.  What default arguments are
9670   // we supposed to consider on ADL candidates, anyway?
9671 
9672   // FIXME: Pass in the explicit template arguments?
9673   ArgumentDependentLookup(Name, Loc, Args, Fns);
9674 
9675   // Erase all of the candidates we already knew about.
9676   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9677                                    CandEnd = CandidateSet.end();
9678        Cand != CandEnd; ++Cand)
9679     if (Cand->Function) {
9680       Fns.erase(Cand->Function);
9681       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9682         Fns.erase(FunTmpl);
9683     }
9684 
9685   // For each of the ADL candidates we found, add it to the overload
9686   // set.
9687   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9688     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9689 
9690     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9691       if (ExplicitTemplateArgs)
9692         continue;
9693 
9694       AddOverloadCandidate(
9695           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9696           PartialOverloading, /*AllowExplicit=*/true,
9697           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9698       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9699         AddOverloadCandidate(
9700             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9701             /*SuppressUserConversions=*/false, PartialOverloading,
9702             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9703             ADLCallKind::UsesADL, std::nullopt,
9704             OverloadCandidateParamOrder::Reversed);
9705       }
9706     } else {
9707       auto *FTD = cast<FunctionTemplateDecl>(*I);
9708       AddTemplateOverloadCandidate(
9709           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9710           /*SuppressUserConversions=*/false, PartialOverloading,
9711           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9712       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9713               *this, Args, FTD->getTemplatedDecl())) {
9714         AddTemplateOverloadCandidate(
9715             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9716             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9717             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9718             OverloadCandidateParamOrder::Reversed);
9719       }
9720     }
9721   }
9722 }
9723 
9724 namespace {
9725 enum class Comparison { Equal, Better, Worse };
9726 }
9727 
9728 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9729 /// overload resolution.
9730 ///
9731 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9732 /// Cand1's first N enable_if attributes have precisely the same conditions as
9733 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9734 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9735 ///
9736 /// Note that you can have a pair of candidates such that Cand1's enable_if
9737 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9738 /// worse than Cand1's.
9739 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9740                                        const FunctionDecl *Cand2) {
9741   // Common case: One (or both) decls don't have enable_if attrs.
9742   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9743   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9744   if (!Cand1Attr || !Cand2Attr) {
9745     if (Cand1Attr == Cand2Attr)
9746       return Comparison::Equal;
9747     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9748   }
9749 
9750   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9751   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9752 
9753   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9754   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9755     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9756     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9757 
9758     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9759     // has fewer enable_if attributes than Cand2, and vice versa.
9760     if (!Cand1A)
9761       return Comparison::Worse;
9762     if (!Cand2A)
9763       return Comparison::Better;
9764 
9765     Cand1ID.clear();
9766     Cand2ID.clear();
9767 
9768     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9769     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9770     if (Cand1ID != Cand2ID)
9771       return Comparison::Worse;
9772   }
9773 
9774   return Comparison::Equal;
9775 }
9776 
9777 static Comparison
9778 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9779                               const OverloadCandidate &Cand2) {
9780   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9781       !Cand2.Function->isMultiVersion())
9782     return Comparison::Equal;
9783 
9784   // If both are invalid, they are equal. If one of them is invalid, the other
9785   // is better.
9786   if (Cand1.Function->isInvalidDecl()) {
9787     if (Cand2.Function->isInvalidDecl())
9788       return Comparison::Equal;
9789     return Comparison::Worse;
9790   }
9791   if (Cand2.Function->isInvalidDecl())
9792     return Comparison::Better;
9793 
9794   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9795   // cpu_dispatch, else arbitrarily based on the identifiers.
9796   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9797   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9798   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9799   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9800 
9801   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9802     return Comparison::Equal;
9803 
9804   if (Cand1CPUDisp && !Cand2CPUDisp)
9805     return Comparison::Better;
9806   if (Cand2CPUDisp && !Cand1CPUDisp)
9807     return Comparison::Worse;
9808 
9809   if (Cand1CPUSpec && Cand2CPUSpec) {
9810     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9811       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9812                  ? Comparison::Better
9813                  : Comparison::Worse;
9814 
9815     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9816         FirstDiff = std::mismatch(
9817             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9818             Cand2CPUSpec->cpus_begin(),
9819             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9820               return LHS->getName() == RHS->getName();
9821             });
9822 
9823     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9824            "Two different cpu-specific versions should not have the same "
9825            "identifier list, otherwise they'd be the same decl!");
9826     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9827                ? Comparison::Better
9828                : Comparison::Worse;
9829   }
9830   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9831 }
9832 
9833 /// Compute the type of the implicit object parameter for the given function,
9834 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
9835 /// null QualType if there is a 'matches anything' implicit object parameter.
9836 static std::optional<QualType>
9837 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
9838   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9839     return std::nullopt;
9840 
9841   auto *M = cast<CXXMethodDecl>(F);
9842   // Static member functions' object parameters match all types.
9843   if (M->isStatic())
9844     return QualType();
9845 
9846   QualType T = M->getThisObjectType();
9847   if (M->getRefQualifier() == RQ_RValue)
9848     return Context.getRValueReferenceType(T);
9849   return Context.getLValueReferenceType(T);
9850 }
9851 
9852 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9853                                    const FunctionDecl *F2, unsigned NumParams) {
9854   if (declaresSameEntity(F1, F2))
9855     return true;
9856 
9857   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9858     if (First) {
9859       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
9860         return *T;
9861     }
9862     assert(I < F->getNumParams());
9863     return F->getParamDecl(I++)->getType();
9864   };
9865 
9866   unsigned I1 = 0, I2 = 0;
9867   for (unsigned I = 0; I != NumParams; ++I) {
9868     QualType T1 = NextParam(F1, I1, I == 0);
9869     QualType T2 = NextParam(F2, I2, I == 0);
9870     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9871     if (!Context.hasSameUnqualifiedType(T1, T2))
9872       return false;
9873   }
9874   return true;
9875 }
9876 
9877 /// We're allowed to use constraints partial ordering only if the candidates
9878 /// have the same parameter types:
9879 /// [over.match.best]p2.6
9880 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9881 /// and F1 is more constrained than F2 [...]
9882 static bool sameFunctionParameterTypeLists(Sema &S,
9883                                           const OverloadCandidate &Cand1,
9884                                           const OverloadCandidate &Cand2) {
9885   if (Cand1.Function && Cand2.Function) {
9886     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9887     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9888     if (PT1->getNumParams() == PT2->getNumParams() &&
9889         PT1->isVariadic() == PT2->isVariadic() &&
9890         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9891                                      Cand1.isReversed() ^ Cand2.isReversed()))
9892       return true;
9893   }
9894   return false;
9895 }
9896 
9897 /// isBetterOverloadCandidate - Determines whether the first overload
9898 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9899 bool clang::isBetterOverloadCandidate(
9900     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9901     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9902   // Define viable functions to be better candidates than non-viable
9903   // functions.
9904   if (!Cand2.Viable)
9905     return Cand1.Viable;
9906   else if (!Cand1.Viable)
9907     return false;
9908 
9909   // [CUDA] A function with 'never' preference is marked not viable, therefore
9910   // is never shown up here. The worst preference shown up here is 'wrong side',
9911   // e.g. an H function called by a HD function in device compilation. This is
9912   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9913   // function which is called only by an H function. A deferred diagnostic will
9914   // be triggered if it is emitted. However a wrong-sided function is still
9915   // a viable candidate here.
9916   //
9917   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9918   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9919   // can be emitted, Cand1 is not better than Cand2. This rule should have
9920   // precedence over other rules.
9921   //
9922   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9923   // other rules should be used to determine which is better. This is because
9924   // host/device based overloading resolution is mostly for determining
9925   // viability of a function. If two functions are both viable, other factors
9926   // should take precedence in preference, e.g. the standard-defined preferences
9927   // like argument conversion ranks or enable_if partial-ordering. The
9928   // preference for pass-object-size parameters is probably most similar to a
9929   // type-based-overloading decision and so should take priority.
9930   //
9931   // If other rules cannot determine which is better, CUDA preference will be
9932   // used again to determine which is better.
9933   //
9934   // TODO: Currently IdentifyCUDAPreference does not return correct values
9935   // for functions called in global variable initializers due to missing
9936   // correct context about device/host. Therefore we can only enforce this
9937   // rule when there is a caller. We should enforce this rule for functions
9938   // in global variable initializers once proper context is added.
9939   //
9940   // TODO: We can only enable the hostness based overloading resolution when
9941   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9942   // overloading resolution diagnostics.
9943   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9944       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9945     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9946       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9947       bool IsCand1ImplicitHD =
9948           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9949       bool IsCand2ImplicitHD =
9950           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9951       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9952       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9953       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9954       // The implicit HD function may be a function in a system header which
9955       // is forced by pragma. In device compilation, if we prefer HD candidates
9956       // over wrong-sided candidates, overloading resolution may change, which
9957       // may result in non-deferrable diagnostics. As a workaround, we let
9958       // implicit HD candidates take equal preference as wrong-sided candidates.
9959       // This will preserve the overloading resolution.
9960       // TODO: We still need special handling of implicit HD functions since
9961       // they may incur other diagnostics to be deferred. We should make all
9962       // host/device related diagnostics deferrable and remove special handling
9963       // of implicit HD functions.
9964       auto EmitThreshold =
9965           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9966            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9967               ? Sema::CFP_Never
9968               : Sema::CFP_WrongSide;
9969       auto Cand1Emittable = P1 > EmitThreshold;
9970       auto Cand2Emittable = P2 > EmitThreshold;
9971       if (Cand1Emittable && !Cand2Emittable)
9972         return true;
9973       if (!Cand1Emittable && Cand2Emittable)
9974         return false;
9975     }
9976   }
9977 
9978   // C++ [over.match.best]p1: (Changed in C++23)
9979   //
9980   //   -- if F is a static member function, ICS1(F) is defined such
9981   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9982   //      any function G, and, symmetrically, ICS1(G) is neither
9983   //      better nor worse than ICS1(F).
9984   unsigned StartArg = 0;
9985   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9986     StartArg = 1;
9987 
9988   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9989     // We don't allow incompatible pointer conversions in C++.
9990     if (!S.getLangOpts().CPlusPlus)
9991       return ICS.isStandard() &&
9992              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9993 
9994     // The only ill-formed conversion we allow in C++ is the string literal to
9995     // char* conversion, which is only considered ill-formed after C++11.
9996     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9997            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9998   };
9999 
10000   // Define functions that don't require ill-formed conversions for a given
10001   // argument to be better candidates than functions that do.
10002   unsigned NumArgs = Cand1.Conversions.size();
10003   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10004   bool HasBetterConversion = false;
10005   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10006     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10007     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10008     if (Cand1Bad != Cand2Bad) {
10009       if (Cand1Bad)
10010         return false;
10011       HasBetterConversion = true;
10012     }
10013   }
10014 
10015   if (HasBetterConversion)
10016     return true;
10017 
10018   // C++ [over.match.best]p1:
10019   //   A viable function F1 is defined to be a better function than another
10020   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
10021   //   conversion sequence than ICSi(F2), and then...
10022   bool HasWorseConversion = false;
10023   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10024     switch (CompareImplicitConversionSequences(S, Loc,
10025                                                Cand1.Conversions[ArgIdx],
10026                                                Cand2.Conversions[ArgIdx])) {
10027     case ImplicitConversionSequence::Better:
10028       // Cand1 has a better conversion sequence.
10029       HasBetterConversion = true;
10030       break;
10031 
10032     case ImplicitConversionSequence::Worse:
10033       if (Cand1.Function && Cand2.Function &&
10034           Cand1.isReversed() != Cand2.isReversed() &&
10035           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
10036                                  NumArgs)) {
10037         // Work around large-scale breakage caused by considering reversed
10038         // forms of operator== in C++20:
10039         //
10040         // When comparing a function against a reversed function with the same
10041         // parameter types, if we have a better conversion for one argument and
10042         // a worse conversion for the other, the implicit conversion sequences
10043         // are treated as being equally good.
10044         //
10045         // This prevents a comparison function from being considered ambiguous
10046         // with a reversed form that is written in the same way.
10047         //
10048         // We diagnose this as an extension from CreateOverloadedBinOp.
10049         HasWorseConversion = true;
10050         break;
10051       }
10052 
10053       // Cand1 can't be better than Cand2.
10054       return false;
10055 
10056     case ImplicitConversionSequence::Indistinguishable:
10057       // Do nothing.
10058       break;
10059     }
10060   }
10061 
10062   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
10063   //       ICSj(F2), or, if not that,
10064   if (HasBetterConversion && !HasWorseConversion)
10065     return true;
10066 
10067   //   -- the context is an initialization by user-defined conversion
10068   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
10069   //      from the return type of F1 to the destination type (i.e.,
10070   //      the type of the entity being initialized) is a better
10071   //      conversion sequence than the standard conversion sequence
10072   //      from the return type of F2 to the destination type.
10073   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10074       Cand1.Function && Cand2.Function &&
10075       isa<CXXConversionDecl>(Cand1.Function) &&
10076       isa<CXXConversionDecl>(Cand2.Function)) {
10077     // First check whether we prefer one of the conversion functions over the
10078     // other. This only distinguishes the results in non-standard, extension
10079     // cases such as the conversion from a lambda closure type to a function
10080     // pointer or block.
10081     ImplicitConversionSequence::CompareKind Result =
10082         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10083     if (Result == ImplicitConversionSequence::Indistinguishable)
10084       Result = CompareStandardConversionSequences(S, Loc,
10085                                                   Cand1.FinalConversion,
10086                                                   Cand2.FinalConversion);
10087 
10088     if (Result != ImplicitConversionSequence::Indistinguishable)
10089       return Result == ImplicitConversionSequence::Better;
10090 
10091     // FIXME: Compare kind of reference binding if conversion functions
10092     // convert to a reference type used in direct reference binding, per
10093     // C++14 [over.match.best]p1 section 2 bullet 3.
10094   }
10095 
10096   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10097   // as combined with the resolution to CWG issue 243.
10098   //
10099   // When the context is initialization by constructor ([over.match.ctor] or
10100   // either phase of [over.match.list]), a constructor is preferred over
10101   // a conversion function.
10102   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10103       Cand1.Function && Cand2.Function &&
10104       isa<CXXConstructorDecl>(Cand1.Function) !=
10105           isa<CXXConstructorDecl>(Cand2.Function))
10106     return isa<CXXConstructorDecl>(Cand1.Function);
10107 
10108   //    -- F1 is a non-template function and F2 is a function template
10109   //       specialization, or, if not that,
10110   bool Cand1IsSpecialization = Cand1.Function &&
10111                                Cand1.Function->getPrimaryTemplate();
10112   bool Cand2IsSpecialization = Cand2.Function &&
10113                                Cand2.Function->getPrimaryTemplate();
10114   if (Cand1IsSpecialization != Cand2IsSpecialization)
10115     return Cand2IsSpecialization;
10116 
10117   //   -- F1 and F2 are function template specializations, and the function
10118   //      template for F1 is more specialized than the template for F2
10119   //      according to the partial ordering rules described in 14.5.5.2, or,
10120   //      if not that,
10121   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10122     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10123             Cand1.Function->getPrimaryTemplate(),
10124             Cand2.Function->getPrimaryTemplate(), Loc,
10125             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10126                                                    : TPOC_Call,
10127             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
10128             Cand1.isReversed() ^ Cand2.isReversed()))
10129       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10130   }
10131 
10132   //   -— F1 and F2 are non-template functions with the same
10133   //      parameter-type-lists, and F1 is more constrained than F2 [...],
10134   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10135       sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10136     FunctionDecl *Function1 = Cand1.Function;
10137     FunctionDecl *Function2 = Cand2.Function;
10138     if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10139       Function1 = MF;
10140     if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10141       Function2 = MF;
10142 
10143     const Expr *RC1 = Function1->getTrailingRequiresClause();
10144     const Expr *RC2 = Function2->getTrailingRequiresClause();
10145     if (RC1 && RC2) {
10146       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10147       if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10148                                    AtLeastAsConstrained1) ||
10149           S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10150                                    AtLeastAsConstrained2))
10151         return false;
10152       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10153         return AtLeastAsConstrained1;
10154     } else if (RC1 || RC2) {
10155       return RC1 != nullptr;
10156     }
10157   }
10158 
10159   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10160   //      class B of D, and for all arguments the corresponding parameters of
10161   //      F1 and F2 have the same type.
10162   // FIXME: Implement the "all parameters have the same type" check.
10163   bool Cand1IsInherited =
10164       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10165   bool Cand2IsInherited =
10166       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10167   if (Cand1IsInherited != Cand2IsInherited)
10168     return Cand2IsInherited;
10169   else if (Cand1IsInherited) {
10170     assert(Cand2IsInherited);
10171     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10172     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10173     if (Cand1Class->isDerivedFrom(Cand2Class))
10174       return true;
10175     if (Cand2Class->isDerivedFrom(Cand1Class))
10176       return false;
10177     // Inherited from sibling base classes: still ambiguous.
10178   }
10179 
10180   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10181   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10182   //      with reversed order of parameters and F1 is not
10183   //
10184   // We rank reversed + different operator as worse than just reversed, but
10185   // that comparison can never happen, because we only consider reversing for
10186   // the maximally-rewritten operator (== or <=>).
10187   if (Cand1.RewriteKind != Cand2.RewriteKind)
10188     return Cand1.RewriteKind < Cand2.RewriteKind;
10189 
10190   // Check C++17 tie-breakers for deduction guides.
10191   {
10192     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10193     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10194     if (Guide1 && Guide2) {
10195       //  -- F1 is generated from a deduction-guide and F2 is not
10196       if (Guide1->isImplicit() != Guide2->isImplicit())
10197         return Guide2->isImplicit();
10198 
10199       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10200       if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10201         return true;
10202     }
10203   }
10204 
10205   // Check for enable_if value-based overload resolution.
10206   if (Cand1.Function && Cand2.Function) {
10207     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10208     if (Cmp != Comparison::Equal)
10209       return Cmp == Comparison::Better;
10210   }
10211 
10212   bool HasPS1 = Cand1.Function != nullptr &&
10213                 functionHasPassObjectSizeParams(Cand1.Function);
10214   bool HasPS2 = Cand2.Function != nullptr &&
10215                 functionHasPassObjectSizeParams(Cand2.Function);
10216   if (HasPS1 != HasPS2 && HasPS1)
10217     return true;
10218 
10219   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10220   if (MV == Comparison::Better)
10221     return true;
10222   if (MV == Comparison::Worse)
10223     return false;
10224 
10225   // If other rules cannot determine which is better, CUDA preference is used
10226   // to determine which is better.
10227   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10228     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10229     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10230            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10231   }
10232 
10233   // General member function overloading is handled above, so this only handles
10234   // constructors with address spaces.
10235   // This only handles address spaces since C++ has no other
10236   // qualifier that can be used with constructors.
10237   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10238   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10239   if (CD1 && CD2) {
10240     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10241     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10242     if (AS1 != AS2) {
10243       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10244         return true;
10245       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10246         return false;
10247     }
10248   }
10249 
10250   return false;
10251 }
10252 
10253 /// Determine whether two declarations are "equivalent" for the purposes of
10254 /// name lookup and overload resolution. This applies when the same internal/no
10255 /// linkage entity is defined by two modules (probably by textually including
10256 /// the same header). In such a case, we don't consider the declarations to
10257 /// declare the same entity, but we also don't want lookups with both
10258 /// declarations visible to be ambiguous in some cases (this happens when using
10259 /// a modularized libstdc++).
10260 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10261                                                   const NamedDecl *B) {
10262   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10263   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10264   if (!VA || !VB)
10265     return false;
10266 
10267   // The declarations must be declaring the same name as an internal linkage
10268   // entity in different modules.
10269   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10270           VB->getDeclContext()->getRedeclContext()) ||
10271       getOwningModule(VA) == getOwningModule(VB) ||
10272       VA->isExternallyVisible() || VB->isExternallyVisible())
10273     return false;
10274 
10275   // Check that the declarations appear to be equivalent.
10276   //
10277   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10278   // For constants and functions, we should check the initializer or body is
10279   // the same. For non-constant variables, we shouldn't allow it at all.
10280   if (Context.hasSameType(VA->getType(), VB->getType()))
10281     return true;
10282 
10283   // Enum constants within unnamed enumerations will have different types, but
10284   // may still be similar enough to be interchangeable for our purposes.
10285   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10286     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10287       // Only handle anonymous enums. If the enumerations were named and
10288       // equivalent, they would have been merged to the same type.
10289       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10290       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10291       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10292           !Context.hasSameType(EnumA->getIntegerType(),
10293                                EnumB->getIntegerType()))
10294         return false;
10295       // Allow this only if the value is the same for both enumerators.
10296       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10297     }
10298   }
10299 
10300   // Nothing else is sufficiently similar.
10301   return false;
10302 }
10303 
10304 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10305     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10306   assert(D && "Unknown declaration");
10307   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10308 
10309   Module *M = getOwningModule(D);
10310   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10311       << !M << (M ? M->getFullModuleName() : "");
10312 
10313   for (auto *E : Equiv) {
10314     Module *M = getOwningModule(E);
10315     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10316         << !M << (M ? M->getFullModuleName() : "");
10317   }
10318 }
10319 
10320 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10321   return FailureKind == ovl_fail_bad_deduction &&
10322          DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10323          static_cast<CNSInfo *>(DeductionFailure.Data)
10324              ->Satisfaction.ContainsErrors;
10325 }
10326 
10327 /// Computes the best viable function (C++ 13.3.3)
10328 /// within an overload candidate set.
10329 ///
10330 /// \param Loc The location of the function name (or operator symbol) for
10331 /// which overload resolution occurs.
10332 ///
10333 /// \param Best If overload resolution was successful or found a deleted
10334 /// function, \p Best points to the candidate function found.
10335 ///
10336 /// \returns The result of overload resolution.
10337 OverloadingResult
10338 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10339                                          iterator &Best) {
10340   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10341   std::transform(begin(), end(), std::back_inserter(Candidates),
10342                  [](OverloadCandidate &Cand) { return &Cand; });
10343 
10344   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10345   // are accepted by both clang and NVCC. However, during a particular
10346   // compilation mode only one call variant is viable. We need to
10347   // exclude non-viable overload candidates from consideration based
10348   // only on their host/device attributes. Specifically, if one
10349   // candidate call is WrongSide and the other is SameSide, we ignore
10350   // the WrongSide candidate.
10351   // We only need to remove wrong-sided candidates here if
10352   // -fgpu-exclude-wrong-side-overloads is off. When
10353   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10354   // uniformly in isBetterOverloadCandidate.
10355   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10356     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10357     bool ContainsSameSideCandidate =
10358         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10359           // Check viable function only.
10360           return Cand->Viable && Cand->Function &&
10361                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10362                      Sema::CFP_SameSide;
10363         });
10364     if (ContainsSameSideCandidate) {
10365       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10366         // Check viable function only to avoid unnecessary data copying/moving.
10367         return Cand->Viable && Cand->Function &&
10368                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10369                    Sema::CFP_WrongSide;
10370       };
10371       llvm::erase_if(Candidates, IsWrongSideCandidate);
10372     }
10373   }
10374 
10375   // Find the best viable function.
10376   Best = end();
10377   for (auto *Cand : Candidates) {
10378     Cand->Best = false;
10379     if (Cand->Viable) {
10380       if (Best == end() ||
10381           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10382         Best = Cand;
10383     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10384       // This candidate has constraint that we were unable to evaluate because
10385       // it referenced an expression that contained an error. Rather than fall
10386       // back onto a potentially unintended candidate (made worse by
10387       // subsuming constraints), treat this as 'no viable candidate'.
10388       Best = end();
10389       return OR_No_Viable_Function;
10390     }
10391   }
10392 
10393   // If we didn't find any viable functions, abort.
10394   if (Best == end())
10395     return OR_No_Viable_Function;
10396 
10397   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10398 
10399   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10400   PendingBest.push_back(&*Best);
10401   Best->Best = true;
10402 
10403   // Make sure that this function is better than every other viable
10404   // function. If not, we have an ambiguity.
10405   while (!PendingBest.empty()) {
10406     auto *Curr = PendingBest.pop_back_val();
10407     for (auto *Cand : Candidates) {
10408       if (Cand->Viable && !Cand->Best &&
10409           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10410         PendingBest.push_back(Cand);
10411         Cand->Best = true;
10412 
10413         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10414                                                      Curr->Function))
10415           EquivalentCands.push_back(Cand->Function);
10416         else
10417           Best = end();
10418       }
10419     }
10420   }
10421 
10422   // If we found more than one best candidate, this is ambiguous.
10423   if (Best == end())
10424     return OR_Ambiguous;
10425 
10426   // Best is the best viable function.
10427   if (Best->Function && Best->Function->isDeleted())
10428     return OR_Deleted;
10429 
10430   if (!EquivalentCands.empty())
10431     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10432                                                     EquivalentCands);
10433 
10434   return OR_Success;
10435 }
10436 
10437 namespace {
10438 
10439 enum OverloadCandidateKind {
10440   oc_function,
10441   oc_method,
10442   oc_reversed_binary_operator,
10443   oc_constructor,
10444   oc_implicit_default_constructor,
10445   oc_implicit_copy_constructor,
10446   oc_implicit_move_constructor,
10447   oc_implicit_copy_assignment,
10448   oc_implicit_move_assignment,
10449   oc_implicit_equality_comparison,
10450   oc_inherited_constructor
10451 };
10452 
10453 enum OverloadCandidateSelect {
10454   ocs_non_template,
10455   ocs_template,
10456   ocs_described_template,
10457 };
10458 
10459 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10460 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10461                           const FunctionDecl *Fn,
10462                           OverloadCandidateRewriteKind CRK,
10463                           std::string &Description) {
10464 
10465   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10466   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10467     isTemplate = true;
10468     Description = S.getTemplateArgumentBindingsText(
10469         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10470   }
10471 
10472   OverloadCandidateSelect Select = [&]() {
10473     if (!Description.empty())
10474       return ocs_described_template;
10475     return isTemplate ? ocs_template : ocs_non_template;
10476   }();
10477 
10478   OverloadCandidateKind Kind = [&]() {
10479     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10480       return oc_implicit_equality_comparison;
10481 
10482     if (CRK & CRK_Reversed)
10483       return oc_reversed_binary_operator;
10484 
10485     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10486       if (!Ctor->isImplicit()) {
10487         if (isa<ConstructorUsingShadowDecl>(Found))
10488           return oc_inherited_constructor;
10489         else
10490           return oc_constructor;
10491       }
10492 
10493       if (Ctor->isDefaultConstructor())
10494         return oc_implicit_default_constructor;
10495 
10496       if (Ctor->isMoveConstructor())
10497         return oc_implicit_move_constructor;
10498 
10499       assert(Ctor->isCopyConstructor() &&
10500              "unexpected sort of implicit constructor");
10501       return oc_implicit_copy_constructor;
10502     }
10503 
10504     if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10505       // This actually gets spelled 'candidate function' for now, but
10506       // it doesn't hurt to split it out.
10507       if (!Meth->isImplicit())
10508         return oc_method;
10509 
10510       if (Meth->isMoveAssignmentOperator())
10511         return oc_implicit_move_assignment;
10512 
10513       if (Meth->isCopyAssignmentOperator())
10514         return oc_implicit_copy_assignment;
10515 
10516       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10517       return oc_method;
10518     }
10519 
10520     return oc_function;
10521   }();
10522 
10523   return std::make_pair(Kind, Select);
10524 }
10525 
10526 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10527   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10528   // set.
10529   if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10530     S.Diag(FoundDecl->getLocation(),
10531            diag::note_ovl_candidate_inherited_constructor)
10532       << Shadow->getNominatedBaseClass();
10533 }
10534 
10535 } // end anonymous namespace
10536 
10537 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10538                                     const FunctionDecl *FD) {
10539   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10540     bool AlwaysTrue;
10541     if (EnableIf->getCond()->isValueDependent() ||
10542         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10543       return false;
10544     if (!AlwaysTrue)
10545       return false;
10546   }
10547   return true;
10548 }
10549 
10550 /// Returns true if we can take the address of the function.
10551 ///
10552 /// \param Complain - If true, we'll emit a diagnostic
10553 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10554 ///   we in overload resolution?
10555 /// \param Loc - The location of the statement we're complaining about. Ignored
10556 ///   if we're not complaining, or if we're in overload resolution.
10557 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10558                                               bool Complain,
10559                                               bool InOverloadResolution,
10560                                               SourceLocation Loc) {
10561   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10562     if (Complain) {
10563       if (InOverloadResolution)
10564         S.Diag(FD->getBeginLoc(),
10565                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10566       else
10567         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10568     }
10569     return false;
10570   }
10571 
10572   if (FD->getTrailingRequiresClause()) {
10573     ConstraintSatisfaction Satisfaction;
10574     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10575       return false;
10576     if (!Satisfaction.IsSatisfied) {
10577       if (Complain) {
10578         if (InOverloadResolution) {
10579           SmallString<128> TemplateArgString;
10580           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10581             TemplateArgString += " ";
10582             TemplateArgString += S.getTemplateArgumentBindingsText(
10583                 FunTmpl->getTemplateParameters(),
10584                 *FD->getTemplateSpecializationArgs());
10585           }
10586 
10587           S.Diag(FD->getBeginLoc(),
10588                  diag::note_ovl_candidate_unsatisfied_constraints)
10589               << TemplateArgString;
10590         } else
10591           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10592               << FD;
10593         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10594       }
10595       return false;
10596     }
10597   }
10598 
10599   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10600     return P->hasAttr<PassObjectSizeAttr>();
10601   });
10602   if (I == FD->param_end())
10603     return true;
10604 
10605   if (Complain) {
10606     // Add one to ParamNo because it's user-facing
10607     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10608     if (InOverloadResolution)
10609       S.Diag(FD->getLocation(),
10610              diag::note_ovl_candidate_has_pass_object_size_params)
10611           << ParamNo;
10612     else
10613       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10614           << FD << ParamNo;
10615   }
10616   return false;
10617 }
10618 
10619 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10620                                                const FunctionDecl *FD) {
10621   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10622                                            /*InOverloadResolution=*/true,
10623                                            /*Loc=*/SourceLocation());
10624 }
10625 
10626 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10627                                              bool Complain,
10628                                              SourceLocation Loc) {
10629   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10630                                              /*InOverloadResolution=*/false,
10631                                              Loc);
10632 }
10633 
10634 // Don't print candidates other than the one that matches the calling
10635 // convention of the call operator, since that is guaranteed to exist.
10636 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
10637   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10638 
10639   if (!ConvD)
10640     return false;
10641   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10642   if (!RD->isLambda())
10643     return false;
10644 
10645   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10646   CallingConv CallOpCC =
10647       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10648   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10649   CallingConv ConvToCC =
10650       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10651 
10652   return ConvToCC != CallOpCC;
10653 }
10654 
10655 // Notes the location of an overload candidate.
10656 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
10657                                  OverloadCandidateRewriteKind RewriteKind,
10658                                  QualType DestType, bool TakingAddress) {
10659   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10660     return;
10661   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10662       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10663     return;
10664   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
10665       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
10666     return;
10667   if (shouldSkipNotingLambdaConversionDecl(Fn))
10668     return;
10669 
10670   std::string FnDesc;
10671   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10672       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10673   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10674                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10675                          << Fn << FnDesc;
10676 
10677   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10678   Diag(Fn->getLocation(), PD);
10679   MaybeEmitInheritedConstructorNote(*this, Found);
10680 }
10681 
10682 static void
10683 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10684   // Perhaps the ambiguity was caused by two atomic constraints that are
10685   // 'identical' but not equivalent:
10686   //
10687   // void foo() requires (sizeof(T) > 4) { } // #1
10688   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10689   //
10690   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10691   // #2 to subsume #1, but these constraint are not considered equivalent
10692   // according to the subsumption rules because they are not the same
10693   // source-level construct. This behavior is quite confusing and we should try
10694   // to help the user figure out what happened.
10695 
10696   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10697   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10698   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10699     if (!I->Function)
10700       continue;
10701     SmallVector<const Expr *, 3> AC;
10702     if (auto *Template = I->Function->getPrimaryTemplate())
10703       Template->getAssociatedConstraints(AC);
10704     else
10705       I->Function->getAssociatedConstraints(AC);
10706     if (AC.empty())
10707       continue;
10708     if (FirstCand == nullptr) {
10709       FirstCand = I->Function;
10710       FirstAC = AC;
10711     } else if (SecondCand == nullptr) {
10712       SecondCand = I->Function;
10713       SecondAC = AC;
10714     } else {
10715       // We have more than one pair of constrained functions - this check is
10716       // expensive and we'd rather not try to diagnose it.
10717       return;
10718     }
10719   }
10720   if (!SecondCand)
10721     return;
10722   // The diagnostic can only happen if there are associated constraints on
10723   // both sides (there needs to be some identical atomic constraint).
10724   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10725                                                       SecondCand, SecondAC))
10726     // Just show the user one diagnostic, they'll probably figure it out
10727     // from here.
10728     return;
10729 }
10730 
10731 // Notes the location of all overload candidates designated through
10732 // OverloadedExpr
10733 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10734                                      bool TakingAddress) {
10735   assert(OverloadedExpr->getType() == Context.OverloadTy);
10736 
10737   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10738   OverloadExpr *OvlExpr = Ovl.Expression;
10739 
10740   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10741                             IEnd = OvlExpr->decls_end();
10742        I != IEnd; ++I) {
10743     if (FunctionTemplateDecl *FunTmpl =
10744                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10745       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10746                             TakingAddress);
10747     } else if (FunctionDecl *Fun
10748                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10749       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10750     }
10751   }
10752 }
10753 
10754 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10755 /// "lead" diagnostic; it will be given two arguments, the source and
10756 /// target types of the conversion.
10757 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10758                                  Sema &S,
10759                                  SourceLocation CaretLoc,
10760                                  const PartialDiagnostic &PDiag) const {
10761   S.Diag(CaretLoc, PDiag)
10762     << Ambiguous.getFromType() << Ambiguous.getToType();
10763   unsigned CandsShown = 0;
10764   AmbiguousConversionSequence::const_iterator I, E;
10765   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10766     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10767       break;
10768     ++CandsShown;
10769     S.NoteOverloadCandidate(I->first, I->second);
10770   }
10771   S.Diags.overloadCandidatesShown(CandsShown);
10772   if (I != E)
10773     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10774 }
10775 
10776 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10777                                   unsigned I, bool TakingCandidateAddress) {
10778   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10779   assert(Conv.isBad());
10780   assert(Cand->Function && "for now, candidate must be a function");
10781   FunctionDecl *Fn = Cand->Function;
10782 
10783   // There's a conversion slot for the object argument if this is a
10784   // non-constructor method.  Note that 'I' corresponds the
10785   // conversion-slot index.
10786   bool isObjectArgument = false;
10787   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10788     if (I == 0)
10789       isObjectArgument = true;
10790     else
10791       I--;
10792   }
10793 
10794   std::string FnDesc;
10795   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10796       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10797                                 FnDesc);
10798 
10799   Expr *FromExpr = Conv.Bad.FromExpr;
10800   QualType FromTy = Conv.Bad.getFromType();
10801   QualType ToTy = Conv.Bad.getToType();
10802   SourceRange ToParamRange =
10803       !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
10804 
10805   if (FromTy == S.Context.OverloadTy) {
10806     assert(FromExpr && "overload set argument came from implicit argument?");
10807     Expr *E = FromExpr->IgnoreParens();
10808     if (isa<UnaryOperator>(E))
10809       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10810     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10811 
10812     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10813         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10814         << ToParamRange << ToTy << Name << I + 1;
10815     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10816     return;
10817   }
10818 
10819   // Do some hand-waving analysis to see if the non-viability is due
10820   // to a qualifier mismatch.
10821   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10822   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10823   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10824     CToTy = RT->getPointeeType();
10825   else {
10826     // TODO: detect and diagnose the full richness of const mismatches.
10827     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10828       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10829         CFromTy = FromPT->getPointeeType();
10830         CToTy = ToPT->getPointeeType();
10831       }
10832   }
10833 
10834   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10835       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10836     Qualifiers FromQs = CFromTy.getQualifiers();
10837     Qualifiers ToQs = CToTy.getQualifiers();
10838 
10839     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10840       if (isObjectArgument)
10841         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10842             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10843             << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10844       else
10845         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10846             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10847             << FnDesc << ToParamRange << FromQs.getAddressSpace()
10848             << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
10849       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10850       return;
10851     }
10852 
10853     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10854       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10855           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10856           << ToParamRange << FromTy << FromQs.getObjCLifetime()
10857           << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
10858       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10859       return;
10860     }
10861 
10862     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10863       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10864           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10865           << ToParamRange << FromTy << FromQs.getObjCGCAttr()
10866           << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
10867       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10868       return;
10869     }
10870 
10871     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10872     assert(CVR && "expected qualifiers mismatch");
10873 
10874     if (isObjectArgument) {
10875       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10876           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10877           << FromTy << (CVR - 1);
10878     } else {
10879       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10880           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10881           << ToParamRange << FromTy << (CVR - 1) << I + 1;
10882     }
10883     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10884     return;
10885   }
10886 
10887   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10888       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10889     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10890         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10891         << (unsigned)isObjectArgument << I + 1
10892         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10893         << ToParamRange;
10894     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10895     return;
10896   }
10897 
10898   // Special diagnostic for failure to convert an initializer list, since
10899   // telling the user that it has type void is not useful.
10900   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10901     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10902         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10903         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10904         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10905             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10906                 ? 2
10907                 : 0);
10908     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10909     return;
10910   }
10911 
10912   // Diagnose references or pointers to incomplete types differently,
10913   // since it's far from impossible that the incompleteness triggered
10914   // the failure.
10915   QualType TempFromTy = FromTy.getNonReferenceType();
10916   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10917     TempFromTy = PTy->getPointeeType();
10918   if (TempFromTy->isIncompleteType()) {
10919     // Emit the generic diagnostic and, optionally, add the hints to it.
10920     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10921         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10922         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10923         << (unsigned)(Cand->Fix.Kind);
10924 
10925     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10926     return;
10927   }
10928 
10929   // Diagnose base -> derived pointer conversions.
10930   unsigned BaseToDerivedConversion = 0;
10931   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10932     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10933       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10934                                                FromPtrTy->getPointeeType()) &&
10935           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10936           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10937           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10938                           FromPtrTy->getPointeeType()))
10939         BaseToDerivedConversion = 1;
10940     }
10941   } else if (const ObjCObjectPointerType *FromPtrTy
10942                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10943     if (const ObjCObjectPointerType *ToPtrTy
10944                                         = ToTy->getAs<ObjCObjectPointerType>())
10945       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10946         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10947           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10948                                                 FromPtrTy->getPointeeType()) &&
10949               FromIface->isSuperClassOf(ToIface))
10950             BaseToDerivedConversion = 2;
10951   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10952     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10953         !FromTy->isIncompleteType() &&
10954         !ToRefTy->getPointeeType()->isIncompleteType() &&
10955         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10956       BaseToDerivedConversion = 3;
10957     }
10958   }
10959 
10960   if (BaseToDerivedConversion) {
10961     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10962         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10963         << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
10964         << I + 1;
10965     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10966     return;
10967   }
10968 
10969   if (isa<ObjCObjectPointerType>(CFromTy) &&
10970       isa<PointerType>(CToTy)) {
10971     Qualifiers FromQs = CFromTy.getQualifiers();
10972     Qualifiers ToQs = CToTy.getQualifiers();
10973     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10974       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10975           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10976           << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
10977           << I + 1;
10978       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10979       return;
10980     }
10981   }
10982 
10983   if (TakingCandidateAddress &&
10984       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10985     return;
10986 
10987   // Emit the generic diagnostic and, optionally, add the hints to it.
10988   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10989   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10990         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10991         << (unsigned)(Cand->Fix.Kind);
10992 
10993   // Check that location of Fn is not in system header.
10994   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
10995     // If we can fix the conversion, suggest the FixIts.
10996     for (const FixItHint &HI : Cand->Fix.Hints)
10997         FDiag << HI;
10998   }
10999 
11000   S.Diag(Fn->getLocation(), FDiag);
11001 
11002   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11003 }
11004 
11005 /// Additional arity mismatch diagnosis specific to a function overload
11006 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11007 /// over a candidate in any candidate set.
11008 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11009                                unsigned NumArgs) {
11010   FunctionDecl *Fn = Cand->Function;
11011   unsigned MinParams = Fn->getMinRequiredArguments();
11012 
11013   // With invalid overloaded operators, it's possible that we think we
11014   // have an arity mismatch when in fact it looks like we have the
11015   // right number of arguments, because only overloaded operators have
11016   // the weird behavior of overloading member and non-member functions.
11017   // Just don't report anything.
11018   if (Fn->isInvalidDecl() &&
11019       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11020     return true;
11021 
11022   if (NumArgs < MinParams) {
11023     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11024            (Cand->FailureKind == ovl_fail_bad_deduction &&
11025             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
11026   } else {
11027     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11028            (Cand->FailureKind == ovl_fail_bad_deduction &&
11029             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
11030   }
11031 
11032   return false;
11033 }
11034 
11035 /// General arity mismatch diagnosis over a candidate in a candidate set.
11036 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11037                                   unsigned NumFormalArgs) {
11038   assert(isa<FunctionDecl>(D) &&
11039       "The templated declaration should at least be a function"
11040       " when diagnosing bad template argument deduction due to too many"
11041       " or too few arguments");
11042 
11043   FunctionDecl *Fn = cast<FunctionDecl>(D);
11044 
11045   // TODO: treat calls to a missing default constructor as a special case
11046   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11047   unsigned MinParams = Fn->getMinRequiredArguments();
11048 
11049   // at least / at most / exactly
11050   unsigned mode, modeCount;
11051   if (NumFormalArgs < MinParams) {
11052     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
11053         FnTy->isTemplateVariadic())
11054       mode = 0; // "at least"
11055     else
11056       mode = 2; // "exactly"
11057     modeCount = MinParams;
11058   } else {
11059     if (MinParams != FnTy->getNumParams())
11060       mode = 1; // "at most"
11061     else
11062       mode = 2; // "exactly"
11063     modeCount = FnTy->getNumParams();
11064   }
11065 
11066   std::string Description;
11067   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11068       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11069 
11070   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
11071     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11072         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11073         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs
11074         << Fn->getParametersSourceRange();
11075   else
11076     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11077         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11078         << Description << mode << modeCount << NumFormalArgs
11079         << Fn->getParametersSourceRange();
11080 
11081   MaybeEmitInheritedConstructorNote(S, Found);
11082 }
11083 
11084 /// Arity mismatch diagnosis specific to a function overload candidate.
11085 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11086                                   unsigned NumFormalArgs) {
11087   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11088     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11089 }
11090 
11091 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11092   if (TemplateDecl *TD = Templated->getDescribedTemplate())
11093     return TD;
11094   llvm_unreachable("Unsupported: Getting the described template declaration"
11095                    " for bad deduction diagnosis");
11096 }
11097 
11098 /// Diagnose a failed template-argument deduction.
11099 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11100                                  DeductionFailureInfo &DeductionFailure,
11101                                  unsigned NumArgs,
11102                                  bool TakingCandidateAddress) {
11103   TemplateParameter Param = DeductionFailure.getTemplateParameter();
11104   NamedDecl *ParamD;
11105   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11106   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11107   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11108   switch (DeductionFailure.Result) {
11109   case Sema::TDK_Success:
11110     llvm_unreachable("TDK_success while diagnosing bad deduction");
11111 
11112   case Sema::TDK_Incomplete: {
11113     assert(ParamD && "no parameter found for incomplete deduction result");
11114     S.Diag(Templated->getLocation(),
11115            diag::note_ovl_candidate_incomplete_deduction)
11116         << ParamD->getDeclName();
11117     MaybeEmitInheritedConstructorNote(S, Found);
11118     return;
11119   }
11120 
11121   case Sema::TDK_IncompletePack: {
11122     assert(ParamD && "no parameter found for incomplete deduction result");
11123     S.Diag(Templated->getLocation(),
11124            diag::note_ovl_candidate_incomplete_deduction_pack)
11125         << ParamD->getDeclName()
11126         << (DeductionFailure.getFirstArg()->pack_size() + 1)
11127         << *DeductionFailure.getFirstArg();
11128     MaybeEmitInheritedConstructorNote(S, Found);
11129     return;
11130   }
11131 
11132   case Sema::TDK_Underqualified: {
11133     assert(ParamD && "no parameter found for bad qualifiers deduction result");
11134     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11135 
11136     QualType Param = DeductionFailure.getFirstArg()->getAsType();
11137 
11138     // Param will have been canonicalized, but it should just be a
11139     // qualified version of ParamD, so move the qualifiers to that.
11140     QualifierCollector Qs;
11141     Qs.strip(Param);
11142     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11143     assert(S.Context.hasSameType(Param, NonCanonParam));
11144 
11145     // Arg has also been canonicalized, but there's nothing we can do
11146     // about that.  It also doesn't matter as much, because it won't
11147     // have any template parameters in it (because deduction isn't
11148     // done on dependent types).
11149     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11150 
11151     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11152         << ParamD->getDeclName() << Arg << NonCanonParam;
11153     MaybeEmitInheritedConstructorNote(S, Found);
11154     return;
11155   }
11156 
11157   case Sema::TDK_Inconsistent: {
11158     assert(ParamD && "no parameter found for inconsistent deduction result");
11159     int which = 0;
11160     if (isa<TemplateTypeParmDecl>(ParamD))
11161       which = 0;
11162     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11163       // Deduction might have failed because we deduced arguments of two
11164       // different types for a non-type template parameter.
11165       // FIXME: Use a different TDK value for this.
11166       QualType T1 =
11167           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11168       QualType T2 =
11169           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11170       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11171         S.Diag(Templated->getLocation(),
11172                diag::note_ovl_candidate_inconsistent_deduction_types)
11173           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11174           << *DeductionFailure.getSecondArg() << T2;
11175         MaybeEmitInheritedConstructorNote(S, Found);
11176         return;
11177       }
11178 
11179       which = 1;
11180     } else {
11181       which = 2;
11182     }
11183 
11184     // Tweak the diagnostic if the problem is that we deduced packs of
11185     // different arities. We'll print the actual packs anyway in case that
11186     // includes additional useful information.
11187     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11188         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11189         DeductionFailure.getFirstArg()->pack_size() !=
11190             DeductionFailure.getSecondArg()->pack_size()) {
11191       which = 3;
11192     }
11193 
11194     S.Diag(Templated->getLocation(),
11195            diag::note_ovl_candidate_inconsistent_deduction)
11196         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11197         << *DeductionFailure.getSecondArg();
11198     MaybeEmitInheritedConstructorNote(S, Found);
11199     return;
11200   }
11201 
11202   case Sema::TDK_InvalidExplicitArguments:
11203     assert(ParamD && "no parameter found for invalid explicit arguments");
11204     if (ParamD->getDeclName())
11205       S.Diag(Templated->getLocation(),
11206              diag::note_ovl_candidate_explicit_arg_mismatch_named)
11207           << ParamD->getDeclName();
11208     else {
11209       int index = 0;
11210       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11211         index = TTP->getIndex();
11212       else if (NonTypeTemplateParmDecl *NTTP
11213                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11214         index = NTTP->getIndex();
11215       else
11216         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11217       S.Diag(Templated->getLocation(),
11218              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11219           << (index + 1);
11220     }
11221     MaybeEmitInheritedConstructorNote(S, Found);
11222     return;
11223 
11224   case Sema::TDK_ConstraintsNotSatisfied: {
11225     // Format the template argument list into the argument string.
11226     SmallString<128> TemplateArgString;
11227     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11228     TemplateArgString = " ";
11229     TemplateArgString += S.getTemplateArgumentBindingsText(
11230         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11231     if (TemplateArgString.size() == 1)
11232       TemplateArgString.clear();
11233     S.Diag(Templated->getLocation(),
11234            diag::note_ovl_candidate_unsatisfied_constraints)
11235         << TemplateArgString;
11236 
11237     S.DiagnoseUnsatisfiedConstraint(
11238         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11239     return;
11240   }
11241   case Sema::TDK_TooManyArguments:
11242   case Sema::TDK_TooFewArguments:
11243     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11244     return;
11245 
11246   case Sema::TDK_InstantiationDepth:
11247     S.Diag(Templated->getLocation(),
11248            diag::note_ovl_candidate_instantiation_depth);
11249     MaybeEmitInheritedConstructorNote(S, Found);
11250     return;
11251 
11252   case Sema::TDK_SubstitutionFailure: {
11253     // Format the template argument list into the argument string.
11254     SmallString<128> TemplateArgString;
11255     if (TemplateArgumentList *Args =
11256             DeductionFailure.getTemplateArgumentList()) {
11257       TemplateArgString = " ";
11258       TemplateArgString += S.getTemplateArgumentBindingsText(
11259           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11260       if (TemplateArgString.size() == 1)
11261         TemplateArgString.clear();
11262     }
11263 
11264     // If this candidate was disabled by enable_if, say so.
11265     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11266     if (PDiag && PDiag->second.getDiagID() ==
11267           diag::err_typename_nested_not_found_enable_if) {
11268       // FIXME: Use the source range of the condition, and the fully-qualified
11269       //        name of the enable_if template. These are both present in PDiag.
11270       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11271         << "'enable_if'" << TemplateArgString;
11272       return;
11273     }
11274 
11275     // We found a specific requirement that disabled the enable_if.
11276     if (PDiag && PDiag->second.getDiagID() ==
11277         diag::err_typename_nested_not_found_requirement) {
11278       S.Diag(Templated->getLocation(),
11279              diag::note_ovl_candidate_disabled_by_requirement)
11280         << PDiag->second.getStringArg(0) << TemplateArgString;
11281       return;
11282     }
11283 
11284     // Format the SFINAE diagnostic into the argument string.
11285     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11286     //        formatted message in another diagnostic.
11287     SmallString<128> SFINAEArgString;
11288     SourceRange R;
11289     if (PDiag) {
11290       SFINAEArgString = ": ";
11291       R = SourceRange(PDiag->first, PDiag->first);
11292       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11293     }
11294 
11295     S.Diag(Templated->getLocation(),
11296            diag::note_ovl_candidate_substitution_failure)
11297         << TemplateArgString << SFINAEArgString << R;
11298     MaybeEmitInheritedConstructorNote(S, Found);
11299     return;
11300   }
11301 
11302   case Sema::TDK_DeducedMismatch:
11303   case Sema::TDK_DeducedMismatchNested: {
11304     // Format the template argument list into the argument string.
11305     SmallString<128> TemplateArgString;
11306     if (TemplateArgumentList *Args =
11307             DeductionFailure.getTemplateArgumentList()) {
11308       TemplateArgString = " ";
11309       TemplateArgString += S.getTemplateArgumentBindingsText(
11310           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11311       if (TemplateArgString.size() == 1)
11312         TemplateArgString.clear();
11313     }
11314 
11315     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11316         << (*DeductionFailure.getCallArgIndex() + 1)
11317         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11318         << TemplateArgString
11319         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11320     break;
11321   }
11322 
11323   case Sema::TDK_NonDeducedMismatch: {
11324     // FIXME: Provide a source location to indicate what we couldn't match.
11325     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11326     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11327     if (FirstTA.getKind() == TemplateArgument::Template &&
11328         SecondTA.getKind() == TemplateArgument::Template) {
11329       TemplateName FirstTN = FirstTA.getAsTemplate();
11330       TemplateName SecondTN = SecondTA.getAsTemplate();
11331       if (FirstTN.getKind() == TemplateName::Template &&
11332           SecondTN.getKind() == TemplateName::Template) {
11333         if (FirstTN.getAsTemplateDecl()->getName() ==
11334             SecondTN.getAsTemplateDecl()->getName()) {
11335           // FIXME: This fixes a bad diagnostic where both templates are named
11336           // the same.  This particular case is a bit difficult since:
11337           // 1) It is passed as a string to the diagnostic printer.
11338           // 2) The diagnostic printer only attempts to find a better
11339           //    name for types, not decls.
11340           // Ideally, this should folded into the diagnostic printer.
11341           S.Diag(Templated->getLocation(),
11342                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11343               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11344           return;
11345         }
11346       }
11347     }
11348 
11349     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11350         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11351       return;
11352 
11353     // FIXME: For generic lambda parameters, check if the function is a lambda
11354     // call operator, and if so, emit a prettier and more informative
11355     // diagnostic that mentions 'auto' and lambda in addition to
11356     // (or instead of?) the canonical template type parameters.
11357     S.Diag(Templated->getLocation(),
11358            diag::note_ovl_candidate_non_deduced_mismatch)
11359         << FirstTA << SecondTA;
11360     return;
11361   }
11362   // TODO: diagnose these individually, then kill off
11363   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11364   case Sema::TDK_MiscellaneousDeductionFailure:
11365     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11366     MaybeEmitInheritedConstructorNote(S, Found);
11367     return;
11368   case Sema::TDK_CUDATargetMismatch:
11369     S.Diag(Templated->getLocation(),
11370            diag::note_cuda_ovl_candidate_target_mismatch);
11371     return;
11372   }
11373 }
11374 
11375 /// Diagnose a failed template-argument deduction, for function calls.
11376 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11377                                  unsigned NumArgs,
11378                                  bool TakingCandidateAddress) {
11379   unsigned TDK = Cand->DeductionFailure.Result;
11380   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11381     if (CheckArityMismatch(S, Cand, NumArgs))
11382       return;
11383   }
11384   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11385                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11386 }
11387 
11388 /// CUDA: diagnose an invalid call across targets.
11389 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11390   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11391   FunctionDecl *Callee = Cand->Function;
11392 
11393   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11394                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11395 
11396   std::string FnDesc;
11397   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11398       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11399                                 Cand->getRewriteKind(), FnDesc);
11400 
11401   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11402       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11403       << FnDesc /* Ignored */
11404       << CalleeTarget << CallerTarget;
11405 
11406   // This could be an implicit constructor for which we could not infer the
11407   // target due to a collsion. Diagnose that case.
11408   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11409   if (Meth != nullptr && Meth->isImplicit()) {
11410     CXXRecordDecl *ParentClass = Meth->getParent();
11411     Sema::CXXSpecialMember CSM;
11412 
11413     switch (FnKindPair.first) {
11414     default:
11415       return;
11416     case oc_implicit_default_constructor:
11417       CSM = Sema::CXXDefaultConstructor;
11418       break;
11419     case oc_implicit_copy_constructor:
11420       CSM = Sema::CXXCopyConstructor;
11421       break;
11422     case oc_implicit_move_constructor:
11423       CSM = Sema::CXXMoveConstructor;
11424       break;
11425     case oc_implicit_copy_assignment:
11426       CSM = Sema::CXXCopyAssignment;
11427       break;
11428     case oc_implicit_move_assignment:
11429       CSM = Sema::CXXMoveAssignment;
11430       break;
11431     };
11432 
11433     bool ConstRHS = false;
11434     if (Meth->getNumParams()) {
11435       if (const ReferenceType *RT =
11436               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11437         ConstRHS = RT->getPointeeType().isConstQualified();
11438       }
11439     }
11440 
11441     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11442                                               /* ConstRHS */ ConstRHS,
11443                                               /* Diagnose */ true);
11444   }
11445 }
11446 
11447 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11448   FunctionDecl *Callee = Cand->Function;
11449   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11450 
11451   S.Diag(Callee->getLocation(),
11452          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11453       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11454 }
11455 
11456 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11457   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11458   assert(ES.isExplicit() && "not an explicit candidate");
11459 
11460   unsigned Kind;
11461   switch (Cand->Function->getDeclKind()) {
11462   case Decl::Kind::CXXConstructor:
11463     Kind = 0;
11464     break;
11465   case Decl::Kind::CXXConversion:
11466     Kind = 1;
11467     break;
11468   case Decl::Kind::CXXDeductionGuide:
11469     Kind = Cand->Function->isImplicit() ? 0 : 2;
11470     break;
11471   default:
11472     llvm_unreachable("invalid Decl");
11473   }
11474 
11475   // Note the location of the first (in-class) declaration; a redeclaration
11476   // (particularly an out-of-class definition) will typically lack the
11477   // 'explicit' specifier.
11478   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11479   FunctionDecl *First = Cand->Function->getFirstDecl();
11480   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11481     First = Pattern->getFirstDecl();
11482 
11483   S.Diag(First->getLocation(),
11484          diag::note_ovl_candidate_explicit)
11485       << Kind << (ES.getExpr() ? 1 : 0)
11486       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11487 }
11488 
11489 /// Generates a 'note' diagnostic for an overload candidate.  We've
11490 /// already generated a primary error at the call site.
11491 ///
11492 /// It really does need to be a single diagnostic with its caret
11493 /// pointed at the candidate declaration.  Yes, this creates some
11494 /// major challenges of technical writing.  Yes, this makes pointing
11495 /// out problems with specific arguments quite awkward.  It's still
11496 /// better than generating twenty screens of text for every failed
11497 /// overload.
11498 ///
11499 /// It would be great to be able to express per-candidate problems
11500 /// more richly for those diagnostic clients that cared, but we'd
11501 /// still have to be just as careful with the default diagnostics.
11502 /// \param CtorDestAS Addr space of object being constructed (for ctor
11503 /// candidates only).
11504 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11505                                   unsigned NumArgs,
11506                                   bool TakingCandidateAddress,
11507                                   LangAS CtorDestAS = LangAS::Default) {
11508   FunctionDecl *Fn = Cand->Function;
11509   if (shouldSkipNotingLambdaConversionDecl(Fn))
11510     return;
11511 
11512   // There is no physical candidate declaration to point to for OpenCL builtins.
11513   // Except for failed conversions, the notes are identical for each candidate,
11514   // so do not generate such notes.
11515   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11516       Cand->FailureKind != ovl_fail_bad_conversion)
11517     return;
11518 
11519   // Note deleted candidates, but only if they're viable.
11520   if (Cand->Viable) {
11521     if (Fn->isDeleted()) {
11522       std::string FnDesc;
11523       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11524           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11525                                     Cand->getRewriteKind(), FnDesc);
11526 
11527       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11528           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11529           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11530       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11531       return;
11532     }
11533 
11534     // We don't really have anything else to say about viable candidates.
11535     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11536     return;
11537   }
11538 
11539   switch (Cand->FailureKind) {
11540   case ovl_fail_too_many_arguments:
11541   case ovl_fail_too_few_arguments:
11542     return DiagnoseArityMismatch(S, Cand, NumArgs);
11543 
11544   case ovl_fail_bad_deduction:
11545     return DiagnoseBadDeduction(S, Cand, NumArgs,
11546                                 TakingCandidateAddress);
11547 
11548   case ovl_fail_illegal_constructor: {
11549     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11550       << (Fn->getPrimaryTemplate() ? 1 : 0);
11551     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11552     return;
11553   }
11554 
11555   case ovl_fail_object_addrspace_mismatch: {
11556     Qualifiers QualsForPrinting;
11557     QualsForPrinting.setAddressSpace(CtorDestAS);
11558     S.Diag(Fn->getLocation(),
11559            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11560         << QualsForPrinting;
11561     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11562     return;
11563   }
11564 
11565   case ovl_fail_trivial_conversion:
11566   case ovl_fail_bad_final_conversion:
11567   case ovl_fail_final_conversion_not_exact:
11568     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11569 
11570   case ovl_fail_bad_conversion: {
11571     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11572     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11573       if (Cand->Conversions[I].isBad())
11574         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11575 
11576     // FIXME: this currently happens when we're called from SemaInit
11577     // when user-conversion overload fails.  Figure out how to handle
11578     // those conditions and diagnose them well.
11579     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11580   }
11581 
11582   case ovl_fail_bad_target:
11583     return DiagnoseBadTarget(S, Cand);
11584 
11585   case ovl_fail_enable_if:
11586     return DiagnoseFailedEnableIfAttr(S, Cand);
11587 
11588   case ovl_fail_explicit:
11589     return DiagnoseFailedExplicitSpec(S, Cand);
11590 
11591   case ovl_fail_inhctor_slice:
11592     // It's generally not interesting to note copy/move constructors here.
11593     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11594       return;
11595     S.Diag(Fn->getLocation(),
11596            diag::note_ovl_candidate_inherited_constructor_slice)
11597       << (Fn->getPrimaryTemplate() ? 1 : 0)
11598       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11599     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11600     return;
11601 
11602   case ovl_fail_addr_not_available: {
11603     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11604     (void)Available;
11605     assert(!Available);
11606     break;
11607   }
11608   case ovl_non_default_multiversion_function:
11609     // Do nothing, these should simply be ignored.
11610     break;
11611 
11612   case ovl_fail_constraints_not_satisfied: {
11613     std::string FnDesc;
11614     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11615         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11616                                   Cand->getRewriteKind(), FnDesc);
11617 
11618     S.Diag(Fn->getLocation(),
11619            diag::note_ovl_candidate_constraints_not_satisfied)
11620         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11621         << FnDesc /* Ignored */;
11622     ConstraintSatisfaction Satisfaction;
11623     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11624       break;
11625     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11626   }
11627   }
11628 }
11629 
11630 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11631   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11632     return;
11633 
11634   // Desugar the type of the surrogate down to a function type,
11635   // retaining as many typedefs as possible while still showing
11636   // the function type (and, therefore, its parameter types).
11637   QualType FnType = Cand->Surrogate->getConversionType();
11638   bool isLValueReference = false;
11639   bool isRValueReference = false;
11640   bool isPointer = false;
11641   if (const LValueReferenceType *FnTypeRef =
11642         FnType->getAs<LValueReferenceType>()) {
11643     FnType = FnTypeRef->getPointeeType();
11644     isLValueReference = true;
11645   } else if (const RValueReferenceType *FnTypeRef =
11646                FnType->getAs<RValueReferenceType>()) {
11647     FnType = FnTypeRef->getPointeeType();
11648     isRValueReference = true;
11649   }
11650   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11651     FnType = FnTypePtr->getPointeeType();
11652     isPointer = true;
11653   }
11654   // Desugar down to a function type.
11655   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11656   // Reconstruct the pointer/reference as appropriate.
11657   if (isPointer) FnType = S.Context.getPointerType(FnType);
11658   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11659   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11660 
11661   if (!Cand->Viable &&
11662       Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
11663     S.Diag(Cand->Surrogate->getLocation(),
11664            diag::note_ovl_surrogate_constraints_not_satisfied)
11665         << Cand->Surrogate;
11666     ConstraintSatisfaction Satisfaction;
11667     if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
11668       S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11669   } else {
11670     S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11671         << FnType;
11672   }
11673 }
11674 
11675 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11676                                          SourceLocation OpLoc,
11677                                          OverloadCandidate *Cand) {
11678   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11679   std::string TypeStr("operator");
11680   TypeStr += Opc;
11681   TypeStr += "(";
11682   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11683   if (Cand->Conversions.size() == 1) {
11684     TypeStr += ")";
11685     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11686   } else {
11687     TypeStr += ", ";
11688     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11689     TypeStr += ")";
11690     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11691   }
11692 }
11693 
11694 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11695                                          OverloadCandidate *Cand) {
11696   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11697     if (ICS.isBad()) break; // all meaningless after first invalid
11698     if (!ICS.isAmbiguous()) continue;
11699 
11700     ICS.DiagnoseAmbiguousConversion(
11701         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11702   }
11703 }
11704 
11705 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11706   if (Cand->Function)
11707     return Cand->Function->getLocation();
11708   if (Cand->IsSurrogate)
11709     return Cand->Surrogate->getLocation();
11710   return SourceLocation();
11711 }
11712 
11713 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11714   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11715   case Sema::TDK_Success:
11716   case Sema::TDK_NonDependentConversionFailure:
11717   case Sema::TDK_AlreadyDiagnosed:
11718     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11719 
11720   case Sema::TDK_Invalid:
11721   case Sema::TDK_Incomplete:
11722   case Sema::TDK_IncompletePack:
11723     return 1;
11724 
11725   case Sema::TDK_Underqualified:
11726   case Sema::TDK_Inconsistent:
11727     return 2;
11728 
11729   case Sema::TDK_SubstitutionFailure:
11730   case Sema::TDK_DeducedMismatch:
11731   case Sema::TDK_ConstraintsNotSatisfied:
11732   case Sema::TDK_DeducedMismatchNested:
11733   case Sema::TDK_NonDeducedMismatch:
11734   case Sema::TDK_MiscellaneousDeductionFailure:
11735   case Sema::TDK_CUDATargetMismatch:
11736     return 3;
11737 
11738   case Sema::TDK_InstantiationDepth:
11739     return 4;
11740 
11741   case Sema::TDK_InvalidExplicitArguments:
11742     return 5;
11743 
11744   case Sema::TDK_TooManyArguments:
11745   case Sema::TDK_TooFewArguments:
11746     return 6;
11747   }
11748   llvm_unreachable("Unhandled deduction result");
11749 }
11750 
11751 namespace {
11752 struct CompareOverloadCandidatesForDisplay {
11753   Sema &S;
11754   SourceLocation Loc;
11755   size_t NumArgs;
11756   OverloadCandidateSet::CandidateSetKind CSK;
11757 
11758   CompareOverloadCandidatesForDisplay(
11759       Sema &S, SourceLocation Loc, size_t NArgs,
11760       OverloadCandidateSet::CandidateSetKind CSK)
11761       : S(S), NumArgs(NArgs), CSK(CSK) {}
11762 
11763   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11764     // If there are too many or too few arguments, that's the high-order bit we
11765     // want to sort by, even if the immediate failure kind was something else.
11766     if (C->FailureKind == ovl_fail_too_many_arguments ||
11767         C->FailureKind == ovl_fail_too_few_arguments)
11768       return static_cast<OverloadFailureKind>(C->FailureKind);
11769 
11770     if (C->Function) {
11771       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11772         return ovl_fail_too_many_arguments;
11773       if (NumArgs < C->Function->getMinRequiredArguments())
11774         return ovl_fail_too_few_arguments;
11775     }
11776 
11777     return static_cast<OverloadFailureKind>(C->FailureKind);
11778   }
11779 
11780   bool operator()(const OverloadCandidate *L,
11781                   const OverloadCandidate *R) {
11782     // Fast-path this check.
11783     if (L == R) return false;
11784 
11785     // Order first by viability.
11786     if (L->Viable) {
11787       if (!R->Viable) return true;
11788 
11789       // TODO: introduce a tri-valued comparison for overload
11790       // candidates.  Would be more worthwhile if we had a sort
11791       // that could exploit it.
11792       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11793         return true;
11794       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11795         return false;
11796     } else if (R->Viable)
11797       return false;
11798 
11799     assert(L->Viable == R->Viable);
11800 
11801     // Criteria by which we can sort non-viable candidates:
11802     if (!L->Viable) {
11803       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11804       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11805 
11806       // 1. Arity mismatches come after other candidates.
11807       if (LFailureKind == ovl_fail_too_many_arguments ||
11808           LFailureKind == ovl_fail_too_few_arguments) {
11809         if (RFailureKind == ovl_fail_too_many_arguments ||
11810             RFailureKind == ovl_fail_too_few_arguments) {
11811           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11812           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11813           if (LDist == RDist) {
11814             if (LFailureKind == RFailureKind)
11815               // Sort non-surrogates before surrogates.
11816               return !L->IsSurrogate && R->IsSurrogate;
11817             // Sort candidates requiring fewer parameters than there were
11818             // arguments given after candidates requiring more parameters
11819             // than there were arguments given.
11820             return LFailureKind == ovl_fail_too_many_arguments;
11821           }
11822           return LDist < RDist;
11823         }
11824         return false;
11825       }
11826       if (RFailureKind == ovl_fail_too_many_arguments ||
11827           RFailureKind == ovl_fail_too_few_arguments)
11828         return true;
11829 
11830       // 2. Bad conversions come first and are ordered by the number
11831       // of bad conversions and quality of good conversions.
11832       if (LFailureKind == ovl_fail_bad_conversion) {
11833         if (RFailureKind != ovl_fail_bad_conversion)
11834           return true;
11835 
11836         // The conversion that can be fixed with a smaller number of changes,
11837         // comes first.
11838         unsigned numLFixes = L->Fix.NumConversionsFixed;
11839         unsigned numRFixes = R->Fix.NumConversionsFixed;
11840         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11841         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11842         if (numLFixes != numRFixes) {
11843           return numLFixes < numRFixes;
11844         }
11845 
11846         // If there's any ordering between the defined conversions...
11847         // FIXME: this might not be transitive.
11848         assert(L->Conversions.size() == R->Conversions.size());
11849 
11850         int leftBetter = 0;
11851         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11852         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11853           switch (CompareImplicitConversionSequences(S, Loc,
11854                                                      L->Conversions[I],
11855                                                      R->Conversions[I])) {
11856           case ImplicitConversionSequence::Better:
11857             leftBetter++;
11858             break;
11859 
11860           case ImplicitConversionSequence::Worse:
11861             leftBetter--;
11862             break;
11863 
11864           case ImplicitConversionSequence::Indistinguishable:
11865             break;
11866           }
11867         }
11868         if (leftBetter > 0) return true;
11869         if (leftBetter < 0) return false;
11870 
11871       } else if (RFailureKind == ovl_fail_bad_conversion)
11872         return false;
11873 
11874       if (LFailureKind == ovl_fail_bad_deduction) {
11875         if (RFailureKind != ovl_fail_bad_deduction)
11876           return true;
11877 
11878         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11879           return RankDeductionFailure(L->DeductionFailure)
11880                < RankDeductionFailure(R->DeductionFailure);
11881       } else if (RFailureKind == ovl_fail_bad_deduction)
11882         return false;
11883 
11884       // TODO: others?
11885     }
11886 
11887     // Sort everything else by location.
11888     SourceLocation LLoc = GetLocationForCandidate(L);
11889     SourceLocation RLoc = GetLocationForCandidate(R);
11890 
11891     // Put candidates without locations (e.g. builtins) at the end.
11892     if (LLoc.isInvalid()) return false;
11893     if (RLoc.isInvalid()) return true;
11894 
11895     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11896   }
11897 };
11898 }
11899 
11900 /// CompleteNonViableCandidate - Normally, overload resolution only
11901 /// computes up to the first bad conversion. Produces the FixIt set if
11902 /// possible.
11903 static void
11904 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11905                            ArrayRef<Expr *> Args,
11906                            OverloadCandidateSet::CandidateSetKind CSK) {
11907   assert(!Cand->Viable);
11908 
11909   // Don't do anything on failures other than bad conversion.
11910   if (Cand->FailureKind != ovl_fail_bad_conversion)
11911     return;
11912 
11913   // We only want the FixIts if all the arguments can be corrected.
11914   bool Unfixable = false;
11915   // Use a implicit copy initialization to check conversion fixes.
11916   Cand->Fix.setConversionChecker(TryCopyInitialization);
11917 
11918   // Attempt to fix the bad conversion.
11919   unsigned ConvCount = Cand->Conversions.size();
11920   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11921        ++ConvIdx) {
11922     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11923     if (Cand->Conversions[ConvIdx].isInitialized() &&
11924         Cand->Conversions[ConvIdx].isBad()) {
11925       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11926       break;
11927     }
11928   }
11929 
11930   // FIXME: this should probably be preserved from the overload
11931   // operation somehow.
11932   bool SuppressUserConversions = false;
11933 
11934   unsigned ConvIdx = 0;
11935   unsigned ArgIdx = 0;
11936   ArrayRef<QualType> ParamTypes;
11937   bool Reversed = Cand->isReversed();
11938 
11939   if (Cand->IsSurrogate) {
11940     QualType ConvType
11941       = Cand->Surrogate->getConversionType().getNonReferenceType();
11942     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11943       ConvType = ConvPtrType->getPointeeType();
11944     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11945     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11946     ConvIdx = 1;
11947   } else if (Cand->Function) {
11948     ParamTypes =
11949         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11950     if (isa<CXXMethodDecl>(Cand->Function) &&
11951         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11952       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11953       ConvIdx = 1;
11954       if (CSK == OverloadCandidateSet::CSK_Operator &&
11955           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11956           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11957               OO_Subscript)
11958         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11959         ArgIdx = 1;
11960     }
11961   } else {
11962     // Builtin operator.
11963     assert(ConvCount <= 3);
11964     ParamTypes = Cand->BuiltinParamTypes;
11965   }
11966 
11967   // Fill in the rest of the conversions.
11968   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11969        ConvIdx != ConvCount;
11970        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11971     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11972     if (Cand->Conversions[ConvIdx].isInitialized()) {
11973       // We've already checked this conversion.
11974     } else if (ParamIdx < ParamTypes.size()) {
11975       if (ParamTypes[ParamIdx]->isDependentType())
11976         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11977             Args[ArgIdx]->getType());
11978       else {
11979         Cand->Conversions[ConvIdx] =
11980             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11981                                   SuppressUserConversions,
11982                                   /*InOverloadResolution=*/true,
11983                                   /*AllowObjCWritebackConversion=*/
11984                                   S.getLangOpts().ObjCAutoRefCount);
11985         // Store the FixIt in the candidate if it exists.
11986         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11987           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11988       }
11989     } else
11990       Cand->Conversions[ConvIdx].setEllipsis();
11991   }
11992 }
11993 
11994 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11995     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11996     SourceLocation OpLoc,
11997     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11998   // Sort the candidates by viability and position.  Sorting directly would
11999   // be prohibitive, so we make a set of pointers and sort those.
12000   SmallVector<OverloadCandidate*, 32> Cands;
12001   if (OCD == OCD_AllCandidates) Cands.reserve(size());
12002   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12003     if (!Filter(*Cand))
12004       continue;
12005     switch (OCD) {
12006     case OCD_AllCandidates:
12007       if (!Cand->Viable) {
12008         if (!Cand->Function && !Cand->IsSurrogate) {
12009           // This a non-viable builtin candidate.  We do not, in general,
12010           // want to list every possible builtin candidate.
12011           continue;
12012         }
12013         CompleteNonViableCandidate(S, Cand, Args, Kind);
12014       }
12015       break;
12016 
12017     case OCD_ViableCandidates:
12018       if (!Cand->Viable)
12019         continue;
12020       break;
12021 
12022     case OCD_AmbiguousCandidates:
12023       if (!Cand->Best)
12024         continue;
12025       break;
12026     }
12027 
12028     Cands.push_back(Cand);
12029   }
12030 
12031   llvm::stable_sort(
12032       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12033 
12034   return Cands;
12035 }
12036 
12037 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12038                                             SourceLocation OpLoc) {
12039   bool DeferHint = false;
12040   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12041     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12042     // host device candidates.
12043     auto WrongSidedCands =
12044         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12045           return (Cand.Viable == false &&
12046                   Cand.FailureKind == ovl_fail_bad_target) ||
12047                  (Cand.Function &&
12048                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
12049                   Cand.Function->template hasAttr<CUDADeviceAttr>());
12050         });
12051     DeferHint = !WrongSidedCands.empty();
12052   }
12053   return DeferHint;
12054 }
12055 
12056 /// When overload resolution fails, prints diagnostic messages containing the
12057 /// candidates in the candidate set.
12058 void OverloadCandidateSet::NoteCandidates(
12059     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12060     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12061     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12062 
12063   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12064 
12065   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12066 
12067   // In WebAssembly we don't want to emit further diagnostics if a table is
12068   // passed as an argument to a function.
12069   bool NoteCands = true;
12070   for (const Expr *Arg : Args) {
12071     if (Arg->getType()->isWebAssemblyTableType())
12072       NoteCands = false;
12073   }
12074 
12075   if (NoteCands)
12076     NoteCandidates(S, Args, Cands, Opc, OpLoc);
12077 
12078   if (OCD == OCD_AmbiguousCandidates)
12079     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12080 }
12081 
12082 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12083                                           ArrayRef<OverloadCandidate *> Cands,
12084                                           StringRef Opc, SourceLocation OpLoc) {
12085   bool ReportedAmbiguousConversions = false;
12086 
12087   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12088   unsigned CandsShown = 0;
12089   auto I = Cands.begin(), E = Cands.end();
12090   for (; I != E; ++I) {
12091     OverloadCandidate *Cand = *I;
12092 
12093     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12094         ShowOverloads == Ovl_Best) {
12095       break;
12096     }
12097     ++CandsShown;
12098 
12099     if (Cand->Function)
12100       NoteFunctionCandidate(S, Cand, Args.size(),
12101                             /*TakingCandidateAddress=*/false, DestAS);
12102     else if (Cand->IsSurrogate)
12103       NoteSurrogateCandidate(S, Cand);
12104     else {
12105       assert(Cand->Viable &&
12106              "Non-viable built-in candidates are not added to Cands.");
12107       // Generally we only see ambiguities including viable builtin
12108       // operators if overload resolution got screwed up by an
12109       // ambiguous user-defined conversion.
12110       //
12111       // FIXME: It's quite possible for different conversions to see
12112       // different ambiguities, though.
12113       if (!ReportedAmbiguousConversions) {
12114         NoteAmbiguousUserConversions(S, OpLoc, Cand);
12115         ReportedAmbiguousConversions = true;
12116       }
12117 
12118       // If this is a viable builtin, print it.
12119       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12120     }
12121   }
12122 
12123   // Inform S.Diags that we've shown an overload set with N elements.  This may
12124   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12125   S.Diags.overloadCandidatesShown(CandsShown);
12126 
12127   if (I != E)
12128     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12129            shouldDeferDiags(S, Args, OpLoc))
12130         << int(E - I);
12131 }
12132 
12133 static SourceLocation
12134 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12135   return Cand->Specialization ? Cand->Specialization->getLocation()
12136                               : SourceLocation();
12137 }
12138 
12139 namespace {
12140 struct CompareTemplateSpecCandidatesForDisplay {
12141   Sema &S;
12142   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12143 
12144   bool operator()(const TemplateSpecCandidate *L,
12145                   const TemplateSpecCandidate *R) {
12146     // Fast-path this check.
12147     if (L == R)
12148       return false;
12149 
12150     // Assuming that both candidates are not matches...
12151 
12152     // Sort by the ranking of deduction failures.
12153     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12154       return RankDeductionFailure(L->DeductionFailure) <
12155              RankDeductionFailure(R->DeductionFailure);
12156 
12157     // Sort everything else by location.
12158     SourceLocation LLoc = GetLocationForCandidate(L);
12159     SourceLocation RLoc = GetLocationForCandidate(R);
12160 
12161     // Put candidates without locations (e.g. builtins) at the end.
12162     if (LLoc.isInvalid())
12163       return false;
12164     if (RLoc.isInvalid())
12165       return true;
12166 
12167     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12168   }
12169 };
12170 }
12171 
12172 /// Diagnose a template argument deduction failure.
12173 /// We are treating these failures as overload failures due to bad
12174 /// deductions.
12175 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12176                                                  bool ForTakingAddress) {
12177   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12178                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12179 }
12180 
12181 void TemplateSpecCandidateSet::destroyCandidates() {
12182   for (iterator i = begin(), e = end(); i != e; ++i) {
12183     i->DeductionFailure.Destroy();
12184   }
12185 }
12186 
12187 void TemplateSpecCandidateSet::clear() {
12188   destroyCandidates();
12189   Candidates.clear();
12190 }
12191 
12192 /// NoteCandidates - When no template specialization match is found, prints
12193 /// diagnostic messages containing the non-matching specializations that form
12194 /// the candidate set.
12195 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12196 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12197 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12198   // Sort the candidates by position (assuming no candidate is a match).
12199   // Sorting directly would be prohibitive, so we make a set of pointers
12200   // and sort those.
12201   SmallVector<TemplateSpecCandidate *, 32> Cands;
12202   Cands.reserve(size());
12203   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12204     if (Cand->Specialization)
12205       Cands.push_back(Cand);
12206     // Otherwise, this is a non-matching builtin candidate.  We do not,
12207     // in general, want to list every possible builtin candidate.
12208   }
12209 
12210   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12211 
12212   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12213   // for generalization purposes (?).
12214   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12215 
12216   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12217   unsigned CandsShown = 0;
12218   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12219     TemplateSpecCandidate *Cand = *I;
12220 
12221     // Set an arbitrary limit on the number of candidates we'll spam
12222     // the user with.  FIXME: This limit should depend on details of the
12223     // candidate list.
12224     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12225       break;
12226     ++CandsShown;
12227 
12228     assert(Cand->Specialization &&
12229            "Non-matching built-in candidates are not added to Cands.");
12230     Cand->NoteDeductionFailure(S, ForTakingAddress);
12231   }
12232 
12233   if (I != E)
12234     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12235 }
12236 
12237 // [PossiblyAFunctionType]  -->   [Return]
12238 // NonFunctionType --> NonFunctionType
12239 // R (A) --> R(A)
12240 // R (*)(A) --> R (A)
12241 // R (&)(A) --> R (A)
12242 // R (S::*)(A) --> R (A)
12243 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12244   QualType Ret = PossiblyAFunctionType;
12245   if (const PointerType *ToTypePtr =
12246     PossiblyAFunctionType->getAs<PointerType>())
12247     Ret = ToTypePtr->getPointeeType();
12248   else if (const ReferenceType *ToTypeRef =
12249     PossiblyAFunctionType->getAs<ReferenceType>())
12250     Ret = ToTypeRef->getPointeeType();
12251   else if (const MemberPointerType *MemTypePtr =
12252     PossiblyAFunctionType->getAs<MemberPointerType>())
12253     Ret = MemTypePtr->getPointeeType();
12254   Ret =
12255     Context.getCanonicalType(Ret).getUnqualifiedType();
12256   return Ret;
12257 }
12258 
12259 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12260                                  bool Complain = true) {
12261   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12262       S.DeduceReturnType(FD, Loc, Complain))
12263     return true;
12264 
12265   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12266   if (S.getLangOpts().CPlusPlus17 &&
12267       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12268       !S.ResolveExceptionSpec(Loc, FPT))
12269     return true;
12270 
12271   return false;
12272 }
12273 
12274 namespace {
12275 // A helper class to help with address of function resolution
12276 // - allows us to avoid passing around all those ugly parameters
12277 class AddressOfFunctionResolver {
12278   Sema& S;
12279   Expr* SourceExpr;
12280   const QualType& TargetType;
12281   QualType TargetFunctionType; // Extracted function type from target type
12282 
12283   bool Complain;
12284   //DeclAccessPair& ResultFunctionAccessPair;
12285   ASTContext& Context;
12286 
12287   bool TargetTypeIsNonStaticMemberFunction;
12288   bool FoundNonTemplateFunction;
12289   bool StaticMemberFunctionFromBoundPointer;
12290   bool HasComplained;
12291 
12292   OverloadExpr::FindResult OvlExprInfo;
12293   OverloadExpr *OvlExpr;
12294   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12295   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12296   TemplateSpecCandidateSet FailedCandidates;
12297 
12298 public:
12299   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12300                             const QualType &TargetType, bool Complain)
12301       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12302         Complain(Complain), Context(S.getASTContext()),
12303         TargetTypeIsNonStaticMemberFunction(
12304             !!TargetType->getAs<MemberPointerType>()),
12305         FoundNonTemplateFunction(false),
12306         StaticMemberFunctionFromBoundPointer(false),
12307         HasComplained(false),
12308         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12309         OvlExpr(OvlExprInfo.Expression),
12310         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12311     ExtractUnqualifiedFunctionTypeFromTargetType();
12312 
12313     if (TargetFunctionType->isFunctionType()) {
12314       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12315         if (!UME->isImplicitAccess() &&
12316             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12317           StaticMemberFunctionFromBoundPointer = true;
12318     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12319       DeclAccessPair dap;
12320       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12321               OvlExpr, false, &dap)) {
12322         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12323           if (!Method->isStatic()) {
12324             // If the target type is a non-function type and the function found
12325             // is a non-static member function, pretend as if that was the
12326             // target, it's the only possible type to end up with.
12327             TargetTypeIsNonStaticMemberFunction = true;
12328 
12329             // And skip adding the function if its not in the proper form.
12330             // We'll diagnose this due to an empty set of functions.
12331             if (!OvlExprInfo.HasFormOfMemberPointer)
12332               return;
12333           }
12334 
12335         Matches.push_back(std::make_pair(dap, Fn));
12336       }
12337       return;
12338     }
12339 
12340     if (OvlExpr->hasExplicitTemplateArgs())
12341       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12342 
12343     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12344       // C++ [over.over]p4:
12345       //   If more than one function is selected, [...]
12346       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12347         if (FoundNonTemplateFunction)
12348           EliminateAllTemplateMatches();
12349         else
12350           EliminateAllExceptMostSpecializedTemplate();
12351       }
12352     }
12353 
12354     if (S.getLangOpts().CUDA && Matches.size() > 1)
12355       EliminateSuboptimalCudaMatches();
12356   }
12357 
12358   bool hasComplained() const { return HasComplained; }
12359 
12360 private:
12361   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12362     QualType Discard;
12363     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12364            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12365   }
12366 
12367   /// \return true if A is considered a better overload candidate for the
12368   /// desired type than B.
12369   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12370     // If A doesn't have exactly the correct type, we don't want to classify it
12371     // as "better" than anything else. This way, the user is required to
12372     // disambiguate for us if there are multiple candidates and no exact match.
12373     return candidateHasExactlyCorrectType(A) &&
12374            (!candidateHasExactlyCorrectType(B) ||
12375             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12376   }
12377 
12378   /// \return true if we were able to eliminate all but one overload candidate,
12379   /// false otherwise.
12380   bool eliminiateSuboptimalOverloadCandidates() {
12381     // Same algorithm as overload resolution -- one pass to pick the "best",
12382     // another pass to be sure that nothing is better than the best.
12383     auto Best = Matches.begin();
12384     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12385       if (isBetterCandidate(I->second, Best->second))
12386         Best = I;
12387 
12388     const FunctionDecl *BestFn = Best->second;
12389     auto IsBestOrInferiorToBest = [this, BestFn](
12390         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12391       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12392     };
12393 
12394     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12395     // option, so we can potentially give the user a better error
12396     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12397       return false;
12398     Matches[0] = *Best;
12399     Matches.resize(1);
12400     return true;
12401   }
12402 
12403   bool isTargetTypeAFunction() const {
12404     return TargetFunctionType->isFunctionType();
12405   }
12406 
12407   // [ToType]     [Return]
12408 
12409   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12410   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12411   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12412   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12413     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12414   }
12415 
12416   // return true if any matching specializations were found
12417   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12418                                    const DeclAccessPair& CurAccessFunPair) {
12419     if (CXXMethodDecl *Method
12420               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12421       // Skip non-static function templates when converting to pointer, and
12422       // static when converting to member pointer.
12423       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12424         return false;
12425     }
12426     else if (TargetTypeIsNonStaticMemberFunction)
12427       return false;
12428 
12429     // C++ [over.over]p2:
12430     //   If the name is a function template, template argument deduction is
12431     //   done (14.8.2.2), and if the argument deduction succeeds, the
12432     //   resulting template argument list is used to generate a single
12433     //   function template specialization, which is added to the set of
12434     //   overloaded functions considered.
12435     FunctionDecl *Specialization = nullptr;
12436     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12437     if (Sema::TemplateDeductionResult Result
12438           = S.DeduceTemplateArguments(FunctionTemplate,
12439                                       &OvlExplicitTemplateArgs,
12440                                       TargetFunctionType, Specialization,
12441                                       Info, /*IsAddressOfFunction*/true)) {
12442       // Make a note of the failed deduction for diagnostics.
12443       FailedCandidates.addCandidate()
12444           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12445                MakeDeductionFailureInfo(Context, Result, Info));
12446       return false;
12447     }
12448 
12449     // Template argument deduction ensures that we have an exact match or
12450     // compatible pointer-to-function arguments that would be adjusted by ICS.
12451     // This function template specicalization works.
12452     assert(S.isSameOrCompatibleFunctionType(
12453               Context.getCanonicalType(Specialization->getType()),
12454               Context.getCanonicalType(TargetFunctionType)));
12455 
12456     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12457       return false;
12458 
12459     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12460     return true;
12461   }
12462 
12463   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12464                                       const DeclAccessPair& CurAccessFunPair) {
12465     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12466       // Skip non-static functions when converting to pointer, and static
12467       // when converting to member pointer.
12468       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12469         return false;
12470     }
12471     else if (TargetTypeIsNonStaticMemberFunction)
12472       return false;
12473 
12474     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12475       if (S.getLangOpts().CUDA)
12476         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12477           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12478             return false;
12479       if (FunDecl->isMultiVersion()) {
12480         const auto *TA = FunDecl->getAttr<TargetAttr>();
12481         if (TA && !TA->isDefaultVersion())
12482           return false;
12483         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12484         if (TVA && !TVA->isDefaultVersion())
12485           return false;
12486       }
12487 
12488       // If any candidate has a placeholder return type, trigger its deduction
12489       // now.
12490       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12491                                Complain)) {
12492         HasComplained |= Complain;
12493         return false;
12494       }
12495 
12496       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12497         return false;
12498 
12499       // If we're in C, we need to support types that aren't exactly identical.
12500       if (!S.getLangOpts().CPlusPlus ||
12501           candidateHasExactlyCorrectType(FunDecl)) {
12502         Matches.push_back(std::make_pair(
12503             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12504         FoundNonTemplateFunction = true;
12505         return true;
12506       }
12507     }
12508 
12509     return false;
12510   }
12511 
12512   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12513     bool Ret = false;
12514 
12515     // If the overload expression doesn't have the form of a pointer to
12516     // member, don't try to convert it to a pointer-to-member type.
12517     if (IsInvalidFormOfPointerToMemberFunction())
12518       return false;
12519 
12520     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12521                                E = OvlExpr->decls_end();
12522          I != E; ++I) {
12523       // Look through any using declarations to find the underlying function.
12524       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12525 
12526       // C++ [over.over]p3:
12527       //   Non-member functions and static member functions match
12528       //   targets of type "pointer-to-function" or "reference-to-function."
12529       //   Nonstatic member functions match targets of
12530       //   type "pointer-to-member-function."
12531       // Note that according to DR 247, the containing class does not matter.
12532       if (FunctionTemplateDecl *FunctionTemplate
12533                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12534         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12535           Ret = true;
12536       }
12537       // If we have explicit template arguments supplied, skip non-templates.
12538       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12539                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12540         Ret = true;
12541     }
12542     assert(Ret || Matches.empty());
12543     return Ret;
12544   }
12545 
12546   void EliminateAllExceptMostSpecializedTemplate() {
12547     //   [...] and any given function template specialization F1 is
12548     //   eliminated if the set contains a second function template
12549     //   specialization whose function template is more specialized
12550     //   than the function template of F1 according to the partial
12551     //   ordering rules of 14.5.5.2.
12552 
12553     // The algorithm specified above is quadratic. We instead use a
12554     // two-pass algorithm (similar to the one used to identify the
12555     // best viable function in an overload set) that identifies the
12556     // best function template (if it exists).
12557 
12558     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12559     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12560       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12561 
12562     // TODO: It looks like FailedCandidates does not serve much purpose
12563     // here, since the no_viable diagnostic has index 0.
12564     UnresolvedSetIterator Result = S.getMostSpecialized(
12565         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12566         SourceExpr->getBeginLoc(), S.PDiag(),
12567         S.PDiag(diag::err_addr_ovl_ambiguous)
12568             << Matches[0].second->getDeclName(),
12569         S.PDiag(diag::note_ovl_candidate)
12570             << (unsigned)oc_function << (unsigned)ocs_described_template,
12571         Complain, TargetFunctionType);
12572 
12573     if (Result != MatchesCopy.end()) {
12574       // Make it the first and only element
12575       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12576       Matches[0].second = cast<FunctionDecl>(*Result);
12577       Matches.resize(1);
12578     } else
12579       HasComplained |= Complain;
12580   }
12581 
12582   void EliminateAllTemplateMatches() {
12583     //   [...] any function template specializations in the set are
12584     //   eliminated if the set also contains a non-template function, [...]
12585     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12586       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12587         ++I;
12588       else {
12589         Matches[I] = Matches[--N];
12590         Matches.resize(N);
12591       }
12592     }
12593   }
12594 
12595   void EliminateSuboptimalCudaMatches() {
12596     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12597                                Matches);
12598   }
12599 
12600 public:
12601   void ComplainNoMatchesFound() const {
12602     assert(Matches.empty());
12603     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12604         << OvlExpr->getName() << TargetFunctionType
12605         << OvlExpr->getSourceRange();
12606     if (FailedCandidates.empty())
12607       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12608                                   /*TakingAddress=*/true);
12609     else {
12610       // We have some deduction failure messages. Use them to diagnose
12611       // the function templates, and diagnose the non-template candidates
12612       // normally.
12613       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12614                                  IEnd = OvlExpr->decls_end();
12615            I != IEnd; ++I)
12616         if (FunctionDecl *Fun =
12617                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12618           if (!functionHasPassObjectSizeParams(Fun))
12619             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12620                                     /*TakingAddress=*/true);
12621       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12622     }
12623   }
12624 
12625   bool IsInvalidFormOfPointerToMemberFunction() const {
12626     return TargetTypeIsNonStaticMemberFunction &&
12627       !OvlExprInfo.HasFormOfMemberPointer;
12628   }
12629 
12630   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12631       // TODO: Should we condition this on whether any functions might
12632       // have matched, or is it more appropriate to do that in callers?
12633       // TODO: a fixit wouldn't hurt.
12634       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12635         << TargetType << OvlExpr->getSourceRange();
12636   }
12637 
12638   bool IsStaticMemberFunctionFromBoundPointer() const {
12639     return StaticMemberFunctionFromBoundPointer;
12640   }
12641 
12642   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12643     S.Diag(OvlExpr->getBeginLoc(),
12644            diag::err_invalid_form_pointer_member_function)
12645         << OvlExpr->getSourceRange();
12646   }
12647 
12648   void ComplainOfInvalidConversion() const {
12649     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12650         << OvlExpr->getName() << TargetType;
12651   }
12652 
12653   void ComplainMultipleMatchesFound() const {
12654     assert(Matches.size() > 1);
12655     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12656         << OvlExpr->getName() << OvlExpr->getSourceRange();
12657     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12658                                 /*TakingAddress=*/true);
12659   }
12660 
12661   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12662 
12663   int getNumMatches() const { return Matches.size(); }
12664 
12665   FunctionDecl* getMatchingFunctionDecl() const {
12666     if (Matches.size() != 1) return nullptr;
12667     return Matches[0].second;
12668   }
12669 
12670   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12671     if (Matches.size() != 1) return nullptr;
12672     return &Matches[0].first;
12673   }
12674 };
12675 }
12676 
12677 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12678 /// an overloaded function (C++ [over.over]), where @p From is an
12679 /// expression with overloaded function type and @p ToType is the type
12680 /// we're trying to resolve to. For example:
12681 ///
12682 /// @code
12683 /// int f(double);
12684 /// int f(int);
12685 ///
12686 /// int (*pfd)(double) = f; // selects f(double)
12687 /// @endcode
12688 ///
12689 /// This routine returns the resulting FunctionDecl if it could be
12690 /// resolved, and NULL otherwise. When @p Complain is true, this
12691 /// routine will emit diagnostics if there is an error.
12692 FunctionDecl *
12693 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12694                                          QualType TargetType,
12695                                          bool Complain,
12696                                          DeclAccessPair &FoundResult,
12697                                          bool *pHadMultipleCandidates) {
12698   assert(AddressOfExpr->getType() == Context.OverloadTy);
12699 
12700   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12701                                      Complain);
12702   int NumMatches = Resolver.getNumMatches();
12703   FunctionDecl *Fn = nullptr;
12704   bool ShouldComplain = Complain && !Resolver.hasComplained();
12705   if (NumMatches == 0 && ShouldComplain) {
12706     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12707       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12708     else
12709       Resolver.ComplainNoMatchesFound();
12710   }
12711   else if (NumMatches > 1 && ShouldComplain)
12712     Resolver.ComplainMultipleMatchesFound();
12713   else if (NumMatches == 1) {
12714     Fn = Resolver.getMatchingFunctionDecl();
12715     assert(Fn);
12716     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12717       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12718     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12719     if (Complain) {
12720       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12721         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12722       else
12723         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12724     }
12725   }
12726 
12727   if (pHadMultipleCandidates)
12728     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12729   return Fn;
12730 }
12731 
12732 /// Given an expression that refers to an overloaded function, try to
12733 /// resolve that function to a single function that can have its address taken.
12734 /// This will modify `Pair` iff it returns non-null.
12735 ///
12736 /// This routine can only succeed if from all of the candidates in the overload
12737 /// set for SrcExpr that can have their addresses taken, there is one candidate
12738 /// that is more constrained than the rest.
12739 FunctionDecl *
12740 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12741   OverloadExpr::FindResult R = OverloadExpr::find(E);
12742   OverloadExpr *Ovl = R.Expression;
12743   bool IsResultAmbiguous = false;
12744   FunctionDecl *Result = nullptr;
12745   DeclAccessPair DAP;
12746   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12747 
12748   auto CheckMoreConstrained = [&](FunctionDecl *FD1,
12749                                   FunctionDecl *FD2) -> std::optional<bool> {
12750     if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
12751       FD1 = MF;
12752     if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
12753       FD2 = MF;
12754     SmallVector<const Expr *, 1> AC1, AC2;
12755     FD1->getAssociatedConstraints(AC1);
12756     FD2->getAssociatedConstraints(AC2);
12757     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12758     if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12759       return std::nullopt;
12760     if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12761       return std::nullopt;
12762     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12763       return std::nullopt;
12764     return AtLeastAsConstrained1;
12765   };
12766 
12767   // Don't use the AddressOfResolver because we're specifically looking for
12768   // cases where we have one overload candidate that lacks
12769   // enable_if/pass_object_size/...
12770   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12771     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12772     if (!FD)
12773       return nullptr;
12774 
12775     if (!checkAddressOfFunctionIsAvailable(FD))
12776       continue;
12777 
12778     // We have more than one result - see if it is more constrained than the
12779     // previous one.
12780     if (Result) {
12781       std::optional<bool> MoreConstrainedThanPrevious =
12782           CheckMoreConstrained(FD, Result);
12783       if (!MoreConstrainedThanPrevious) {
12784         IsResultAmbiguous = true;
12785         AmbiguousDecls.push_back(FD);
12786         continue;
12787       }
12788       if (!*MoreConstrainedThanPrevious)
12789         continue;
12790       // FD is more constrained - replace Result with it.
12791     }
12792     IsResultAmbiguous = false;
12793     DAP = I.getPair();
12794     Result = FD;
12795   }
12796 
12797   if (IsResultAmbiguous)
12798     return nullptr;
12799 
12800   if (Result) {
12801     SmallVector<const Expr *, 1> ResultAC;
12802     // We skipped over some ambiguous declarations which might be ambiguous with
12803     // the selected result.
12804     for (FunctionDecl *Skipped : AmbiguousDecls)
12805       if (!CheckMoreConstrained(Skipped, Result))
12806         return nullptr;
12807     Pair = DAP;
12808   }
12809   return Result;
12810 }
12811 
12812 /// Given an overloaded function, tries to turn it into a non-overloaded
12813 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12814 /// will perform access checks, diagnose the use of the resultant decl, and, if
12815 /// requested, potentially perform a function-to-pointer decay.
12816 ///
12817 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12818 /// Otherwise, returns true. This may emit diagnostics and return true.
12819 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12820     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
12821   Expr *E = SrcExpr.get();
12822   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12823 
12824   DeclAccessPair DAP;
12825   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12826   if (!Found || Found->isCPUDispatchMultiVersion() ||
12827       Found->isCPUSpecificMultiVersion())
12828     return false;
12829 
12830   // Emitting multiple diagnostics for a function that is both inaccessible and
12831   // unavailable is consistent with our behavior elsewhere. So, always check
12832   // for both.
12833   DiagnoseUseOfDecl(Found, E->getExprLoc());
12834   CheckAddressOfMemberAccess(E, DAP);
12835   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12836   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
12837     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12838   else
12839     SrcExpr = Fixed;
12840   return true;
12841 }
12842 
12843 /// Given an expression that refers to an overloaded function, try to
12844 /// resolve that overloaded function expression down to a single function.
12845 ///
12846 /// This routine can only resolve template-ids that refer to a single function
12847 /// template, where that template-id refers to a single template whose template
12848 /// arguments are either provided by the template-id or have defaults,
12849 /// as described in C++0x [temp.arg.explicit]p3.
12850 ///
12851 /// If no template-ids are found, no diagnostics are emitted and NULL is
12852 /// returned.
12853 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
12854     OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
12855     TemplateSpecCandidateSet *FailedTSC) {
12856   // C++ [over.over]p1:
12857   //   [...] [Note: any redundant set of parentheses surrounding the
12858   //   overloaded function name is ignored (5.1). ]
12859   // C++ [over.over]p1:
12860   //   [...] The overloaded function name can be preceded by the &
12861   //   operator.
12862 
12863   // If we didn't actually find any template-ids, we're done.
12864   if (!ovl->hasExplicitTemplateArgs())
12865     return nullptr;
12866 
12867   TemplateArgumentListInfo ExplicitTemplateArgs;
12868   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12869 
12870   // Look through all of the overloaded functions, searching for one
12871   // whose type matches exactly.
12872   FunctionDecl *Matched = nullptr;
12873   for (UnresolvedSetIterator I = ovl->decls_begin(),
12874          E = ovl->decls_end(); I != E; ++I) {
12875     // C++0x [temp.arg.explicit]p3:
12876     //   [...] In contexts where deduction is done and fails, or in contexts
12877     //   where deduction is not done, if a template argument list is
12878     //   specified and it, along with any default template arguments,
12879     //   identifies a single function template specialization, then the
12880     //   template-id is an lvalue for the function template specialization.
12881     FunctionTemplateDecl *FunctionTemplate
12882       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12883 
12884     // C++ [over.over]p2:
12885     //   If the name is a function template, template argument deduction is
12886     //   done (14.8.2.2), and if the argument deduction succeeds, the
12887     //   resulting template argument list is used to generate a single
12888     //   function template specialization, which is added to the set of
12889     //   overloaded functions considered.
12890     FunctionDecl *Specialization = nullptr;
12891     TemplateDeductionInfo Info(ovl->getNameLoc());
12892     if (TemplateDeductionResult Result
12893           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12894                                     Specialization, Info,
12895                                     /*IsAddressOfFunction*/true)) {
12896       // Make a note of the failed deduction for diagnostics.
12897       if (FailedTSC)
12898         FailedTSC->addCandidate().set(
12899             I.getPair(), FunctionTemplate->getTemplatedDecl(),
12900             MakeDeductionFailureInfo(Context, Result, Info));
12901       continue;
12902     }
12903 
12904     assert(Specialization && "no specialization and no error?");
12905 
12906     // Multiple matches; we can't resolve to a single declaration.
12907     if (Matched) {
12908       if (Complain) {
12909         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12910           << ovl->getName();
12911         NoteAllOverloadCandidates(ovl);
12912       }
12913       return nullptr;
12914     }
12915 
12916     Matched = Specialization;
12917     if (FoundResult) *FoundResult = I.getPair();
12918   }
12919 
12920   if (Matched &&
12921       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12922     return nullptr;
12923 
12924   return Matched;
12925 }
12926 
12927 // Resolve and fix an overloaded expression that can be resolved
12928 // because it identifies a single function template specialization.
12929 //
12930 // Last three arguments should only be supplied if Complain = true
12931 //
12932 // Return true if it was logically possible to so resolve the
12933 // expression, regardless of whether or not it succeeded.  Always
12934 // returns true if 'complain' is set.
12935 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12936     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
12937     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
12938     unsigned DiagIDForComplaining) {
12939   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12940 
12941   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12942 
12943   DeclAccessPair found;
12944   ExprResult SingleFunctionExpression;
12945   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12946                            ovl.Expression, /*complain*/ false, &found)) {
12947     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12948       SrcExpr = ExprError();
12949       return true;
12950     }
12951 
12952     // It is only correct to resolve to an instance method if we're
12953     // resolving a form that's permitted to be a pointer to member.
12954     // Otherwise we'll end up making a bound member expression, which
12955     // is illegal in all the contexts we resolve like this.
12956     if (!ovl.HasFormOfMemberPointer &&
12957         isa<CXXMethodDecl>(fn) &&
12958         cast<CXXMethodDecl>(fn)->isInstance()) {
12959       if (!complain) return false;
12960 
12961       Diag(ovl.Expression->getExprLoc(),
12962            diag::err_bound_member_function)
12963         << 0 << ovl.Expression->getSourceRange();
12964 
12965       // TODO: I believe we only end up here if there's a mix of
12966       // static and non-static candidates (otherwise the expression
12967       // would have 'bound member' type, not 'overload' type).
12968       // Ideally we would note which candidate was chosen and why
12969       // the static candidates were rejected.
12970       SrcExpr = ExprError();
12971       return true;
12972     }
12973 
12974     // Fix the expression to refer to 'fn'.
12975     SingleFunctionExpression =
12976         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12977 
12978     // If desired, do function-to-pointer decay.
12979     if (doFunctionPointerConversion) {
12980       SingleFunctionExpression =
12981         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12982       if (SingleFunctionExpression.isInvalid()) {
12983         SrcExpr = ExprError();
12984         return true;
12985       }
12986     }
12987   }
12988 
12989   if (!SingleFunctionExpression.isUsable()) {
12990     if (complain) {
12991       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12992         << ovl.Expression->getName()
12993         << DestTypeForComplaining
12994         << OpRangeForComplaining
12995         << ovl.Expression->getQualifierLoc().getSourceRange();
12996       NoteAllOverloadCandidates(SrcExpr.get());
12997 
12998       SrcExpr = ExprError();
12999       return true;
13000     }
13001 
13002     return false;
13003   }
13004 
13005   SrcExpr = SingleFunctionExpression;
13006   return true;
13007 }
13008 
13009 /// Add a single candidate to the overload set.
13010 static void AddOverloadedCallCandidate(Sema &S,
13011                                        DeclAccessPair FoundDecl,
13012                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
13013                                        ArrayRef<Expr *> Args,
13014                                        OverloadCandidateSet &CandidateSet,
13015                                        bool PartialOverloading,
13016                                        bool KnownValid) {
13017   NamedDecl *Callee = FoundDecl.getDecl();
13018   if (isa<UsingShadowDecl>(Callee))
13019     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13020 
13021   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13022     if (ExplicitTemplateArgs) {
13023       assert(!KnownValid && "Explicit template arguments?");
13024       return;
13025     }
13026     // Prevent ill-formed function decls to be added as overload candidates.
13027     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13028       return;
13029 
13030     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13031                            /*SuppressUserConversions=*/false,
13032                            PartialOverloading);
13033     return;
13034   }
13035 
13036   if (FunctionTemplateDecl *FuncTemplate
13037       = dyn_cast<FunctionTemplateDecl>(Callee)) {
13038     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13039                                    ExplicitTemplateArgs, Args, CandidateSet,
13040                                    /*SuppressUserConversions=*/false,
13041                                    PartialOverloading);
13042     return;
13043   }
13044 
13045   assert(!KnownValid && "unhandled case in overloaded call candidate");
13046 }
13047 
13048 /// Add the overload candidates named by callee and/or found by argument
13049 /// dependent lookup to the given overload set.
13050 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13051                                        ArrayRef<Expr *> Args,
13052                                        OverloadCandidateSet &CandidateSet,
13053                                        bool PartialOverloading) {
13054 
13055 #ifndef NDEBUG
13056   // Verify that ArgumentDependentLookup is consistent with the rules
13057   // in C++0x [basic.lookup.argdep]p3:
13058   //
13059   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
13060   //   and let Y be the lookup set produced by argument dependent
13061   //   lookup (defined as follows). If X contains
13062   //
13063   //     -- a declaration of a class member, or
13064   //
13065   //     -- a block-scope function declaration that is not a
13066   //        using-declaration, or
13067   //
13068   //     -- a declaration that is neither a function or a function
13069   //        template
13070   //
13071   //   then Y is empty.
13072 
13073   if (ULE->requiresADL()) {
13074     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13075            E = ULE->decls_end(); I != E; ++I) {
13076       assert(!(*I)->getDeclContext()->isRecord());
13077       assert(isa<UsingShadowDecl>(*I) ||
13078              !(*I)->getDeclContext()->isFunctionOrMethod());
13079       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13080     }
13081   }
13082 #endif
13083 
13084   // It would be nice to avoid this copy.
13085   TemplateArgumentListInfo TABuffer;
13086   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13087   if (ULE->hasExplicitTemplateArgs()) {
13088     ULE->copyTemplateArgumentsInto(TABuffer);
13089     ExplicitTemplateArgs = &TABuffer;
13090   }
13091 
13092   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13093          E = ULE->decls_end(); I != E; ++I)
13094     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13095                                CandidateSet, PartialOverloading,
13096                                /*KnownValid*/ true);
13097 
13098   if (ULE->requiresADL())
13099     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13100                                          Args, ExplicitTemplateArgs,
13101                                          CandidateSet, PartialOverloading);
13102 }
13103 
13104 /// Add the call candidates from the given set of lookup results to the given
13105 /// overload set. Non-function lookup results are ignored.
13106 void Sema::AddOverloadedCallCandidates(
13107     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13108     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13109   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13110     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13111                                CandidateSet, false, /*KnownValid*/ false);
13112 }
13113 
13114 /// Determine whether a declaration with the specified name could be moved into
13115 /// a different namespace.
13116 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13117   switch (Name.getCXXOverloadedOperator()) {
13118   case OO_New: case OO_Array_New:
13119   case OO_Delete: case OO_Array_Delete:
13120     return false;
13121 
13122   default:
13123     return true;
13124   }
13125 }
13126 
13127 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13128 /// template, where the non-dependent name was declared after the template
13129 /// was defined. This is common in code written for a compilers which do not
13130 /// correctly implement two-stage name lookup.
13131 ///
13132 /// Returns true if a viable candidate was found and a diagnostic was issued.
13133 static bool DiagnoseTwoPhaseLookup(
13134     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13135     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13136     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13137     CXXRecordDecl **FoundInClass = nullptr) {
13138   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13139     return false;
13140 
13141   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13142     if (DC->isTransparentContext())
13143       continue;
13144 
13145     SemaRef.LookupQualifiedName(R, DC);
13146 
13147     if (!R.empty()) {
13148       R.suppressDiagnostics();
13149 
13150       OverloadCandidateSet Candidates(FnLoc, CSK);
13151       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13152                                           Candidates);
13153 
13154       OverloadCandidateSet::iterator Best;
13155       OverloadingResult OR =
13156           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13157 
13158       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13159         // We either found non-function declarations or a best viable function
13160         // at class scope. A class-scope lookup result disables ADL. Don't
13161         // look past this, but let the caller know that we found something that
13162         // either is, or might be, usable in this class.
13163         if (FoundInClass) {
13164           *FoundInClass = RD;
13165           if (OR == OR_Success) {
13166             R.clear();
13167             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13168             R.resolveKind();
13169           }
13170         }
13171         return false;
13172       }
13173 
13174       if (OR != OR_Success) {
13175         // There wasn't a unique best function or function template.
13176         return false;
13177       }
13178 
13179       // Find the namespaces where ADL would have looked, and suggest
13180       // declaring the function there instead.
13181       Sema::AssociatedNamespaceSet AssociatedNamespaces;
13182       Sema::AssociatedClassSet AssociatedClasses;
13183       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13184                                                  AssociatedNamespaces,
13185                                                  AssociatedClasses);
13186       Sema::AssociatedNamespaceSet SuggestedNamespaces;
13187       if (canBeDeclaredInNamespace(R.getLookupName())) {
13188         DeclContext *Std = SemaRef.getStdNamespace();
13189         for (Sema::AssociatedNamespaceSet::iterator
13190                it = AssociatedNamespaces.begin(),
13191                end = AssociatedNamespaces.end(); it != end; ++it) {
13192           // Never suggest declaring a function within namespace 'std'.
13193           if (Std && Std->Encloses(*it))
13194             continue;
13195 
13196           // Never suggest declaring a function within a namespace with a
13197           // reserved name, like __gnu_cxx.
13198           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13199           if (NS &&
13200               NS->getQualifiedNameAsString().find("__") != std::string::npos)
13201             continue;
13202 
13203           SuggestedNamespaces.insert(*it);
13204         }
13205       }
13206 
13207       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13208         << R.getLookupName();
13209       if (SuggestedNamespaces.empty()) {
13210         SemaRef.Diag(Best->Function->getLocation(),
13211                      diag::note_not_found_by_two_phase_lookup)
13212           << R.getLookupName() << 0;
13213       } else if (SuggestedNamespaces.size() == 1) {
13214         SemaRef.Diag(Best->Function->getLocation(),
13215                      diag::note_not_found_by_two_phase_lookup)
13216           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13217       } else {
13218         // FIXME: It would be useful to list the associated namespaces here,
13219         // but the diagnostics infrastructure doesn't provide a way to produce
13220         // a localized representation of a list of items.
13221         SemaRef.Diag(Best->Function->getLocation(),
13222                      diag::note_not_found_by_two_phase_lookup)
13223           << R.getLookupName() << 2;
13224       }
13225 
13226       // Try to recover by calling this function.
13227       return true;
13228     }
13229 
13230     R.clear();
13231   }
13232 
13233   return false;
13234 }
13235 
13236 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13237 /// template, where the non-dependent operator was declared after the template
13238 /// was defined.
13239 ///
13240 /// Returns true if a viable candidate was found and a diagnostic was issued.
13241 static bool
13242 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13243                                SourceLocation OpLoc,
13244                                ArrayRef<Expr *> Args) {
13245   DeclarationName OpName =
13246     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13247   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13248   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13249                                 OverloadCandidateSet::CSK_Operator,
13250                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13251 }
13252 
13253 namespace {
13254 class BuildRecoveryCallExprRAII {
13255   Sema &SemaRef;
13256   Sema::SatisfactionStackResetRAII SatStack;
13257 
13258 public:
13259   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13260     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13261     SemaRef.IsBuildingRecoveryCallExpr = true;
13262   }
13263 
13264   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13265 };
13266 }
13267 
13268 /// Attempts to recover from a call where no functions were found.
13269 ///
13270 /// This function will do one of three things:
13271 ///  * Diagnose, recover, and return a recovery expression.
13272 ///  * Diagnose, fail to recover, and return ExprError().
13273 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13274 ///    expected to diagnose as appropriate.
13275 static ExprResult
13276 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13277                       UnresolvedLookupExpr *ULE,
13278                       SourceLocation LParenLoc,
13279                       MutableArrayRef<Expr *> Args,
13280                       SourceLocation RParenLoc,
13281                       bool EmptyLookup, bool AllowTypoCorrection) {
13282   // Do not try to recover if it is already building a recovery call.
13283   // This stops infinite loops for template instantiations like
13284   //
13285   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13286   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13287   if (SemaRef.IsBuildingRecoveryCallExpr)
13288     return ExprResult();
13289   BuildRecoveryCallExprRAII RCE(SemaRef);
13290 
13291   CXXScopeSpec SS;
13292   SS.Adopt(ULE->getQualifierLoc());
13293   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13294 
13295   TemplateArgumentListInfo TABuffer;
13296   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13297   if (ULE->hasExplicitTemplateArgs()) {
13298     ULE->copyTemplateArgumentsInto(TABuffer);
13299     ExplicitTemplateArgs = &TABuffer;
13300   }
13301 
13302   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13303                  Sema::LookupOrdinaryName);
13304   CXXRecordDecl *FoundInClass = nullptr;
13305   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13306                              OverloadCandidateSet::CSK_Normal,
13307                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13308     // OK, diagnosed a two-phase lookup issue.
13309   } else if (EmptyLookup) {
13310     // Try to recover from an empty lookup with typo correction.
13311     R.clear();
13312     NoTypoCorrectionCCC NoTypoValidator{};
13313     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13314                                                 ExplicitTemplateArgs != nullptr,
13315                                                 dyn_cast<MemberExpr>(Fn));
13316     CorrectionCandidateCallback &Validator =
13317         AllowTypoCorrection
13318             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13319             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13320     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13321                                     Args))
13322       return ExprError();
13323   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13324     // We found a usable declaration of the name in a dependent base of some
13325     // enclosing class.
13326     // FIXME: We should also explain why the candidates found by name lookup
13327     // were not viable.
13328     if (SemaRef.DiagnoseDependentMemberLookup(R))
13329       return ExprError();
13330   } else {
13331     // We had viable candidates and couldn't recover; let the caller diagnose
13332     // this.
13333     return ExprResult();
13334   }
13335 
13336   // If we get here, we should have issued a diagnostic and formed a recovery
13337   // lookup result.
13338   assert(!R.empty() && "lookup results empty despite recovery");
13339 
13340   // If recovery created an ambiguity, just bail out.
13341   if (R.isAmbiguous()) {
13342     R.suppressDiagnostics();
13343     return ExprError();
13344   }
13345 
13346   // Build an implicit member call if appropriate.  Just drop the
13347   // casts and such from the call, we don't really care.
13348   ExprResult NewFn = ExprError();
13349   if ((*R.begin())->isCXXClassMember())
13350     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13351                                                     ExplicitTemplateArgs, S);
13352   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13353     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13354                                         ExplicitTemplateArgs);
13355   else
13356     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13357 
13358   if (NewFn.isInvalid())
13359     return ExprError();
13360 
13361   // This shouldn't cause an infinite loop because we're giving it
13362   // an expression with viable lookup results, which should never
13363   // end up here.
13364   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13365                                MultiExprArg(Args.data(), Args.size()),
13366                                RParenLoc);
13367 }
13368 
13369 /// Constructs and populates an OverloadedCandidateSet from
13370 /// the given function.
13371 /// \returns true when an the ExprResult output parameter has been set.
13372 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13373                                   UnresolvedLookupExpr *ULE,
13374                                   MultiExprArg Args,
13375                                   SourceLocation RParenLoc,
13376                                   OverloadCandidateSet *CandidateSet,
13377                                   ExprResult *Result) {
13378 #ifndef NDEBUG
13379   if (ULE->requiresADL()) {
13380     // To do ADL, we must have found an unqualified name.
13381     assert(!ULE->getQualifier() && "qualified name with ADL");
13382 
13383     // We don't perform ADL for implicit declarations of builtins.
13384     // Verify that this was correctly set up.
13385     FunctionDecl *F;
13386     if (ULE->decls_begin() != ULE->decls_end() &&
13387         ULE->decls_begin() + 1 == ULE->decls_end() &&
13388         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13389         F->getBuiltinID() && F->isImplicit())
13390       llvm_unreachable("performing ADL for builtin");
13391 
13392     // We don't perform ADL in C.
13393     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13394   }
13395 #endif
13396 
13397   UnbridgedCastsSet UnbridgedCasts;
13398   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13399     *Result = ExprError();
13400     return true;
13401   }
13402 
13403   // Add the functions denoted by the callee to the set of candidate
13404   // functions, including those from argument-dependent lookup.
13405   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13406 
13407   if (getLangOpts().MSVCCompat &&
13408       CurContext->isDependentContext() && !isSFINAEContext() &&
13409       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13410 
13411     OverloadCandidateSet::iterator Best;
13412     if (CandidateSet->empty() ||
13413         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13414             OR_No_Viable_Function) {
13415       // In Microsoft mode, if we are inside a template class member function
13416       // then create a type dependent CallExpr. The goal is to postpone name
13417       // lookup to instantiation time to be able to search into type dependent
13418       // base classes.
13419       CallExpr *CE =
13420           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13421                            RParenLoc, CurFPFeatureOverrides());
13422       CE->markDependentForPostponedNameLookup();
13423       *Result = CE;
13424       return true;
13425     }
13426   }
13427 
13428   if (CandidateSet->empty())
13429     return false;
13430 
13431   UnbridgedCasts.restore();
13432   return false;
13433 }
13434 
13435 // Guess at what the return type for an unresolvable overload should be.
13436 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13437                                    OverloadCandidateSet::iterator *Best) {
13438   std::optional<QualType> Result;
13439   // Adjust Type after seeing a candidate.
13440   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13441     if (!Candidate.Function)
13442       return;
13443     if (Candidate.Function->isInvalidDecl())
13444       return;
13445     QualType T = Candidate.Function->getReturnType();
13446     if (T.isNull())
13447       return;
13448     if (!Result)
13449       Result = T;
13450     else if (Result != T)
13451       Result = QualType();
13452   };
13453 
13454   // Look for an unambiguous type from a progressively larger subset.
13455   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13456   //
13457   // First, consider only the best candidate.
13458   if (Best && *Best != CS.end())
13459     ConsiderCandidate(**Best);
13460   // Next, consider only viable candidates.
13461   if (!Result)
13462     for (const auto &C : CS)
13463       if (C.Viable)
13464         ConsiderCandidate(C);
13465   // Finally, consider all candidates.
13466   if (!Result)
13467     for (const auto &C : CS)
13468       ConsiderCandidate(C);
13469 
13470   if (!Result)
13471     return QualType();
13472   auto Value = *Result;
13473   if (Value.isNull() || Value->isUndeducedType())
13474     return QualType();
13475   return Value;
13476 }
13477 
13478 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13479 /// the completed call expression. If overload resolution fails, emits
13480 /// diagnostics and returns ExprError()
13481 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13482                                            UnresolvedLookupExpr *ULE,
13483                                            SourceLocation LParenLoc,
13484                                            MultiExprArg Args,
13485                                            SourceLocation RParenLoc,
13486                                            Expr *ExecConfig,
13487                                            OverloadCandidateSet *CandidateSet,
13488                                            OverloadCandidateSet::iterator *Best,
13489                                            OverloadingResult OverloadResult,
13490                                            bool AllowTypoCorrection) {
13491   switch (OverloadResult) {
13492   case OR_Success: {
13493     FunctionDecl *FDecl = (*Best)->Function;
13494     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13495     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13496       return ExprError();
13497     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13498     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13499                                          ExecConfig, /*IsExecConfig=*/false,
13500                                          (*Best)->IsADLCandidate);
13501   }
13502 
13503   case OR_No_Viable_Function: {
13504     // Try to recover by looking for viable functions which the user might
13505     // have meant to call.
13506     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13507                                                 Args, RParenLoc,
13508                                                 CandidateSet->empty(),
13509                                                 AllowTypoCorrection);
13510     if (Recovery.isInvalid() || Recovery.isUsable())
13511       return Recovery;
13512 
13513     // If the user passes in a function that we can't take the address of, we
13514     // generally end up emitting really bad error messages. Here, we attempt to
13515     // emit better ones.
13516     for (const Expr *Arg : Args) {
13517       if (!Arg->getType()->isFunctionType())
13518         continue;
13519       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13520         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13521         if (FD &&
13522             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13523                                                        Arg->getExprLoc()))
13524           return ExprError();
13525       }
13526     }
13527 
13528     CandidateSet->NoteCandidates(
13529         PartialDiagnosticAt(
13530             Fn->getBeginLoc(),
13531             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13532                 << ULE->getName() << Fn->getSourceRange()),
13533         SemaRef, OCD_AllCandidates, Args);
13534     break;
13535   }
13536 
13537   case OR_Ambiguous:
13538     CandidateSet->NoteCandidates(
13539         PartialDiagnosticAt(Fn->getBeginLoc(),
13540                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13541                                 << ULE->getName() << Fn->getSourceRange()),
13542         SemaRef, OCD_AmbiguousCandidates, Args);
13543     break;
13544 
13545   case OR_Deleted: {
13546     CandidateSet->NoteCandidates(
13547         PartialDiagnosticAt(Fn->getBeginLoc(),
13548                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13549                                 << ULE->getName() << Fn->getSourceRange()),
13550         SemaRef, OCD_AllCandidates, Args);
13551 
13552     // We emitted an error for the unavailable/deleted function call but keep
13553     // the call in the AST.
13554     FunctionDecl *FDecl = (*Best)->Function;
13555     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13556     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13557                                          ExecConfig, /*IsExecConfig=*/false,
13558                                          (*Best)->IsADLCandidate);
13559   }
13560   }
13561 
13562   // Overload resolution failed, try to recover.
13563   SmallVector<Expr *, 8> SubExprs = {Fn};
13564   SubExprs.append(Args.begin(), Args.end());
13565   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13566                                     chooseRecoveryType(*CandidateSet, Best));
13567 }
13568 
13569 static void markUnaddressableCandidatesUnviable(Sema &S,
13570                                                 OverloadCandidateSet &CS) {
13571   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13572     if (I->Viable &&
13573         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13574       I->Viable = false;
13575       I->FailureKind = ovl_fail_addr_not_available;
13576     }
13577   }
13578 }
13579 
13580 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13581 /// (which eventually refers to the declaration Func) and the call
13582 /// arguments Args/NumArgs, attempt to resolve the function call down
13583 /// to a specific function. If overload resolution succeeds, returns
13584 /// the call expression produced by overload resolution.
13585 /// Otherwise, emits diagnostics and returns ExprError.
13586 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13587                                          UnresolvedLookupExpr *ULE,
13588                                          SourceLocation LParenLoc,
13589                                          MultiExprArg Args,
13590                                          SourceLocation RParenLoc,
13591                                          Expr *ExecConfig,
13592                                          bool AllowTypoCorrection,
13593                                          bool CalleesAddressIsTaken) {
13594   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13595                                     OverloadCandidateSet::CSK_Normal);
13596   ExprResult result;
13597 
13598   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13599                              &result))
13600     return result;
13601 
13602   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13603   // functions that aren't addressible are considered unviable.
13604   if (CalleesAddressIsTaken)
13605     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13606 
13607   OverloadCandidateSet::iterator Best;
13608   OverloadingResult OverloadResult =
13609       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13610 
13611   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13612                                   ExecConfig, &CandidateSet, &Best,
13613                                   OverloadResult, AllowTypoCorrection);
13614 }
13615 
13616 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13617   return Functions.size() > 1 ||
13618          (Functions.size() == 1 &&
13619           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13620 }
13621 
13622 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13623                                             NestedNameSpecifierLoc NNSLoc,
13624                                             DeclarationNameInfo DNI,
13625                                             const UnresolvedSetImpl &Fns,
13626                                             bool PerformADL) {
13627   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13628                                       PerformADL, IsOverloaded(Fns),
13629                                       Fns.begin(), Fns.end());
13630 }
13631 
13632 /// Create a unary operation that may resolve to an overloaded
13633 /// operator.
13634 ///
13635 /// \param OpLoc The location of the operator itself (e.g., '*').
13636 ///
13637 /// \param Opc The UnaryOperatorKind that describes this operator.
13638 ///
13639 /// \param Fns The set of non-member functions that will be
13640 /// considered by overload resolution. The caller needs to build this
13641 /// set based on the context using, e.g.,
13642 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13643 /// set should not contain any member functions; those will be added
13644 /// by CreateOverloadedUnaryOp().
13645 ///
13646 /// \param Input The input argument.
13647 ExprResult
13648 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13649                               const UnresolvedSetImpl &Fns,
13650                               Expr *Input, bool PerformADL) {
13651   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13652   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13653   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13654   // TODO: provide better source location info.
13655   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13656 
13657   if (checkPlaceholderForOverload(*this, Input))
13658     return ExprError();
13659 
13660   Expr *Args[2] = { Input, nullptr };
13661   unsigned NumArgs = 1;
13662 
13663   // For post-increment and post-decrement, add the implicit '0' as
13664   // the second argument, so that we know this is a post-increment or
13665   // post-decrement.
13666   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13667     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13668     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13669                                      SourceLocation());
13670     NumArgs = 2;
13671   }
13672 
13673   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13674 
13675   if (Input->isTypeDependent()) {
13676     if (Fns.empty())
13677       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13678                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13679                                    CurFPFeatureOverrides());
13680 
13681     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13682     ExprResult Fn = CreateUnresolvedLookupExpr(
13683         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13684     if (Fn.isInvalid())
13685       return ExprError();
13686     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13687                                        Context.DependentTy, VK_PRValue, OpLoc,
13688                                        CurFPFeatureOverrides());
13689   }
13690 
13691   // Build an empty overload set.
13692   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13693 
13694   // Add the candidates from the given function set.
13695   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13696 
13697   // Add operator candidates that are member functions.
13698   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13699 
13700   // Add candidates from ADL.
13701   if (PerformADL) {
13702     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13703                                          /*ExplicitTemplateArgs*/nullptr,
13704                                          CandidateSet);
13705   }
13706 
13707   // Add builtin operator candidates.
13708   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13709 
13710   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13711 
13712   // Perform overload resolution.
13713   OverloadCandidateSet::iterator Best;
13714   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13715   case OR_Success: {
13716     // We found a built-in operator or an overloaded operator.
13717     FunctionDecl *FnDecl = Best->Function;
13718 
13719     if (FnDecl) {
13720       Expr *Base = nullptr;
13721       // We matched an overloaded operator. Build a call to that
13722       // operator.
13723 
13724       // Convert the arguments.
13725       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13726         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13727 
13728         ExprResult InputRes =
13729           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13730                                               Best->FoundDecl, Method);
13731         if (InputRes.isInvalid())
13732           return ExprError();
13733         Base = Input = InputRes.get();
13734       } else {
13735         // Convert the arguments.
13736         ExprResult InputInit
13737           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13738                                                       Context,
13739                                                       FnDecl->getParamDecl(0)),
13740                                       SourceLocation(),
13741                                       Input);
13742         if (InputInit.isInvalid())
13743           return ExprError();
13744         Input = InputInit.get();
13745       }
13746 
13747       // Build the actual expression node.
13748       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13749                                                 Base, HadMultipleCandidates,
13750                                                 OpLoc);
13751       if (FnExpr.isInvalid())
13752         return ExprError();
13753 
13754       // Determine the result type.
13755       QualType ResultTy = FnDecl->getReturnType();
13756       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13757       ResultTy = ResultTy.getNonLValueExprType(Context);
13758 
13759       Args[0] = Input;
13760       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13761           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13762           CurFPFeatureOverrides(), Best->IsADLCandidate);
13763 
13764       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13765         return ExprError();
13766 
13767       if (CheckFunctionCall(FnDecl, TheCall,
13768                             FnDecl->getType()->castAs<FunctionProtoType>()))
13769         return ExprError();
13770       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13771     } else {
13772       // We matched a built-in operator. Convert the arguments, then
13773       // break out so that we will build the appropriate built-in
13774       // operator node.
13775       ExprResult InputRes = PerformImplicitConversion(
13776           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13777           CCK_ForBuiltinOverloadedOp);
13778       if (InputRes.isInvalid())
13779         return ExprError();
13780       Input = InputRes.get();
13781       break;
13782     }
13783   }
13784 
13785   case OR_No_Viable_Function:
13786     // This is an erroneous use of an operator which can be overloaded by
13787     // a non-member function. Check for non-member operators which were
13788     // defined too late to be candidates.
13789     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13790       // FIXME: Recover by calling the found function.
13791       return ExprError();
13792 
13793     // No viable function; fall through to handling this as a
13794     // built-in operator, which will produce an error message for us.
13795     break;
13796 
13797   case OR_Ambiguous:
13798     CandidateSet.NoteCandidates(
13799         PartialDiagnosticAt(OpLoc,
13800                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13801                                 << UnaryOperator::getOpcodeStr(Opc)
13802                                 << Input->getType() << Input->getSourceRange()),
13803         *this, OCD_AmbiguousCandidates, ArgsArray,
13804         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13805     return ExprError();
13806 
13807   case OR_Deleted:
13808     CandidateSet.NoteCandidates(
13809         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13810                                        << UnaryOperator::getOpcodeStr(Opc)
13811                                        << Input->getSourceRange()),
13812         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13813         OpLoc);
13814     return ExprError();
13815   }
13816 
13817   // Either we found no viable overloaded operator or we matched a
13818   // built-in operator. In either case, fall through to trying to
13819   // build a built-in operation.
13820   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13821 }
13822 
13823 /// Perform lookup for an overloaded binary operator.
13824 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13825                                  OverloadedOperatorKind Op,
13826                                  const UnresolvedSetImpl &Fns,
13827                                  ArrayRef<Expr *> Args, bool PerformADL) {
13828   SourceLocation OpLoc = CandidateSet.getLocation();
13829 
13830   OverloadedOperatorKind ExtraOp =
13831       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13832           ? getRewrittenOverloadedOperator(Op)
13833           : OO_None;
13834 
13835   // Add the candidates from the given function set. This also adds the
13836   // rewritten candidates using these functions if necessary.
13837   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13838 
13839   // Add operator candidates that are member functions.
13840   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13841   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
13842     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13843                                 OverloadCandidateParamOrder::Reversed);
13844 
13845   // In C++20, also add any rewritten member candidates.
13846   if (ExtraOp) {
13847     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13848     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
13849       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13850                                   CandidateSet,
13851                                   OverloadCandidateParamOrder::Reversed);
13852   }
13853 
13854   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13855   // performed for an assignment operator (nor for operator[] nor operator->,
13856   // which don't get here).
13857   if (Op != OO_Equal && PerformADL) {
13858     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13859     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13860                                          /*ExplicitTemplateArgs*/ nullptr,
13861                                          CandidateSet);
13862     if (ExtraOp) {
13863       DeclarationName ExtraOpName =
13864           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13865       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13866                                            /*ExplicitTemplateArgs*/ nullptr,
13867                                            CandidateSet);
13868     }
13869   }
13870 
13871   // Add builtin operator candidates.
13872   //
13873   // FIXME: We don't add any rewritten candidates here. This is strictly
13874   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13875   // resulting in our selecting a rewritten builtin candidate. For example:
13876   //
13877   //   enum class E { e };
13878   //   bool operator!=(E, E) requires false;
13879   //   bool k = E::e != E::e;
13880   //
13881   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13882   // it seems unreasonable to consider rewritten builtin candidates. A core
13883   // issue has been filed proposing to removed this requirement.
13884   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13885 }
13886 
13887 /// Create a binary operation that may resolve to an overloaded
13888 /// operator.
13889 ///
13890 /// \param OpLoc The location of the operator itself (e.g., '+').
13891 ///
13892 /// \param Opc The BinaryOperatorKind that describes this operator.
13893 ///
13894 /// \param Fns The set of non-member functions that will be
13895 /// considered by overload resolution. The caller needs to build this
13896 /// set based on the context using, e.g.,
13897 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13898 /// set should not contain any member functions; those will be added
13899 /// by CreateOverloadedBinOp().
13900 ///
13901 /// \param LHS Left-hand argument.
13902 /// \param RHS Right-hand argument.
13903 /// \param PerformADL Whether to consider operator candidates found by ADL.
13904 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13905 ///        C++20 operator rewrites.
13906 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13907 ///        the function in question. Such a function is never a candidate in
13908 ///        our overload resolution. This also enables synthesizing a three-way
13909 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13910 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13911                                        BinaryOperatorKind Opc,
13912                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13913                                        Expr *RHS, bool PerformADL,
13914                                        bool AllowRewrittenCandidates,
13915                                        FunctionDecl *DefaultedFn) {
13916   Expr *Args[2] = { LHS, RHS };
13917   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13918 
13919   if (!getLangOpts().CPlusPlus20)
13920     AllowRewrittenCandidates = false;
13921 
13922   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13923 
13924   // If either side is type-dependent, create an appropriate dependent
13925   // expression.
13926   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13927     if (Fns.empty()) {
13928       // If there are no functions to store, just build a dependent
13929       // BinaryOperator or CompoundAssignment.
13930       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13931         return CompoundAssignOperator::Create(
13932             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13933             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13934             Context.DependentTy);
13935       return BinaryOperator::Create(
13936           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13937           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13938     }
13939 
13940     // FIXME: save results of ADL from here?
13941     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13942     // TODO: provide better source location info in DNLoc component.
13943     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13944     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13945     ExprResult Fn = CreateUnresolvedLookupExpr(
13946         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13947     if (Fn.isInvalid())
13948       return ExprError();
13949     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13950                                        Context.DependentTy, VK_PRValue, OpLoc,
13951                                        CurFPFeatureOverrides());
13952   }
13953 
13954   // Always do placeholder-like conversions on the RHS.
13955   if (checkPlaceholderForOverload(*this, Args[1]))
13956     return ExprError();
13957 
13958   // Do placeholder-like conversion on the LHS; note that we should
13959   // not get here with a PseudoObject LHS.
13960   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13961   if (checkPlaceholderForOverload(*this, Args[0]))
13962     return ExprError();
13963 
13964   // If this is the assignment operator, we only perform overload resolution
13965   // if the left-hand side is a class or enumeration type. This is actually
13966   // a hack. The standard requires that we do overload resolution between the
13967   // various built-in candidates, but as DR507 points out, this can lead to
13968   // problems. So we do it this way, which pretty much follows what GCC does.
13969   // Note that we go the traditional code path for compound assignment forms.
13970   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13971     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13972 
13973   // If this is the .* operator, which is not overloadable, just
13974   // create a built-in binary operator.
13975   if (Opc == BO_PtrMemD)
13976     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13977 
13978   // Build the overload set.
13979   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
13980                                     OverloadCandidateSet::OperatorRewriteInfo(
13981                                         Op, OpLoc, AllowRewrittenCandidates));
13982   if (DefaultedFn)
13983     CandidateSet.exclude(DefaultedFn);
13984   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13985 
13986   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13987 
13988   // Perform overload resolution.
13989   OverloadCandidateSet::iterator Best;
13990   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13991     case OR_Success: {
13992       // We found a built-in operator or an overloaded operator.
13993       FunctionDecl *FnDecl = Best->Function;
13994 
13995       bool IsReversed = Best->isReversed();
13996       if (IsReversed)
13997         std::swap(Args[0], Args[1]);
13998 
13999       if (FnDecl) {
14000         Expr *Base = nullptr;
14001         // We matched an overloaded operator. Build a call to that
14002         // operator.
14003 
14004         OverloadedOperatorKind ChosenOp =
14005             FnDecl->getDeclName().getCXXOverloadedOperator();
14006 
14007         // C++2a [over.match.oper]p9:
14008         //   If a rewritten operator== candidate is selected by overload
14009         //   resolution for an operator@, its return type shall be cv bool
14010         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14011             !FnDecl->getReturnType()->isBooleanType()) {
14012           bool IsExtension =
14013               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14014           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14015                                   : diag::err_ovl_rewrite_equalequal_not_bool)
14016               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14017               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14018           Diag(FnDecl->getLocation(), diag::note_declared_at);
14019           if (!IsExtension)
14020             return ExprError();
14021         }
14022 
14023         if (AllowRewrittenCandidates && !IsReversed &&
14024             CandidateSet.getRewriteInfo().isReversible()) {
14025           // We could have reversed this operator, but didn't. Check if some
14026           // reversed form was a viable candidate, and if so, if it had a
14027           // better conversion for either parameter. If so, this call is
14028           // formally ambiguous, and allowing it is an extension.
14029           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14030           for (OverloadCandidate &Cand : CandidateSet) {
14031             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14032                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
14033               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14034                 if (CompareImplicitConversionSequences(
14035                         *this, OpLoc, Cand.Conversions[ArgIdx],
14036                         Best->Conversions[ArgIdx]) ==
14037                     ImplicitConversionSequence::Better) {
14038                   AmbiguousWith.push_back(Cand.Function);
14039                   break;
14040                 }
14041               }
14042             }
14043           }
14044 
14045           if (!AmbiguousWith.empty()) {
14046             bool AmbiguousWithSelf =
14047                 AmbiguousWith.size() == 1 &&
14048                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14049             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14050                 << BinaryOperator::getOpcodeStr(Opc)
14051                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14052                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14053             if (AmbiguousWithSelf) {
14054               Diag(FnDecl->getLocation(),
14055                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
14056               // Mark member== const or provide matching != to disallow reversed
14057               // args. Eg.
14058               // struct S { bool operator==(const S&); };
14059               // S()==S();
14060               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14061                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14062                     !MD->isConst() &&
14063                     Context.hasSameUnqualifiedType(
14064                         MD->getThisObjectType(),
14065                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14066                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
14067                                                    Args[0]->getType()) &&
14068                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
14069                                                    Args[1]->getType()))
14070                   Diag(FnDecl->getLocation(),
14071                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14072             } else {
14073               Diag(FnDecl->getLocation(),
14074                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14075               for (auto *F : AmbiguousWith)
14076                 Diag(F->getLocation(),
14077                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14078             }
14079           }
14080         }
14081 
14082         // Convert the arguments.
14083         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14084           // Best->Access is only meaningful for class members.
14085           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14086 
14087           ExprResult Arg1 =
14088             PerformCopyInitialization(
14089               InitializedEntity::InitializeParameter(Context,
14090                                                      FnDecl->getParamDecl(0)),
14091               SourceLocation(), Args[1]);
14092           if (Arg1.isInvalid())
14093             return ExprError();
14094 
14095           ExprResult Arg0 =
14096             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14097                                                 Best->FoundDecl, Method);
14098           if (Arg0.isInvalid())
14099             return ExprError();
14100           Base = Args[0] = Arg0.getAs<Expr>();
14101           Args[1] = RHS = Arg1.getAs<Expr>();
14102         } else {
14103           // Convert the arguments.
14104           ExprResult Arg0 = PerformCopyInitialization(
14105             InitializedEntity::InitializeParameter(Context,
14106                                                    FnDecl->getParamDecl(0)),
14107             SourceLocation(), Args[0]);
14108           if (Arg0.isInvalid())
14109             return ExprError();
14110 
14111           ExprResult Arg1 =
14112             PerformCopyInitialization(
14113               InitializedEntity::InitializeParameter(Context,
14114                                                      FnDecl->getParamDecl(1)),
14115               SourceLocation(), Args[1]);
14116           if (Arg1.isInvalid())
14117             return ExprError();
14118           Args[0] = LHS = Arg0.getAs<Expr>();
14119           Args[1] = RHS = Arg1.getAs<Expr>();
14120         }
14121 
14122         // Build the actual expression node.
14123         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14124                                                   Best->FoundDecl, Base,
14125                                                   HadMultipleCandidates, OpLoc);
14126         if (FnExpr.isInvalid())
14127           return ExprError();
14128 
14129         // Determine the result type.
14130         QualType ResultTy = FnDecl->getReturnType();
14131         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14132         ResultTy = ResultTy.getNonLValueExprType(Context);
14133 
14134         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14135             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14136             CurFPFeatureOverrides(), Best->IsADLCandidate);
14137 
14138         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14139                                 FnDecl))
14140           return ExprError();
14141 
14142         ArrayRef<const Expr *> ArgsArray(Args, 2);
14143         const Expr *ImplicitThis = nullptr;
14144         // Cut off the implicit 'this'.
14145         if (isa<CXXMethodDecl>(FnDecl)) {
14146           ImplicitThis = ArgsArray[0];
14147           ArgsArray = ArgsArray.slice(1);
14148         }
14149 
14150         // Check for a self move.
14151         if (Op == OO_Equal)
14152           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14153 
14154         if (ImplicitThis) {
14155           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14156           QualType ThisTypeFromDecl = Context.getPointerType(
14157               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
14158 
14159           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14160                             ThisTypeFromDecl);
14161         }
14162 
14163         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14164                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14165                   VariadicDoesNotApply);
14166 
14167         ExprResult R = MaybeBindToTemporary(TheCall);
14168         if (R.isInvalid())
14169           return ExprError();
14170 
14171         R = CheckForImmediateInvocation(R, FnDecl);
14172         if (R.isInvalid())
14173           return ExprError();
14174 
14175         // For a rewritten candidate, we've already reversed the arguments
14176         // if needed. Perform the rest of the rewrite now.
14177         if ((Best->RewriteKind & CRK_DifferentOperator) ||
14178             (Op == OO_Spaceship && IsReversed)) {
14179           if (Op == OO_ExclaimEqual) {
14180             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14181             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14182           } else {
14183             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14184             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14185             Expr *ZeroLiteral =
14186                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14187 
14188             Sema::CodeSynthesisContext Ctx;
14189             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14190             Ctx.Entity = FnDecl;
14191             pushCodeSynthesisContext(Ctx);
14192 
14193             R = CreateOverloadedBinOp(
14194                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14195                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14196                 /*AllowRewrittenCandidates=*/false);
14197 
14198             popCodeSynthesisContext();
14199           }
14200           if (R.isInvalid())
14201             return ExprError();
14202         } else {
14203           assert(ChosenOp == Op && "unexpected operator name");
14204         }
14205 
14206         // Make a note in the AST if we did any rewriting.
14207         if (Best->RewriteKind != CRK_None)
14208           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14209 
14210         return R;
14211       } else {
14212         // We matched a built-in operator. Convert the arguments, then
14213         // break out so that we will build the appropriate built-in
14214         // operator node.
14215         ExprResult ArgsRes0 = PerformImplicitConversion(
14216             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14217             AA_Passing, CCK_ForBuiltinOverloadedOp);
14218         if (ArgsRes0.isInvalid())
14219           return ExprError();
14220         Args[0] = ArgsRes0.get();
14221 
14222         ExprResult ArgsRes1 = PerformImplicitConversion(
14223             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14224             AA_Passing, CCK_ForBuiltinOverloadedOp);
14225         if (ArgsRes1.isInvalid())
14226           return ExprError();
14227         Args[1] = ArgsRes1.get();
14228         break;
14229       }
14230     }
14231 
14232     case OR_No_Viable_Function: {
14233       // C++ [over.match.oper]p9:
14234       //   If the operator is the operator , [...] and there are no
14235       //   viable functions, then the operator is assumed to be the
14236       //   built-in operator and interpreted according to clause 5.
14237       if (Opc == BO_Comma)
14238         break;
14239 
14240       // When defaulting an 'operator<=>', we can try to synthesize a three-way
14241       // compare result using '==' and '<'.
14242       if (DefaultedFn && Opc == BO_Cmp) {
14243         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14244                                                           Args[1], DefaultedFn);
14245         if (E.isInvalid() || E.isUsable())
14246           return E;
14247       }
14248 
14249       // For class as left operand for assignment or compound assignment
14250       // operator do not fall through to handling in built-in, but report that
14251       // no overloaded assignment operator found
14252       ExprResult Result = ExprError();
14253       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14254       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14255                                                    Args, OpLoc);
14256       DeferDiagsRAII DDR(*this,
14257                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14258       if (Args[0]->getType()->isRecordType() &&
14259           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14260         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14261              << BinaryOperator::getOpcodeStr(Opc)
14262              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14263         if (Args[0]->getType()->isIncompleteType()) {
14264           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14265             << Args[0]->getType()
14266             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14267         }
14268       } else {
14269         // This is an erroneous use of an operator which can be overloaded by
14270         // a non-member function. Check for non-member operators which were
14271         // defined too late to be candidates.
14272         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14273           // FIXME: Recover by calling the found function.
14274           return ExprError();
14275 
14276         // No viable function; try to create a built-in operation, which will
14277         // produce an error. Then, show the non-viable candidates.
14278         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14279       }
14280       assert(Result.isInvalid() &&
14281              "C++ binary operator overloading is missing candidates!");
14282       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14283       return Result;
14284     }
14285 
14286     case OR_Ambiguous:
14287       CandidateSet.NoteCandidates(
14288           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14289                                          << BinaryOperator::getOpcodeStr(Opc)
14290                                          << Args[0]->getType()
14291                                          << Args[1]->getType()
14292                                          << Args[0]->getSourceRange()
14293                                          << Args[1]->getSourceRange()),
14294           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14295           OpLoc);
14296       return ExprError();
14297 
14298     case OR_Deleted:
14299       if (isImplicitlyDeleted(Best->Function)) {
14300         FunctionDecl *DeletedFD = Best->Function;
14301         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14302         if (DFK.isSpecialMember()) {
14303           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14304             << Args[0]->getType() << DFK.asSpecialMember();
14305         } else {
14306           assert(DFK.isComparison());
14307           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14308             << Args[0]->getType() << DeletedFD;
14309         }
14310 
14311         // The user probably meant to call this special member. Just
14312         // explain why it's deleted.
14313         NoteDeletedFunction(DeletedFD);
14314         return ExprError();
14315       }
14316       CandidateSet.NoteCandidates(
14317           PartialDiagnosticAt(
14318               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14319                          << getOperatorSpelling(Best->Function->getDeclName()
14320                                                     .getCXXOverloadedOperator())
14321                          << Args[0]->getSourceRange()
14322                          << Args[1]->getSourceRange()),
14323           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14324           OpLoc);
14325       return ExprError();
14326   }
14327 
14328   // We matched a built-in operator; build it.
14329   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14330 }
14331 
14332 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14333     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14334     FunctionDecl *DefaultedFn) {
14335   const ComparisonCategoryInfo *Info =
14336       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14337   // If we're not producing a known comparison category type, we can't
14338   // synthesize a three-way comparison. Let the caller diagnose this.
14339   if (!Info)
14340     return ExprResult((Expr*)nullptr);
14341 
14342   // If we ever want to perform this synthesis more generally, we will need to
14343   // apply the temporary materialization conversion to the operands.
14344   assert(LHS->isGLValue() && RHS->isGLValue() &&
14345          "cannot use prvalue expressions more than once");
14346   Expr *OrigLHS = LHS;
14347   Expr *OrigRHS = RHS;
14348 
14349   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14350   // each of them multiple times below.
14351   LHS = new (Context)
14352       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14353                       LHS->getObjectKind(), LHS);
14354   RHS = new (Context)
14355       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14356                       RHS->getObjectKind(), RHS);
14357 
14358   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14359                                         DefaultedFn);
14360   if (Eq.isInvalid())
14361     return ExprError();
14362 
14363   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14364                                           true, DefaultedFn);
14365   if (Less.isInvalid())
14366     return ExprError();
14367 
14368   ExprResult Greater;
14369   if (Info->isPartial()) {
14370     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14371                                     DefaultedFn);
14372     if (Greater.isInvalid())
14373       return ExprError();
14374   }
14375 
14376   // Form the list of comparisons we're going to perform.
14377   struct Comparison {
14378     ExprResult Cmp;
14379     ComparisonCategoryResult Result;
14380   } Comparisons[4] =
14381   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14382                           : ComparisonCategoryResult::Equivalent},
14383     {Less, ComparisonCategoryResult::Less},
14384     {Greater, ComparisonCategoryResult::Greater},
14385     {ExprResult(), ComparisonCategoryResult::Unordered},
14386   };
14387 
14388   int I = Info->isPartial() ? 3 : 2;
14389 
14390   // Combine the comparisons with suitable conditional expressions.
14391   ExprResult Result;
14392   for (; I >= 0; --I) {
14393     // Build a reference to the comparison category constant.
14394     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14395     // FIXME: Missing a constant for a comparison category. Diagnose this?
14396     if (!VI)
14397       return ExprResult((Expr*)nullptr);
14398     ExprResult ThisResult =
14399         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14400     if (ThisResult.isInvalid())
14401       return ExprError();
14402 
14403     // Build a conditional unless this is the final case.
14404     if (Result.get()) {
14405       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14406                                   ThisResult.get(), Result.get());
14407       if (Result.isInvalid())
14408         return ExprError();
14409     } else {
14410       Result = ThisResult;
14411     }
14412   }
14413 
14414   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14415   // bind the OpaqueValueExprs before they're (repeatedly) used.
14416   Expr *SyntacticForm = BinaryOperator::Create(
14417       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14418       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14419       CurFPFeatureOverrides());
14420   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14421   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14422 }
14423 
14424 static bool PrepareArgumentsForCallToObjectOfClassType(
14425     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14426     MultiExprArg Args, SourceLocation LParenLoc) {
14427 
14428   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14429   unsigned NumParams = Proto->getNumParams();
14430   unsigned NumArgsSlots =
14431       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14432   // Build the full argument list for the method call (the implicit object
14433   // parameter is placed at the beginning of the list).
14434   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14435   bool IsError = false;
14436   // Initialize the implicit object parameter.
14437   // Check the argument types.
14438   for (unsigned i = 0; i != NumParams; i++) {
14439     Expr *Arg;
14440     if (i < Args.size()) {
14441       Arg = Args[i];
14442       ExprResult InputInit =
14443           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14444                                           S.Context, Method->getParamDecl(i)),
14445                                       SourceLocation(), Arg);
14446       IsError |= InputInit.isInvalid();
14447       Arg = InputInit.getAs<Expr>();
14448     } else {
14449       ExprResult DefArg =
14450           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14451       if (DefArg.isInvalid()) {
14452         IsError = true;
14453         break;
14454       }
14455       Arg = DefArg.getAs<Expr>();
14456     }
14457 
14458     MethodArgs.push_back(Arg);
14459   }
14460   return IsError;
14461 }
14462 
14463 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14464                                                     SourceLocation RLoc,
14465                                                     Expr *Base,
14466                                                     MultiExprArg ArgExpr) {
14467   SmallVector<Expr *, 2> Args;
14468   Args.push_back(Base);
14469   for (auto *e : ArgExpr) {
14470     Args.push_back(e);
14471   }
14472   DeclarationName OpName =
14473       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14474 
14475   SourceRange Range = ArgExpr.empty()
14476                           ? SourceRange{}
14477                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14478                                         ArgExpr.back()->getEndLoc());
14479 
14480   // If either side is type-dependent, create an appropriate dependent
14481   // expression.
14482   if (Expr::hasAnyTypeDependentArguments(Args)) {
14483 
14484     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14485     // CHECKME: no 'operator' keyword?
14486     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14487     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14488     ExprResult Fn = CreateUnresolvedLookupExpr(
14489         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14490     if (Fn.isInvalid())
14491       return ExprError();
14492     // Can't add any actual overloads yet
14493 
14494     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14495                                        Context.DependentTy, VK_PRValue, RLoc,
14496                                        CurFPFeatureOverrides());
14497   }
14498 
14499   // Handle placeholders
14500   UnbridgedCastsSet UnbridgedCasts;
14501   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14502     return ExprError();
14503   }
14504   // Build an empty overload set.
14505   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14506 
14507   // Subscript can only be overloaded as a member function.
14508 
14509   // Add operator candidates that are member functions.
14510   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14511 
14512   // Add builtin operator candidates.
14513   if (Args.size() == 2)
14514     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14515 
14516   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14517 
14518   // Perform overload resolution.
14519   OverloadCandidateSet::iterator Best;
14520   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14521     case OR_Success: {
14522       // We found a built-in operator or an overloaded operator.
14523       FunctionDecl *FnDecl = Best->Function;
14524 
14525       if (FnDecl) {
14526         // We matched an overloaded operator. Build a call to that
14527         // operator.
14528 
14529         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14530 
14531         // Convert the arguments.
14532         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14533         SmallVector<Expr *, 2> MethodArgs;
14534 
14535         // Handle 'this' parameter if the selected function is not static.
14536         if (Method->isInstance()) {
14537           ExprResult Arg0 = PerformObjectArgumentInitialization(
14538               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14539           if (Arg0.isInvalid())
14540             return ExprError();
14541 
14542           MethodArgs.push_back(Arg0.get());
14543         }
14544 
14545         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14546             *this, MethodArgs, Method, ArgExpr, LLoc);
14547         if (IsError)
14548           return ExprError();
14549 
14550         // Build the actual expression node.
14551         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14552         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14553         ExprResult FnExpr = CreateFunctionRefExpr(
14554             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14555             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14556         if (FnExpr.isInvalid())
14557           return ExprError();
14558 
14559         // Determine the result type
14560         QualType ResultTy = FnDecl->getReturnType();
14561         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14562         ResultTy = ResultTy.getNonLValueExprType(Context);
14563 
14564         CallExpr *TheCall;
14565         if (Method->isInstance())
14566           TheCall = CXXOperatorCallExpr::Create(
14567               Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK,
14568               RLoc, CurFPFeatureOverrides());
14569         else
14570           TheCall =
14571               CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
14572                                RLoc, CurFPFeatureOverrides());
14573 
14574         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14575           return ExprError();
14576 
14577         if (CheckFunctionCall(Method, TheCall,
14578                               Method->getType()->castAs<FunctionProtoType>()))
14579           return ExprError();
14580 
14581         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14582                                            FnDecl);
14583       } else {
14584         // We matched a built-in operator. Convert the arguments, then
14585         // break out so that we will build the appropriate built-in
14586         // operator node.
14587         ExprResult ArgsRes0 = PerformImplicitConversion(
14588             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14589             AA_Passing, CCK_ForBuiltinOverloadedOp);
14590         if (ArgsRes0.isInvalid())
14591           return ExprError();
14592         Args[0] = ArgsRes0.get();
14593 
14594         ExprResult ArgsRes1 = PerformImplicitConversion(
14595             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14596             AA_Passing, CCK_ForBuiltinOverloadedOp);
14597         if (ArgsRes1.isInvalid())
14598           return ExprError();
14599         Args[1] = ArgsRes1.get();
14600 
14601         break;
14602       }
14603     }
14604 
14605     case OR_No_Viable_Function: {
14606       PartialDiagnostic PD =
14607           CandidateSet.empty()
14608               ? (PDiag(diag::err_ovl_no_oper)
14609                  << Args[0]->getType() << /*subscript*/ 0
14610                  << Args[0]->getSourceRange() << Range)
14611               : (PDiag(diag::err_ovl_no_viable_subscript)
14612                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14613       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14614                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14615       return ExprError();
14616     }
14617 
14618     case OR_Ambiguous:
14619       if (Args.size() == 2) {
14620         CandidateSet.NoteCandidates(
14621             PartialDiagnosticAt(
14622                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14623                           << "[]" << Args[0]->getType() << Args[1]->getType()
14624                           << Args[0]->getSourceRange() << Range),
14625             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14626       } else {
14627         CandidateSet.NoteCandidates(
14628             PartialDiagnosticAt(LLoc,
14629                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14630                                     << Args[0]->getType()
14631                                     << Args[0]->getSourceRange() << Range),
14632             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14633       }
14634       return ExprError();
14635 
14636     case OR_Deleted:
14637       CandidateSet.NoteCandidates(
14638           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14639                                         << "[]" << Args[0]->getSourceRange()
14640                                         << Range),
14641           *this, OCD_AllCandidates, Args, "[]", LLoc);
14642       return ExprError();
14643     }
14644 
14645   // We matched a built-in operator; build it.
14646   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14647 }
14648 
14649 /// BuildCallToMemberFunction - Build a call to a member
14650 /// function. MemExpr is the expression that refers to the member
14651 /// function (and includes the object parameter), Args/NumArgs are the
14652 /// arguments to the function call (not including the object
14653 /// parameter). The caller needs to validate that the member
14654 /// expression refers to a non-static member function or an overloaded
14655 /// member function.
14656 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14657                                            SourceLocation LParenLoc,
14658                                            MultiExprArg Args,
14659                                            SourceLocation RParenLoc,
14660                                            Expr *ExecConfig, bool IsExecConfig,
14661                                            bool AllowRecovery) {
14662   assert(MemExprE->getType() == Context.BoundMemberTy ||
14663          MemExprE->getType() == Context.OverloadTy);
14664 
14665   // Dig out the member expression. This holds both the object
14666   // argument and the member function we're referring to.
14667   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14668 
14669   // Determine whether this is a call to a pointer-to-member function.
14670   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14671     assert(op->getType() == Context.BoundMemberTy);
14672     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14673 
14674     QualType fnType =
14675       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14676 
14677     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14678     QualType resultType = proto->getCallResultType(Context);
14679     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14680 
14681     // Check that the object type isn't more qualified than the
14682     // member function we're calling.
14683     Qualifiers funcQuals = proto->getMethodQuals();
14684 
14685     QualType objectType = op->getLHS()->getType();
14686     if (op->getOpcode() == BO_PtrMemI)
14687       objectType = objectType->castAs<PointerType>()->getPointeeType();
14688     Qualifiers objectQuals = objectType.getQualifiers();
14689 
14690     Qualifiers difference = objectQuals - funcQuals;
14691     difference.removeObjCGCAttr();
14692     difference.removeAddressSpace();
14693     if (difference) {
14694       std::string qualsString = difference.getAsString();
14695       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14696         << fnType.getUnqualifiedType()
14697         << qualsString
14698         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14699     }
14700 
14701     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14702         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14703         CurFPFeatureOverrides(), proto->getNumParams());
14704 
14705     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14706                             call, nullptr))
14707       return ExprError();
14708 
14709     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14710       return ExprError();
14711 
14712     if (CheckOtherCall(call, proto))
14713       return ExprError();
14714 
14715     return MaybeBindToTemporary(call);
14716   }
14717 
14718   // We only try to build a recovery expr at this level if we can preserve
14719   // the return type, otherwise we return ExprError() and let the caller
14720   // recover.
14721   auto BuildRecoveryExpr = [&](QualType Type) {
14722     if (!AllowRecovery)
14723       return ExprError();
14724     std::vector<Expr *> SubExprs = {MemExprE};
14725     llvm::append_range(SubExprs, Args);
14726     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14727                               Type);
14728   };
14729   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14730     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14731                             RParenLoc, CurFPFeatureOverrides());
14732 
14733   UnbridgedCastsSet UnbridgedCasts;
14734   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14735     return ExprError();
14736 
14737   MemberExpr *MemExpr;
14738   CXXMethodDecl *Method = nullptr;
14739   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14740   NestedNameSpecifier *Qualifier = nullptr;
14741   if (isa<MemberExpr>(NakedMemExpr)) {
14742     MemExpr = cast<MemberExpr>(NakedMemExpr);
14743     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14744     FoundDecl = MemExpr->getFoundDecl();
14745     Qualifier = MemExpr->getQualifier();
14746     UnbridgedCasts.restore();
14747   } else {
14748     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14749     Qualifier = UnresExpr->getQualifier();
14750 
14751     QualType ObjectType = UnresExpr->getBaseType();
14752     Expr::Classification ObjectClassification
14753       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14754                             : UnresExpr->getBase()->Classify(Context);
14755 
14756     // Add overload candidates
14757     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14758                                       OverloadCandidateSet::CSK_Normal);
14759 
14760     // FIXME: avoid copy.
14761     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14762     if (UnresExpr->hasExplicitTemplateArgs()) {
14763       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14764       TemplateArgs = &TemplateArgsBuffer;
14765     }
14766 
14767     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14768            E = UnresExpr->decls_end(); I != E; ++I) {
14769 
14770       NamedDecl *Func = *I;
14771       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14772       if (isa<UsingShadowDecl>(Func))
14773         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14774 
14775 
14776       // Microsoft supports direct constructor calls.
14777       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14778         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14779                              CandidateSet,
14780                              /*SuppressUserConversions*/ false);
14781       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14782         // If explicit template arguments were provided, we can't call a
14783         // non-template member function.
14784         if (TemplateArgs)
14785           continue;
14786 
14787         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14788                            ObjectClassification, Args, CandidateSet,
14789                            /*SuppressUserConversions=*/false);
14790       } else {
14791         AddMethodTemplateCandidate(
14792             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14793             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14794             /*SuppressUserConversions=*/false);
14795       }
14796     }
14797 
14798     DeclarationName DeclName = UnresExpr->getMemberName();
14799 
14800     UnbridgedCasts.restore();
14801 
14802     OverloadCandidateSet::iterator Best;
14803     bool Succeeded = false;
14804     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14805                                             Best)) {
14806     case OR_Success:
14807       Method = cast<CXXMethodDecl>(Best->Function);
14808       FoundDecl = Best->FoundDecl;
14809       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14810       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14811         break;
14812       // If FoundDecl is different from Method (such as if one is a template
14813       // and the other a specialization), make sure DiagnoseUseOfDecl is
14814       // called on both.
14815       // FIXME: This would be more comprehensively addressed by modifying
14816       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14817       // being used.
14818       if (Method != FoundDecl.getDecl() &&
14819           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
14820         break;
14821       Succeeded = true;
14822       break;
14823 
14824     case OR_No_Viable_Function:
14825       CandidateSet.NoteCandidates(
14826           PartialDiagnosticAt(
14827               UnresExpr->getMemberLoc(),
14828               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14829                   << DeclName << MemExprE->getSourceRange()),
14830           *this, OCD_AllCandidates, Args);
14831       break;
14832     case OR_Ambiguous:
14833       CandidateSet.NoteCandidates(
14834           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14835                               PDiag(diag::err_ovl_ambiguous_member_call)
14836                                   << DeclName << MemExprE->getSourceRange()),
14837           *this, OCD_AmbiguousCandidates, Args);
14838       break;
14839     case OR_Deleted:
14840       CandidateSet.NoteCandidates(
14841           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14842                               PDiag(diag::err_ovl_deleted_member_call)
14843                                   << DeclName << MemExprE->getSourceRange()),
14844           *this, OCD_AllCandidates, Args);
14845       break;
14846     }
14847     // Overload resolution fails, try to recover.
14848     if (!Succeeded)
14849       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14850 
14851     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14852 
14853     // If overload resolution picked a static member, build a
14854     // non-member call based on that function.
14855     if (Method->isStatic()) {
14856       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14857                                    ExecConfig, IsExecConfig);
14858     }
14859 
14860     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14861   }
14862 
14863   QualType ResultType = Method->getReturnType();
14864   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14865   ResultType = ResultType.getNonLValueExprType(Context);
14866 
14867   assert(Method && "Member call to something that isn't a method?");
14868   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14869   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14870       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14871       CurFPFeatureOverrides(), Proto->getNumParams());
14872 
14873   // Check for a valid return type.
14874   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14875                           TheCall, Method))
14876     return BuildRecoveryExpr(ResultType);
14877 
14878   // Convert the object argument (for a non-static member function call).
14879   // We only need to do this if there was actually an overload; otherwise
14880   // it was done at lookup.
14881   if (!Method->isStatic()) {
14882     ExprResult ObjectArg =
14883       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14884                                           FoundDecl, Method);
14885     if (ObjectArg.isInvalid())
14886       return ExprError();
14887     MemExpr->setBase(ObjectArg.get());
14888   }
14889 
14890   // Convert the rest of the arguments
14891   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14892                               RParenLoc))
14893     return BuildRecoveryExpr(ResultType);
14894 
14895   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14896 
14897   if (CheckFunctionCall(Method, TheCall, Proto))
14898     return ExprError();
14899 
14900   // In the case the method to call was not selected by the overloading
14901   // resolution process, we still need to handle the enable_if attribute. Do
14902   // that here, so it will not hide previous -- and more relevant -- errors.
14903   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14904     if (const EnableIfAttr *Attr =
14905             CheckEnableIf(Method, LParenLoc, Args, true)) {
14906       Diag(MemE->getMemberLoc(),
14907            diag::err_ovl_no_viable_member_function_in_call)
14908           << Method << Method->getSourceRange();
14909       Diag(Method->getLocation(),
14910            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14911           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14912       return ExprError();
14913     }
14914   }
14915 
14916   if ((isa<CXXConstructorDecl>(CurContext) ||
14917        isa<CXXDestructorDecl>(CurContext)) &&
14918       TheCall->getMethodDecl()->isPure()) {
14919     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14920 
14921     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14922         MemExpr->performsVirtualDispatch(getLangOpts())) {
14923       Diag(MemExpr->getBeginLoc(),
14924            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14925           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14926           << MD->getParent();
14927 
14928       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14929       if (getLangOpts().AppleKext)
14930         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14931             << MD->getParent() << MD->getDeclName();
14932     }
14933   }
14934 
14935   if (CXXDestructorDecl *DD =
14936           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14937     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14938     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14939     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14940                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14941                          MemExpr->getMemberLoc());
14942   }
14943 
14944   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14945                                      TheCall->getMethodDecl());
14946 }
14947 
14948 /// BuildCallToObjectOfClassType - Build a call to an object of class
14949 /// type (C++ [over.call.object]), which can end up invoking an
14950 /// overloaded function call operator (@c operator()) or performing a
14951 /// user-defined conversion on the object argument.
14952 ExprResult
14953 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14954                                    SourceLocation LParenLoc,
14955                                    MultiExprArg Args,
14956                                    SourceLocation RParenLoc) {
14957   if (checkPlaceholderForOverload(*this, Obj))
14958     return ExprError();
14959   ExprResult Object = Obj;
14960 
14961   UnbridgedCastsSet UnbridgedCasts;
14962   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14963     return ExprError();
14964 
14965   assert(Object.get()->getType()->isRecordType() &&
14966          "Requires object type argument");
14967 
14968   // C++ [over.call.object]p1:
14969   //  If the primary-expression E in the function call syntax
14970   //  evaluates to a class object of type "cv T", then the set of
14971   //  candidate functions includes at least the function call
14972   //  operators of T. The function call operators of T are obtained by
14973   //  ordinary lookup of the name operator() in the context of
14974   //  (E).operator().
14975   OverloadCandidateSet CandidateSet(LParenLoc,
14976                                     OverloadCandidateSet::CSK_Operator);
14977   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14978 
14979   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14980                           diag::err_incomplete_object_call, Object.get()))
14981     return true;
14982 
14983   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14984   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14985   LookupQualifiedName(R, Record->getDecl());
14986   R.suppressDiagnostics();
14987 
14988   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14989        Oper != OperEnd; ++Oper) {
14990     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14991                        Object.get()->Classify(Context), Args, CandidateSet,
14992                        /*SuppressUserConversion=*/false);
14993   }
14994 
14995   // When calling a lambda, both the call operator, and
14996   // the conversion operator to function pointer
14997   // are considered. But when constraint checking
14998   // on the call operator fails, it will also fail on the
14999   // conversion operator as the constraints are always the same.
15000   // As the user probably does not intend to perform a surrogate call,
15001   // we filter them out to produce better error diagnostics, ie to avoid
15002   // showing 2 failed overloads instead of one.
15003   bool IgnoreSurrogateFunctions = false;
15004   if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15005     const OverloadCandidate &Candidate = *CandidateSet.begin();
15006     if (!Candidate.Viable &&
15007         Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15008       IgnoreSurrogateFunctions = true;
15009   }
15010 
15011   // C++ [over.call.object]p2:
15012   //   In addition, for each (non-explicit in C++0x) conversion function
15013   //   declared in T of the form
15014   //
15015   //        operator conversion-type-id () cv-qualifier;
15016   //
15017   //   where cv-qualifier is the same cv-qualification as, or a
15018   //   greater cv-qualification than, cv, and where conversion-type-id
15019   //   denotes the type "pointer to function of (P1,...,Pn) returning
15020   //   R", or the type "reference to pointer to function of
15021   //   (P1,...,Pn) returning R", or the type "reference to function
15022   //   of (P1,...,Pn) returning R", a surrogate call function [...]
15023   //   is also considered as a candidate function. Similarly,
15024   //   surrogate call functions are added to the set of candidate
15025   //   functions for each conversion function declared in an
15026   //   accessible base class provided the function is not hidden
15027   //   within T by another intervening declaration.
15028   const auto &Conversions =
15029       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15030   for (auto I = Conversions.begin(), E = Conversions.end();
15031        !IgnoreSurrogateFunctions && I != E; ++I) {
15032     NamedDecl *D = *I;
15033     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15034     if (isa<UsingShadowDecl>(D))
15035       D = cast<UsingShadowDecl>(D)->getTargetDecl();
15036 
15037     // Skip over templated conversion functions; they aren't
15038     // surrogates.
15039     if (isa<FunctionTemplateDecl>(D))
15040       continue;
15041 
15042     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15043     if (!Conv->isExplicit()) {
15044       // Strip the reference type (if any) and then the pointer type (if
15045       // any) to get down to what might be a function type.
15046       QualType ConvType = Conv->getConversionType().getNonReferenceType();
15047       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15048         ConvType = ConvPtrType->getPointeeType();
15049 
15050       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15051       {
15052         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15053                               Object.get(), Args, CandidateSet);
15054       }
15055     }
15056   }
15057 
15058   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15059 
15060   // Perform overload resolution.
15061   OverloadCandidateSet::iterator Best;
15062   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15063                                           Best)) {
15064   case OR_Success:
15065     // Overload resolution succeeded; we'll build the appropriate call
15066     // below.
15067     break;
15068 
15069   case OR_No_Viable_Function: {
15070     PartialDiagnostic PD =
15071         CandidateSet.empty()
15072             ? (PDiag(diag::err_ovl_no_oper)
15073                << Object.get()->getType() << /*call*/ 1
15074                << Object.get()->getSourceRange())
15075             : (PDiag(diag::err_ovl_no_viable_object_call)
15076                << Object.get()->getType() << Object.get()->getSourceRange());
15077     CandidateSet.NoteCandidates(
15078         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15079         OCD_AllCandidates, Args);
15080     break;
15081   }
15082   case OR_Ambiguous:
15083     CandidateSet.NoteCandidates(
15084         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15085                             PDiag(diag::err_ovl_ambiguous_object_call)
15086                                 << Object.get()->getType()
15087                                 << Object.get()->getSourceRange()),
15088         *this, OCD_AmbiguousCandidates, Args);
15089     break;
15090 
15091   case OR_Deleted:
15092     CandidateSet.NoteCandidates(
15093         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15094                             PDiag(diag::err_ovl_deleted_object_call)
15095                                 << Object.get()->getType()
15096                                 << Object.get()->getSourceRange()),
15097         *this, OCD_AllCandidates, Args);
15098     break;
15099   }
15100 
15101   if (Best == CandidateSet.end())
15102     return true;
15103 
15104   UnbridgedCasts.restore();
15105 
15106   if (Best->Function == nullptr) {
15107     // Since there is no function declaration, this is one of the
15108     // surrogate candidates. Dig out the conversion function.
15109     CXXConversionDecl *Conv
15110       = cast<CXXConversionDecl>(
15111                          Best->Conversions[0].UserDefined.ConversionFunction);
15112 
15113     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15114                               Best->FoundDecl);
15115     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15116       return ExprError();
15117     assert(Conv == Best->FoundDecl.getDecl() &&
15118              "Found Decl & conversion-to-functionptr should be same, right?!");
15119     // We selected one of the surrogate functions that converts the
15120     // object parameter to a function pointer. Perform the conversion
15121     // on the object argument, then let BuildCallExpr finish the job.
15122 
15123     // Create an implicit member expr to refer to the conversion operator.
15124     // and then call it.
15125     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15126                                              Conv, HadMultipleCandidates);
15127     if (Call.isInvalid())
15128       return ExprError();
15129     // Record usage of conversion in an implicit cast.
15130     Call = ImplicitCastExpr::Create(
15131         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15132         nullptr, VK_PRValue, CurFPFeatureOverrides());
15133 
15134     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15135   }
15136 
15137   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15138 
15139   // We found an overloaded operator(). Build a CXXOperatorCallExpr
15140   // that calls this method, using Object for the implicit object
15141   // parameter and passing along the remaining arguments.
15142   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15143 
15144   // An error diagnostic has already been printed when parsing the declaration.
15145   if (Method->isInvalidDecl())
15146     return ExprError();
15147 
15148   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15149   unsigned NumParams = Proto->getNumParams();
15150 
15151   DeclarationNameInfo OpLocInfo(
15152                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15153   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15154   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15155                                            Obj, HadMultipleCandidates,
15156                                            OpLocInfo.getLoc(),
15157                                            OpLocInfo.getInfo());
15158   if (NewFn.isInvalid())
15159     return true;
15160 
15161   SmallVector<Expr *, 8> MethodArgs;
15162   MethodArgs.reserve(NumParams + 1);
15163 
15164   bool IsError = false;
15165 
15166   // Initialize the implicit object parameter if needed.
15167   // Since C++23, this could also be a call to a static call operator
15168   // which we emit as a regular CallExpr.
15169   if (Method->isInstance()) {
15170     ExprResult ObjRes = PerformObjectArgumentInitialization(
15171         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15172     if (ObjRes.isInvalid())
15173       IsError = true;
15174     else
15175       Object = ObjRes;
15176     MethodArgs.push_back(Object.get());
15177   }
15178 
15179   IsError |= PrepareArgumentsForCallToObjectOfClassType(
15180       *this, MethodArgs, Method, Args, LParenLoc);
15181 
15182   // If this is a variadic call, handle args passed through "...".
15183   if (Proto->isVariadic()) {
15184     // Promote the arguments (C99 6.5.2.2p7).
15185     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15186       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15187                                                         nullptr);
15188       IsError |= Arg.isInvalid();
15189       MethodArgs.push_back(Arg.get());
15190     }
15191   }
15192 
15193   if (IsError)
15194     return true;
15195 
15196   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15197 
15198   // Once we've built TheCall, all of the expressions are properly owned.
15199   QualType ResultTy = Method->getReturnType();
15200   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15201   ResultTy = ResultTy.getNonLValueExprType(Context);
15202 
15203   CallExpr *TheCall;
15204   if (Method->isInstance())
15205     TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
15206                                           MethodArgs, ResultTy, VK, RParenLoc,
15207                                           CurFPFeatureOverrides());
15208   else
15209     TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
15210                                RParenLoc, CurFPFeatureOverrides());
15211 
15212   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15213     return true;
15214 
15215   if (CheckFunctionCall(Method, TheCall, Proto))
15216     return true;
15217 
15218   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15219 }
15220 
15221 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15222 ///  (if one exists), where @c Base is an expression of class type and
15223 /// @c Member is the name of the member we're trying to find.
15224 ExprResult
15225 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15226                                bool *NoArrowOperatorFound) {
15227   assert(Base->getType()->isRecordType() &&
15228          "left-hand side must have class type");
15229 
15230   if (checkPlaceholderForOverload(*this, Base))
15231     return ExprError();
15232 
15233   SourceLocation Loc = Base->getExprLoc();
15234 
15235   // C++ [over.ref]p1:
15236   //
15237   //   [...] An expression x->m is interpreted as (x.operator->())->m
15238   //   for a class object x of type T if T::operator->() exists and if
15239   //   the operator is selected as the best match function by the
15240   //   overload resolution mechanism (13.3).
15241   DeclarationName OpName =
15242     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15243   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15244 
15245   if (RequireCompleteType(Loc, Base->getType(),
15246                           diag::err_typecheck_incomplete_tag, Base))
15247     return ExprError();
15248 
15249   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15250   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15251   R.suppressDiagnostics();
15252 
15253   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15254        Oper != OperEnd; ++Oper) {
15255     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15256                        std::nullopt, CandidateSet,
15257                        /*SuppressUserConversion=*/false);
15258   }
15259 
15260   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15261 
15262   // Perform overload resolution.
15263   OverloadCandidateSet::iterator Best;
15264   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15265   case OR_Success:
15266     // Overload resolution succeeded; we'll build the call below.
15267     break;
15268 
15269   case OR_No_Viable_Function: {
15270     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15271     if (CandidateSet.empty()) {
15272       QualType BaseType = Base->getType();
15273       if (NoArrowOperatorFound) {
15274         // Report this specific error to the caller instead of emitting a
15275         // diagnostic, as requested.
15276         *NoArrowOperatorFound = true;
15277         return ExprError();
15278       }
15279       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15280         << BaseType << Base->getSourceRange();
15281       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15282         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15283           << FixItHint::CreateReplacement(OpLoc, ".");
15284       }
15285     } else
15286       Diag(OpLoc, diag::err_ovl_no_viable_oper)
15287         << "operator->" << Base->getSourceRange();
15288     CandidateSet.NoteCandidates(*this, Base, Cands);
15289     return ExprError();
15290   }
15291   case OR_Ambiguous:
15292     CandidateSet.NoteCandidates(
15293         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15294                                        << "->" << Base->getType()
15295                                        << Base->getSourceRange()),
15296         *this, OCD_AmbiguousCandidates, Base);
15297     return ExprError();
15298 
15299   case OR_Deleted:
15300     CandidateSet.NoteCandidates(
15301         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15302                                        << "->" << Base->getSourceRange()),
15303         *this, OCD_AllCandidates, Base);
15304     return ExprError();
15305   }
15306 
15307   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15308 
15309   // Convert the object parameter.
15310   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15311   ExprResult BaseResult =
15312     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15313                                         Best->FoundDecl, Method);
15314   if (BaseResult.isInvalid())
15315     return ExprError();
15316   Base = BaseResult.get();
15317 
15318   // Build the operator call.
15319   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15320                                             Base, HadMultipleCandidates, OpLoc);
15321   if (FnExpr.isInvalid())
15322     return ExprError();
15323 
15324   QualType ResultTy = Method->getReturnType();
15325   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15326   ResultTy = ResultTy.getNonLValueExprType(Context);
15327   CXXOperatorCallExpr *TheCall =
15328       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15329                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15330 
15331   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15332     return ExprError();
15333 
15334   if (CheckFunctionCall(Method, TheCall,
15335                         Method->getType()->castAs<FunctionProtoType>()))
15336     return ExprError();
15337 
15338   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15339 }
15340 
15341 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15342 /// a literal operator described by the provided lookup results.
15343 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15344                                           DeclarationNameInfo &SuffixInfo,
15345                                           ArrayRef<Expr*> Args,
15346                                           SourceLocation LitEndLoc,
15347                                        TemplateArgumentListInfo *TemplateArgs) {
15348   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15349 
15350   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15351                                     OverloadCandidateSet::CSK_Normal);
15352   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15353                                  TemplateArgs);
15354 
15355   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15356 
15357   // Perform overload resolution. This will usually be trivial, but might need
15358   // to perform substitutions for a literal operator template.
15359   OverloadCandidateSet::iterator Best;
15360   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15361   case OR_Success:
15362   case OR_Deleted:
15363     break;
15364 
15365   case OR_No_Viable_Function:
15366     CandidateSet.NoteCandidates(
15367         PartialDiagnosticAt(UDSuffixLoc,
15368                             PDiag(diag::err_ovl_no_viable_function_in_call)
15369                                 << R.getLookupName()),
15370         *this, OCD_AllCandidates, Args);
15371     return ExprError();
15372 
15373   case OR_Ambiguous:
15374     CandidateSet.NoteCandidates(
15375         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15376                                                 << R.getLookupName()),
15377         *this, OCD_AmbiguousCandidates, Args);
15378     return ExprError();
15379   }
15380 
15381   FunctionDecl *FD = Best->Function;
15382   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15383                                         nullptr, HadMultipleCandidates,
15384                                         SuffixInfo.getLoc(),
15385                                         SuffixInfo.getInfo());
15386   if (Fn.isInvalid())
15387     return true;
15388 
15389   // Check the argument types. This should almost always be a no-op, except
15390   // that array-to-pointer decay is applied to string literals.
15391   Expr *ConvArgs[2];
15392   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15393     ExprResult InputInit = PerformCopyInitialization(
15394       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15395       SourceLocation(), Args[ArgIdx]);
15396     if (InputInit.isInvalid())
15397       return true;
15398     ConvArgs[ArgIdx] = InputInit.get();
15399   }
15400 
15401   QualType ResultTy = FD->getReturnType();
15402   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15403   ResultTy = ResultTy.getNonLValueExprType(Context);
15404 
15405   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15406       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
15407       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15408 
15409   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15410     return ExprError();
15411 
15412   if (CheckFunctionCall(FD, UDL, nullptr))
15413     return ExprError();
15414 
15415   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15416 }
15417 
15418 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15419 /// given LookupResult is non-empty, it is assumed to describe a member which
15420 /// will be invoked. Otherwise, the function will be found via argument
15421 /// dependent lookup.
15422 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15423 /// otherwise CallExpr is set to ExprError() and some non-success value
15424 /// is returned.
15425 Sema::ForRangeStatus
15426 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15427                                 SourceLocation RangeLoc,
15428                                 const DeclarationNameInfo &NameInfo,
15429                                 LookupResult &MemberLookup,
15430                                 OverloadCandidateSet *CandidateSet,
15431                                 Expr *Range, ExprResult *CallExpr) {
15432   Scope *S = nullptr;
15433 
15434   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15435   if (!MemberLookup.empty()) {
15436     ExprResult MemberRef =
15437         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15438                                  /*IsPtr=*/false, CXXScopeSpec(),
15439                                  /*TemplateKWLoc=*/SourceLocation(),
15440                                  /*FirstQualifierInScope=*/nullptr,
15441                                  MemberLookup,
15442                                  /*TemplateArgs=*/nullptr, S);
15443     if (MemberRef.isInvalid()) {
15444       *CallExpr = ExprError();
15445       return FRS_DiagnosticIssued;
15446     }
15447     *CallExpr =
15448         BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
15449     if (CallExpr->isInvalid()) {
15450       *CallExpr = ExprError();
15451       return FRS_DiagnosticIssued;
15452     }
15453   } else {
15454     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15455                                                 NestedNameSpecifierLoc(),
15456                                                 NameInfo, UnresolvedSet<0>());
15457     if (FnR.isInvalid())
15458       return FRS_DiagnosticIssued;
15459     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15460 
15461     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15462                                                     CandidateSet, CallExpr);
15463     if (CandidateSet->empty() || CandidateSetError) {
15464       *CallExpr = ExprError();
15465       return FRS_NoViableFunction;
15466     }
15467     OverloadCandidateSet::iterator Best;
15468     OverloadingResult OverloadResult =
15469         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15470 
15471     if (OverloadResult == OR_No_Viable_Function) {
15472       *CallExpr = ExprError();
15473       return FRS_NoViableFunction;
15474     }
15475     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15476                                          Loc, nullptr, CandidateSet, &Best,
15477                                          OverloadResult,
15478                                          /*AllowTypoCorrection=*/false);
15479     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15480       *CallExpr = ExprError();
15481       return FRS_DiagnosticIssued;
15482     }
15483   }
15484   return FRS_Success;
15485 }
15486 
15487 
15488 /// FixOverloadedFunctionReference - E is an expression that refers to
15489 /// a C++ overloaded function (possibly with some parentheses and
15490 /// perhaps a '&' around it). We have resolved the overloaded function
15491 /// to the function declaration Fn, so patch up the expression E to
15492 /// refer (possibly indirectly) to Fn. Returns the new expr.
15493 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15494                                            FunctionDecl *Fn) {
15495   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15496     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15497                                                    Found, Fn);
15498     if (SubExpr == PE->getSubExpr())
15499       return PE;
15500 
15501     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15502   }
15503 
15504   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15505     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15506                                                    Found, Fn);
15507     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15508                                SubExpr->getType()) &&
15509            "Implicit cast type cannot be determined from overload");
15510     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15511     if (SubExpr == ICE->getSubExpr())
15512       return ICE;
15513 
15514     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15515                                     SubExpr, nullptr, ICE->getValueKind(),
15516                                     CurFPFeatureOverrides());
15517   }
15518 
15519   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15520     if (!GSE->isResultDependent()) {
15521       Expr *SubExpr =
15522           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15523       if (SubExpr == GSE->getResultExpr())
15524         return GSE;
15525 
15526       // Replace the resulting type information before rebuilding the generic
15527       // selection expression.
15528       ArrayRef<Expr *> A = GSE->getAssocExprs();
15529       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15530       unsigned ResultIdx = GSE->getResultIndex();
15531       AssocExprs[ResultIdx] = SubExpr;
15532 
15533       if (GSE->isExprPredicate())
15534         return GenericSelectionExpr::Create(
15535             Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15536             GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15537             GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15538             ResultIdx);
15539       return GenericSelectionExpr::Create(
15540           Context, GSE->getGenericLoc(), GSE->getControllingType(),
15541           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15542           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15543           ResultIdx);
15544     }
15545     // Rather than fall through to the unreachable, return the original generic
15546     // selection expression.
15547     return GSE;
15548   }
15549 
15550   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15551     assert(UnOp->getOpcode() == UO_AddrOf &&
15552            "Can only take the address of an overloaded function");
15553     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15554       if (Method->isStatic()) {
15555         // Do nothing: static member functions aren't any different
15556         // from non-member functions.
15557       } else {
15558         // Fix the subexpression, which really has to be an
15559         // UnresolvedLookupExpr holding an overloaded member function
15560         // or template.
15561         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15562                                                        Found, Fn);
15563         if (SubExpr == UnOp->getSubExpr())
15564           return UnOp;
15565 
15566         assert(isa<DeclRefExpr>(SubExpr)
15567                && "fixed to something other than a decl ref");
15568         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15569                && "fixed to a member ref with no nested name qualifier");
15570 
15571         // We have taken the address of a pointer to member
15572         // function. Perform the computation here so that we get the
15573         // appropriate pointer to member type.
15574         QualType ClassType
15575           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15576         QualType MemPtrType
15577           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15578         // Under the MS ABI, lock down the inheritance model now.
15579         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15580           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15581 
15582         return UnaryOperator::Create(
15583             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15584             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15585       }
15586     }
15587     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15588                                                    Found, Fn);
15589     if (SubExpr == UnOp->getSubExpr())
15590       return UnOp;
15591 
15592     // FIXME: This can't currently fail, but in principle it could.
15593     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15594         .get();
15595   }
15596 
15597   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15598     // FIXME: avoid copy.
15599     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15600     if (ULE->hasExplicitTemplateArgs()) {
15601       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15602       TemplateArgs = &TemplateArgsBuffer;
15603     }
15604 
15605     QualType Type = Fn->getType();
15606     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15607 
15608     // FIXME: Duplicated from BuildDeclarationNameExpr.
15609     if (unsigned BID = Fn->getBuiltinID()) {
15610       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15611         Type = Context.BuiltinFnTy;
15612         ValueKind = VK_PRValue;
15613       }
15614     }
15615 
15616     DeclRefExpr *DRE = BuildDeclRefExpr(
15617         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15618         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15619     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15620     return DRE;
15621   }
15622 
15623   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15624     // FIXME: avoid copy.
15625     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15626     if (MemExpr->hasExplicitTemplateArgs()) {
15627       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15628       TemplateArgs = &TemplateArgsBuffer;
15629     }
15630 
15631     Expr *Base;
15632 
15633     // If we're filling in a static method where we used to have an
15634     // implicit member access, rewrite to a simple decl ref.
15635     if (MemExpr->isImplicitAccess()) {
15636       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15637         DeclRefExpr *DRE = BuildDeclRefExpr(
15638             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15639             MemExpr->getQualifierLoc(), Found.getDecl(),
15640             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15641         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15642         return DRE;
15643       } else {
15644         SourceLocation Loc = MemExpr->getMemberLoc();
15645         if (MemExpr->getQualifier())
15646           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15647         Base =
15648             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15649       }
15650     } else
15651       Base = MemExpr->getBase();
15652 
15653     ExprValueKind valueKind;
15654     QualType type;
15655     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15656       valueKind = VK_LValue;
15657       type = Fn->getType();
15658     } else {
15659       valueKind = VK_PRValue;
15660       type = Context.BoundMemberTy;
15661     }
15662 
15663     return BuildMemberExpr(
15664         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15665         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15666         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15667         type, valueKind, OK_Ordinary, TemplateArgs);
15668   }
15669 
15670   llvm_unreachable("Invalid reference to overloaded function");
15671 }
15672 
15673 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15674                                                 DeclAccessPair Found,
15675                                                 FunctionDecl *Fn) {
15676   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15677 }
15678 
15679 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15680                                   FunctionDecl *Function) {
15681   if (!PartialOverloading || !Function)
15682     return true;
15683   if (Function->isVariadic())
15684     return false;
15685   if (const auto *Proto =
15686           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15687     if (Proto->isTemplateVariadic())
15688       return false;
15689   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15690     if (const auto *Proto =
15691             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15692       if (Proto->isTemplateVariadic())
15693         return false;
15694   return true;
15695 }
15696