xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
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/CXXInheritance.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DependenceFlags.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/Type.h"
22 #include "clang/AST/TypeOrdering.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Overload.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateDeduction.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/Casting.h"
40 #include <algorithm>
41 #include <cstdlib>
42 #include <optional>
43 
44 using namespace clang;
45 using namespace sema;
46 
47 using AllowedExplicit = Sema::AllowedExplicit;
48 
49 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
50   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
51     return P->hasAttr<PassObjectSizeAttr>();
52   });
53 }
54 
55 /// A convenience routine for creating a decayed reference to a function.
56 static ExprResult CreateFunctionRefExpr(
57     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
58     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
59     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
60   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
61     return ExprError();
62   // If FoundDecl is different from Fn (such as if one is a template
63   // and the other a specialization), make sure DiagnoseUseOfDecl is
64   // called on both.
65   // FIXME: This would be more comprehensively addressed by modifying
66   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
67   // being used.
68   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
69     return ExprError();
70   DeclRefExpr *DRE = new (S.Context)
71       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
72   if (HadMultipleCandidates)
73     DRE->setHadMultipleCandidates(true);
74 
75   S.MarkDeclRefReferenced(DRE, Base);
76   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
77     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
78       S.ResolveExceptionSpec(Loc, FPT);
79       DRE->setType(Fn->getType());
80     }
81   }
82   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
83                              CK_FunctionToPointerDecay);
84 }
85 
86 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
87                                  bool InOverloadResolution,
88                                  StandardConversionSequence &SCS,
89                                  bool CStyle,
90                                  bool AllowObjCWritebackConversion);
91 
92 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
93                                                  QualType &ToType,
94                                                  bool InOverloadResolution,
95                                                  StandardConversionSequence &SCS,
96                                                  bool CStyle);
97 static OverloadingResult
98 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
99                         UserDefinedConversionSequence& User,
100                         OverloadCandidateSet& Conversions,
101                         AllowedExplicit AllowExplicit,
102                         bool AllowObjCConversionOnExplicit);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
106                                    const StandardConversionSequence& SCS1,
107                                    const StandardConversionSequence& SCS2);
108 
109 static ImplicitConversionSequence::CompareKind
110 CompareQualificationConversions(Sema &S,
111                                 const StandardConversionSequence& SCS1,
112                                 const StandardConversionSequence& SCS2);
113 
114 static ImplicitConversionSequence::CompareKind
115 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
116                                 const StandardConversionSequence& SCS1,
117                                 const StandardConversionSequence& SCS2);
118 
119 /// GetConversionRank - Retrieve the implicit conversion rank
120 /// corresponding to the given implicit conversion kind.
121 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
122   static const ImplicitConversionRank
123     Rank[(int)ICK_Num_Conversion_Kinds] = {
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Promotion,
131     ICR_Promotion,
132     ICR_Promotion,
133     ICR_Conversion,
134     ICR_Conversion,
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_OCL_Scalar_Widening,
145     ICR_Complex_Real_Conversion,
146     ICR_Conversion,
147     ICR_Conversion,
148     ICR_Writeback_Conversion,
149     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
150                      // it was omitted by the patch that added
151                      // ICK_Zero_Event_Conversion
152     ICR_C_Conversion,
153     ICR_C_Conversion_Extension
154   };
155   return Rank[(int)Kind];
156 }
157 
158 /// GetImplicitConversionName - Return the name of this kind of
159 /// implicit conversion.
160 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
161   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
162     "No conversion",
163     "Lvalue-to-rvalue",
164     "Array-to-pointer",
165     "Function-to-pointer",
166     "Function pointer conversion",
167     "Qualification",
168     "Integral promotion",
169     "Floating point promotion",
170     "Complex promotion",
171     "Integral conversion",
172     "Floating conversion",
173     "Complex conversion",
174     "Floating-integral conversion",
175     "Pointer conversion",
176     "Pointer-to-member conversion",
177     "Boolean conversion",
178     "Compatible-types conversion",
179     "Derived-to-base conversion",
180     "Vector conversion",
181     "SVE Vector conversion",
182     "Vector splat",
183     "Complex-real conversion",
184     "Block Pointer conversion",
185     "Transparent Union Conversion",
186     "Writeback conversion",
187     "OpenCL Zero Event Conversion",
188     "C specific type conversion",
189     "Incompatible pointer conversion"
190   };
191   return Name[Kind];
192 }
193 
194 /// StandardConversionSequence - Set the standard conversion
195 /// sequence to the identity conversion.
196 void StandardConversionSequence::setAsIdentityConversion() {
197   First = ICK_Identity;
198   Second = ICK_Identity;
199   Third = ICK_Identity;
200   DeprecatedStringLiteralToCharPtr = false;
201   QualificationIncludesObjCLifetime = false;
202   ReferenceBinding = false;
203   DirectBinding = false;
204   IsLvalueReference = true;
205   BindsToFunctionLvalue = false;
206   BindsToRvalue = false;
207   BindsImplicitObjectArgumentWithoutRefQualifier = false;
208   ObjCLifetimeConversionBinding = false;
209   CopyConstructor = nullptr;
210 }
211 
212 /// getRank - Retrieve the rank of this standard conversion sequence
213 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
214 /// implicit conversions.
215 ImplicitConversionRank StandardConversionSequence::getRank() const {
216   ImplicitConversionRank Rank = ICR_Exact_Match;
217   if  (GetConversionRank(First) > Rank)
218     Rank = GetConversionRank(First);
219   if  (GetConversionRank(Second) > Rank)
220     Rank = GetConversionRank(Second);
221   if  (GetConversionRank(Third) > Rank)
222     Rank = GetConversionRank(Third);
223   return Rank;
224 }
225 
226 /// isPointerConversionToBool - Determines whether this conversion is
227 /// a conversion of a pointer or pointer-to-member to bool. This is
228 /// used as part of the ranking of standard conversion sequences
229 /// (C++ 13.3.3.2p4).
230 bool StandardConversionSequence::isPointerConversionToBool() const {
231   // Note that FromType has not necessarily been transformed by the
232   // array-to-pointer or function-to-pointer implicit conversions, so
233   // check for their presence as well as checking whether FromType is
234   // a pointer.
235   if (getToType(1)->isBooleanType() &&
236       (getFromType()->isPointerType() ||
237        getFromType()->isMemberPointerType() ||
238        getFromType()->isObjCObjectPointerType() ||
239        getFromType()->isBlockPointerType() ||
240        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
241     return true;
242 
243   return false;
244 }
245 
246 /// isPointerConversionToVoidPointer - Determines whether this
247 /// conversion is a conversion of a pointer to a void pointer. This is
248 /// used as part of the ranking of standard conversion sequences (C++
249 /// 13.3.3.2p4).
250 bool
251 StandardConversionSequence::
252 isPointerConversionToVoidPointer(ASTContext& Context) const {
253   QualType FromType = getFromType();
254   QualType ToType = getToType(1);
255 
256   // Note that FromType has not necessarily been transformed by the
257   // array-to-pointer implicit conversion, so check for its presence
258   // and redo the conversion to get a pointer.
259   if (First == ICK_Array_To_Pointer)
260     FromType = Context.getArrayDecayedType(FromType);
261 
262   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
263     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
264       return ToPtrType->getPointeeType()->isVoidType();
265 
266   return false;
267 }
268 
269 /// Skip any implicit casts which could be either part of a narrowing conversion
270 /// or after one in an implicit conversion.
271 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
272                                              const Expr *Converted) {
273   // We can have cleanups wrapping the converted expression; these need to be
274   // preserved so that destructors run if necessary.
275   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
276     Expr *Inner =
277         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
278     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
279                                     EWC->getObjects());
280   }
281 
282   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283     switch (ICE->getCastKind()) {
284     case CK_NoOp:
285     case CK_IntegralCast:
286     case CK_IntegralToBoolean:
287     case CK_IntegralToFloating:
288     case CK_BooleanToSignedIntegral:
289     case CK_FloatingToIntegral:
290     case CK_FloatingToBoolean:
291     case CK_FloatingCast:
292       Converted = ICE->getSubExpr();
293       continue;
294 
295     default:
296       return Converted;
297     }
298   }
299 
300   return Converted;
301 }
302 
303 /// Check if this standard conversion sequence represents a narrowing
304 /// conversion, according to C++11 [dcl.init.list]p7.
305 ///
306 /// \param Ctx  The AST context.
307 /// \param Converted  The result of applying this standard conversion sequence.
308 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
309 ///        value of the expression prior to the narrowing conversion.
310 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
311 ///        type of the expression prior to the narrowing conversion.
312 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
313 ///        from floating point types to integral types should be ignored.
314 NarrowingKind StandardConversionSequence::getNarrowingKind(
315     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
316     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
317   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
318 
319   // C++11 [dcl.init.list]p7:
320   //   A narrowing conversion is an implicit conversion ...
321   QualType FromType = getToType(0);
322   QualType ToType = getToType(1);
323 
324   // A conversion to an enumeration type is narrowing if the conversion to
325   // the underlying type is narrowing. This only arises for expressions of
326   // the form 'Enum{init}'.
327   if (auto *ET = ToType->getAs<EnumType>())
328     ToType = ET->getDecl()->getIntegerType();
329 
330   switch (Second) {
331   // 'bool' is an integral type; dispatch to the right place to handle it.
332   case ICK_Boolean_Conversion:
333     if (FromType->isRealFloatingType())
334       goto FloatingIntegralConversion;
335     if (FromType->isIntegralOrUnscopedEnumerationType())
336       goto IntegralConversion;
337     // -- from a pointer type or pointer-to-member type to bool, or
338     return NK_Type_Narrowing;
339 
340   // -- from a floating-point type to an integer type, or
341   //
342   // -- from an integer type or unscoped enumeration type to a floating-point
343   //    type, except where the source is a constant expression and the actual
344   //    value after conversion will fit into the target type and will produce
345   //    the original value when converted back to the original type, or
346   case ICK_Floating_Integral:
347   FloatingIntegralConversion:
348     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
349       return NK_Type_Narrowing;
350     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
351                ToType->isRealFloatingType()) {
352       if (IgnoreFloatToIntegralConversion)
353         return NK_Not_Narrowing;
354       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
355       assert(Initializer && "Unknown conversion expression");
356 
357       // If it's value-dependent, we can't tell whether it's narrowing.
358       if (Initializer->isValueDependent())
359         return NK_Dependent_Narrowing;
360 
361       if (std::optional<llvm::APSInt> IntConstantValue =
362               Initializer->getIntegerConstantExpr(Ctx)) {
363         // Convert the integer to the floating type.
364         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
365         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
366                                 llvm::APFloat::rmNearestTiesToEven);
367         // And back.
368         llvm::APSInt ConvertedValue = *IntConstantValue;
369         bool ignored;
370         Result.convertToInteger(ConvertedValue,
371                                 llvm::APFloat::rmTowardZero, &ignored);
372         // If the resulting value is different, this was a narrowing conversion.
373         if (*IntConstantValue != ConvertedValue) {
374           ConstantValue = APValue(*IntConstantValue);
375           ConstantType = Initializer->getType();
376           return NK_Constant_Narrowing;
377         }
378       } else {
379         // Variables are always narrowings.
380         return NK_Variable_Narrowing;
381       }
382     }
383     return NK_Not_Narrowing;
384 
385   // -- from long double to double or float, or from double to float, except
386   //    where the source is a constant expression and the actual value after
387   //    conversion is within the range of values that can be represented (even
388   //    if it cannot be represented exactly), or
389   case ICK_Floating_Conversion:
390     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
391         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
392       // FromType is larger than ToType.
393       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
394 
395       // If it's value-dependent, we can't tell whether it's narrowing.
396       if (Initializer->isValueDependent())
397         return NK_Dependent_Narrowing;
398 
399       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
400         // Constant!
401         assert(ConstantValue.isFloat());
402         llvm::APFloat FloatVal = ConstantValue.getFloat();
403         // Convert the source value into the target type.
404         bool ignored;
405         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
406           Ctx.getFloatTypeSemantics(ToType),
407           llvm::APFloat::rmNearestTiesToEven, &ignored);
408         // If there was no overflow, the source value is within the range of
409         // values that can be represented.
410         if (ConvertStatus & llvm::APFloat::opOverflow) {
411           ConstantType = Initializer->getType();
412           return NK_Constant_Narrowing;
413         }
414       } else {
415         return NK_Variable_Narrowing;
416       }
417     }
418     return NK_Not_Narrowing;
419 
420   // -- from an integer type or unscoped enumeration type to an integer type
421   //    that cannot represent all the values of the original type, except where
422   //    the source is a constant expression and the actual value after
423   //    conversion will fit into the target type and will produce the original
424   //    value when converted back to the original type.
425   case ICK_Integral_Conversion:
426   IntegralConversion: {
427     assert(FromType->isIntegralOrUnscopedEnumerationType());
428     assert(ToType->isIntegralOrUnscopedEnumerationType());
429     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
430     const unsigned FromWidth = Ctx.getIntWidth(FromType);
431     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
432     const unsigned ToWidth = Ctx.getIntWidth(ToType);
433 
434     if (FromWidth > ToWidth ||
435         (FromWidth == ToWidth && FromSigned != ToSigned) ||
436         (FromSigned && !ToSigned)) {
437       // Not all values of FromType can be represented in ToType.
438       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439 
440       // If it's value-dependent, we can't tell whether it's narrowing.
441       if (Initializer->isValueDependent())
442         return NK_Dependent_Narrowing;
443 
444       std::optional<llvm::APSInt> OptInitializerValue;
445       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
446         // Such conversions on variables are always narrowing.
447         return NK_Variable_Narrowing;
448       }
449       llvm::APSInt &InitializerValue = *OptInitializerValue;
450       bool Narrowing = false;
451       if (FromWidth < ToWidth) {
452         // Negative -> unsigned is narrowing. Otherwise, more bits is never
453         // narrowing.
454         if (InitializerValue.isSigned() && InitializerValue.isNegative())
455           Narrowing = true;
456       } else {
457         // Add a bit to the InitializerValue so we don't have to worry about
458         // signed vs. unsigned comparisons.
459         InitializerValue = InitializerValue.extend(
460           InitializerValue.getBitWidth() + 1);
461         // Convert the initializer to and from the target width and signed-ness.
462         llvm::APSInt ConvertedValue = InitializerValue;
463         ConvertedValue = ConvertedValue.trunc(ToWidth);
464         ConvertedValue.setIsSigned(ToSigned);
465         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
466         ConvertedValue.setIsSigned(InitializerValue.isSigned());
467         // If the result is different, this was a narrowing conversion.
468         if (ConvertedValue != InitializerValue)
469           Narrowing = true;
470       }
471       if (Narrowing) {
472         ConstantType = Initializer->getType();
473         ConstantValue = APValue(InitializerValue);
474         return NK_Constant_Narrowing;
475       }
476     }
477     return NK_Not_Narrowing;
478   }
479 
480   default:
481     // Other kinds of conversions are not narrowings.
482     return NK_Not_Narrowing;
483   }
484 }
485 
486 /// dump - Print this standard conversion sequence to standard
487 /// error. Useful for debugging overloading issues.
488 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
489   raw_ostream &OS = llvm::errs();
490   bool PrintedSomething = false;
491   if (First != ICK_Identity) {
492     OS << GetImplicitConversionName(First);
493     PrintedSomething = true;
494   }
495 
496   if (Second != ICK_Identity) {
497     if (PrintedSomething) {
498       OS << " -> ";
499     }
500     OS << GetImplicitConversionName(Second);
501 
502     if (CopyConstructor) {
503       OS << " (by copy constructor)";
504     } else if (DirectBinding) {
505       OS << " (direct reference binding)";
506     } else if (ReferenceBinding) {
507       OS << " (reference binding)";
508     }
509     PrintedSomething = true;
510   }
511 
512   if (Third != ICK_Identity) {
513     if (PrintedSomething) {
514       OS << " -> ";
515     }
516     OS << GetImplicitConversionName(Third);
517     PrintedSomething = true;
518   }
519 
520   if (!PrintedSomething) {
521     OS << "No conversions required";
522   }
523 }
524 
525 /// dump - Print this user-defined conversion sequence to standard
526 /// error. Useful for debugging overloading issues.
527 void UserDefinedConversionSequence::dump() const {
528   raw_ostream &OS = llvm::errs();
529   if (Before.First || Before.Second || Before.Third) {
530     Before.dump();
531     OS << " -> ";
532   }
533   if (ConversionFunction)
534     OS << '\'' << *ConversionFunction << '\'';
535   else
536     OS << "aggregate initialization";
537   if (After.First || After.Second || After.Third) {
538     OS << " -> ";
539     After.dump();
540   }
541 }
542 
543 /// dump - Print this implicit conversion sequence to standard
544 /// error. Useful for debugging overloading issues.
545 void ImplicitConversionSequence::dump() const {
546   raw_ostream &OS = llvm::errs();
547   if (hasInitializerListContainerType())
548     OS << "Worst list element conversion: ";
549   switch (ConversionKind) {
550   case StandardConversion:
551     OS << "Standard conversion: ";
552     Standard.dump();
553     break;
554   case UserDefinedConversion:
555     OS << "User-defined conversion: ";
556     UserDefined.dump();
557     break;
558   case EllipsisConversion:
559     OS << "Ellipsis conversion";
560     break;
561   case AmbiguousConversion:
562     OS << "Ambiguous conversion";
563     break;
564   case BadConversion:
565     OS << "Bad conversion";
566     break;
567   }
568 
569   OS << "\n";
570 }
571 
572 void AmbiguousConversionSequence::construct() {
573   new (&conversions()) ConversionSet();
574 }
575 
576 void AmbiguousConversionSequence::destruct() {
577   conversions().~ConversionSet();
578 }
579 
580 void
581 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
582   FromTypePtr = O.FromTypePtr;
583   ToTypePtr = O.ToTypePtr;
584   new (&conversions()) ConversionSet(O.conversions());
585 }
586 
587 namespace {
588   // Structure used by DeductionFailureInfo to store
589   // template argument information.
590   struct DFIArguments {
591     TemplateArgument FirstArg;
592     TemplateArgument SecondArg;
593   };
594   // Structure used by DeductionFailureInfo to store
595   // template parameter and template argument information.
596   struct DFIParamWithArguments : DFIArguments {
597     TemplateParameter Param;
598   };
599   // Structure used by DeductionFailureInfo to store template argument
600   // information and the index of the problematic call argument.
601   struct DFIDeducedMismatchArgs : DFIArguments {
602     TemplateArgumentList *TemplateArgs;
603     unsigned CallArgIndex;
604   };
605   // Structure used by DeductionFailureInfo to store information about
606   // unsatisfied constraints.
607   struct CNSInfo {
608     TemplateArgumentList *TemplateArgs;
609     ConstraintSatisfaction Satisfaction;
610   };
611 }
612 
613 /// Convert from Sema's representation of template deduction information
614 /// to the form used in overload-candidate information.
615 DeductionFailureInfo
616 clang::MakeDeductionFailureInfo(ASTContext &Context,
617                                 Sema::TemplateDeductionResult TDK,
618                                 TemplateDeductionInfo &Info) {
619   DeductionFailureInfo Result;
620   Result.Result = static_cast<unsigned>(TDK);
621   Result.HasDiagnostic = false;
622   switch (TDK) {
623   case Sema::TDK_Invalid:
624   case Sema::TDK_InstantiationDepth:
625   case Sema::TDK_TooManyArguments:
626   case Sema::TDK_TooFewArguments:
627   case Sema::TDK_MiscellaneousDeductionFailure:
628   case Sema::TDK_CUDATargetMismatch:
629     Result.Data = nullptr;
630     break;
631 
632   case Sema::TDK_Incomplete:
633   case Sema::TDK_InvalidExplicitArguments:
634     Result.Data = Info.Param.getOpaqueValue();
635     break;
636 
637   case Sema::TDK_DeducedMismatch:
638   case Sema::TDK_DeducedMismatchNested: {
639     // FIXME: Should allocate from normal heap so that we can free this later.
640     auto *Saved = new (Context) DFIDeducedMismatchArgs;
641     Saved->FirstArg = Info.FirstArg;
642     Saved->SecondArg = Info.SecondArg;
643     Saved->TemplateArgs = Info.takeSugared();
644     Saved->CallArgIndex = Info.CallArgIndex;
645     Result.Data = Saved;
646     break;
647   }
648 
649   case Sema::TDK_NonDeducedMismatch: {
650     // FIXME: Should allocate from normal heap so that we can free this later.
651     DFIArguments *Saved = new (Context) DFIArguments;
652     Saved->FirstArg = Info.FirstArg;
653     Saved->SecondArg = Info.SecondArg;
654     Result.Data = Saved;
655     break;
656   }
657 
658   case Sema::TDK_IncompletePack:
659     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
660   case Sema::TDK_Inconsistent:
661   case Sema::TDK_Underqualified: {
662     // FIXME: Should allocate from normal heap so that we can free this later.
663     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
664     Saved->Param = Info.Param;
665     Saved->FirstArg = Info.FirstArg;
666     Saved->SecondArg = Info.SecondArg;
667     Result.Data = Saved;
668     break;
669   }
670 
671   case Sema::TDK_SubstitutionFailure:
672     Result.Data = Info.takeSugared();
673     if (Info.hasSFINAEDiagnostic()) {
674       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
675           SourceLocation(), PartialDiagnostic::NullDiagnostic());
676       Info.takeSFINAEDiagnostic(*Diag);
677       Result.HasDiagnostic = true;
678     }
679     break;
680 
681   case Sema::TDK_ConstraintsNotSatisfied: {
682     CNSInfo *Saved = new (Context) CNSInfo;
683     Saved->TemplateArgs = Info.takeSugared();
684     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
685     Result.Data = Saved;
686     break;
687   }
688 
689   case Sema::TDK_Success:
690   case Sema::TDK_NonDependentConversionFailure:
691   case Sema::TDK_AlreadyDiagnosed:
692     llvm_unreachable("not a deduction failure");
693   }
694 
695   return Result;
696 }
697 
698 void DeductionFailureInfo::Destroy() {
699   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
700   case Sema::TDK_Success:
701   case Sema::TDK_Invalid:
702   case Sema::TDK_InstantiationDepth:
703   case Sema::TDK_Incomplete:
704   case Sema::TDK_TooManyArguments:
705   case Sema::TDK_TooFewArguments:
706   case Sema::TDK_InvalidExplicitArguments:
707   case Sema::TDK_CUDATargetMismatch:
708   case Sema::TDK_NonDependentConversionFailure:
709     break;
710 
711   case Sema::TDK_IncompletePack:
712   case Sema::TDK_Inconsistent:
713   case Sema::TDK_Underqualified:
714   case Sema::TDK_DeducedMismatch:
715   case Sema::TDK_DeducedMismatchNested:
716   case Sema::TDK_NonDeducedMismatch:
717     // FIXME: Destroy the data?
718     Data = nullptr;
719     break;
720 
721   case Sema::TDK_SubstitutionFailure:
722     // FIXME: Destroy the template argument list?
723     Data = nullptr;
724     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
725       Diag->~PartialDiagnosticAt();
726       HasDiagnostic = false;
727     }
728     break;
729 
730   case Sema::TDK_ConstraintsNotSatisfied:
731     // FIXME: Destroy the template argument list?
732     Data = nullptr;
733     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
734       Diag->~PartialDiagnosticAt();
735       HasDiagnostic = false;
736     }
737     break;
738 
739   // Unhandled
740   case Sema::TDK_MiscellaneousDeductionFailure:
741   case Sema::TDK_AlreadyDiagnosed:
742     break;
743   }
744 }
745 
746 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
747   if (HasDiagnostic)
748     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
749   return nullptr;
750 }
751 
752 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
753   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754   case Sema::TDK_Success:
755   case Sema::TDK_Invalid:
756   case Sema::TDK_InstantiationDepth:
757   case Sema::TDK_TooManyArguments:
758   case Sema::TDK_TooFewArguments:
759   case Sema::TDK_SubstitutionFailure:
760   case Sema::TDK_DeducedMismatch:
761   case Sema::TDK_DeducedMismatchNested:
762   case Sema::TDK_NonDeducedMismatch:
763   case Sema::TDK_CUDATargetMismatch:
764   case Sema::TDK_NonDependentConversionFailure:
765   case Sema::TDK_ConstraintsNotSatisfied:
766     return TemplateParameter();
767 
768   case Sema::TDK_Incomplete:
769   case Sema::TDK_InvalidExplicitArguments:
770     return TemplateParameter::getFromOpaqueValue(Data);
771 
772   case Sema::TDK_IncompletePack:
773   case Sema::TDK_Inconsistent:
774   case Sema::TDK_Underqualified:
775     return static_cast<DFIParamWithArguments*>(Data)->Param;
776 
777   // Unhandled
778   case Sema::TDK_MiscellaneousDeductionFailure:
779   case Sema::TDK_AlreadyDiagnosed:
780     break;
781   }
782 
783   return TemplateParameter();
784 }
785 
786 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
787   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
788   case Sema::TDK_Success:
789   case Sema::TDK_Invalid:
790   case Sema::TDK_InstantiationDepth:
791   case Sema::TDK_TooManyArguments:
792   case Sema::TDK_TooFewArguments:
793   case Sema::TDK_Incomplete:
794   case Sema::TDK_IncompletePack:
795   case Sema::TDK_InvalidExplicitArguments:
796   case Sema::TDK_Inconsistent:
797   case Sema::TDK_Underqualified:
798   case Sema::TDK_NonDeducedMismatch:
799   case Sema::TDK_CUDATargetMismatch:
800   case Sema::TDK_NonDependentConversionFailure:
801     return nullptr;
802 
803   case Sema::TDK_DeducedMismatch:
804   case Sema::TDK_DeducedMismatchNested:
805     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
806 
807   case Sema::TDK_SubstitutionFailure:
808     return static_cast<TemplateArgumentList*>(Data);
809 
810   case Sema::TDK_ConstraintsNotSatisfied:
811     return static_cast<CNSInfo*>(Data)->TemplateArgs;
812 
813   // Unhandled
814   case Sema::TDK_MiscellaneousDeductionFailure:
815   case Sema::TDK_AlreadyDiagnosed:
816     break;
817   }
818 
819   return nullptr;
820 }
821 
822 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
823   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
824   case Sema::TDK_Success:
825   case Sema::TDK_Invalid:
826   case Sema::TDK_InstantiationDepth:
827   case Sema::TDK_Incomplete:
828   case Sema::TDK_TooManyArguments:
829   case Sema::TDK_TooFewArguments:
830   case Sema::TDK_InvalidExplicitArguments:
831   case Sema::TDK_SubstitutionFailure:
832   case Sema::TDK_CUDATargetMismatch:
833   case Sema::TDK_NonDependentConversionFailure:
834   case Sema::TDK_ConstraintsNotSatisfied:
835     return nullptr;
836 
837   case Sema::TDK_IncompletePack:
838   case Sema::TDK_Inconsistent:
839   case Sema::TDK_Underqualified:
840   case Sema::TDK_DeducedMismatch:
841   case Sema::TDK_DeducedMismatchNested:
842   case Sema::TDK_NonDeducedMismatch:
843     return &static_cast<DFIArguments*>(Data)->FirstArg;
844 
845   // Unhandled
846   case Sema::TDK_MiscellaneousDeductionFailure:
847   case Sema::TDK_AlreadyDiagnosed:
848     break;
849   }
850 
851   return nullptr;
852 }
853 
854 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
855   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
856   case Sema::TDK_Success:
857   case Sema::TDK_Invalid:
858   case Sema::TDK_InstantiationDepth:
859   case Sema::TDK_Incomplete:
860   case Sema::TDK_IncompletePack:
861   case Sema::TDK_TooManyArguments:
862   case Sema::TDK_TooFewArguments:
863   case Sema::TDK_InvalidExplicitArguments:
864   case Sema::TDK_SubstitutionFailure:
865   case Sema::TDK_CUDATargetMismatch:
866   case Sema::TDK_NonDependentConversionFailure:
867   case Sema::TDK_ConstraintsNotSatisfied:
868     return nullptr;
869 
870   case Sema::TDK_Inconsistent:
871   case Sema::TDK_Underqualified:
872   case Sema::TDK_DeducedMismatch:
873   case Sema::TDK_DeducedMismatchNested:
874   case Sema::TDK_NonDeducedMismatch:
875     return &static_cast<DFIArguments*>(Data)->SecondArg;
876 
877   // Unhandled
878   case Sema::TDK_MiscellaneousDeductionFailure:
879   case Sema::TDK_AlreadyDiagnosed:
880     break;
881   }
882 
883   return nullptr;
884 }
885 
886 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
887   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
888   case Sema::TDK_DeducedMismatch:
889   case Sema::TDK_DeducedMismatchNested:
890     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
891 
892   default:
893     return std::nullopt;
894   }
895 }
896 
897 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
898                                 const FunctionDecl *Y) {
899   if (!X || !Y)
900     return false;
901   if (X->getNumParams() != Y->getNumParams())
902     return false;
903   for (unsigned I = 0; I < X->getNumParams(); ++I)
904     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
905                                     Y->getParamDecl(I)->getType()))
906       return false;
907   if (auto *FTX = X->getDescribedFunctionTemplate()) {
908     auto *FTY = Y->getDescribedFunctionTemplate();
909     if (!FTY)
910       return false;
911     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
912                                          FTY->getTemplateParameters()))
913       return false;
914   }
915   return true;
916 }
917 
918 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
919                                   Expr *FirstOperand, FunctionDecl *EqFD) {
920   assert(EqFD->getOverloadedOperator() ==
921          OverloadedOperatorKind::OO_EqualEqual);
922   // C++2a [over.match.oper]p4:
923   // A non-template function or function template F named operator== is a
924   // rewrite target with first operand o unless a search for the name operator!=
925   // in the scope S from the instantiation context of the operator expression
926   // finds a function or function template that would correspond
927   // ([basic.scope.scope]) to F if its name were operator==, where S is the
928   // scope of the class type of o if F is a class member, and the namespace
929   // scope of which F is a member otherwise. A function template specialization
930   // named operator== is a rewrite target if its function template is a rewrite
931   // target.
932   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
933       OverloadedOperatorKind::OO_ExclaimEqual);
934   if (isa<CXXMethodDecl>(EqFD)) {
935     // If F is a class member, search scope is class type of first operand.
936     QualType RHS = FirstOperand->getType();
937     auto *RHSRec = RHS->getAs<RecordType>();
938     if (!RHSRec)
939       return true;
940     LookupResult Members(S, NotEqOp, OpLoc,
941                          Sema::LookupNameKind::LookupMemberName);
942     S.LookupQualifiedName(Members, RHSRec->getDecl());
943     Members.suppressDiagnostics();
944     for (NamedDecl *Op : Members)
945       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
946         return false;
947     return true;
948   }
949   // Otherwise the search scope is the namespace scope of which F is a member.
950   LookupResult NonMembers(S, NotEqOp, OpLoc,
951                           Sema::LookupNameKind::LookupOperatorName);
952   S.LookupName(NonMembers,
953                S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
954   NonMembers.suppressDiagnostics();
955   for (NamedDecl *Op : NonMembers) {
956     auto *FD = Op->getAsFunction();
957     if(auto* UD = dyn_cast<UsingShadowDecl>(Op))
958       FD = UD->getUnderlyingDecl()->getAsFunction();
959     if (FunctionsCorrespond(S.Context, EqFD, FD) &&
960         declaresSameEntity(cast<Decl>(EqFD->getDeclContext()),
961                            cast<Decl>(Op->getDeclContext())))
962       return false;
963   }
964   return true;
965 }
966 
967 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
968     OverloadedOperatorKind Op) {
969   if (!AllowRewrittenCandidates)
970     return false;
971   return Op == OO_EqualEqual || Op == OO_Spaceship;
972 }
973 
974 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
975     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
976   auto Op = FD->getOverloadedOperator();
977   if (!allowsReversed(Op))
978     return false;
979   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
980     assert(OriginalArgs.size() == 2);
981     if (!shouldAddReversedEqEq(
982             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
983       return false;
984   }
985   // Don't bother adding a reversed candidate that can never be a better
986   // match than the non-reversed version.
987   return FD->getNumParams() != 2 ||
988          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
989                                            FD->getParamDecl(1)->getType()) ||
990          FD->hasAttr<EnableIfAttr>();
991 }
992 
993 void OverloadCandidateSet::destroyCandidates() {
994   for (iterator i = begin(), e = end(); i != e; ++i) {
995     for (auto &C : i->Conversions)
996       C.~ImplicitConversionSequence();
997     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
998       i->DeductionFailure.Destroy();
999   }
1000 }
1001 
1002 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1003   destroyCandidates();
1004   SlabAllocator.Reset();
1005   NumInlineBytesUsed = 0;
1006   Candidates.clear();
1007   Functions.clear();
1008   Kind = CSK;
1009 }
1010 
1011 namespace {
1012   class UnbridgedCastsSet {
1013     struct Entry {
1014       Expr **Addr;
1015       Expr *Saved;
1016     };
1017     SmallVector<Entry, 2> Entries;
1018 
1019   public:
1020     void save(Sema &S, Expr *&E) {
1021       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1022       Entry entry = { &E, E };
1023       Entries.push_back(entry);
1024       E = S.stripARCUnbridgedCast(E);
1025     }
1026 
1027     void restore() {
1028       for (SmallVectorImpl<Entry>::iterator
1029              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1030         *i->Addr = i->Saved;
1031     }
1032   };
1033 }
1034 
1035 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1036 /// preprocessing on the given expression.
1037 ///
1038 /// \param unbridgedCasts a collection to which to add unbridged casts;
1039 ///   without this, they will be immediately diagnosed as errors
1040 ///
1041 /// Return true on unrecoverable error.
1042 static bool
1043 checkPlaceholderForOverload(Sema &S, Expr *&E,
1044                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1045   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1046     // We can't handle overloaded expressions here because overload
1047     // resolution might reasonably tweak them.
1048     if (placeholder->getKind() == BuiltinType::Overload) return false;
1049 
1050     // If the context potentially accepts unbridged ARC casts, strip
1051     // the unbridged cast and add it to the collection for later restoration.
1052     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1053         unbridgedCasts) {
1054       unbridgedCasts->save(S, E);
1055       return false;
1056     }
1057 
1058     // Go ahead and check everything else.
1059     ExprResult result = S.CheckPlaceholderExpr(E);
1060     if (result.isInvalid())
1061       return true;
1062 
1063     E = result.get();
1064     return false;
1065   }
1066 
1067   // Nothing to do.
1068   return false;
1069 }
1070 
1071 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1072 /// placeholders.
1073 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1074                                             UnbridgedCastsSet &unbridged) {
1075   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1076     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1077       return true;
1078 
1079   return false;
1080 }
1081 
1082 /// Determine whether the given New declaration is an overload of the
1083 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1084 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1085 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1086 /// functions (or function templates) at all. When it does return Ovl_Match or
1087 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1088 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1089 /// declaration.
1090 ///
1091 /// Example: Given the following input:
1092 ///
1093 ///   void f(int, float); // #1
1094 ///   void f(int, int); // #2
1095 ///   int f(int, int); // #3
1096 ///
1097 /// When we process #1, there is no previous declaration of "f", so IsOverload
1098 /// will not be used.
1099 ///
1100 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1101 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1102 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1103 /// unchanged.
1104 ///
1105 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1106 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1107 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1108 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1109 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1110 ///
1111 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1112 /// by a using declaration. The rules for whether to hide shadow declarations
1113 /// ignore some properties which otherwise figure into a function template's
1114 /// signature.
1115 Sema::OverloadKind
1116 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1117                     NamedDecl *&Match, bool NewIsUsingDecl) {
1118   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1119          I != E; ++I) {
1120     NamedDecl *OldD = *I;
1121 
1122     bool OldIsUsingDecl = false;
1123     if (isa<UsingShadowDecl>(OldD)) {
1124       OldIsUsingDecl = true;
1125 
1126       // We can always introduce two using declarations into the same
1127       // context, even if they have identical signatures.
1128       if (NewIsUsingDecl) continue;
1129 
1130       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1131     }
1132 
1133     // A using-declaration does not conflict with another declaration
1134     // if one of them is hidden.
1135     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1136       continue;
1137 
1138     // If either declaration was introduced by a using declaration,
1139     // we'll need to use slightly different rules for matching.
1140     // Essentially, these rules are the normal rules, except that
1141     // function templates hide function templates with different
1142     // return types or template parameter lists.
1143     bool UseMemberUsingDeclRules =
1144       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1145       !New->getFriendObjectKind();
1146 
1147     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1148       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1149         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1150           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1151           continue;
1152         }
1153 
1154         if (!isa<FunctionTemplateDecl>(OldD) &&
1155             !shouldLinkPossiblyHiddenDecl(*I, New))
1156           continue;
1157 
1158         // C++20 [temp.friend] p9: A non-template friend declaration with a
1159         // requires-clause shall be a definition.  A friend function template
1160         // with a constraint that depends on a template parameter from an
1161         // enclosing template shall be a definition.  Such a constrained friend
1162         // function or function template declaration does not declare the same
1163         // function or function template as a declaration in any other scope.
1164         if (Context.FriendsDifferByConstraints(OldF, New))
1165           continue;
1166 
1167         Match = *I;
1168         return Ovl_Match;
1169       }
1170 
1171       // Builtins that have custom typechecking or have a reference should
1172       // not be overloadable or redeclarable.
1173       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1174         Match = *I;
1175         return Ovl_NonFunction;
1176       }
1177     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1178       // We can overload with these, which can show up when doing
1179       // redeclaration checks for UsingDecls.
1180       assert(Old.getLookupKind() == LookupUsingDeclName);
1181     } else if (isa<TagDecl>(OldD)) {
1182       // We can always overload with tags by hiding them.
1183     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1184       // Optimistically assume that an unresolved using decl will
1185       // overload; if it doesn't, we'll have to diagnose during
1186       // template instantiation.
1187       //
1188       // Exception: if the scope is dependent and this is not a class
1189       // member, the using declaration can only introduce an enumerator.
1190       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1191         Match = *I;
1192         return Ovl_NonFunction;
1193       }
1194     } else {
1195       // (C++ 13p1):
1196       //   Only function declarations can be overloaded; object and type
1197       //   declarations cannot be overloaded.
1198       Match = *I;
1199       return Ovl_NonFunction;
1200     }
1201   }
1202 
1203   // C++ [temp.friend]p1:
1204   //   For a friend function declaration that is not a template declaration:
1205   //    -- if the name of the friend is a qualified or unqualified template-id,
1206   //       [...], otherwise
1207   //    -- if the name of the friend is a qualified-id and a matching
1208   //       non-template function is found in the specified class or namespace,
1209   //       the friend declaration refers to that function, otherwise,
1210   //    -- if the name of the friend is a qualified-id and a matching function
1211   //       template is found in the specified class or namespace, the friend
1212   //       declaration refers to the deduced specialization of that function
1213   //       template, otherwise
1214   //    -- the name shall be an unqualified-id [...]
1215   // If we get here for a qualified friend declaration, we've just reached the
1216   // third bullet. If the type of the friend is dependent, skip this lookup
1217   // until instantiation.
1218   if (New->getFriendObjectKind() && New->getQualifier() &&
1219       !New->getDescribedFunctionTemplate() &&
1220       !New->getDependentSpecializationInfo() &&
1221       !New->getType()->isDependentType()) {
1222     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1223     TemplateSpecResult.addAllDecls(Old);
1224     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1225                                             /*QualifiedFriend*/true)) {
1226       New->setInvalidDecl();
1227       return Ovl_Overload;
1228     }
1229 
1230     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1231     return Ovl_Match;
1232   }
1233 
1234   return Ovl_Overload;
1235 }
1236 
1237 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1238                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1239                       bool ConsiderRequiresClauses) {
1240   // C++ [basic.start.main]p2: This function shall not be overloaded.
1241   if (New->isMain())
1242     return false;
1243 
1244   // MSVCRT user defined entry points cannot be overloaded.
1245   if (New->isMSVCRTEntryPoint())
1246     return false;
1247 
1248   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1249   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1250 
1251   // C++ [temp.fct]p2:
1252   //   A function template can be overloaded with other function templates
1253   //   and with normal (non-template) functions.
1254   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1255     return true;
1256 
1257   // Is the function New an overload of the function Old?
1258   QualType OldQType = Context.getCanonicalType(Old->getType());
1259   QualType NewQType = Context.getCanonicalType(New->getType());
1260 
1261   // Compare the signatures (C++ 1.3.10) of the two functions to
1262   // determine whether they are overloads. If we find any mismatch
1263   // in the signature, they are overloads.
1264 
1265   // If either of these functions is a K&R-style function (no
1266   // prototype), then we consider them to have matching signatures.
1267   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1268       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1269     return false;
1270 
1271   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1272   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1273 
1274   // The signature of a function includes the types of its
1275   // parameters (C++ 1.3.10), which includes the presence or absence
1276   // of the ellipsis; see C++ DR 357).
1277   if (OldQType != NewQType &&
1278       (OldType->getNumParams() != NewType->getNumParams() ||
1279        OldType->isVariadic() != NewType->isVariadic() ||
1280        !FunctionParamTypesAreEqual(OldType, NewType)))
1281     return true;
1282 
1283   if (NewTemplate) {
1284     // C++ [temp.over.link]p4:
1285     //   The signature of a function template consists of its function
1286     //   signature, its return type and its template parameter list. The names
1287     //   of the template parameters are significant only for establishing the
1288     //   relationship between the template parameters and the rest of the
1289     //   signature.
1290     //
1291     // We check the return type and template parameter lists for function
1292     // templates first; the remaining checks follow.
1293     bool SameTemplateParameterList = TemplateParameterListsAreEqual(
1294         NewTemplate->getTemplateParameters(),
1295         OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
1296     bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
1297                                               New->getDeclaredReturnType());
1298     // FIXME(GH58571): Match template parameter list even for non-constrained
1299     // template heads. This currently ensures that the code prior to C++20 is
1300     // not newly broken.
1301     bool ConstraintsInTemplateHead =
1302         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1303         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1304     // C++ [namespace.udecl]p11:
1305     //   The set of declarations named by a using-declarator that inhabits a
1306     //   class C does not include member functions and member function
1307     //   templates of a base class that "correspond" to (and thus would
1308     //   conflict with) a declaration of a function or function template in
1309     //   C.
1310     // Comparing return types is not required for the "correspond" check to
1311     // decide whether a member introduced by a shadow declaration is hidden.
1312     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1313         !SameTemplateParameterList)
1314       return true;
1315     if (!UseMemberUsingDeclRules &&
1316         (!SameTemplateParameterList || !SameReturnType))
1317       return true;
1318   }
1319 
1320   if (ConsiderRequiresClauses) {
1321     Expr *NewRC = New->getTrailingRequiresClause(),
1322          *OldRC = Old->getTrailingRequiresClause();
1323     if ((NewRC != nullptr) != (OldRC != nullptr))
1324       return true;
1325 
1326     if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1327         return true;
1328   }
1329 
1330   // If the function is a class member, its signature includes the
1331   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1332   //
1333   // As part of this, also check whether one of the member functions
1334   // is static, in which case they are not overloads (C++
1335   // 13.1p2). While not part of the definition of the signature,
1336   // this check is important to determine whether these functions
1337   // can be overloaded.
1338   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1339   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1340   if (OldMethod && NewMethod &&
1341       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1342     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1343       if (!UseMemberUsingDeclRules &&
1344           (OldMethod->getRefQualifier() == RQ_None ||
1345            NewMethod->getRefQualifier() == RQ_None)) {
1346         // C++20 [over.load]p2:
1347         //   - Member function declarations with the same name, the same
1348         //     parameter-type-list, and the same trailing requires-clause (if
1349         //     any), as well as member function template declarations with the
1350         //     same name, the same parameter-type-list, the same trailing
1351         //     requires-clause (if any), and the same template-head, cannot be
1352         //     overloaded if any of them, but not all, have a ref-qualifier.
1353         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1354             << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1355         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1356       }
1357       return true;
1358     }
1359 
1360     // We may not have applied the implicit const for a constexpr member
1361     // function yet (because we haven't yet resolved whether this is a static
1362     // or non-static member function). Add it now, on the assumption that this
1363     // is a redeclaration of OldMethod.
1364     auto OldQuals = OldMethod->getMethodQualifiers();
1365     auto NewQuals = NewMethod->getMethodQualifiers();
1366     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1367         !isa<CXXConstructorDecl>(NewMethod))
1368       NewQuals.addConst();
1369     // We do not allow overloading based off of '__restrict'.
1370     OldQuals.removeRestrict();
1371     NewQuals.removeRestrict();
1372     if (OldQuals != NewQuals)
1373       return true;
1374   }
1375 
1376   // Though pass_object_size is placed on parameters and takes an argument, we
1377   // consider it to be a function-level modifier for the sake of function
1378   // identity. Either the function has one or more parameters with
1379   // pass_object_size or it doesn't.
1380   if (functionHasPassObjectSizeParams(New) !=
1381       functionHasPassObjectSizeParams(Old))
1382     return true;
1383 
1384   // enable_if attributes are an order-sensitive part of the signature.
1385   for (specific_attr_iterator<EnableIfAttr>
1386          NewI = New->specific_attr_begin<EnableIfAttr>(),
1387          NewE = New->specific_attr_end<EnableIfAttr>(),
1388          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1389          OldE = Old->specific_attr_end<EnableIfAttr>();
1390        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1391     if (NewI == NewE || OldI == OldE)
1392       return true;
1393     llvm::FoldingSetNodeID NewID, OldID;
1394     NewI->getCond()->Profile(NewID, Context, true);
1395     OldI->getCond()->Profile(OldID, Context, true);
1396     if (NewID != OldID)
1397       return true;
1398   }
1399 
1400   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1401     // Don't allow overloading of destructors.  (In theory we could, but it
1402     // would be a giant change to clang.)
1403     if (!isa<CXXDestructorDecl>(New)) {
1404       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1405                          OldTarget = IdentifyCUDATarget(Old);
1406       if (NewTarget != CFT_InvalidTarget) {
1407         assert((OldTarget != CFT_InvalidTarget) &&
1408                "Unexpected invalid target.");
1409 
1410         // Allow overloading of functions with same signature and different CUDA
1411         // target attributes.
1412         if (NewTarget != OldTarget)
1413           return true;
1414       }
1415     }
1416   }
1417 
1418   // The signatures match; this is not an overload.
1419   return false;
1420 }
1421 
1422 /// Tries a user-defined conversion from From to ToType.
1423 ///
1424 /// Produces an implicit conversion sequence for when a standard conversion
1425 /// is not an option. See TryImplicitConversion for more information.
1426 static ImplicitConversionSequence
1427 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1428                          bool SuppressUserConversions,
1429                          AllowedExplicit AllowExplicit,
1430                          bool InOverloadResolution,
1431                          bool CStyle,
1432                          bool AllowObjCWritebackConversion,
1433                          bool AllowObjCConversionOnExplicit) {
1434   ImplicitConversionSequence ICS;
1435 
1436   if (SuppressUserConversions) {
1437     // We're not in the case above, so there is no conversion that
1438     // we can perform.
1439     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1440     return ICS;
1441   }
1442 
1443   // Attempt user-defined conversion.
1444   OverloadCandidateSet Conversions(From->getExprLoc(),
1445                                    OverloadCandidateSet::CSK_Normal);
1446   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1447                                   Conversions, AllowExplicit,
1448                                   AllowObjCConversionOnExplicit)) {
1449   case OR_Success:
1450   case OR_Deleted:
1451     ICS.setUserDefined();
1452     // C++ [over.ics.user]p4:
1453     //   A conversion of an expression of class type to the same class
1454     //   type is given Exact Match rank, and a conversion of an
1455     //   expression of class type to a base class of that type is
1456     //   given Conversion rank, in spite of the fact that a copy
1457     //   constructor (i.e., a user-defined conversion function) is
1458     //   called for those cases.
1459     if (CXXConstructorDecl *Constructor
1460           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1461       QualType FromCanon
1462         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1463       QualType ToCanon
1464         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1465       if (Constructor->isCopyConstructor() &&
1466           (FromCanon == ToCanon ||
1467            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1468         // Turn this into a "standard" conversion sequence, so that it
1469         // gets ranked with standard conversion sequences.
1470         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1471         ICS.setStandard();
1472         ICS.Standard.setAsIdentityConversion();
1473         ICS.Standard.setFromType(From->getType());
1474         ICS.Standard.setAllToTypes(ToType);
1475         ICS.Standard.CopyConstructor = Constructor;
1476         ICS.Standard.FoundCopyConstructor = Found;
1477         if (ToCanon != FromCanon)
1478           ICS.Standard.Second = ICK_Derived_To_Base;
1479       }
1480     }
1481     break;
1482 
1483   case OR_Ambiguous:
1484     ICS.setAmbiguous();
1485     ICS.Ambiguous.setFromType(From->getType());
1486     ICS.Ambiguous.setToType(ToType);
1487     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1488          Cand != Conversions.end(); ++Cand)
1489       if (Cand->Best)
1490         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1491     break;
1492 
1493     // Fall through.
1494   case OR_No_Viable_Function:
1495     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1496     break;
1497   }
1498 
1499   return ICS;
1500 }
1501 
1502 /// TryImplicitConversion - Attempt to perform an implicit conversion
1503 /// from the given expression (Expr) to the given type (ToType). This
1504 /// function returns an implicit conversion sequence that can be used
1505 /// to perform the initialization. Given
1506 ///
1507 ///   void f(float f);
1508 ///   void g(int i) { f(i); }
1509 ///
1510 /// this routine would produce an implicit conversion sequence to
1511 /// describe the initialization of f from i, which will be a standard
1512 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1513 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1514 //
1515 /// Note that this routine only determines how the conversion can be
1516 /// performed; it does not actually perform the conversion. As such,
1517 /// it will not produce any diagnostics if no conversion is available,
1518 /// but will instead return an implicit conversion sequence of kind
1519 /// "BadConversion".
1520 ///
1521 /// If @p SuppressUserConversions, then user-defined conversions are
1522 /// not permitted.
1523 /// If @p AllowExplicit, then explicit user-defined conversions are
1524 /// permitted.
1525 ///
1526 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1527 /// writeback conversion, which allows __autoreleasing id* parameters to
1528 /// be initialized with __strong id* or __weak id* arguments.
1529 static ImplicitConversionSequence
1530 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1531                       bool SuppressUserConversions,
1532                       AllowedExplicit AllowExplicit,
1533                       bool InOverloadResolution,
1534                       bool CStyle,
1535                       bool AllowObjCWritebackConversion,
1536                       bool AllowObjCConversionOnExplicit) {
1537   ImplicitConversionSequence ICS;
1538   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1539                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1540     ICS.setStandard();
1541     return ICS;
1542   }
1543 
1544   if (!S.getLangOpts().CPlusPlus) {
1545     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1546     return ICS;
1547   }
1548 
1549   // C++ [over.ics.user]p4:
1550   //   A conversion of an expression of class type to the same class
1551   //   type is given Exact Match rank, and a conversion of an
1552   //   expression of class type to a base class of that type is
1553   //   given Conversion rank, in spite of the fact that a copy/move
1554   //   constructor (i.e., a user-defined conversion function) is
1555   //   called for those cases.
1556   QualType FromType = From->getType();
1557   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1558       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1559        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1560     ICS.setStandard();
1561     ICS.Standard.setAsIdentityConversion();
1562     ICS.Standard.setFromType(FromType);
1563     ICS.Standard.setAllToTypes(ToType);
1564 
1565     // We don't actually check at this point whether there is a valid
1566     // copy/move constructor, since overloading just assumes that it
1567     // exists. When we actually perform initialization, we'll find the
1568     // appropriate constructor to copy the returned object, if needed.
1569     ICS.Standard.CopyConstructor = nullptr;
1570 
1571     // Determine whether this is considered a derived-to-base conversion.
1572     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1573       ICS.Standard.Second = ICK_Derived_To_Base;
1574 
1575     return ICS;
1576   }
1577 
1578   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1579                                   AllowExplicit, InOverloadResolution, CStyle,
1580                                   AllowObjCWritebackConversion,
1581                                   AllowObjCConversionOnExplicit);
1582 }
1583 
1584 ImplicitConversionSequence
1585 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1586                             bool SuppressUserConversions,
1587                             AllowedExplicit AllowExplicit,
1588                             bool InOverloadResolution,
1589                             bool CStyle,
1590                             bool AllowObjCWritebackConversion) {
1591   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1592                                  AllowExplicit, InOverloadResolution, CStyle,
1593                                  AllowObjCWritebackConversion,
1594                                  /*AllowObjCConversionOnExplicit=*/false);
1595 }
1596 
1597 /// PerformImplicitConversion - Perform an implicit conversion of the
1598 /// expression From to the type ToType. Returns the
1599 /// converted expression. Flavor is the kind of conversion we're
1600 /// performing, used in the error message. If @p AllowExplicit,
1601 /// explicit user-defined conversions are permitted.
1602 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1603                                            AssignmentAction Action,
1604                                            bool AllowExplicit) {
1605   if (checkPlaceholderForOverload(*this, From))
1606     return ExprError();
1607 
1608   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1609   bool AllowObjCWritebackConversion
1610     = getLangOpts().ObjCAutoRefCount &&
1611       (Action == AA_Passing || Action == AA_Sending);
1612   if (getLangOpts().ObjC)
1613     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1614                                       From->getType(), From);
1615   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1616       *this, From, ToType,
1617       /*SuppressUserConversions=*/false,
1618       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1619       /*InOverloadResolution=*/false,
1620       /*CStyle=*/false, AllowObjCWritebackConversion,
1621       /*AllowObjCConversionOnExplicit=*/false);
1622   return PerformImplicitConversion(From, ToType, ICS, Action);
1623 }
1624 
1625 /// Determine whether the conversion from FromType to ToType is a valid
1626 /// conversion that strips "noexcept" or "noreturn" off the nested function
1627 /// type.
1628 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1629                                 QualType &ResultTy) {
1630   if (Context.hasSameUnqualifiedType(FromType, ToType))
1631     return false;
1632 
1633   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1634   //                    or F(t noexcept) -> F(t)
1635   // where F adds one of the following at most once:
1636   //   - a pointer
1637   //   - a member pointer
1638   //   - a block pointer
1639   // Changes here need matching changes in FindCompositePointerType.
1640   CanQualType CanTo = Context.getCanonicalType(ToType);
1641   CanQualType CanFrom = Context.getCanonicalType(FromType);
1642   Type::TypeClass TyClass = CanTo->getTypeClass();
1643   if (TyClass != CanFrom->getTypeClass()) return false;
1644   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1645     if (TyClass == Type::Pointer) {
1646       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1647       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1648     } else if (TyClass == Type::BlockPointer) {
1649       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1650       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1651     } else if (TyClass == Type::MemberPointer) {
1652       auto ToMPT = CanTo.castAs<MemberPointerType>();
1653       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1654       // A function pointer conversion cannot change the class of the function.
1655       if (ToMPT->getClass() != FromMPT->getClass())
1656         return false;
1657       CanTo = ToMPT->getPointeeType();
1658       CanFrom = FromMPT->getPointeeType();
1659     } else {
1660       return false;
1661     }
1662 
1663     TyClass = CanTo->getTypeClass();
1664     if (TyClass != CanFrom->getTypeClass()) return false;
1665     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1666       return false;
1667   }
1668 
1669   const auto *FromFn = cast<FunctionType>(CanFrom);
1670   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1671 
1672   const auto *ToFn = cast<FunctionType>(CanTo);
1673   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1674 
1675   bool Changed = false;
1676 
1677   // Drop 'noreturn' if not present in target type.
1678   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1679     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1680     Changed = true;
1681   }
1682 
1683   // Drop 'noexcept' if not present in target type.
1684   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1685     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1686     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1687       FromFn = cast<FunctionType>(
1688           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1689                                                    EST_None)
1690                  .getTypePtr());
1691       Changed = true;
1692     }
1693 
1694     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1695     // only if the ExtParameterInfo lists of the two function prototypes can be
1696     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1697     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1698     bool CanUseToFPT, CanUseFromFPT;
1699     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1700                                       CanUseFromFPT, NewParamInfos) &&
1701         CanUseToFPT && !CanUseFromFPT) {
1702       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1703       ExtInfo.ExtParameterInfos =
1704           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1705       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1706                                             FromFPT->getParamTypes(), ExtInfo);
1707       FromFn = QT->getAs<FunctionType>();
1708       Changed = true;
1709     }
1710   }
1711 
1712   if (!Changed)
1713     return false;
1714 
1715   assert(QualType(FromFn, 0).isCanonical());
1716   if (QualType(FromFn, 0) != CanTo) return false;
1717 
1718   ResultTy = ToType;
1719   return true;
1720 }
1721 
1722 /// Determine whether the conversion from FromType to ToType is a valid
1723 /// vector conversion.
1724 ///
1725 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1726 /// conversion.
1727 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1728                                ImplicitConversionKind &ICK, Expr *From,
1729                                bool InOverloadResolution, bool CStyle) {
1730   // We need at least one of these types to be a vector type to have a vector
1731   // conversion.
1732   if (!ToType->isVectorType() && !FromType->isVectorType())
1733     return false;
1734 
1735   // Identical types require no conversions.
1736   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1737     return false;
1738 
1739   // There are no conversions between extended vector types, only identity.
1740   if (ToType->isExtVectorType()) {
1741     // There are no conversions between extended vector types other than the
1742     // identity conversion.
1743     if (FromType->isExtVectorType())
1744       return false;
1745 
1746     // Vector splat from any arithmetic type to a vector.
1747     if (FromType->isArithmeticType()) {
1748       ICK = ICK_Vector_Splat;
1749       return true;
1750     }
1751   }
1752 
1753   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1754     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1755         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1756       ICK = ICK_SVE_Vector_Conversion;
1757       return true;
1758     }
1759 
1760   // We can perform the conversion between vector types in the following cases:
1761   // 1)vector types are equivalent AltiVec and GCC vector types
1762   // 2)lax vector conversions are permitted and the vector types are of the
1763   //   same size
1764   // 3)the destination type does not have the ARM MVE strict-polymorphism
1765   //   attribute, which inhibits lax vector conversion for overload resolution
1766   //   only
1767   if (ToType->isVectorType() && FromType->isVectorType()) {
1768     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1769         (S.isLaxVectorConversion(FromType, ToType) &&
1770          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1771       if (S.isLaxVectorConversion(FromType, ToType) &&
1772           S.anyAltivecTypes(FromType, ToType) &&
1773           !S.areSameVectorElemTypes(FromType, ToType) &&
1774           !InOverloadResolution && !CStyle) {
1775         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1776             << FromType << ToType;
1777       }
1778       ICK = ICK_Vector_Conversion;
1779       return true;
1780     }
1781   }
1782 
1783   return false;
1784 }
1785 
1786 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1787                                 bool InOverloadResolution,
1788                                 StandardConversionSequence &SCS,
1789                                 bool CStyle);
1790 
1791 /// IsStandardConversion - Determines whether there is a standard
1792 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1793 /// expression From to the type ToType. Standard conversion sequences
1794 /// only consider non-class types; for conversions that involve class
1795 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1796 /// contain the standard conversion sequence required to perform this
1797 /// conversion and this routine will return true. Otherwise, this
1798 /// routine will return false and the value of SCS is unspecified.
1799 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1800                                  bool InOverloadResolution,
1801                                  StandardConversionSequence &SCS,
1802                                  bool CStyle,
1803                                  bool AllowObjCWritebackConversion) {
1804   QualType FromType = From->getType();
1805 
1806   // Standard conversions (C++ [conv])
1807   SCS.setAsIdentityConversion();
1808   SCS.IncompatibleObjC = false;
1809   SCS.setFromType(FromType);
1810   SCS.CopyConstructor = nullptr;
1811 
1812   // There are no standard conversions for class types in C++, so
1813   // abort early. When overloading in C, however, we do permit them.
1814   if (S.getLangOpts().CPlusPlus &&
1815       (FromType->isRecordType() || ToType->isRecordType()))
1816     return false;
1817 
1818   // The first conversion can be an lvalue-to-rvalue conversion,
1819   // array-to-pointer conversion, or function-to-pointer conversion
1820   // (C++ 4p1).
1821 
1822   if (FromType == S.Context.OverloadTy) {
1823     DeclAccessPair AccessPair;
1824     if (FunctionDecl *Fn
1825           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1826                                                  AccessPair)) {
1827       // We were able to resolve the address of the overloaded function,
1828       // so we can convert to the type of that function.
1829       FromType = Fn->getType();
1830       SCS.setFromType(FromType);
1831 
1832       // we can sometimes resolve &foo<int> regardless of ToType, so check
1833       // if the type matches (identity) or we are converting to bool
1834       if (!S.Context.hasSameUnqualifiedType(
1835                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1836         QualType resultTy;
1837         // if the function type matches except for [[noreturn]], it's ok
1838         if (!S.IsFunctionConversion(FromType,
1839               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1840           // otherwise, only a boolean conversion is standard
1841           if (!ToType->isBooleanType())
1842             return false;
1843       }
1844 
1845       // Check if the "from" expression is taking the address of an overloaded
1846       // function and recompute the FromType accordingly. Take advantage of the
1847       // fact that non-static member functions *must* have such an address-of
1848       // expression.
1849       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1850       if (Method && !Method->isStatic()) {
1851         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1852                "Non-unary operator on non-static member address");
1853         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1854                == UO_AddrOf &&
1855                "Non-address-of operator on non-static member address");
1856         const Type *ClassType
1857           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1858         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1859       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1860         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1861                UO_AddrOf &&
1862                "Non-address-of operator for overloaded function expression");
1863         FromType = S.Context.getPointerType(FromType);
1864       }
1865     } else {
1866       return false;
1867     }
1868   }
1869   // Lvalue-to-rvalue conversion (C++11 4.1):
1870   //   A glvalue (3.10) of a non-function, non-array type T can
1871   //   be converted to a prvalue.
1872   bool argIsLValue = From->isGLValue();
1873   if (argIsLValue &&
1874       !FromType->isFunctionType() && !FromType->isArrayType() &&
1875       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1876     SCS.First = ICK_Lvalue_To_Rvalue;
1877 
1878     // C11 6.3.2.1p2:
1879     //   ... if the lvalue has atomic type, the value has the non-atomic version
1880     //   of the type of the lvalue ...
1881     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1882       FromType = Atomic->getValueType();
1883 
1884     // If T is a non-class type, the type of the rvalue is the
1885     // cv-unqualified version of T. Otherwise, the type of the rvalue
1886     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1887     // just strip the qualifiers because they don't matter.
1888     FromType = FromType.getUnqualifiedType();
1889   } else if (FromType->isArrayType()) {
1890     // Array-to-pointer conversion (C++ 4.2)
1891     SCS.First = ICK_Array_To_Pointer;
1892 
1893     // An lvalue or rvalue of type "array of N T" or "array of unknown
1894     // bound of T" can be converted to an rvalue of type "pointer to
1895     // T" (C++ 4.2p1).
1896     FromType = S.Context.getArrayDecayedType(FromType);
1897 
1898     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1899       // This conversion is deprecated in C++03 (D.4)
1900       SCS.DeprecatedStringLiteralToCharPtr = true;
1901 
1902       // For the purpose of ranking in overload resolution
1903       // (13.3.3.1.1), this conversion is considered an
1904       // array-to-pointer conversion followed by a qualification
1905       // conversion (4.4). (C++ 4.2p2)
1906       SCS.Second = ICK_Identity;
1907       SCS.Third = ICK_Qualification;
1908       SCS.QualificationIncludesObjCLifetime = false;
1909       SCS.setAllToTypes(FromType);
1910       return true;
1911     }
1912   } else if (FromType->isFunctionType() && argIsLValue) {
1913     // Function-to-pointer conversion (C++ 4.3).
1914     SCS.First = ICK_Function_To_Pointer;
1915 
1916     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1917       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1918         if (!S.checkAddressOfFunctionIsAvailable(FD))
1919           return false;
1920 
1921     // An lvalue of function type T can be converted to an rvalue of
1922     // type "pointer to T." The result is a pointer to the
1923     // function. (C++ 4.3p1).
1924     FromType = S.Context.getPointerType(FromType);
1925   } else {
1926     // We don't require any conversions for the first step.
1927     SCS.First = ICK_Identity;
1928   }
1929   SCS.setToType(0, FromType);
1930 
1931   // The second conversion can be an integral promotion, floating
1932   // point promotion, integral conversion, floating point conversion,
1933   // floating-integral conversion, pointer conversion,
1934   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1935   // For overloading in C, this can also be a "compatible-type"
1936   // conversion.
1937   bool IncompatibleObjC = false;
1938   ImplicitConversionKind SecondICK = ICK_Identity;
1939   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1940     // The unqualified versions of the types are the same: there's no
1941     // conversion to do.
1942     SCS.Second = ICK_Identity;
1943   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1944     // Integral promotion (C++ 4.5).
1945     SCS.Second = ICK_Integral_Promotion;
1946     FromType = ToType.getUnqualifiedType();
1947   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1948     // Floating point promotion (C++ 4.6).
1949     SCS.Second = ICK_Floating_Promotion;
1950     FromType = ToType.getUnqualifiedType();
1951   } else if (S.IsComplexPromotion(FromType, ToType)) {
1952     // Complex promotion (Clang extension)
1953     SCS.Second = ICK_Complex_Promotion;
1954     FromType = ToType.getUnqualifiedType();
1955   } else if (ToType->isBooleanType() &&
1956              (FromType->isArithmeticType() ||
1957               FromType->isAnyPointerType() ||
1958               FromType->isBlockPointerType() ||
1959               FromType->isMemberPointerType())) {
1960     // Boolean conversions (C++ 4.12).
1961     SCS.Second = ICK_Boolean_Conversion;
1962     FromType = S.Context.BoolTy;
1963   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1964              ToType->isIntegralType(S.Context)) {
1965     // Integral conversions (C++ 4.7).
1966     SCS.Second = ICK_Integral_Conversion;
1967     FromType = ToType.getUnqualifiedType();
1968   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1969     // Complex conversions (C99 6.3.1.6)
1970     SCS.Second = ICK_Complex_Conversion;
1971     FromType = ToType.getUnqualifiedType();
1972   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1973              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1974     // Complex-real conversions (C99 6.3.1.7)
1975     SCS.Second = ICK_Complex_Real;
1976     FromType = ToType.getUnqualifiedType();
1977   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1978     // FIXME: disable conversions between long double, __ibm128 and __float128
1979     // if their representation is different until there is back end support
1980     // We of course allow this conversion if long double is really double.
1981 
1982     // Conversions between bfloat and other floats are not permitted.
1983     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1984       return false;
1985 
1986     // Conversions between IEEE-quad and IBM-extended semantics are not
1987     // permitted.
1988     const llvm::fltSemantics &FromSem =
1989         S.Context.getFloatTypeSemantics(FromType);
1990     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1991     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1992          &ToSem == &llvm::APFloat::IEEEquad()) ||
1993         (&FromSem == &llvm::APFloat::IEEEquad() &&
1994          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1995       return false;
1996 
1997     // Floating point conversions (C++ 4.8).
1998     SCS.Second = ICK_Floating_Conversion;
1999     FromType = ToType.getUnqualifiedType();
2000   } else if ((FromType->isRealFloatingType() &&
2001               ToType->isIntegralType(S.Context)) ||
2002              (FromType->isIntegralOrUnscopedEnumerationType() &&
2003               ToType->isRealFloatingType())) {
2004     // Conversions between bfloat and int are not permitted.
2005     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
2006       return false;
2007 
2008     // Floating-integral conversions (C++ 4.9).
2009     SCS.Second = ICK_Floating_Integral;
2010     FromType = ToType.getUnqualifiedType();
2011   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2012     SCS.Second = ICK_Block_Pointer_Conversion;
2013   } else if (AllowObjCWritebackConversion &&
2014              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2015     SCS.Second = ICK_Writeback_Conversion;
2016   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2017                                    FromType, IncompatibleObjC)) {
2018     // Pointer conversions (C++ 4.10).
2019     SCS.Second = ICK_Pointer_Conversion;
2020     SCS.IncompatibleObjC = IncompatibleObjC;
2021     FromType = FromType.getUnqualifiedType();
2022   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2023                                          InOverloadResolution, FromType)) {
2024     // Pointer to member conversions (4.11).
2025     SCS.Second = ICK_Pointer_Member;
2026   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2027                                 InOverloadResolution, CStyle)) {
2028     SCS.Second = SecondICK;
2029     FromType = ToType.getUnqualifiedType();
2030   } else if (!S.getLangOpts().CPlusPlus &&
2031              S.Context.typesAreCompatible(ToType, FromType)) {
2032     // Compatible conversions (Clang extension for C function overloading)
2033     SCS.Second = ICK_Compatible_Conversion;
2034     FromType = ToType.getUnqualifiedType();
2035   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2036                                              InOverloadResolution,
2037                                              SCS, CStyle)) {
2038     SCS.Second = ICK_TransparentUnionConversion;
2039     FromType = ToType;
2040   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2041                                  CStyle)) {
2042     // tryAtomicConversion has updated the standard conversion sequence
2043     // appropriately.
2044     return true;
2045   } else if (ToType->isEventT() &&
2046              From->isIntegerConstantExpr(S.getASTContext()) &&
2047              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2048     SCS.Second = ICK_Zero_Event_Conversion;
2049     FromType = ToType;
2050   } else if (ToType->isQueueT() &&
2051              From->isIntegerConstantExpr(S.getASTContext()) &&
2052              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2053     SCS.Second = ICK_Zero_Queue_Conversion;
2054     FromType = ToType;
2055   } else if (ToType->isSamplerT() &&
2056              From->isIntegerConstantExpr(S.getASTContext())) {
2057     SCS.Second = ICK_Compatible_Conversion;
2058     FromType = ToType;
2059   } else {
2060     // No second conversion required.
2061     SCS.Second = ICK_Identity;
2062   }
2063   SCS.setToType(1, FromType);
2064 
2065   // The third conversion can be a function pointer conversion or a
2066   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2067   bool ObjCLifetimeConversion;
2068   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2069     // Function pointer conversions (removing 'noexcept') including removal of
2070     // 'noreturn' (Clang extension).
2071     SCS.Third = ICK_Function_Conversion;
2072   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2073                                          ObjCLifetimeConversion)) {
2074     SCS.Third = ICK_Qualification;
2075     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2076     FromType = ToType;
2077   } else {
2078     // No conversion required
2079     SCS.Third = ICK_Identity;
2080   }
2081 
2082   // C++ [over.best.ics]p6:
2083   //   [...] Any difference in top-level cv-qualification is
2084   //   subsumed by the initialization itself and does not constitute
2085   //   a conversion. [...]
2086   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2087   QualType CanonTo = S.Context.getCanonicalType(ToType);
2088   if (CanonFrom.getLocalUnqualifiedType()
2089                                      == CanonTo.getLocalUnqualifiedType() &&
2090       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2091     FromType = ToType;
2092     CanonFrom = CanonTo;
2093   }
2094 
2095   SCS.setToType(2, FromType);
2096 
2097   if (CanonFrom == CanonTo)
2098     return true;
2099 
2100   // If we have not converted the argument type to the parameter type,
2101   // this is a bad conversion sequence, unless we're resolving an overload in C.
2102   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2103     return false;
2104 
2105   ExprResult ER = ExprResult{From};
2106   Sema::AssignConvertType Conv =
2107       S.CheckSingleAssignmentConstraints(ToType, ER,
2108                                          /*Diagnose=*/false,
2109                                          /*DiagnoseCFAudited=*/false,
2110                                          /*ConvertRHS=*/false);
2111   ImplicitConversionKind SecondConv;
2112   switch (Conv) {
2113   case Sema::Compatible:
2114     SecondConv = ICK_C_Only_Conversion;
2115     break;
2116   // For our purposes, discarding qualifiers is just as bad as using an
2117   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2118   // qualifiers, as well.
2119   case Sema::CompatiblePointerDiscardsQualifiers:
2120   case Sema::IncompatiblePointer:
2121   case Sema::IncompatiblePointerSign:
2122     SecondConv = ICK_Incompatible_Pointer_Conversion;
2123     break;
2124   default:
2125     return false;
2126   }
2127 
2128   // First can only be an lvalue conversion, so we pretend that this was the
2129   // second conversion. First should already be valid from earlier in the
2130   // function.
2131   SCS.Second = SecondConv;
2132   SCS.setToType(1, ToType);
2133 
2134   // Third is Identity, because Second should rank us worse than any other
2135   // conversion. This could also be ICK_Qualification, but it's simpler to just
2136   // lump everything in with the second conversion, and we don't gain anything
2137   // from making this ICK_Qualification.
2138   SCS.Third = ICK_Identity;
2139   SCS.setToType(2, ToType);
2140   return true;
2141 }
2142 
2143 static bool
2144 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2145                                      QualType &ToType,
2146                                      bool InOverloadResolution,
2147                                      StandardConversionSequence &SCS,
2148                                      bool CStyle) {
2149 
2150   const RecordType *UT = ToType->getAsUnionType();
2151   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2152     return false;
2153   // The field to initialize within the transparent union.
2154   RecordDecl *UD = UT->getDecl();
2155   // It's compatible if the expression matches any of the fields.
2156   for (const auto *it : UD->fields()) {
2157     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2158                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2159       ToType = it->getType();
2160       return true;
2161     }
2162   }
2163   return false;
2164 }
2165 
2166 /// IsIntegralPromotion - Determines whether the conversion from the
2167 /// expression From (whose potentially-adjusted type is FromType) to
2168 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2169 /// sets PromotedType to the promoted type.
2170 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2171   const BuiltinType *To = ToType->getAs<BuiltinType>();
2172   // All integers are built-in.
2173   if (!To) {
2174     return false;
2175   }
2176 
2177   // An rvalue of type char, signed char, unsigned char, short int, or
2178   // unsigned short int can be converted to an rvalue of type int if
2179   // int can represent all the values of the source type; otherwise,
2180   // the source rvalue can be converted to an rvalue of type unsigned
2181   // int (C++ 4.5p1).
2182   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2183       !FromType->isEnumeralType()) {
2184     if ( // We can promote any signed, promotable integer type to an int
2185         (FromType->isSignedIntegerType() ||
2186          // We can promote any unsigned integer type whose size is
2187          // less than int to an int.
2188          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2189       return To->getKind() == BuiltinType::Int;
2190     }
2191 
2192     return To->getKind() == BuiltinType::UInt;
2193   }
2194 
2195   // C++11 [conv.prom]p3:
2196   //   A prvalue of an unscoped enumeration type whose underlying type is not
2197   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2198   //   following types that can represent all the values of the enumeration
2199   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2200   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2201   //   long long int. If none of the types in that list can represent all the
2202   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2203   //   type can be converted to an rvalue a prvalue of the extended integer type
2204   //   with lowest integer conversion rank (4.13) greater than the rank of long
2205   //   long in which all the values of the enumeration can be represented. If
2206   //   there are two such extended types, the signed one is chosen.
2207   // C++11 [conv.prom]p4:
2208   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2209   //   can be converted to a prvalue of its underlying type. Moreover, if
2210   //   integral promotion can be applied to its underlying type, a prvalue of an
2211   //   unscoped enumeration type whose underlying type is fixed can also be
2212   //   converted to a prvalue of the promoted underlying type.
2213   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2214     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2215     // provided for a scoped enumeration.
2216     if (FromEnumType->getDecl()->isScoped())
2217       return false;
2218 
2219     // We can perform an integral promotion to the underlying type of the enum,
2220     // even if that's not the promoted type. Note that the check for promoting
2221     // the underlying type is based on the type alone, and does not consider
2222     // the bitfield-ness of the actual source expression.
2223     if (FromEnumType->getDecl()->isFixed()) {
2224       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2225       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2226              IsIntegralPromotion(nullptr, Underlying, ToType);
2227     }
2228 
2229     // We have already pre-calculated the promotion type, so this is trivial.
2230     if (ToType->isIntegerType() &&
2231         isCompleteType(From->getBeginLoc(), FromType))
2232       return Context.hasSameUnqualifiedType(
2233           ToType, FromEnumType->getDecl()->getPromotionType());
2234 
2235     // C++ [conv.prom]p5:
2236     //   If the bit-field has an enumerated type, it is treated as any other
2237     //   value of that type for promotion purposes.
2238     //
2239     // ... so do not fall through into the bit-field checks below in C++.
2240     if (getLangOpts().CPlusPlus)
2241       return false;
2242   }
2243 
2244   // C++0x [conv.prom]p2:
2245   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2246   //   to an rvalue a prvalue of the first of the following types that can
2247   //   represent all the values of its underlying type: int, unsigned int,
2248   //   long int, unsigned long int, long long int, or unsigned long long int.
2249   //   If none of the types in that list can represent all the values of its
2250   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2251   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2252   //   type.
2253   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2254       ToType->isIntegerType()) {
2255     // Determine whether the type we're converting from is signed or
2256     // unsigned.
2257     bool FromIsSigned = FromType->isSignedIntegerType();
2258     uint64_t FromSize = Context.getTypeSize(FromType);
2259 
2260     // The types we'll try to promote to, in the appropriate
2261     // order. Try each of these types.
2262     QualType PromoteTypes[6] = {
2263       Context.IntTy, Context.UnsignedIntTy,
2264       Context.LongTy, Context.UnsignedLongTy ,
2265       Context.LongLongTy, Context.UnsignedLongLongTy
2266     };
2267     for (int Idx = 0; Idx < 6; ++Idx) {
2268       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2269       if (FromSize < ToSize ||
2270           (FromSize == ToSize &&
2271            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2272         // We found the type that we can promote to. If this is the
2273         // type we wanted, we have a promotion. Otherwise, no
2274         // promotion.
2275         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2276       }
2277     }
2278   }
2279 
2280   // An rvalue for an integral bit-field (9.6) can be converted to an
2281   // rvalue of type int if int can represent all the values of the
2282   // bit-field; otherwise, it can be converted to unsigned int if
2283   // unsigned int can represent all the values of the bit-field. If
2284   // the bit-field is larger yet, no integral promotion applies to
2285   // it. If the bit-field has an enumerated type, it is treated as any
2286   // other value of that type for promotion purposes (C++ 4.5p3).
2287   // FIXME: We should delay checking of bit-fields until we actually perform the
2288   // conversion.
2289   //
2290   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2291   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2292   // bit-fields and those whose underlying type is larger than int) for GCC
2293   // compatibility.
2294   if (From) {
2295     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2296       std::optional<llvm::APSInt> BitWidth;
2297       if (FromType->isIntegralType(Context) &&
2298           (BitWidth =
2299                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2300         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2301         ToSize = Context.getTypeSize(ToType);
2302 
2303         // Are we promoting to an int from a bitfield that fits in an int?
2304         if (*BitWidth < ToSize ||
2305             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2306           return To->getKind() == BuiltinType::Int;
2307         }
2308 
2309         // Are we promoting to an unsigned int from an unsigned bitfield
2310         // that fits into an unsigned int?
2311         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2312           return To->getKind() == BuiltinType::UInt;
2313         }
2314 
2315         return false;
2316       }
2317     }
2318   }
2319 
2320   // An rvalue of type bool can be converted to an rvalue of type int,
2321   // with false becoming zero and true becoming one (C++ 4.5p4).
2322   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2323     return true;
2324   }
2325 
2326   return false;
2327 }
2328 
2329 /// IsFloatingPointPromotion - Determines whether the conversion from
2330 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2331 /// returns true and sets PromotedType to the promoted type.
2332 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2333   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2334     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2335       /// An rvalue of type float can be converted to an rvalue of type
2336       /// double. (C++ 4.6p1).
2337       if (FromBuiltin->getKind() == BuiltinType::Float &&
2338           ToBuiltin->getKind() == BuiltinType::Double)
2339         return true;
2340 
2341       // C99 6.3.1.5p1:
2342       //   When a float is promoted to double or long double, or a
2343       //   double is promoted to long double [...].
2344       if (!getLangOpts().CPlusPlus &&
2345           (FromBuiltin->getKind() == BuiltinType::Float ||
2346            FromBuiltin->getKind() == BuiltinType::Double) &&
2347           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2348            ToBuiltin->getKind() == BuiltinType::Float128 ||
2349            ToBuiltin->getKind() == BuiltinType::Ibm128))
2350         return true;
2351 
2352       // Half can be promoted to float.
2353       if (!getLangOpts().NativeHalfType &&
2354            FromBuiltin->getKind() == BuiltinType::Half &&
2355           ToBuiltin->getKind() == BuiltinType::Float)
2356         return true;
2357     }
2358 
2359   return false;
2360 }
2361 
2362 /// Determine if a conversion is a complex promotion.
2363 ///
2364 /// A complex promotion is defined as a complex -> complex conversion
2365 /// where the conversion between the underlying real types is a
2366 /// floating-point or integral promotion.
2367 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2368   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2369   if (!FromComplex)
2370     return false;
2371 
2372   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2373   if (!ToComplex)
2374     return false;
2375 
2376   return IsFloatingPointPromotion(FromComplex->getElementType(),
2377                                   ToComplex->getElementType()) ||
2378     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2379                         ToComplex->getElementType());
2380 }
2381 
2382 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2383 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2384 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2385 /// if non-empty, will be a pointer to ToType that may or may not have
2386 /// the right set of qualifiers on its pointee.
2387 ///
2388 static QualType
2389 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2390                                    QualType ToPointee, QualType ToType,
2391                                    ASTContext &Context,
2392                                    bool StripObjCLifetime = false) {
2393   assert((FromPtr->getTypeClass() == Type::Pointer ||
2394           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2395          "Invalid similarly-qualified pointer type");
2396 
2397   /// Conversions to 'id' subsume cv-qualifier conversions.
2398   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2399     return ToType.getUnqualifiedType();
2400 
2401   QualType CanonFromPointee
2402     = Context.getCanonicalType(FromPtr->getPointeeType());
2403   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2404   Qualifiers Quals = CanonFromPointee.getQualifiers();
2405 
2406   if (StripObjCLifetime)
2407     Quals.removeObjCLifetime();
2408 
2409   // Exact qualifier match -> return the pointer type we're converting to.
2410   if (CanonToPointee.getLocalQualifiers() == Quals) {
2411     // ToType is exactly what we need. Return it.
2412     if (!ToType.isNull())
2413       return ToType.getUnqualifiedType();
2414 
2415     // Build a pointer to ToPointee. It has the right qualifiers
2416     // already.
2417     if (isa<ObjCObjectPointerType>(ToType))
2418       return Context.getObjCObjectPointerType(ToPointee);
2419     return Context.getPointerType(ToPointee);
2420   }
2421 
2422   // Just build a canonical type that has the right qualifiers.
2423   QualType QualifiedCanonToPointee
2424     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2425 
2426   if (isa<ObjCObjectPointerType>(ToType))
2427     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2428   return Context.getPointerType(QualifiedCanonToPointee);
2429 }
2430 
2431 static bool isNullPointerConstantForConversion(Expr *Expr,
2432                                                bool InOverloadResolution,
2433                                                ASTContext &Context) {
2434   // Handle value-dependent integral null pointer constants correctly.
2435   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2436   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2437       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2438     return !InOverloadResolution;
2439 
2440   return Expr->isNullPointerConstant(Context,
2441                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2442                                         : Expr::NPC_ValueDependentIsNull);
2443 }
2444 
2445 /// IsPointerConversion - Determines whether the conversion of the
2446 /// expression From, which has the (possibly adjusted) type FromType,
2447 /// can be converted to the type ToType via a pointer conversion (C++
2448 /// 4.10). If so, returns true and places the converted type (that
2449 /// might differ from ToType in its cv-qualifiers at some level) into
2450 /// ConvertedType.
2451 ///
2452 /// This routine also supports conversions to and from block pointers
2453 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2454 /// pointers to interfaces. FIXME: Once we've determined the
2455 /// appropriate overloading rules for Objective-C, we may want to
2456 /// split the Objective-C checks into a different routine; however,
2457 /// GCC seems to consider all of these conversions to be pointer
2458 /// conversions, so for now they live here. IncompatibleObjC will be
2459 /// set if the conversion is an allowed Objective-C conversion that
2460 /// should result in a warning.
2461 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2462                                bool InOverloadResolution,
2463                                QualType& ConvertedType,
2464                                bool &IncompatibleObjC) {
2465   IncompatibleObjC = false;
2466   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2467                               IncompatibleObjC))
2468     return true;
2469 
2470   // Conversion from a null pointer constant to any Objective-C pointer type.
2471   if (ToType->isObjCObjectPointerType() &&
2472       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2473     ConvertedType = ToType;
2474     return true;
2475   }
2476 
2477   // Blocks: Block pointers can be converted to void*.
2478   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2479       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2480     ConvertedType = ToType;
2481     return true;
2482   }
2483   // Blocks: A null pointer constant can be converted to a block
2484   // pointer type.
2485   if (ToType->isBlockPointerType() &&
2486       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2487     ConvertedType = ToType;
2488     return true;
2489   }
2490 
2491   // If the left-hand-side is nullptr_t, the right side can be a null
2492   // pointer constant.
2493   if (ToType->isNullPtrType() &&
2494       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2495     ConvertedType = ToType;
2496     return true;
2497   }
2498 
2499   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2500   if (!ToTypePtr)
2501     return false;
2502 
2503   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2504   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2505     ConvertedType = ToType;
2506     return true;
2507   }
2508 
2509   // Beyond this point, both types need to be pointers
2510   // , including objective-c pointers.
2511   QualType ToPointeeType = ToTypePtr->getPointeeType();
2512   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2513       !getLangOpts().ObjCAutoRefCount) {
2514     ConvertedType = BuildSimilarlyQualifiedPointerType(
2515         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2516         Context);
2517     return true;
2518   }
2519   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2520   if (!FromTypePtr)
2521     return false;
2522 
2523   QualType FromPointeeType = FromTypePtr->getPointeeType();
2524 
2525   // If the unqualified pointee types are the same, this can't be a
2526   // pointer conversion, so don't do all of the work below.
2527   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2528     return false;
2529 
2530   // An rvalue of type "pointer to cv T," where T is an object type,
2531   // can be converted to an rvalue of type "pointer to cv void" (C++
2532   // 4.10p2).
2533   if (FromPointeeType->isIncompleteOrObjectType() &&
2534       ToPointeeType->isVoidType()) {
2535     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2536                                                        ToPointeeType,
2537                                                        ToType, Context,
2538                                                    /*StripObjCLifetime=*/true);
2539     return true;
2540   }
2541 
2542   // MSVC allows implicit function to void* type conversion.
2543   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2544       ToPointeeType->isVoidType()) {
2545     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2546                                                        ToPointeeType,
2547                                                        ToType, Context);
2548     return true;
2549   }
2550 
2551   // When we're overloading in C, we allow a special kind of pointer
2552   // conversion for compatible-but-not-identical pointee types.
2553   if (!getLangOpts().CPlusPlus &&
2554       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2555     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2556                                                        ToPointeeType,
2557                                                        ToType, Context);
2558     return true;
2559   }
2560 
2561   // C++ [conv.ptr]p3:
2562   //
2563   //   An rvalue of type "pointer to cv D," where D is a class type,
2564   //   can be converted to an rvalue of type "pointer to cv B," where
2565   //   B is a base class (clause 10) of D. If B is an inaccessible
2566   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2567   //   necessitates this conversion is ill-formed. The result of the
2568   //   conversion is a pointer to the base class sub-object of the
2569   //   derived class object. The null pointer value is converted to
2570   //   the null pointer value of the destination type.
2571   //
2572   // Note that we do not check for ambiguity or inaccessibility
2573   // here. That is handled by CheckPointerConversion.
2574   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2575       ToPointeeType->isRecordType() &&
2576       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2577       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2578     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2579                                                        ToPointeeType,
2580                                                        ToType, Context);
2581     return true;
2582   }
2583 
2584   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2585       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2586     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2587                                                        ToPointeeType,
2588                                                        ToType, Context);
2589     return true;
2590   }
2591 
2592   return false;
2593 }
2594 
2595 /// Adopt the given qualifiers for the given type.
2596 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2597   Qualifiers TQs = T.getQualifiers();
2598 
2599   // Check whether qualifiers already match.
2600   if (TQs == Qs)
2601     return T;
2602 
2603   if (Qs.compatiblyIncludes(TQs))
2604     return Context.getQualifiedType(T, Qs);
2605 
2606   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2607 }
2608 
2609 /// isObjCPointerConversion - Determines whether this is an
2610 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2611 /// with the same arguments and return values.
2612 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2613                                    QualType& ConvertedType,
2614                                    bool &IncompatibleObjC) {
2615   if (!getLangOpts().ObjC)
2616     return false;
2617 
2618   // The set of qualifiers on the type we're converting from.
2619   Qualifiers FromQualifiers = FromType.getQualifiers();
2620 
2621   // First, we handle all conversions on ObjC object pointer types.
2622   const ObjCObjectPointerType* ToObjCPtr =
2623     ToType->getAs<ObjCObjectPointerType>();
2624   const ObjCObjectPointerType *FromObjCPtr =
2625     FromType->getAs<ObjCObjectPointerType>();
2626 
2627   if (ToObjCPtr && FromObjCPtr) {
2628     // If the pointee types are the same (ignoring qualifications),
2629     // then this is not a pointer conversion.
2630     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2631                                        FromObjCPtr->getPointeeType()))
2632       return false;
2633 
2634     // Conversion between Objective-C pointers.
2635     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2636       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2637       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2638       if (getLangOpts().CPlusPlus && LHS && RHS &&
2639           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2640                                                 FromObjCPtr->getPointeeType()))
2641         return false;
2642       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2643                                                    ToObjCPtr->getPointeeType(),
2644                                                          ToType, Context);
2645       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2646       return true;
2647     }
2648 
2649     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2650       // Okay: this is some kind of implicit downcast of Objective-C
2651       // interfaces, which is permitted. However, we're going to
2652       // complain about it.
2653       IncompatibleObjC = true;
2654       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2655                                                    ToObjCPtr->getPointeeType(),
2656                                                          ToType, Context);
2657       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2658       return true;
2659     }
2660   }
2661   // Beyond this point, both types need to be C pointers or block pointers.
2662   QualType ToPointeeType;
2663   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2664     ToPointeeType = ToCPtr->getPointeeType();
2665   else if (const BlockPointerType *ToBlockPtr =
2666             ToType->getAs<BlockPointerType>()) {
2667     // Objective C++: We're able to convert from a pointer to any object
2668     // to a block pointer type.
2669     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2670       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2671       return true;
2672     }
2673     ToPointeeType = ToBlockPtr->getPointeeType();
2674   }
2675   else if (FromType->getAs<BlockPointerType>() &&
2676            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2677     // Objective C++: We're able to convert from a block pointer type to a
2678     // pointer to any object.
2679     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2680     return true;
2681   }
2682   else
2683     return false;
2684 
2685   QualType FromPointeeType;
2686   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2687     FromPointeeType = FromCPtr->getPointeeType();
2688   else if (const BlockPointerType *FromBlockPtr =
2689            FromType->getAs<BlockPointerType>())
2690     FromPointeeType = FromBlockPtr->getPointeeType();
2691   else
2692     return false;
2693 
2694   // If we have pointers to pointers, recursively check whether this
2695   // is an Objective-C conversion.
2696   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2697       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2698                               IncompatibleObjC)) {
2699     // We always complain about this conversion.
2700     IncompatibleObjC = true;
2701     ConvertedType = Context.getPointerType(ConvertedType);
2702     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2703     return true;
2704   }
2705   // Allow conversion of pointee being objective-c pointer to another one;
2706   // as in I* to id.
2707   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2708       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2709       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2710                               IncompatibleObjC)) {
2711 
2712     ConvertedType = Context.getPointerType(ConvertedType);
2713     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2714     return true;
2715   }
2716 
2717   // If we have pointers to functions or blocks, check whether the only
2718   // differences in the argument and result types are in Objective-C
2719   // pointer conversions. If so, we permit the conversion (but
2720   // complain about it).
2721   const FunctionProtoType *FromFunctionType
2722     = FromPointeeType->getAs<FunctionProtoType>();
2723   const FunctionProtoType *ToFunctionType
2724     = ToPointeeType->getAs<FunctionProtoType>();
2725   if (FromFunctionType && ToFunctionType) {
2726     // If the function types are exactly the same, this isn't an
2727     // Objective-C pointer conversion.
2728     if (Context.getCanonicalType(FromPointeeType)
2729           == Context.getCanonicalType(ToPointeeType))
2730       return false;
2731 
2732     // Perform the quick checks that will tell us whether these
2733     // function types are obviously different.
2734     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2735         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2736         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2737       return false;
2738 
2739     bool HasObjCConversion = false;
2740     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2741         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2742       // Okay, the types match exactly. Nothing to do.
2743     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2744                                        ToFunctionType->getReturnType(),
2745                                        ConvertedType, IncompatibleObjC)) {
2746       // Okay, we have an Objective-C pointer conversion.
2747       HasObjCConversion = true;
2748     } else {
2749       // Function types are too different. Abort.
2750       return false;
2751     }
2752 
2753     // Check argument types.
2754     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2755          ArgIdx != NumArgs; ++ArgIdx) {
2756       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2757       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2758       if (Context.getCanonicalType(FromArgType)
2759             == Context.getCanonicalType(ToArgType)) {
2760         // Okay, the types match exactly. Nothing to do.
2761       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2762                                          ConvertedType, IncompatibleObjC)) {
2763         // Okay, we have an Objective-C pointer conversion.
2764         HasObjCConversion = true;
2765       } else {
2766         // Argument types are too different. Abort.
2767         return false;
2768       }
2769     }
2770 
2771     if (HasObjCConversion) {
2772       // We had an Objective-C conversion. Allow this pointer
2773       // conversion, but complain about it.
2774       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2775       IncompatibleObjC = true;
2776       return true;
2777     }
2778   }
2779 
2780   return false;
2781 }
2782 
2783 /// Determine whether this is an Objective-C writeback conversion,
2784 /// used for parameter passing when performing automatic reference counting.
2785 ///
2786 /// \param FromType The type we're converting form.
2787 ///
2788 /// \param ToType The type we're converting to.
2789 ///
2790 /// \param ConvertedType The type that will be produced after applying
2791 /// this conversion.
2792 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2793                                      QualType &ConvertedType) {
2794   if (!getLangOpts().ObjCAutoRefCount ||
2795       Context.hasSameUnqualifiedType(FromType, ToType))
2796     return false;
2797 
2798   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2799   QualType ToPointee;
2800   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2801     ToPointee = ToPointer->getPointeeType();
2802   else
2803     return false;
2804 
2805   Qualifiers ToQuals = ToPointee.getQualifiers();
2806   if (!ToPointee->isObjCLifetimeType() ||
2807       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2808       !ToQuals.withoutObjCLifetime().empty())
2809     return false;
2810 
2811   // Argument must be a pointer to __strong to __weak.
2812   QualType FromPointee;
2813   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2814     FromPointee = FromPointer->getPointeeType();
2815   else
2816     return false;
2817 
2818   Qualifiers FromQuals = FromPointee.getQualifiers();
2819   if (!FromPointee->isObjCLifetimeType() ||
2820       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2821        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2822     return false;
2823 
2824   // Make sure that we have compatible qualifiers.
2825   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2826   if (!ToQuals.compatiblyIncludes(FromQuals))
2827     return false;
2828 
2829   // Remove qualifiers from the pointee type we're converting from; they
2830   // aren't used in the compatibility check belong, and we'll be adding back
2831   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2832   FromPointee = FromPointee.getUnqualifiedType();
2833 
2834   // The unqualified form of the pointee types must be compatible.
2835   ToPointee = ToPointee.getUnqualifiedType();
2836   bool IncompatibleObjC;
2837   if (Context.typesAreCompatible(FromPointee, ToPointee))
2838     FromPointee = ToPointee;
2839   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2840                                     IncompatibleObjC))
2841     return false;
2842 
2843   /// Construct the type we're converting to, which is a pointer to
2844   /// __autoreleasing pointee.
2845   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2846   ConvertedType = Context.getPointerType(FromPointee);
2847   return true;
2848 }
2849 
2850 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2851                                     QualType& ConvertedType) {
2852   QualType ToPointeeType;
2853   if (const BlockPointerType *ToBlockPtr =
2854         ToType->getAs<BlockPointerType>())
2855     ToPointeeType = ToBlockPtr->getPointeeType();
2856   else
2857     return false;
2858 
2859   QualType FromPointeeType;
2860   if (const BlockPointerType *FromBlockPtr =
2861       FromType->getAs<BlockPointerType>())
2862     FromPointeeType = FromBlockPtr->getPointeeType();
2863   else
2864     return false;
2865   // We have pointer to blocks, check whether the only
2866   // differences in the argument and result types are in Objective-C
2867   // pointer conversions. If so, we permit the conversion.
2868 
2869   const FunctionProtoType *FromFunctionType
2870     = FromPointeeType->getAs<FunctionProtoType>();
2871   const FunctionProtoType *ToFunctionType
2872     = ToPointeeType->getAs<FunctionProtoType>();
2873 
2874   if (!FromFunctionType || !ToFunctionType)
2875     return false;
2876 
2877   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2878     return true;
2879 
2880   // Perform the quick checks that will tell us whether these
2881   // function types are obviously different.
2882   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2883       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2884     return false;
2885 
2886   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2887   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2888   if (FromEInfo != ToEInfo)
2889     return false;
2890 
2891   bool IncompatibleObjC = false;
2892   if (Context.hasSameType(FromFunctionType->getReturnType(),
2893                           ToFunctionType->getReturnType())) {
2894     // Okay, the types match exactly. Nothing to do.
2895   } else {
2896     QualType RHS = FromFunctionType->getReturnType();
2897     QualType LHS = ToFunctionType->getReturnType();
2898     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2899         !RHS.hasQualifiers() && LHS.hasQualifiers())
2900        LHS = LHS.getUnqualifiedType();
2901 
2902      if (Context.hasSameType(RHS,LHS)) {
2903        // OK exact match.
2904      } else if (isObjCPointerConversion(RHS, LHS,
2905                                         ConvertedType, IncompatibleObjC)) {
2906      if (IncompatibleObjC)
2907        return false;
2908      // Okay, we have an Objective-C pointer conversion.
2909      }
2910      else
2911        return false;
2912    }
2913 
2914    // Check argument types.
2915    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2916         ArgIdx != NumArgs; ++ArgIdx) {
2917      IncompatibleObjC = false;
2918      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2919      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2920      if (Context.hasSameType(FromArgType, ToArgType)) {
2921        // Okay, the types match exactly. Nothing to do.
2922      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2923                                         ConvertedType, IncompatibleObjC)) {
2924        if (IncompatibleObjC)
2925          return false;
2926        // Okay, we have an Objective-C pointer conversion.
2927      } else
2928        // Argument types are too different. Abort.
2929        return false;
2930    }
2931 
2932    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2933    bool CanUseToFPT, CanUseFromFPT;
2934    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2935                                       CanUseToFPT, CanUseFromFPT,
2936                                       NewParamInfos))
2937      return false;
2938 
2939    ConvertedType = ToType;
2940    return true;
2941 }
2942 
2943 enum {
2944   ft_default,
2945   ft_different_class,
2946   ft_parameter_arity,
2947   ft_parameter_mismatch,
2948   ft_return_type,
2949   ft_qualifer_mismatch,
2950   ft_noexcept
2951 };
2952 
2953 /// Attempts to get the FunctionProtoType from a Type. Handles
2954 /// MemberFunctionPointers properly.
2955 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2956   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2957     return FPT;
2958 
2959   if (auto *MPT = FromType->getAs<MemberPointerType>())
2960     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2961 
2962   return nullptr;
2963 }
2964 
2965 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2966 /// function types.  Catches different number of parameter, mismatch in
2967 /// parameter types, and different return types.
2968 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2969                                       QualType FromType, QualType ToType) {
2970   // If either type is not valid, include no extra info.
2971   if (FromType.isNull() || ToType.isNull()) {
2972     PDiag << ft_default;
2973     return;
2974   }
2975 
2976   // Get the function type from the pointers.
2977   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2978     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2979                *ToMember = ToType->castAs<MemberPointerType>();
2980     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2981       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2982             << QualType(FromMember->getClass(), 0);
2983       return;
2984     }
2985     FromType = FromMember->getPointeeType();
2986     ToType = ToMember->getPointeeType();
2987   }
2988 
2989   if (FromType->isPointerType())
2990     FromType = FromType->getPointeeType();
2991   if (ToType->isPointerType())
2992     ToType = ToType->getPointeeType();
2993 
2994   // Remove references.
2995   FromType = FromType.getNonReferenceType();
2996   ToType = ToType.getNonReferenceType();
2997 
2998   // Don't print extra info for non-specialized template functions.
2999   if (FromType->isInstantiationDependentType() &&
3000       !FromType->getAs<TemplateSpecializationType>()) {
3001     PDiag << ft_default;
3002     return;
3003   }
3004 
3005   // No extra info for same types.
3006   if (Context.hasSameType(FromType, ToType)) {
3007     PDiag << ft_default;
3008     return;
3009   }
3010 
3011   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3012                           *ToFunction = tryGetFunctionProtoType(ToType);
3013 
3014   // Both types need to be function types.
3015   if (!FromFunction || !ToFunction) {
3016     PDiag << ft_default;
3017     return;
3018   }
3019 
3020   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3021     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3022           << FromFunction->getNumParams();
3023     return;
3024   }
3025 
3026   // Handle different parameter types.
3027   unsigned ArgPos;
3028   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3029     PDiag << ft_parameter_mismatch << ArgPos + 1
3030           << ToFunction->getParamType(ArgPos)
3031           << FromFunction->getParamType(ArgPos);
3032     return;
3033   }
3034 
3035   // Handle different return type.
3036   if (!Context.hasSameType(FromFunction->getReturnType(),
3037                            ToFunction->getReturnType())) {
3038     PDiag << ft_return_type << ToFunction->getReturnType()
3039           << FromFunction->getReturnType();
3040     return;
3041   }
3042 
3043   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3044     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3045           << FromFunction->getMethodQuals();
3046     return;
3047   }
3048 
3049   // Handle exception specification differences on canonical type (in C++17
3050   // onwards).
3051   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3052           ->isNothrow() !=
3053       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3054           ->isNothrow()) {
3055     PDiag << ft_noexcept;
3056     return;
3057   }
3058 
3059   // Unable to find a difference, so add no extra info.
3060   PDiag << ft_default;
3061 }
3062 
3063 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3064 /// for equality of their parameter types. Caller has already checked that
3065 /// they have same number of parameters.  If the parameters are different,
3066 /// ArgPos will have the parameter index of the first different parameter.
3067 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3068 /// reverse order. That's useful if one of the functions is being used as a C++20
3069 /// synthesized operator overload with a reversed parameter order.
3070 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3071                                       const FunctionProtoType *NewType,
3072                                       unsigned *ArgPos, bool Reversed) {
3073   assert(OldType->getNumParams() == NewType->getNumParams() &&
3074          "Can't compare parameters of functions with different number of "
3075          "parameters!");
3076   for (size_t I = 0; I < OldType->getNumParams(); I++) {
3077     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3078     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
3079 
3080     // Ignore address spaces in pointee type. This is to disallow overloading
3081     // on __ptr32/__ptr64 address spaces.
3082     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
3083     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
3084 
3085     if (!Context.hasSameType(Old, New)) {
3086       if (ArgPos)
3087         *ArgPos = I;
3088       return false;
3089     }
3090   }
3091   return true;
3092 }
3093 
3094 /// CheckPointerConversion - Check the pointer conversion from the
3095 /// expression From to the type ToType. This routine checks for
3096 /// ambiguous or inaccessible derived-to-base pointer
3097 /// conversions for which IsPointerConversion has already returned
3098 /// true. It returns true and produces a diagnostic if there was an
3099 /// error, or returns false otherwise.
3100 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3101                                   CastKind &Kind,
3102                                   CXXCastPath& BasePath,
3103                                   bool IgnoreBaseAccess,
3104                                   bool Diagnose) {
3105   QualType FromType = From->getType();
3106   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3107 
3108   Kind = CK_BitCast;
3109 
3110   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3111       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3112           Expr::NPCK_ZeroExpression) {
3113     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3114       DiagRuntimeBehavior(From->getExprLoc(), From,
3115                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3116                             << ToType << From->getSourceRange());
3117     else if (!isUnevaluatedContext())
3118       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3119         << ToType << From->getSourceRange();
3120   }
3121   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3122     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3123       QualType FromPointeeType = FromPtrType->getPointeeType(),
3124                ToPointeeType   = ToPtrType->getPointeeType();
3125 
3126       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3127           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3128         // We must have a derived-to-base conversion. Check an
3129         // ambiguous or inaccessible conversion.
3130         unsigned InaccessibleID = 0;
3131         unsigned AmbiguousID = 0;
3132         if (Diagnose) {
3133           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3134           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3135         }
3136         if (CheckDerivedToBaseConversion(
3137                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3138                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3139                 &BasePath, IgnoreBaseAccess))
3140           return true;
3141 
3142         // The conversion was successful.
3143         Kind = CK_DerivedToBase;
3144       }
3145 
3146       if (Diagnose && !IsCStyleOrFunctionalCast &&
3147           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3148         assert(getLangOpts().MSVCCompat &&
3149                "this should only be possible with MSVCCompat!");
3150         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3151             << From->getSourceRange();
3152       }
3153     }
3154   } else if (const ObjCObjectPointerType *ToPtrType =
3155                ToType->getAs<ObjCObjectPointerType>()) {
3156     if (const ObjCObjectPointerType *FromPtrType =
3157           FromType->getAs<ObjCObjectPointerType>()) {
3158       // Objective-C++ conversions are always okay.
3159       // FIXME: We should have a different class of conversions for the
3160       // Objective-C++ implicit conversions.
3161       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3162         return false;
3163     } else if (FromType->isBlockPointerType()) {
3164       Kind = CK_BlockPointerToObjCPointerCast;
3165     } else {
3166       Kind = CK_CPointerToObjCPointerCast;
3167     }
3168   } else if (ToType->isBlockPointerType()) {
3169     if (!FromType->isBlockPointerType())
3170       Kind = CK_AnyPointerToBlockPointerCast;
3171   }
3172 
3173   // We shouldn't fall into this case unless it's valid for other
3174   // reasons.
3175   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3176     Kind = CK_NullToPointer;
3177 
3178   return false;
3179 }
3180 
3181 /// IsMemberPointerConversion - Determines whether the conversion of the
3182 /// expression From, which has the (possibly adjusted) type FromType, can be
3183 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3184 /// If so, returns true and places the converted type (that might differ from
3185 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3186 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3187                                      QualType ToType,
3188                                      bool InOverloadResolution,
3189                                      QualType &ConvertedType) {
3190   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3191   if (!ToTypePtr)
3192     return false;
3193 
3194   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3195   if (From->isNullPointerConstant(Context,
3196                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3197                                         : Expr::NPC_ValueDependentIsNull)) {
3198     ConvertedType = ToType;
3199     return true;
3200   }
3201 
3202   // Otherwise, both types have to be member pointers.
3203   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3204   if (!FromTypePtr)
3205     return false;
3206 
3207   // A pointer to member of B can be converted to a pointer to member of D,
3208   // where D is derived from B (C++ 4.11p2).
3209   QualType FromClass(FromTypePtr->getClass(), 0);
3210   QualType ToClass(ToTypePtr->getClass(), 0);
3211 
3212   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3213       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3214     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3215                                                  ToClass.getTypePtr());
3216     return true;
3217   }
3218 
3219   return false;
3220 }
3221 
3222 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3223 /// expression From to the type ToType. This routine checks for ambiguous or
3224 /// virtual or inaccessible base-to-derived member pointer conversions
3225 /// for which IsMemberPointerConversion has already returned true. It returns
3226 /// true and produces a diagnostic if there was an error, or returns false
3227 /// otherwise.
3228 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3229                                         CastKind &Kind,
3230                                         CXXCastPath &BasePath,
3231                                         bool IgnoreBaseAccess) {
3232   QualType FromType = From->getType();
3233   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3234   if (!FromPtrType) {
3235     // This must be a null pointer to member pointer conversion
3236     assert(From->isNullPointerConstant(Context,
3237                                        Expr::NPC_ValueDependentIsNull) &&
3238            "Expr must be null pointer constant!");
3239     Kind = CK_NullToMemberPointer;
3240     return false;
3241   }
3242 
3243   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3244   assert(ToPtrType && "No member pointer cast has a target type "
3245                       "that is not a member pointer.");
3246 
3247   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3248   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3249 
3250   // FIXME: What about dependent types?
3251   assert(FromClass->isRecordType() && "Pointer into non-class.");
3252   assert(ToClass->isRecordType() && "Pointer into non-class.");
3253 
3254   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3255                      /*DetectVirtual=*/true);
3256   bool DerivationOkay =
3257       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3258   assert(DerivationOkay &&
3259          "Should not have been called if derivation isn't OK.");
3260   (void)DerivationOkay;
3261 
3262   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3263                                   getUnqualifiedType())) {
3264     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3265     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3266       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3267     return true;
3268   }
3269 
3270   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3271     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3272       << FromClass << ToClass << QualType(VBase, 0)
3273       << From->getSourceRange();
3274     return true;
3275   }
3276 
3277   if (!IgnoreBaseAccess)
3278     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3279                          Paths.front(),
3280                          diag::err_downcast_from_inaccessible_base);
3281 
3282   // Must be a base to derived member conversion.
3283   BuildBasePathArray(Paths, BasePath);
3284   Kind = CK_BaseToDerivedMemberPointer;
3285   return false;
3286 }
3287 
3288 /// Determine whether the lifetime conversion between the two given
3289 /// qualifiers sets is nontrivial.
3290 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3291                                                Qualifiers ToQuals) {
3292   // Converting anything to const __unsafe_unretained is trivial.
3293   if (ToQuals.hasConst() &&
3294       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3295     return false;
3296 
3297   return true;
3298 }
3299 
3300 /// Perform a single iteration of the loop for checking if a qualification
3301 /// conversion is valid.
3302 ///
3303 /// Specifically, check whether any change between the qualifiers of \p
3304 /// FromType and \p ToType is permissible, given knowledge about whether every
3305 /// outer layer is const-qualified.
3306 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3307                                           bool CStyle, bool IsTopLevel,
3308                                           bool &PreviousToQualsIncludeConst,
3309                                           bool &ObjCLifetimeConversion) {
3310   Qualifiers FromQuals = FromType.getQualifiers();
3311   Qualifiers ToQuals = ToType.getQualifiers();
3312 
3313   // Ignore __unaligned qualifier.
3314   FromQuals.removeUnaligned();
3315 
3316   // Objective-C ARC:
3317   //   Check Objective-C lifetime conversions.
3318   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3319     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3320       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3321         ObjCLifetimeConversion = true;
3322       FromQuals.removeObjCLifetime();
3323       ToQuals.removeObjCLifetime();
3324     } else {
3325       // Qualification conversions cannot cast between different
3326       // Objective-C lifetime qualifiers.
3327       return false;
3328     }
3329   }
3330 
3331   // Allow addition/removal of GC attributes but not changing GC attributes.
3332   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3333       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3334     FromQuals.removeObjCGCAttr();
3335     ToQuals.removeObjCGCAttr();
3336   }
3337 
3338   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3339   //      2,j, and similarly for volatile.
3340   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3341     return false;
3342 
3343   // If address spaces mismatch:
3344   //  - in top level it is only valid to convert to addr space that is a
3345   //    superset in all cases apart from C-style casts where we allow
3346   //    conversions between overlapping address spaces.
3347   //  - in non-top levels it is not a valid conversion.
3348   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3349       (!IsTopLevel ||
3350        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3351          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3352     return false;
3353 
3354   //   -- if the cv 1,j and cv 2,j are different, then const is in
3355   //      every cv for 0 < k < j.
3356   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3357       !PreviousToQualsIncludeConst)
3358     return false;
3359 
3360   // The following wording is from C++20, where the result of the conversion
3361   // is T3, not T2.
3362   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3363   //      "array of unknown bound of"
3364   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3365     return false;
3366 
3367   //   -- if the resulting P3,i is different from P1,i [...], then const is
3368   //      added to every cv 3_k for 0 < k < i.
3369   if (!CStyle && FromType->isConstantArrayType() &&
3370       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3371     return false;
3372 
3373   // Keep track of whether all prior cv-qualifiers in the "to" type
3374   // include const.
3375   PreviousToQualsIncludeConst =
3376       PreviousToQualsIncludeConst && ToQuals.hasConst();
3377   return true;
3378 }
3379 
3380 /// IsQualificationConversion - Determines whether the conversion from
3381 /// an rvalue of type FromType to ToType is a qualification conversion
3382 /// (C++ 4.4).
3383 ///
3384 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3385 /// when the qualification conversion involves a change in the Objective-C
3386 /// object lifetime.
3387 bool
3388 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3389                                 bool CStyle, bool &ObjCLifetimeConversion) {
3390   FromType = Context.getCanonicalType(FromType);
3391   ToType = Context.getCanonicalType(ToType);
3392   ObjCLifetimeConversion = false;
3393 
3394   // If FromType and ToType are the same type, this is not a
3395   // qualification conversion.
3396   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3397     return false;
3398 
3399   // (C++ 4.4p4):
3400   //   A conversion can add cv-qualifiers at levels other than the first
3401   //   in multi-level pointers, subject to the following rules: [...]
3402   bool PreviousToQualsIncludeConst = true;
3403   bool UnwrappedAnyPointer = false;
3404   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3405     if (!isQualificationConversionStep(
3406             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3407             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3408       return false;
3409     UnwrappedAnyPointer = true;
3410   }
3411 
3412   // We are left with FromType and ToType being the pointee types
3413   // after unwrapping the original FromType and ToType the same number
3414   // of times. If we unwrapped any pointers, and if FromType and
3415   // ToType have the same unqualified type (since we checked
3416   // qualifiers above), then this is a qualification conversion.
3417   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3418 }
3419 
3420 /// - Determine whether this is a conversion from a scalar type to an
3421 /// atomic type.
3422 ///
3423 /// If successful, updates \c SCS's second and third steps in the conversion
3424 /// sequence to finish the conversion.
3425 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3426                                 bool InOverloadResolution,
3427                                 StandardConversionSequence &SCS,
3428                                 bool CStyle) {
3429   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3430   if (!ToAtomic)
3431     return false;
3432 
3433   StandardConversionSequence InnerSCS;
3434   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3435                             InOverloadResolution, InnerSCS,
3436                             CStyle, /*AllowObjCWritebackConversion=*/false))
3437     return false;
3438 
3439   SCS.Second = InnerSCS.Second;
3440   SCS.setToType(1, InnerSCS.getToType(1));
3441   SCS.Third = InnerSCS.Third;
3442   SCS.QualificationIncludesObjCLifetime
3443     = InnerSCS.QualificationIncludesObjCLifetime;
3444   SCS.setToType(2, InnerSCS.getToType(2));
3445   return true;
3446 }
3447 
3448 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3449                                               CXXConstructorDecl *Constructor,
3450                                               QualType Type) {
3451   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3452   if (CtorType->getNumParams() > 0) {
3453     QualType FirstArg = CtorType->getParamType(0);
3454     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3455       return true;
3456   }
3457   return false;
3458 }
3459 
3460 static OverloadingResult
3461 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3462                                        CXXRecordDecl *To,
3463                                        UserDefinedConversionSequence &User,
3464                                        OverloadCandidateSet &CandidateSet,
3465                                        bool AllowExplicit) {
3466   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3467   for (auto *D : S.LookupConstructors(To)) {
3468     auto Info = getConstructorInfo(D);
3469     if (!Info)
3470       continue;
3471 
3472     bool Usable = !Info.Constructor->isInvalidDecl() &&
3473                   S.isInitListConstructor(Info.Constructor);
3474     if (Usable) {
3475       bool SuppressUserConversions = false;
3476       if (Info.ConstructorTmpl)
3477         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3478                                        /*ExplicitArgs*/ nullptr, From,
3479                                        CandidateSet, SuppressUserConversions,
3480                                        /*PartialOverloading*/ false,
3481                                        AllowExplicit);
3482       else
3483         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3484                                CandidateSet, SuppressUserConversions,
3485                                /*PartialOverloading*/ false, AllowExplicit);
3486     }
3487   }
3488 
3489   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3490 
3491   OverloadCandidateSet::iterator Best;
3492   switch (auto Result =
3493               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3494   case OR_Deleted:
3495   case OR_Success: {
3496     // Record the standard conversion we used and the conversion function.
3497     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3498     QualType ThisType = Constructor->getThisType();
3499     // Initializer lists don't have conversions as such.
3500     User.Before.setAsIdentityConversion();
3501     User.HadMultipleCandidates = HadMultipleCandidates;
3502     User.ConversionFunction = Constructor;
3503     User.FoundConversionFunction = Best->FoundDecl;
3504     User.After.setAsIdentityConversion();
3505     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3506     User.After.setAllToTypes(ToType);
3507     return Result;
3508   }
3509 
3510   case OR_No_Viable_Function:
3511     return OR_No_Viable_Function;
3512   case OR_Ambiguous:
3513     return OR_Ambiguous;
3514   }
3515 
3516   llvm_unreachable("Invalid OverloadResult!");
3517 }
3518 
3519 /// Determines whether there is a user-defined conversion sequence
3520 /// (C++ [over.ics.user]) that converts expression From to the type
3521 /// ToType. If such a conversion exists, User will contain the
3522 /// user-defined conversion sequence that performs such a conversion
3523 /// and this routine will return true. Otherwise, this routine returns
3524 /// false and User is unspecified.
3525 ///
3526 /// \param AllowExplicit  true if the conversion should consider C++0x
3527 /// "explicit" conversion functions as well as non-explicit conversion
3528 /// functions (C++0x [class.conv.fct]p2).
3529 ///
3530 /// \param AllowObjCConversionOnExplicit true if the conversion should
3531 /// allow an extra Objective-C pointer conversion on uses of explicit
3532 /// constructors. Requires \c AllowExplicit to also be set.
3533 static OverloadingResult
3534 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3535                         UserDefinedConversionSequence &User,
3536                         OverloadCandidateSet &CandidateSet,
3537                         AllowedExplicit AllowExplicit,
3538                         bool AllowObjCConversionOnExplicit) {
3539   assert(AllowExplicit != AllowedExplicit::None ||
3540          !AllowObjCConversionOnExplicit);
3541   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3542 
3543   // Whether we will only visit constructors.
3544   bool ConstructorsOnly = false;
3545 
3546   // If the type we are conversion to is a class type, enumerate its
3547   // constructors.
3548   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3549     // C++ [over.match.ctor]p1:
3550     //   When objects of class type are direct-initialized (8.5), or
3551     //   copy-initialized from an expression of the same or a
3552     //   derived class type (8.5), overload resolution selects the
3553     //   constructor. [...] For copy-initialization, the candidate
3554     //   functions are all the converting constructors (12.3.1) of
3555     //   that class. The argument list is the expression-list within
3556     //   the parentheses of the initializer.
3557     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3558         (From->getType()->getAs<RecordType>() &&
3559          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3560       ConstructorsOnly = true;
3561 
3562     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3563       // We're not going to find any constructors.
3564     } else if (CXXRecordDecl *ToRecordDecl
3565                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3566 
3567       Expr **Args = &From;
3568       unsigned NumArgs = 1;
3569       bool ListInitializing = false;
3570       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3571         // But first, see if there is an init-list-constructor that will work.
3572         OverloadingResult Result = IsInitializerListConstructorConversion(
3573             S, From, ToType, ToRecordDecl, User, CandidateSet,
3574             AllowExplicit == AllowedExplicit::All);
3575         if (Result != OR_No_Viable_Function)
3576           return Result;
3577         // Never mind.
3578         CandidateSet.clear(
3579             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3580 
3581         // If we're list-initializing, we pass the individual elements as
3582         // arguments, not the entire list.
3583         Args = InitList->getInits();
3584         NumArgs = InitList->getNumInits();
3585         ListInitializing = true;
3586       }
3587 
3588       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3589         auto Info = getConstructorInfo(D);
3590         if (!Info)
3591           continue;
3592 
3593         bool Usable = !Info.Constructor->isInvalidDecl();
3594         if (!ListInitializing)
3595           Usable = Usable && Info.Constructor->isConvertingConstructor(
3596                                  /*AllowExplicit*/ true);
3597         if (Usable) {
3598           bool SuppressUserConversions = !ConstructorsOnly;
3599           // C++20 [over.best.ics.general]/4.5:
3600           //   if the target is the first parameter of a constructor [of class
3601           //   X] and the constructor [...] is a candidate by [...] the second
3602           //   phase of [over.match.list] when the initializer list has exactly
3603           //   one element that is itself an initializer list, [...] and the
3604           //   conversion is to X or reference to cv X, user-defined conversion
3605           //   sequences are not cnosidered.
3606           if (SuppressUserConversions && ListInitializing) {
3607             SuppressUserConversions =
3608                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3609                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3610                                                   ToType);
3611           }
3612           if (Info.ConstructorTmpl)
3613             S.AddTemplateOverloadCandidate(
3614                 Info.ConstructorTmpl, Info.FoundDecl,
3615                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3616                 CandidateSet, SuppressUserConversions,
3617                 /*PartialOverloading*/ false,
3618                 AllowExplicit == AllowedExplicit::All);
3619           else
3620             // Allow one user-defined conversion when user specifies a
3621             // From->ToType conversion via an static cast (c-style, etc).
3622             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3623                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
3624                                    SuppressUserConversions,
3625                                    /*PartialOverloading*/ false,
3626                                    AllowExplicit == AllowedExplicit::All);
3627         }
3628       }
3629     }
3630   }
3631 
3632   // Enumerate conversion functions, if we're allowed to.
3633   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3634   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3635     // No conversion functions from incomplete types.
3636   } else if (const RecordType *FromRecordType =
3637                  From->getType()->getAs<RecordType>()) {
3638     if (CXXRecordDecl *FromRecordDecl
3639          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3640       // Add all of the conversion functions as candidates.
3641       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3642       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3643         DeclAccessPair FoundDecl = I.getPair();
3644         NamedDecl *D = FoundDecl.getDecl();
3645         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3646         if (isa<UsingShadowDecl>(D))
3647           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3648 
3649         CXXConversionDecl *Conv;
3650         FunctionTemplateDecl *ConvTemplate;
3651         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3652           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3653         else
3654           Conv = cast<CXXConversionDecl>(D);
3655 
3656         if (ConvTemplate)
3657           S.AddTemplateConversionCandidate(
3658               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3659               CandidateSet, AllowObjCConversionOnExplicit,
3660               AllowExplicit != AllowedExplicit::None);
3661         else
3662           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3663                                    CandidateSet, AllowObjCConversionOnExplicit,
3664                                    AllowExplicit != AllowedExplicit::None);
3665       }
3666     }
3667   }
3668 
3669   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3670 
3671   OverloadCandidateSet::iterator Best;
3672   switch (auto Result =
3673               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3674   case OR_Success:
3675   case OR_Deleted:
3676     // Record the standard conversion we used and the conversion function.
3677     if (CXXConstructorDecl *Constructor
3678           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3679       // C++ [over.ics.user]p1:
3680       //   If the user-defined conversion is specified by a
3681       //   constructor (12.3.1), the initial standard conversion
3682       //   sequence converts the source type to the type required by
3683       //   the argument of the constructor.
3684       //
3685       QualType ThisType = Constructor->getThisType();
3686       if (isa<InitListExpr>(From)) {
3687         // Initializer lists don't have conversions as such.
3688         User.Before.setAsIdentityConversion();
3689       } else {
3690         if (Best->Conversions[0].isEllipsis())
3691           User.EllipsisConversion = true;
3692         else {
3693           User.Before = Best->Conversions[0].Standard;
3694           User.EllipsisConversion = false;
3695         }
3696       }
3697       User.HadMultipleCandidates = HadMultipleCandidates;
3698       User.ConversionFunction = Constructor;
3699       User.FoundConversionFunction = Best->FoundDecl;
3700       User.After.setAsIdentityConversion();
3701       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3702       User.After.setAllToTypes(ToType);
3703       return Result;
3704     }
3705     if (CXXConversionDecl *Conversion
3706                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3707       // C++ [over.ics.user]p1:
3708       //
3709       //   [...] If the user-defined conversion is specified by a
3710       //   conversion function (12.3.2), the initial standard
3711       //   conversion sequence converts the source type to the
3712       //   implicit object parameter of the conversion function.
3713       User.Before = Best->Conversions[0].Standard;
3714       User.HadMultipleCandidates = HadMultipleCandidates;
3715       User.ConversionFunction = Conversion;
3716       User.FoundConversionFunction = Best->FoundDecl;
3717       User.EllipsisConversion = false;
3718 
3719       // C++ [over.ics.user]p2:
3720       //   The second standard conversion sequence converts the
3721       //   result of the user-defined conversion to the target type
3722       //   for the sequence. Since an implicit conversion sequence
3723       //   is an initialization, the special rules for
3724       //   initialization by user-defined conversion apply when
3725       //   selecting the best user-defined conversion for a
3726       //   user-defined conversion sequence (see 13.3.3 and
3727       //   13.3.3.1).
3728       User.After = Best->FinalConversion;
3729       return Result;
3730     }
3731     llvm_unreachable("Not a constructor or conversion function?");
3732 
3733   case OR_No_Viable_Function:
3734     return OR_No_Viable_Function;
3735 
3736   case OR_Ambiguous:
3737     return OR_Ambiguous;
3738   }
3739 
3740   llvm_unreachable("Invalid OverloadResult!");
3741 }
3742 
3743 bool
3744 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3745   ImplicitConversionSequence ICS;
3746   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3747                                     OverloadCandidateSet::CSK_Normal);
3748   OverloadingResult OvResult =
3749     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3750                             CandidateSet, AllowedExplicit::None, false);
3751 
3752   if (!(OvResult == OR_Ambiguous ||
3753         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3754     return false;
3755 
3756   auto Cands = CandidateSet.CompleteCandidates(
3757       *this,
3758       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3759       From);
3760   if (OvResult == OR_Ambiguous)
3761     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3762         << From->getType() << ToType << From->getSourceRange();
3763   else { // OR_No_Viable_Function && !CandidateSet.empty()
3764     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3765                              diag::err_typecheck_nonviable_condition_incomplete,
3766                              From->getType(), From->getSourceRange()))
3767       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3768           << false << From->getType() << From->getSourceRange() << ToType;
3769   }
3770 
3771   CandidateSet.NoteCandidates(
3772                               *this, From, Cands);
3773   return true;
3774 }
3775 
3776 // Helper for compareConversionFunctions that gets the FunctionType that the
3777 // conversion-operator return  value 'points' to, or nullptr.
3778 static const FunctionType *
3779 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3780   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3781   const PointerType *RetPtrTy =
3782       ConvFuncTy->getReturnType()->getAs<PointerType>();
3783 
3784   if (!RetPtrTy)
3785     return nullptr;
3786 
3787   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3788 }
3789 
3790 /// Compare the user-defined conversion functions or constructors
3791 /// of two user-defined conversion sequences to determine whether any ordering
3792 /// is possible.
3793 static ImplicitConversionSequence::CompareKind
3794 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3795                            FunctionDecl *Function2) {
3796   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3797   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3798   if (!Conv1 || !Conv2)
3799     return ImplicitConversionSequence::Indistinguishable;
3800 
3801   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3802     return ImplicitConversionSequence::Indistinguishable;
3803 
3804   // Objective-C++:
3805   //   If both conversion functions are implicitly-declared conversions from
3806   //   a lambda closure type to a function pointer and a block pointer,
3807   //   respectively, always prefer the conversion to a function pointer,
3808   //   because the function pointer is more lightweight and is more likely
3809   //   to keep code working.
3810   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3811     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3812     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3813     if (Block1 != Block2)
3814       return Block1 ? ImplicitConversionSequence::Worse
3815                     : ImplicitConversionSequence::Better;
3816   }
3817 
3818   // In order to support multiple calling conventions for the lambda conversion
3819   // operator (such as when the free and member function calling convention is
3820   // different), prefer the 'free' mechanism, followed by the calling-convention
3821   // of operator(). The latter is in place to support the MSVC-like solution of
3822   // defining ALL of the possible conversions in regards to calling-convention.
3823   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3824   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3825 
3826   if (Conv1FuncRet && Conv2FuncRet &&
3827       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3828     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3829     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3830 
3831     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3832     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3833 
3834     CallingConv CallOpCC =
3835         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3836     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3837         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3838     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3839         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3840 
3841     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3842     for (CallingConv CC : PrefOrder) {
3843       if (Conv1CC == CC)
3844         return ImplicitConversionSequence::Better;
3845       if (Conv2CC == CC)
3846         return ImplicitConversionSequence::Worse;
3847     }
3848   }
3849 
3850   return ImplicitConversionSequence::Indistinguishable;
3851 }
3852 
3853 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3854     const ImplicitConversionSequence &ICS) {
3855   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3856          (ICS.isUserDefined() &&
3857           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3858 }
3859 
3860 /// CompareImplicitConversionSequences - Compare two implicit
3861 /// conversion sequences to determine whether one is better than the
3862 /// other or if they are indistinguishable (C++ 13.3.3.2).
3863 static ImplicitConversionSequence::CompareKind
3864 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3865                                    const ImplicitConversionSequence& ICS1,
3866                                    const ImplicitConversionSequence& ICS2)
3867 {
3868   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3869   // conversion sequences (as defined in 13.3.3.1)
3870   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3871   //      conversion sequence than a user-defined conversion sequence or
3872   //      an ellipsis conversion sequence, and
3873   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3874   //      conversion sequence than an ellipsis conversion sequence
3875   //      (13.3.3.1.3).
3876   //
3877   // C++0x [over.best.ics]p10:
3878   //   For the purpose of ranking implicit conversion sequences as
3879   //   described in 13.3.3.2, the ambiguous conversion sequence is
3880   //   treated as a user-defined sequence that is indistinguishable
3881   //   from any other user-defined conversion sequence.
3882 
3883   // String literal to 'char *' conversion has been deprecated in C++03. It has
3884   // been removed from C++11. We still accept this conversion, if it happens at
3885   // the best viable function. Otherwise, this conversion is considered worse
3886   // than ellipsis conversion. Consider this as an extension; this is not in the
3887   // standard. For example:
3888   //
3889   // int &f(...);    // #1
3890   // void f(char*);  // #2
3891   // void g() { int &r = f("foo"); }
3892   //
3893   // In C++03, we pick #2 as the best viable function.
3894   // In C++11, we pick #1 as the best viable function, because ellipsis
3895   // conversion is better than string-literal to char* conversion (since there
3896   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3897   // convert arguments, #2 would be the best viable function in C++11.
3898   // If the best viable function has this conversion, a warning will be issued
3899   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3900 
3901   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3902       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3903           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3904       // Ill-formedness must not differ
3905       ICS1.isBad() == ICS2.isBad())
3906     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3907                ? ImplicitConversionSequence::Worse
3908                : ImplicitConversionSequence::Better;
3909 
3910   if (ICS1.getKindRank() < ICS2.getKindRank())
3911     return ImplicitConversionSequence::Better;
3912   if (ICS2.getKindRank() < ICS1.getKindRank())
3913     return ImplicitConversionSequence::Worse;
3914 
3915   // The following checks require both conversion sequences to be of
3916   // the same kind.
3917   if (ICS1.getKind() != ICS2.getKind())
3918     return ImplicitConversionSequence::Indistinguishable;
3919 
3920   ImplicitConversionSequence::CompareKind Result =
3921       ImplicitConversionSequence::Indistinguishable;
3922 
3923   // Two implicit conversion sequences of the same form are
3924   // indistinguishable conversion sequences unless one of the
3925   // following rules apply: (C++ 13.3.3.2p3):
3926 
3927   // List-initialization sequence L1 is a better conversion sequence than
3928   // list-initialization sequence L2 if:
3929   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3930   //   if not that,
3931   // — L1 and L2 convert to arrays of the same element type, and either the
3932   //   number of elements n_1 initialized by L1 is less than the number of
3933   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3934   //   an array of unknown bound and L1 does not,
3935   // even if one of the other rules in this paragraph would otherwise apply.
3936   if (!ICS1.isBad()) {
3937     bool StdInit1 = false, StdInit2 = false;
3938     if (ICS1.hasInitializerListContainerType())
3939       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3940                                         nullptr);
3941     if (ICS2.hasInitializerListContainerType())
3942       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3943                                         nullptr);
3944     if (StdInit1 != StdInit2)
3945       return StdInit1 ? ImplicitConversionSequence::Better
3946                       : ImplicitConversionSequence::Worse;
3947 
3948     if (ICS1.hasInitializerListContainerType() &&
3949         ICS2.hasInitializerListContainerType())
3950       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3951               ICS1.getInitializerListContainerType()))
3952         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3953                 ICS2.getInitializerListContainerType())) {
3954           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3955                                                CAT2->getElementType())) {
3956             // Both to arrays of the same element type
3957             if (CAT1->getSize() != CAT2->getSize())
3958               // Different sized, the smaller wins
3959               return CAT1->getSize().ult(CAT2->getSize())
3960                          ? ImplicitConversionSequence::Better
3961                          : ImplicitConversionSequence::Worse;
3962             if (ICS1.isInitializerListOfIncompleteArray() !=
3963                 ICS2.isInitializerListOfIncompleteArray())
3964               // One is incomplete, it loses
3965               return ICS2.isInitializerListOfIncompleteArray()
3966                          ? ImplicitConversionSequence::Better
3967                          : ImplicitConversionSequence::Worse;
3968           }
3969         }
3970   }
3971 
3972   if (ICS1.isStandard())
3973     // Standard conversion sequence S1 is a better conversion sequence than
3974     // standard conversion sequence S2 if [...]
3975     Result = CompareStandardConversionSequences(S, Loc,
3976                                                 ICS1.Standard, ICS2.Standard);
3977   else if (ICS1.isUserDefined()) {
3978     // User-defined conversion sequence U1 is a better conversion
3979     // sequence than another user-defined conversion sequence U2 if
3980     // they contain the same user-defined conversion function or
3981     // constructor and if the second standard conversion sequence of
3982     // U1 is better than the second standard conversion sequence of
3983     // U2 (C++ 13.3.3.2p3).
3984     if (ICS1.UserDefined.ConversionFunction ==
3985           ICS2.UserDefined.ConversionFunction)
3986       Result = CompareStandardConversionSequences(S, Loc,
3987                                                   ICS1.UserDefined.After,
3988                                                   ICS2.UserDefined.After);
3989     else
3990       Result = compareConversionFunctions(S,
3991                                           ICS1.UserDefined.ConversionFunction,
3992                                           ICS2.UserDefined.ConversionFunction);
3993   }
3994 
3995   return Result;
3996 }
3997 
3998 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3999 // determine if one is a proper subset of the other.
4000 static ImplicitConversionSequence::CompareKind
4001 compareStandardConversionSubsets(ASTContext &Context,
4002                                  const StandardConversionSequence& SCS1,
4003                                  const StandardConversionSequence& SCS2) {
4004   ImplicitConversionSequence::CompareKind Result
4005     = ImplicitConversionSequence::Indistinguishable;
4006 
4007   // the identity conversion sequence is considered to be a subsequence of
4008   // any non-identity conversion sequence
4009   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4010     return ImplicitConversionSequence::Better;
4011   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4012     return ImplicitConversionSequence::Worse;
4013 
4014   if (SCS1.Second != SCS2.Second) {
4015     if (SCS1.Second == ICK_Identity)
4016       Result = ImplicitConversionSequence::Better;
4017     else if (SCS2.Second == ICK_Identity)
4018       Result = ImplicitConversionSequence::Worse;
4019     else
4020       return ImplicitConversionSequence::Indistinguishable;
4021   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4022     return ImplicitConversionSequence::Indistinguishable;
4023 
4024   if (SCS1.Third == SCS2.Third) {
4025     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4026                              : ImplicitConversionSequence::Indistinguishable;
4027   }
4028 
4029   if (SCS1.Third == ICK_Identity)
4030     return Result == ImplicitConversionSequence::Worse
4031              ? ImplicitConversionSequence::Indistinguishable
4032              : ImplicitConversionSequence::Better;
4033 
4034   if (SCS2.Third == ICK_Identity)
4035     return Result == ImplicitConversionSequence::Better
4036              ? ImplicitConversionSequence::Indistinguishable
4037              : ImplicitConversionSequence::Worse;
4038 
4039   return ImplicitConversionSequence::Indistinguishable;
4040 }
4041 
4042 /// Determine whether one of the given reference bindings is better
4043 /// than the other based on what kind of bindings they are.
4044 static bool
4045 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4046                              const StandardConversionSequence &SCS2) {
4047   // C++0x [over.ics.rank]p3b4:
4048   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4049   //      implicit object parameter of a non-static member function declared
4050   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4051   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4052   //      lvalue reference to a function lvalue and S2 binds an rvalue
4053   //      reference*.
4054   //
4055   // FIXME: Rvalue references. We're going rogue with the above edits,
4056   // because the semantics in the current C++0x working paper (N3225 at the
4057   // time of this writing) break the standard definition of std::forward
4058   // and std::reference_wrapper when dealing with references to functions.
4059   // Proposed wording changes submitted to CWG for consideration.
4060   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4061       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4062     return false;
4063 
4064   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4065           SCS2.IsLvalueReference) ||
4066          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4067           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4068 }
4069 
4070 enum class FixedEnumPromotion {
4071   None,
4072   ToUnderlyingType,
4073   ToPromotedUnderlyingType
4074 };
4075 
4076 /// Returns kind of fixed enum promotion the \a SCS uses.
4077 static FixedEnumPromotion
4078 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4079 
4080   if (SCS.Second != ICK_Integral_Promotion)
4081     return FixedEnumPromotion::None;
4082 
4083   QualType FromType = SCS.getFromType();
4084   if (!FromType->isEnumeralType())
4085     return FixedEnumPromotion::None;
4086 
4087   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4088   if (!Enum->isFixed())
4089     return FixedEnumPromotion::None;
4090 
4091   QualType UnderlyingType = Enum->getIntegerType();
4092   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4093     return FixedEnumPromotion::ToUnderlyingType;
4094 
4095   return FixedEnumPromotion::ToPromotedUnderlyingType;
4096 }
4097 
4098 /// CompareStandardConversionSequences - Compare two standard
4099 /// conversion sequences to determine whether one is better than the
4100 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4101 static ImplicitConversionSequence::CompareKind
4102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4103                                    const StandardConversionSequence& SCS1,
4104                                    const StandardConversionSequence& SCS2)
4105 {
4106   // Standard conversion sequence S1 is a better conversion sequence
4107   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4108 
4109   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4110   //     sequences in the canonical form defined by 13.3.3.1.1,
4111   //     excluding any Lvalue Transformation; the identity conversion
4112   //     sequence is considered to be a subsequence of any
4113   //     non-identity conversion sequence) or, if not that,
4114   if (ImplicitConversionSequence::CompareKind CK
4115         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4116     return CK;
4117 
4118   //  -- the rank of S1 is better than the rank of S2 (by the rules
4119   //     defined below), or, if not that,
4120   ImplicitConversionRank Rank1 = SCS1.getRank();
4121   ImplicitConversionRank Rank2 = SCS2.getRank();
4122   if (Rank1 < Rank2)
4123     return ImplicitConversionSequence::Better;
4124   else if (Rank2 < Rank1)
4125     return ImplicitConversionSequence::Worse;
4126 
4127   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4128   // are indistinguishable unless one of the following rules
4129   // applies:
4130 
4131   //   A conversion that is not a conversion of a pointer, or
4132   //   pointer to member, to bool is better than another conversion
4133   //   that is such a conversion.
4134   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4135     return SCS2.isPointerConversionToBool()
4136              ? ImplicitConversionSequence::Better
4137              : ImplicitConversionSequence::Worse;
4138 
4139   // C++14 [over.ics.rank]p4b2:
4140   // This is retroactively applied to C++11 by CWG 1601.
4141   //
4142   //   A conversion that promotes an enumeration whose underlying type is fixed
4143   //   to its underlying type is better than one that promotes to the promoted
4144   //   underlying type, if the two are different.
4145   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4146   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4147   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4148       FEP1 != FEP2)
4149     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4150                ? ImplicitConversionSequence::Better
4151                : ImplicitConversionSequence::Worse;
4152 
4153   // C++ [over.ics.rank]p4b2:
4154   //
4155   //   If class B is derived directly or indirectly from class A,
4156   //   conversion of B* to A* is better than conversion of B* to
4157   //   void*, and conversion of A* to void* is better than conversion
4158   //   of B* to void*.
4159   bool SCS1ConvertsToVoid
4160     = SCS1.isPointerConversionToVoidPointer(S.Context);
4161   bool SCS2ConvertsToVoid
4162     = SCS2.isPointerConversionToVoidPointer(S.Context);
4163   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4164     // Exactly one of the conversion sequences is a conversion to
4165     // a void pointer; it's the worse conversion.
4166     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4167                               : ImplicitConversionSequence::Worse;
4168   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4169     // Neither conversion sequence converts to a void pointer; compare
4170     // their derived-to-base conversions.
4171     if (ImplicitConversionSequence::CompareKind DerivedCK
4172           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4173       return DerivedCK;
4174   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4175              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4176     // Both conversion sequences are conversions to void
4177     // pointers. Compare the source types to determine if there's an
4178     // inheritance relationship in their sources.
4179     QualType FromType1 = SCS1.getFromType();
4180     QualType FromType2 = SCS2.getFromType();
4181 
4182     // Adjust the types we're converting from via the array-to-pointer
4183     // conversion, if we need to.
4184     if (SCS1.First == ICK_Array_To_Pointer)
4185       FromType1 = S.Context.getArrayDecayedType(FromType1);
4186     if (SCS2.First == ICK_Array_To_Pointer)
4187       FromType2 = S.Context.getArrayDecayedType(FromType2);
4188 
4189     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4190     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4191 
4192     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4193       return ImplicitConversionSequence::Better;
4194     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4195       return ImplicitConversionSequence::Worse;
4196 
4197     // Objective-C++: If one interface is more specific than the
4198     // other, it is the better one.
4199     const ObjCObjectPointerType* FromObjCPtr1
4200       = FromType1->getAs<ObjCObjectPointerType>();
4201     const ObjCObjectPointerType* FromObjCPtr2
4202       = FromType2->getAs<ObjCObjectPointerType>();
4203     if (FromObjCPtr1 && FromObjCPtr2) {
4204       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4205                                                           FromObjCPtr2);
4206       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4207                                                            FromObjCPtr1);
4208       if (AssignLeft != AssignRight) {
4209         return AssignLeft? ImplicitConversionSequence::Better
4210                          : ImplicitConversionSequence::Worse;
4211       }
4212     }
4213   }
4214 
4215   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4216     // Check for a better reference binding based on the kind of bindings.
4217     if (isBetterReferenceBindingKind(SCS1, SCS2))
4218       return ImplicitConversionSequence::Better;
4219     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4220       return ImplicitConversionSequence::Worse;
4221   }
4222 
4223   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4224   // bullet 3).
4225   if (ImplicitConversionSequence::CompareKind QualCK
4226         = CompareQualificationConversions(S, SCS1, SCS2))
4227     return QualCK;
4228 
4229   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4230     // C++ [over.ics.rank]p3b4:
4231     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4232     //      which the references refer are the same type except for
4233     //      top-level cv-qualifiers, and the type to which the reference
4234     //      initialized by S2 refers is more cv-qualified than the type
4235     //      to which the reference initialized by S1 refers.
4236     QualType T1 = SCS1.getToType(2);
4237     QualType T2 = SCS2.getToType(2);
4238     T1 = S.Context.getCanonicalType(T1);
4239     T2 = S.Context.getCanonicalType(T2);
4240     Qualifiers T1Quals, T2Quals;
4241     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4242     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4243     if (UnqualT1 == UnqualT2) {
4244       // Objective-C++ ARC: If the references refer to objects with different
4245       // lifetimes, prefer bindings that don't change lifetime.
4246       if (SCS1.ObjCLifetimeConversionBinding !=
4247                                           SCS2.ObjCLifetimeConversionBinding) {
4248         return SCS1.ObjCLifetimeConversionBinding
4249                                            ? ImplicitConversionSequence::Worse
4250                                            : ImplicitConversionSequence::Better;
4251       }
4252 
4253       // If the type is an array type, promote the element qualifiers to the
4254       // type for comparison.
4255       if (isa<ArrayType>(T1) && T1Quals)
4256         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4257       if (isa<ArrayType>(T2) && T2Quals)
4258         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4259       if (T2.isMoreQualifiedThan(T1))
4260         return ImplicitConversionSequence::Better;
4261       if (T1.isMoreQualifiedThan(T2))
4262         return ImplicitConversionSequence::Worse;
4263     }
4264   }
4265 
4266   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4267   // floating-to-integral conversion if the integral conversion
4268   // is between types of the same size.
4269   // For example:
4270   // void f(float);
4271   // void f(int);
4272   // int main {
4273   //    long a;
4274   //    f(a);
4275   // }
4276   // Here, MSVC will call f(int) instead of generating a compile error
4277   // as clang will do in standard mode.
4278   if (S.getLangOpts().MSVCCompat &&
4279       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4280       SCS1.Second == ICK_Integral_Conversion &&
4281       SCS2.Second == ICK_Floating_Integral &&
4282       S.Context.getTypeSize(SCS1.getFromType()) ==
4283           S.Context.getTypeSize(SCS1.getToType(2)))
4284     return ImplicitConversionSequence::Better;
4285 
4286   // Prefer a compatible vector conversion over a lax vector conversion
4287   // For example:
4288   //
4289   // typedef float __v4sf __attribute__((__vector_size__(16)));
4290   // void f(vector float);
4291   // void f(vector signed int);
4292   // int main() {
4293   //   __v4sf a;
4294   //   f(a);
4295   // }
4296   // Here, we'd like to choose f(vector float) and not
4297   // report an ambiguous call error
4298   if (SCS1.Second == ICK_Vector_Conversion &&
4299       SCS2.Second == ICK_Vector_Conversion) {
4300     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4301         SCS1.getFromType(), SCS1.getToType(2));
4302     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4303         SCS2.getFromType(), SCS2.getToType(2));
4304 
4305     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4306       return SCS1IsCompatibleVectorConversion
4307                  ? ImplicitConversionSequence::Better
4308                  : ImplicitConversionSequence::Worse;
4309   }
4310 
4311   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4312       SCS2.Second == ICK_SVE_Vector_Conversion) {
4313     bool SCS1IsCompatibleSVEVectorConversion =
4314         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4315     bool SCS2IsCompatibleSVEVectorConversion =
4316         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4317 
4318     if (SCS1IsCompatibleSVEVectorConversion !=
4319         SCS2IsCompatibleSVEVectorConversion)
4320       return SCS1IsCompatibleSVEVectorConversion
4321                  ? ImplicitConversionSequence::Better
4322                  : ImplicitConversionSequence::Worse;
4323   }
4324 
4325   return ImplicitConversionSequence::Indistinguishable;
4326 }
4327 
4328 /// CompareQualificationConversions - Compares two standard conversion
4329 /// sequences to determine whether they can be ranked based on their
4330 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4331 static ImplicitConversionSequence::CompareKind
4332 CompareQualificationConversions(Sema &S,
4333                                 const StandardConversionSequence& SCS1,
4334                                 const StandardConversionSequence& SCS2) {
4335   // C++ [over.ics.rank]p3:
4336   //  -- S1 and S2 differ only in their qualification conversion and
4337   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4338   // [C++98]
4339   //     [...] and the cv-qualification signature of type T1 is a proper subset
4340   //     of the cv-qualification signature of type T2, and S1 is not the
4341   //     deprecated string literal array-to-pointer conversion (4.2).
4342   // [C++2a]
4343   //     [...] where T1 can be converted to T2 by a qualification conversion.
4344   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4345       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4346     return ImplicitConversionSequence::Indistinguishable;
4347 
4348   // FIXME: the example in the standard doesn't use a qualification
4349   // conversion (!)
4350   QualType T1 = SCS1.getToType(2);
4351   QualType T2 = SCS2.getToType(2);
4352   T1 = S.Context.getCanonicalType(T1);
4353   T2 = S.Context.getCanonicalType(T2);
4354   assert(!T1->isReferenceType() && !T2->isReferenceType());
4355   Qualifiers T1Quals, T2Quals;
4356   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4357   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4358 
4359   // If the types are the same, we won't learn anything by unwrapping
4360   // them.
4361   if (UnqualT1 == UnqualT2)
4362     return ImplicitConversionSequence::Indistinguishable;
4363 
4364   // Don't ever prefer a standard conversion sequence that uses the deprecated
4365   // string literal array to pointer conversion.
4366   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4367   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4368 
4369   // Objective-C++ ARC:
4370   //   Prefer qualification conversions not involving a change in lifetime
4371   //   to qualification conversions that do change lifetime.
4372   if (SCS1.QualificationIncludesObjCLifetime &&
4373       !SCS2.QualificationIncludesObjCLifetime)
4374     CanPick1 = false;
4375   if (SCS2.QualificationIncludesObjCLifetime &&
4376       !SCS1.QualificationIncludesObjCLifetime)
4377     CanPick2 = false;
4378 
4379   bool ObjCLifetimeConversion;
4380   if (CanPick1 &&
4381       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4382     CanPick1 = false;
4383   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4384   // directions, so we can't short-cut this second check in general.
4385   if (CanPick2 &&
4386       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4387     CanPick2 = false;
4388 
4389   if (CanPick1 != CanPick2)
4390     return CanPick1 ? ImplicitConversionSequence::Better
4391                     : ImplicitConversionSequence::Worse;
4392   return ImplicitConversionSequence::Indistinguishable;
4393 }
4394 
4395 /// CompareDerivedToBaseConversions - Compares two standard conversion
4396 /// sequences to determine whether they can be ranked based on their
4397 /// various kinds of derived-to-base conversions (C++
4398 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4399 /// conversions between Objective-C interface types.
4400 static ImplicitConversionSequence::CompareKind
4401 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4402                                 const StandardConversionSequence& SCS1,
4403                                 const StandardConversionSequence& SCS2) {
4404   QualType FromType1 = SCS1.getFromType();
4405   QualType ToType1 = SCS1.getToType(1);
4406   QualType FromType2 = SCS2.getFromType();
4407   QualType ToType2 = SCS2.getToType(1);
4408 
4409   // Adjust the types we're converting from via the array-to-pointer
4410   // conversion, if we need to.
4411   if (SCS1.First == ICK_Array_To_Pointer)
4412     FromType1 = S.Context.getArrayDecayedType(FromType1);
4413   if (SCS2.First == ICK_Array_To_Pointer)
4414     FromType2 = S.Context.getArrayDecayedType(FromType2);
4415 
4416   // Canonicalize all of the types.
4417   FromType1 = S.Context.getCanonicalType(FromType1);
4418   ToType1 = S.Context.getCanonicalType(ToType1);
4419   FromType2 = S.Context.getCanonicalType(FromType2);
4420   ToType2 = S.Context.getCanonicalType(ToType2);
4421 
4422   // C++ [over.ics.rank]p4b3:
4423   //
4424   //   If class B is derived directly or indirectly from class A and
4425   //   class C is derived directly or indirectly from B,
4426   //
4427   // Compare based on pointer conversions.
4428   if (SCS1.Second == ICK_Pointer_Conversion &&
4429       SCS2.Second == ICK_Pointer_Conversion &&
4430       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4431       FromType1->isPointerType() && FromType2->isPointerType() &&
4432       ToType1->isPointerType() && ToType2->isPointerType()) {
4433     QualType FromPointee1 =
4434         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4435     QualType ToPointee1 =
4436         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4437     QualType FromPointee2 =
4438         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4439     QualType ToPointee2 =
4440         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4441 
4442     //   -- conversion of C* to B* is better than conversion of C* to A*,
4443     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4444       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4445         return ImplicitConversionSequence::Better;
4446       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4447         return ImplicitConversionSequence::Worse;
4448     }
4449 
4450     //   -- conversion of B* to A* is better than conversion of C* to A*,
4451     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4452       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4453         return ImplicitConversionSequence::Better;
4454       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4455         return ImplicitConversionSequence::Worse;
4456     }
4457   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4458              SCS2.Second == ICK_Pointer_Conversion) {
4459     const ObjCObjectPointerType *FromPtr1
4460       = FromType1->getAs<ObjCObjectPointerType>();
4461     const ObjCObjectPointerType *FromPtr2
4462       = FromType2->getAs<ObjCObjectPointerType>();
4463     const ObjCObjectPointerType *ToPtr1
4464       = ToType1->getAs<ObjCObjectPointerType>();
4465     const ObjCObjectPointerType *ToPtr2
4466       = ToType2->getAs<ObjCObjectPointerType>();
4467 
4468     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4469       // Apply the same conversion ranking rules for Objective-C pointer types
4470       // that we do for C++ pointers to class types. However, we employ the
4471       // Objective-C pseudo-subtyping relationship used for assignment of
4472       // Objective-C pointer types.
4473       bool FromAssignLeft
4474         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4475       bool FromAssignRight
4476         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4477       bool ToAssignLeft
4478         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4479       bool ToAssignRight
4480         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4481 
4482       // A conversion to an a non-id object pointer type or qualified 'id'
4483       // type is better than a conversion to 'id'.
4484       if (ToPtr1->isObjCIdType() &&
4485           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4486         return ImplicitConversionSequence::Worse;
4487       if (ToPtr2->isObjCIdType() &&
4488           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4489         return ImplicitConversionSequence::Better;
4490 
4491       // A conversion to a non-id object pointer type is better than a
4492       // conversion to a qualified 'id' type
4493       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4494         return ImplicitConversionSequence::Worse;
4495       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4496         return ImplicitConversionSequence::Better;
4497 
4498       // A conversion to an a non-Class object pointer type or qualified 'Class'
4499       // type is better than a conversion to 'Class'.
4500       if (ToPtr1->isObjCClassType() &&
4501           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4502         return ImplicitConversionSequence::Worse;
4503       if (ToPtr2->isObjCClassType() &&
4504           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4505         return ImplicitConversionSequence::Better;
4506 
4507       // A conversion to a non-Class object pointer type is better than a
4508       // conversion to a qualified 'Class' type.
4509       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4510         return ImplicitConversionSequence::Worse;
4511       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4512         return ImplicitConversionSequence::Better;
4513 
4514       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4515       if (S.Context.hasSameType(FromType1, FromType2) &&
4516           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4517           (ToAssignLeft != ToAssignRight)) {
4518         if (FromPtr1->isSpecialized()) {
4519           // "conversion of B<A> * to B * is better than conversion of B * to
4520           // C *.
4521           bool IsFirstSame =
4522               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4523           bool IsSecondSame =
4524               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4525           if (IsFirstSame) {
4526             if (!IsSecondSame)
4527               return ImplicitConversionSequence::Better;
4528           } else if (IsSecondSame)
4529             return ImplicitConversionSequence::Worse;
4530         }
4531         return ToAssignLeft? ImplicitConversionSequence::Worse
4532                            : ImplicitConversionSequence::Better;
4533       }
4534 
4535       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4536       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4537           (FromAssignLeft != FromAssignRight))
4538         return FromAssignLeft? ImplicitConversionSequence::Better
4539         : ImplicitConversionSequence::Worse;
4540     }
4541   }
4542 
4543   // Ranking of member-pointer types.
4544   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4545       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4546       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4547     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4548     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4549     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4550     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4551     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4552     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4553     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4554     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4555     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4556     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4557     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4558     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4559     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4560     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4561       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4562         return ImplicitConversionSequence::Worse;
4563       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4564         return ImplicitConversionSequence::Better;
4565     }
4566     // conversion of B::* to C::* is better than conversion of A::* to C::*
4567     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4568       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4569         return ImplicitConversionSequence::Better;
4570       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4571         return ImplicitConversionSequence::Worse;
4572     }
4573   }
4574 
4575   if (SCS1.Second == ICK_Derived_To_Base) {
4576     //   -- conversion of C to B is better than conversion of C to A,
4577     //   -- binding of an expression of type C to a reference of type
4578     //      B& is better than binding an expression of type C to a
4579     //      reference of type A&,
4580     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4581         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4582       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4583         return ImplicitConversionSequence::Better;
4584       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4585         return ImplicitConversionSequence::Worse;
4586     }
4587 
4588     //   -- conversion of B to A is better than conversion of C to A.
4589     //   -- binding of an expression of type B to a reference of type
4590     //      A& is better than binding an expression of type C to a
4591     //      reference of type A&,
4592     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4593         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4594       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4595         return ImplicitConversionSequence::Better;
4596       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4597         return ImplicitConversionSequence::Worse;
4598     }
4599   }
4600 
4601   return ImplicitConversionSequence::Indistinguishable;
4602 }
4603 
4604 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4605   if (!T.getQualifiers().hasUnaligned())
4606     return T;
4607 
4608   Qualifiers Q;
4609   T = Ctx.getUnqualifiedArrayType(T, Q);
4610   Q.removeUnaligned();
4611   return Ctx.getQualifiedType(T, Q);
4612 }
4613 
4614 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4615 /// determine whether they are reference-compatible,
4616 /// reference-related, or incompatible, for use in C++ initialization by
4617 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4618 /// type, and the first type (T1) is the pointee type of the reference
4619 /// type being initialized.
4620 Sema::ReferenceCompareResult
4621 Sema::CompareReferenceRelationship(SourceLocation Loc,
4622                                    QualType OrigT1, QualType OrigT2,
4623                                    ReferenceConversions *ConvOut) {
4624   assert(!OrigT1->isReferenceType() &&
4625     "T1 must be the pointee type of the reference type");
4626   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4627 
4628   QualType T1 = Context.getCanonicalType(OrigT1);
4629   QualType T2 = Context.getCanonicalType(OrigT2);
4630   Qualifiers T1Quals, T2Quals;
4631   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4632   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4633 
4634   ReferenceConversions ConvTmp;
4635   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4636   Conv = ReferenceConversions();
4637 
4638   // C++2a [dcl.init.ref]p4:
4639   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4640   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4641   //   T1 is a base class of T2.
4642   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4643   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4644   //   "pointer to cv1 T1" via a standard conversion sequence.
4645 
4646   // Check for standard conversions we can apply to pointers: derived-to-base
4647   // conversions, ObjC pointer conversions, and function pointer conversions.
4648   // (Qualification conversions are checked last.)
4649   QualType ConvertedT2;
4650   if (UnqualT1 == UnqualT2) {
4651     // Nothing to do.
4652   } else if (isCompleteType(Loc, OrigT2) &&
4653              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4654     Conv |= ReferenceConversions::DerivedToBase;
4655   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4656            UnqualT2->isObjCObjectOrInterfaceType() &&
4657            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4658     Conv |= ReferenceConversions::ObjC;
4659   else if (UnqualT2->isFunctionType() &&
4660            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4661     Conv |= ReferenceConversions::Function;
4662     // No need to check qualifiers; function types don't have them.
4663     return Ref_Compatible;
4664   }
4665   bool ConvertedReferent = Conv != 0;
4666 
4667   // We can have a qualification conversion. Compute whether the types are
4668   // similar at the same time.
4669   bool PreviousToQualsIncludeConst = true;
4670   bool TopLevel = true;
4671   do {
4672     if (T1 == T2)
4673       break;
4674 
4675     // We will need a qualification conversion.
4676     Conv |= ReferenceConversions::Qualification;
4677 
4678     // Track whether we performed a qualification conversion anywhere other
4679     // than the top level. This matters for ranking reference bindings in
4680     // overload resolution.
4681     if (!TopLevel)
4682       Conv |= ReferenceConversions::NestedQualification;
4683 
4684     // MS compiler ignores __unaligned qualifier for references; do the same.
4685     T1 = withoutUnaligned(Context, T1);
4686     T2 = withoutUnaligned(Context, T2);
4687 
4688     // If we find a qualifier mismatch, the types are not reference-compatible,
4689     // but are still be reference-related if they're similar.
4690     bool ObjCLifetimeConversion = false;
4691     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4692                                        PreviousToQualsIncludeConst,
4693                                        ObjCLifetimeConversion))
4694       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4695                  ? Ref_Related
4696                  : Ref_Incompatible;
4697 
4698     // FIXME: Should we track this for any level other than the first?
4699     if (ObjCLifetimeConversion)
4700       Conv |= ReferenceConversions::ObjCLifetime;
4701 
4702     TopLevel = false;
4703   } while (Context.UnwrapSimilarTypes(T1, T2));
4704 
4705   // At this point, if the types are reference-related, we must either have the
4706   // same inner type (ignoring qualifiers), or must have already worked out how
4707   // to convert the referent.
4708   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4709              ? Ref_Compatible
4710              : Ref_Incompatible;
4711 }
4712 
4713 /// Look for a user-defined conversion to a value reference-compatible
4714 ///        with DeclType. Return true if something definite is found.
4715 static bool
4716 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4717                          QualType DeclType, SourceLocation DeclLoc,
4718                          Expr *Init, QualType T2, bool AllowRvalues,
4719                          bool AllowExplicit) {
4720   assert(T2->isRecordType() && "Can only find conversions of record types.");
4721   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4722 
4723   OverloadCandidateSet CandidateSet(
4724       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4725   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4726   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4727     NamedDecl *D = *I;
4728     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4729     if (isa<UsingShadowDecl>(D))
4730       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4731 
4732     FunctionTemplateDecl *ConvTemplate
4733       = dyn_cast<FunctionTemplateDecl>(D);
4734     CXXConversionDecl *Conv;
4735     if (ConvTemplate)
4736       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4737     else
4738       Conv = cast<CXXConversionDecl>(D);
4739 
4740     if (AllowRvalues) {
4741       // If we are initializing an rvalue reference, don't permit conversion
4742       // functions that return lvalues.
4743       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4744         const ReferenceType *RefType
4745           = Conv->getConversionType()->getAs<LValueReferenceType>();
4746         if (RefType && !RefType->getPointeeType()->isFunctionType())
4747           continue;
4748       }
4749 
4750       if (!ConvTemplate &&
4751           S.CompareReferenceRelationship(
4752               DeclLoc,
4753               Conv->getConversionType()
4754                   .getNonReferenceType()
4755                   .getUnqualifiedType(),
4756               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4757               Sema::Ref_Incompatible)
4758         continue;
4759     } else {
4760       // If the conversion function doesn't return a reference type,
4761       // it can't be considered for this conversion. An rvalue reference
4762       // is only acceptable if its referencee is a function type.
4763 
4764       const ReferenceType *RefType =
4765         Conv->getConversionType()->getAs<ReferenceType>();
4766       if (!RefType ||
4767           (!RefType->isLValueReferenceType() &&
4768            !RefType->getPointeeType()->isFunctionType()))
4769         continue;
4770     }
4771 
4772     if (ConvTemplate)
4773       S.AddTemplateConversionCandidate(
4774           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4775           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4776     else
4777       S.AddConversionCandidate(
4778           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4779           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4780   }
4781 
4782   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4783 
4784   OverloadCandidateSet::iterator Best;
4785   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4786   case OR_Success:
4787     // C++ [over.ics.ref]p1:
4788     //
4789     //   [...] If the parameter binds directly to the result of
4790     //   applying a conversion function to the argument
4791     //   expression, the implicit conversion sequence is a
4792     //   user-defined conversion sequence (13.3.3.1.2), with the
4793     //   second standard conversion sequence either an identity
4794     //   conversion or, if the conversion function returns an
4795     //   entity of a type that is a derived class of the parameter
4796     //   type, a derived-to-base Conversion.
4797     if (!Best->FinalConversion.DirectBinding)
4798       return false;
4799 
4800     ICS.setUserDefined();
4801     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4802     ICS.UserDefined.After = Best->FinalConversion;
4803     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4804     ICS.UserDefined.ConversionFunction = Best->Function;
4805     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4806     ICS.UserDefined.EllipsisConversion = false;
4807     assert(ICS.UserDefined.After.ReferenceBinding &&
4808            ICS.UserDefined.After.DirectBinding &&
4809            "Expected a direct reference binding!");
4810     return true;
4811 
4812   case OR_Ambiguous:
4813     ICS.setAmbiguous();
4814     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4815          Cand != CandidateSet.end(); ++Cand)
4816       if (Cand->Best)
4817         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4818     return true;
4819 
4820   case OR_No_Viable_Function:
4821   case OR_Deleted:
4822     // There was no suitable conversion, or we found a deleted
4823     // conversion; continue with other checks.
4824     return false;
4825   }
4826 
4827   llvm_unreachable("Invalid OverloadResult!");
4828 }
4829 
4830 /// Compute an implicit conversion sequence for reference
4831 /// initialization.
4832 static ImplicitConversionSequence
4833 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4834                  SourceLocation DeclLoc,
4835                  bool SuppressUserConversions,
4836                  bool AllowExplicit) {
4837   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4838 
4839   // Most paths end in a failed conversion.
4840   ImplicitConversionSequence ICS;
4841   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4842 
4843   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4844   QualType T2 = Init->getType();
4845 
4846   // If the initializer is the address of an overloaded function, try
4847   // to resolve the overloaded function. If all goes well, T2 is the
4848   // type of the resulting function.
4849   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4850     DeclAccessPair Found;
4851     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4852                                                                 false, Found))
4853       T2 = Fn->getType();
4854   }
4855 
4856   // Compute some basic properties of the types and the initializer.
4857   bool isRValRef = DeclType->isRValueReferenceType();
4858   Expr::Classification InitCategory = Init->Classify(S.Context);
4859 
4860   Sema::ReferenceConversions RefConv;
4861   Sema::ReferenceCompareResult RefRelationship =
4862       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4863 
4864   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4865     ICS.setStandard();
4866     ICS.Standard.First = ICK_Identity;
4867     // FIXME: A reference binding can be a function conversion too. We should
4868     // consider that when ordering reference-to-function bindings.
4869     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4870                               ? ICK_Derived_To_Base
4871                               : (RefConv & Sema::ReferenceConversions::ObjC)
4872                                     ? ICK_Compatible_Conversion
4873                                     : ICK_Identity;
4874     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4875     // a reference binding that performs a non-top-level qualification
4876     // conversion as a qualification conversion, not as an identity conversion.
4877     ICS.Standard.Third = (RefConv &
4878                               Sema::ReferenceConversions::NestedQualification)
4879                              ? ICK_Qualification
4880                              : ICK_Identity;
4881     ICS.Standard.setFromType(T2);
4882     ICS.Standard.setToType(0, T2);
4883     ICS.Standard.setToType(1, T1);
4884     ICS.Standard.setToType(2, T1);
4885     ICS.Standard.ReferenceBinding = true;
4886     ICS.Standard.DirectBinding = BindsDirectly;
4887     ICS.Standard.IsLvalueReference = !isRValRef;
4888     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4889     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4890     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4891     ICS.Standard.ObjCLifetimeConversionBinding =
4892         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4893     ICS.Standard.CopyConstructor = nullptr;
4894     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4895   };
4896 
4897   // C++0x [dcl.init.ref]p5:
4898   //   A reference to type "cv1 T1" is initialized by an expression
4899   //   of type "cv2 T2" as follows:
4900 
4901   //     -- If reference is an lvalue reference and the initializer expression
4902   if (!isRValRef) {
4903     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4904     //        reference-compatible with "cv2 T2," or
4905     //
4906     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4907     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4908       // C++ [over.ics.ref]p1:
4909       //   When a parameter of reference type binds directly (8.5.3)
4910       //   to an argument expression, the implicit conversion sequence
4911       //   is the identity conversion, unless the argument expression
4912       //   has a type that is a derived class of the parameter type,
4913       //   in which case the implicit conversion sequence is a
4914       //   derived-to-base Conversion (13.3.3.1).
4915       SetAsReferenceBinding(/*BindsDirectly=*/true);
4916 
4917       // Nothing more to do: the inaccessibility/ambiguity check for
4918       // derived-to-base conversions is suppressed when we're
4919       // computing the implicit conversion sequence (C++
4920       // [over.best.ics]p2).
4921       return ICS;
4922     }
4923 
4924     //       -- has a class type (i.e., T2 is a class type), where T1 is
4925     //          not reference-related to T2, and can be implicitly
4926     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4927     //          is reference-compatible with "cv3 T3" 92) (this
4928     //          conversion is selected by enumerating the applicable
4929     //          conversion functions (13.3.1.6) and choosing the best
4930     //          one through overload resolution (13.3)),
4931     if (!SuppressUserConversions && T2->isRecordType() &&
4932         S.isCompleteType(DeclLoc, T2) &&
4933         RefRelationship == Sema::Ref_Incompatible) {
4934       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4935                                    Init, T2, /*AllowRvalues=*/false,
4936                                    AllowExplicit))
4937         return ICS;
4938     }
4939   }
4940 
4941   //     -- Otherwise, the reference shall be an lvalue reference to a
4942   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4943   //        shall be an rvalue reference.
4944   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4945     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4946       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4947     return ICS;
4948   }
4949 
4950   //       -- If the initializer expression
4951   //
4952   //            -- is an xvalue, class prvalue, array prvalue or function
4953   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4954   if (RefRelationship == Sema::Ref_Compatible &&
4955       (InitCategory.isXValue() ||
4956        (InitCategory.isPRValue() &&
4957           (T2->isRecordType() || T2->isArrayType())) ||
4958        (InitCategory.isLValue() && T2->isFunctionType()))) {
4959     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4960     // binding unless we're binding to a class prvalue.
4961     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4962     // allow the use of rvalue references in C++98/03 for the benefit of
4963     // standard library implementors; therefore, we need the xvalue check here.
4964     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4965                           !(InitCategory.isPRValue() || T2->isRecordType()));
4966     return ICS;
4967   }
4968 
4969   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4970   //               reference-related to T2, and can be implicitly converted to
4971   //               an xvalue, class prvalue, or function lvalue of type
4972   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4973   //               "cv3 T3",
4974   //
4975   //          then the reference is bound to the value of the initializer
4976   //          expression in the first case and to the result of the conversion
4977   //          in the second case (or, in either case, to an appropriate base
4978   //          class subobject).
4979   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4980       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4981       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4982                                Init, T2, /*AllowRvalues=*/true,
4983                                AllowExplicit)) {
4984     // In the second case, if the reference is an rvalue reference
4985     // and the second standard conversion sequence of the
4986     // user-defined conversion sequence includes an lvalue-to-rvalue
4987     // conversion, the program is ill-formed.
4988     if (ICS.isUserDefined() && isRValRef &&
4989         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4990       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4991 
4992     return ICS;
4993   }
4994 
4995   // A temporary of function type cannot be created; don't even try.
4996   if (T1->isFunctionType())
4997     return ICS;
4998 
4999   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5000   //          initialized from the initializer expression using the
5001   //          rules for a non-reference copy initialization (8.5). The
5002   //          reference is then bound to the temporary. If T1 is
5003   //          reference-related to T2, cv1 must be the same
5004   //          cv-qualification as, or greater cv-qualification than,
5005   //          cv2; otherwise, the program is ill-formed.
5006   if (RefRelationship == Sema::Ref_Related) {
5007     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5008     // we would be reference-compatible or reference-compatible with
5009     // added qualification. But that wasn't the case, so the reference
5010     // initialization fails.
5011     //
5012     // Note that we only want to check address spaces and cvr-qualifiers here.
5013     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5014     Qualifiers T1Quals = T1.getQualifiers();
5015     Qualifiers T2Quals = T2.getQualifiers();
5016     T1Quals.removeObjCGCAttr();
5017     T1Quals.removeObjCLifetime();
5018     T2Quals.removeObjCGCAttr();
5019     T2Quals.removeObjCLifetime();
5020     // MS compiler ignores __unaligned qualifier for references; do the same.
5021     T1Quals.removeUnaligned();
5022     T2Quals.removeUnaligned();
5023     if (!T1Quals.compatiblyIncludes(T2Quals))
5024       return ICS;
5025   }
5026 
5027   // If at least one of the types is a class type, the types are not
5028   // related, and we aren't allowed any user conversions, the
5029   // reference binding fails. This case is important for breaking
5030   // recursion, since TryImplicitConversion below will attempt to
5031   // create a temporary through the use of a copy constructor.
5032   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5033       (T1->isRecordType() || T2->isRecordType()))
5034     return ICS;
5035 
5036   // If T1 is reference-related to T2 and the reference is an rvalue
5037   // reference, the initializer expression shall not be an lvalue.
5038   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5039       Init->Classify(S.Context).isLValue()) {
5040     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5041     return ICS;
5042   }
5043 
5044   // C++ [over.ics.ref]p2:
5045   //   When a parameter of reference type is not bound directly to
5046   //   an argument expression, the conversion sequence is the one
5047   //   required to convert the argument expression to the
5048   //   underlying type of the reference according to
5049   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5050   //   to copy-initializing a temporary of the underlying type with
5051   //   the argument expression. Any difference in top-level
5052   //   cv-qualification is subsumed by the initialization itself
5053   //   and does not constitute a conversion.
5054   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5055                               AllowedExplicit::None,
5056                               /*InOverloadResolution=*/false,
5057                               /*CStyle=*/false,
5058                               /*AllowObjCWritebackConversion=*/false,
5059                               /*AllowObjCConversionOnExplicit=*/false);
5060 
5061   // Of course, that's still a reference binding.
5062   if (ICS.isStandard()) {
5063     ICS.Standard.ReferenceBinding = true;
5064     ICS.Standard.IsLvalueReference = !isRValRef;
5065     ICS.Standard.BindsToFunctionLvalue = false;
5066     ICS.Standard.BindsToRvalue = true;
5067     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5068     ICS.Standard.ObjCLifetimeConversionBinding = false;
5069   } else if (ICS.isUserDefined()) {
5070     const ReferenceType *LValRefType =
5071         ICS.UserDefined.ConversionFunction->getReturnType()
5072             ->getAs<LValueReferenceType>();
5073 
5074     // C++ [over.ics.ref]p3:
5075     //   Except for an implicit object parameter, for which see 13.3.1, a
5076     //   standard conversion sequence cannot be formed if it requires [...]
5077     //   binding an rvalue reference to an lvalue other than a function
5078     //   lvalue.
5079     // Note that the function case is not possible here.
5080     if (isRValRef && LValRefType) {
5081       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5082       return ICS;
5083     }
5084 
5085     ICS.UserDefined.After.ReferenceBinding = true;
5086     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5087     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5088     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5089     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5090     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5091   }
5092 
5093   return ICS;
5094 }
5095 
5096 static ImplicitConversionSequence
5097 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5098                       bool SuppressUserConversions,
5099                       bool InOverloadResolution,
5100                       bool AllowObjCWritebackConversion,
5101                       bool AllowExplicit = false);
5102 
5103 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5104 /// initializer list From.
5105 static ImplicitConversionSequence
5106 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5107                   bool SuppressUserConversions,
5108                   bool InOverloadResolution,
5109                   bool AllowObjCWritebackConversion) {
5110   // C++11 [over.ics.list]p1:
5111   //   When an argument is an initializer list, it is not an expression and
5112   //   special rules apply for converting it to a parameter type.
5113 
5114   ImplicitConversionSequence Result;
5115   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5116 
5117   // We need a complete type for what follows.  With one C++20 exception,
5118   // incomplete types can never be initialized from init lists.
5119   QualType InitTy = ToType;
5120   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5121   if (AT && S.getLangOpts().CPlusPlus20)
5122     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5123       // C++20 allows list initialization of an incomplete array type.
5124       InitTy = IAT->getElementType();
5125   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5126     return Result;
5127 
5128   // Per DR1467:
5129   //   If the parameter type is a class X and the initializer list has a single
5130   //   element of type cv U, where U is X or a class derived from X, the
5131   //   implicit conversion sequence is the one required to convert the element
5132   //   to the parameter type.
5133   //
5134   //   Otherwise, if the parameter type is a character array [... ]
5135   //   and the initializer list has a single element that is an
5136   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5137   //   implicit conversion sequence is the identity conversion.
5138   if (From->getNumInits() == 1) {
5139     if (ToType->isRecordType()) {
5140       QualType InitType = From->getInit(0)->getType();
5141       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5142           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5143         return TryCopyInitialization(S, From->getInit(0), ToType,
5144                                      SuppressUserConversions,
5145                                      InOverloadResolution,
5146                                      AllowObjCWritebackConversion);
5147     }
5148 
5149     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5150       InitializedEntity Entity =
5151           InitializedEntity::InitializeParameter(S.Context, ToType,
5152                                                  /*Consumed=*/false);
5153       if (S.CanPerformCopyInitialization(Entity, From)) {
5154         Result.setStandard();
5155         Result.Standard.setAsIdentityConversion();
5156         Result.Standard.setFromType(ToType);
5157         Result.Standard.setAllToTypes(ToType);
5158         return Result;
5159       }
5160     }
5161   }
5162 
5163   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5164   // C++11 [over.ics.list]p2:
5165   //   If the parameter type is std::initializer_list<X> or "array of X" and
5166   //   all the elements can be implicitly converted to X, the implicit
5167   //   conversion sequence is the worst conversion necessary to convert an
5168   //   element of the list to X.
5169   //
5170   // C++14 [over.ics.list]p3:
5171   //   Otherwise, if the parameter type is "array of N X", if the initializer
5172   //   list has exactly N elements or if it has fewer than N elements and X is
5173   //   default-constructible, and if all the elements of the initializer list
5174   //   can be implicitly converted to X, the implicit conversion sequence is
5175   //   the worst conversion necessary to convert an element of the list to X.
5176   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5177     unsigned e = From->getNumInits();
5178     ImplicitConversionSequence DfltElt;
5179     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5180                    QualType());
5181     QualType ContTy = ToType;
5182     bool IsUnbounded = false;
5183     if (AT) {
5184       InitTy = AT->getElementType();
5185       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5186         if (CT->getSize().ult(e)) {
5187           // Too many inits, fatally bad
5188           Result.setBad(BadConversionSequence::too_many_initializers, From,
5189                         ToType);
5190           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5191           return Result;
5192         }
5193         if (CT->getSize().ugt(e)) {
5194           // Need an init from empty {}, is there one?
5195           InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5196                                  From->getEndLoc());
5197           EmptyList.setType(S.Context.VoidTy);
5198           DfltElt = TryListConversion(
5199               S, &EmptyList, InitTy, SuppressUserConversions,
5200               InOverloadResolution, AllowObjCWritebackConversion);
5201           if (DfltElt.isBad()) {
5202             // No {} init, fatally bad
5203             Result.setBad(BadConversionSequence::too_few_initializers, From,
5204                           ToType);
5205             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5206             return Result;
5207           }
5208         }
5209       } else {
5210         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5211         IsUnbounded = true;
5212         if (!e) {
5213           // Cannot convert to zero-sized.
5214           Result.setBad(BadConversionSequence::too_few_initializers, From,
5215                         ToType);
5216           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5217           return Result;
5218         }
5219         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5220         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5221                                                 ArrayType::Normal, 0);
5222       }
5223     }
5224 
5225     Result.setStandard();
5226     Result.Standard.setAsIdentityConversion();
5227     Result.Standard.setFromType(InitTy);
5228     Result.Standard.setAllToTypes(InitTy);
5229     for (unsigned i = 0; i < e; ++i) {
5230       Expr *Init = From->getInit(i);
5231       ImplicitConversionSequence ICS = TryCopyInitialization(
5232           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5233           AllowObjCWritebackConversion);
5234 
5235       // Keep the worse conversion seen so far.
5236       // FIXME: Sequences are not totally ordered, so 'worse' can be
5237       // ambiguous. CWG has been informed.
5238       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5239                                              Result) ==
5240           ImplicitConversionSequence::Worse) {
5241         Result = ICS;
5242         // Bail as soon as we find something unconvertible.
5243         if (Result.isBad()) {
5244           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5245           return Result;
5246         }
5247       }
5248     }
5249 
5250     // If we needed any implicit {} initialization, compare that now.
5251     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5252     // has been informed that this might not be the best thing.
5253     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5254                                 S, From->getEndLoc(), DfltElt, Result) ==
5255                                 ImplicitConversionSequence::Worse)
5256       Result = DfltElt;
5257     // Record the type being initialized so that we may compare sequences
5258     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5259     return Result;
5260   }
5261 
5262   // C++14 [over.ics.list]p4:
5263   // C++11 [over.ics.list]p3:
5264   //   Otherwise, if the parameter is a non-aggregate class X and overload
5265   //   resolution chooses a single best constructor [...] the implicit
5266   //   conversion sequence is a user-defined conversion sequence. If multiple
5267   //   constructors are viable but none is better than the others, the
5268   //   implicit conversion sequence is a user-defined conversion sequence.
5269   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5270     // This function can deal with initializer lists.
5271     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5272                                     AllowedExplicit::None,
5273                                     InOverloadResolution, /*CStyle=*/false,
5274                                     AllowObjCWritebackConversion,
5275                                     /*AllowObjCConversionOnExplicit=*/false);
5276   }
5277 
5278   // C++14 [over.ics.list]p5:
5279   // C++11 [over.ics.list]p4:
5280   //   Otherwise, if the parameter has an aggregate type which can be
5281   //   initialized from the initializer list [...] the implicit conversion
5282   //   sequence is a user-defined conversion sequence.
5283   if (ToType->isAggregateType()) {
5284     // Type is an aggregate, argument is an init list. At this point it comes
5285     // down to checking whether the initialization works.
5286     // FIXME: Find out whether this parameter is consumed or not.
5287     InitializedEntity Entity =
5288         InitializedEntity::InitializeParameter(S.Context, ToType,
5289                                                /*Consumed=*/false);
5290     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5291                                                                  From)) {
5292       Result.setUserDefined();
5293       Result.UserDefined.Before.setAsIdentityConversion();
5294       // Initializer lists don't have a type.
5295       Result.UserDefined.Before.setFromType(QualType());
5296       Result.UserDefined.Before.setAllToTypes(QualType());
5297 
5298       Result.UserDefined.After.setAsIdentityConversion();
5299       Result.UserDefined.After.setFromType(ToType);
5300       Result.UserDefined.After.setAllToTypes(ToType);
5301       Result.UserDefined.ConversionFunction = nullptr;
5302     }
5303     return Result;
5304   }
5305 
5306   // C++14 [over.ics.list]p6:
5307   // C++11 [over.ics.list]p5:
5308   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5309   if (ToType->isReferenceType()) {
5310     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5311     // mention initializer lists in any way. So we go by what list-
5312     // initialization would do and try to extrapolate from that.
5313 
5314     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5315 
5316     // If the initializer list has a single element that is reference-related
5317     // to the parameter type, we initialize the reference from that.
5318     if (From->getNumInits() == 1) {
5319       Expr *Init = From->getInit(0);
5320 
5321       QualType T2 = Init->getType();
5322 
5323       // If the initializer is the address of an overloaded function, try
5324       // to resolve the overloaded function. If all goes well, T2 is the
5325       // type of the resulting function.
5326       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5327         DeclAccessPair Found;
5328         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5329                                    Init, ToType, false, Found))
5330           T2 = Fn->getType();
5331       }
5332 
5333       // Compute some basic properties of the types and the initializer.
5334       Sema::ReferenceCompareResult RefRelationship =
5335           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5336 
5337       if (RefRelationship >= Sema::Ref_Related) {
5338         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5339                                 SuppressUserConversions,
5340                                 /*AllowExplicit=*/false);
5341       }
5342     }
5343 
5344     // Otherwise, we bind the reference to a temporary created from the
5345     // initializer list.
5346     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5347                                InOverloadResolution,
5348                                AllowObjCWritebackConversion);
5349     if (Result.isFailure())
5350       return Result;
5351     assert(!Result.isEllipsis() &&
5352            "Sub-initialization cannot result in ellipsis conversion.");
5353 
5354     // Can we even bind to a temporary?
5355     if (ToType->isRValueReferenceType() ||
5356         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5357       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5358                                             Result.UserDefined.After;
5359       SCS.ReferenceBinding = true;
5360       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5361       SCS.BindsToRvalue = true;
5362       SCS.BindsToFunctionLvalue = false;
5363       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5364       SCS.ObjCLifetimeConversionBinding = false;
5365     } else
5366       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5367                     From, ToType);
5368     return Result;
5369   }
5370 
5371   // C++14 [over.ics.list]p7:
5372   // C++11 [over.ics.list]p6:
5373   //   Otherwise, if the parameter type is not a class:
5374   if (!ToType->isRecordType()) {
5375     //    - if the initializer list has one element that is not itself an
5376     //      initializer list, the implicit conversion sequence is the one
5377     //      required to convert the element to the parameter type.
5378     unsigned NumInits = From->getNumInits();
5379     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5380       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5381                                      SuppressUserConversions,
5382                                      InOverloadResolution,
5383                                      AllowObjCWritebackConversion);
5384     //    - if the initializer list has no elements, the implicit conversion
5385     //      sequence is the identity conversion.
5386     else if (NumInits == 0) {
5387       Result.setStandard();
5388       Result.Standard.setAsIdentityConversion();
5389       Result.Standard.setFromType(ToType);
5390       Result.Standard.setAllToTypes(ToType);
5391     }
5392     return Result;
5393   }
5394 
5395   // C++14 [over.ics.list]p8:
5396   // C++11 [over.ics.list]p7:
5397   //   In all cases other than those enumerated above, no conversion is possible
5398   return Result;
5399 }
5400 
5401 /// TryCopyInitialization - Try to copy-initialize a value of type
5402 /// ToType from the expression From. Return the implicit conversion
5403 /// sequence required to pass this argument, which may be a bad
5404 /// conversion sequence (meaning that the argument cannot be passed to
5405 /// a parameter of this type). If @p SuppressUserConversions, then we
5406 /// do not permit any user-defined conversion sequences.
5407 static ImplicitConversionSequence
5408 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5409                       bool SuppressUserConversions,
5410                       bool InOverloadResolution,
5411                       bool AllowObjCWritebackConversion,
5412                       bool AllowExplicit) {
5413   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5414     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5415                              InOverloadResolution,AllowObjCWritebackConversion);
5416 
5417   if (ToType->isReferenceType())
5418     return TryReferenceInit(S, From, ToType,
5419                             /*FIXME:*/ From->getBeginLoc(),
5420                             SuppressUserConversions, AllowExplicit);
5421 
5422   return TryImplicitConversion(S, From, ToType,
5423                                SuppressUserConversions,
5424                                AllowedExplicit::None,
5425                                InOverloadResolution,
5426                                /*CStyle=*/false,
5427                                AllowObjCWritebackConversion,
5428                                /*AllowObjCConversionOnExplicit=*/false);
5429 }
5430 
5431 static bool TryCopyInitialization(const CanQualType FromQTy,
5432                                   const CanQualType ToQTy,
5433                                   Sema &S,
5434                                   SourceLocation Loc,
5435                                   ExprValueKind FromVK) {
5436   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5437   ImplicitConversionSequence ICS =
5438     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5439 
5440   return !ICS.isBad();
5441 }
5442 
5443 /// TryObjectArgumentInitialization - Try to initialize the object
5444 /// parameter of the given member function (@c Method) from the
5445 /// expression @p From.
5446 static ImplicitConversionSequence
5447 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5448                                 Expr::Classification FromClassification,
5449                                 CXXMethodDecl *Method,
5450                                 CXXRecordDecl *ActingContext) {
5451   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5452   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5453   //                 const volatile object.
5454   Qualifiers Quals = Method->getMethodQualifiers();
5455   if (isa<CXXDestructorDecl>(Method)) {
5456     Quals.addConst();
5457     Quals.addVolatile();
5458   }
5459 
5460   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5461 
5462   // Set up the conversion sequence as a "bad" conversion, to allow us
5463   // to exit early.
5464   ImplicitConversionSequence ICS;
5465 
5466   // We need to have an object of class type.
5467   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5468     FromType = PT->getPointeeType();
5469 
5470     // When we had a pointer, it's implicitly dereferenced, so we
5471     // better have an lvalue.
5472     assert(FromClassification.isLValue());
5473   }
5474 
5475   assert(FromType->isRecordType());
5476 
5477   // C++0x [over.match.funcs]p4:
5478   //   For non-static member functions, the type of the implicit object
5479   //   parameter is
5480   //
5481   //     - "lvalue reference to cv X" for functions declared without a
5482   //        ref-qualifier or with the & ref-qualifier
5483   //     - "rvalue reference to cv X" for functions declared with the &&
5484   //        ref-qualifier
5485   //
5486   // where X is the class of which the function is a member and cv is the
5487   // cv-qualification on the member function declaration.
5488   //
5489   // However, when finding an implicit conversion sequence for the argument, we
5490   // are not allowed to perform user-defined conversions
5491   // (C++ [over.match.funcs]p5). We perform a simplified version of
5492   // reference binding here, that allows class rvalues to bind to
5493   // non-constant references.
5494 
5495   // First check the qualifiers.
5496   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5497   if (ImplicitParamType.getCVRQualifiers()
5498                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5499       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5500     ICS.setBad(BadConversionSequence::bad_qualifiers,
5501                FromType, ImplicitParamType);
5502     return ICS;
5503   }
5504 
5505   if (FromTypeCanon.hasAddressSpace()) {
5506     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5507     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5508     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5509       ICS.setBad(BadConversionSequence::bad_qualifiers,
5510                  FromType, ImplicitParamType);
5511       return ICS;
5512     }
5513   }
5514 
5515   // Check that we have either the same type or a derived type. It
5516   // affects the conversion rank.
5517   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5518   ImplicitConversionKind SecondKind;
5519   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5520     SecondKind = ICK_Identity;
5521   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5522     SecondKind = ICK_Derived_To_Base;
5523   else {
5524     ICS.setBad(BadConversionSequence::unrelated_class,
5525                FromType, ImplicitParamType);
5526     return ICS;
5527   }
5528 
5529   // Check the ref-qualifier.
5530   switch (Method->getRefQualifier()) {
5531   case RQ_None:
5532     // Do nothing; we don't care about lvalueness or rvalueness.
5533     break;
5534 
5535   case RQ_LValue:
5536     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5537       // non-const lvalue reference cannot bind to an rvalue
5538       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5539                  ImplicitParamType);
5540       return ICS;
5541     }
5542     break;
5543 
5544   case RQ_RValue:
5545     if (!FromClassification.isRValue()) {
5546       // rvalue reference cannot bind to an lvalue
5547       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5548                  ImplicitParamType);
5549       return ICS;
5550     }
5551     break;
5552   }
5553 
5554   // Success. Mark this as a reference binding.
5555   ICS.setStandard();
5556   ICS.Standard.setAsIdentityConversion();
5557   ICS.Standard.Second = SecondKind;
5558   ICS.Standard.setFromType(FromType);
5559   ICS.Standard.setAllToTypes(ImplicitParamType);
5560   ICS.Standard.ReferenceBinding = true;
5561   ICS.Standard.DirectBinding = true;
5562   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5563   ICS.Standard.BindsToFunctionLvalue = false;
5564   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5565   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5566     = (Method->getRefQualifier() == RQ_None);
5567   return ICS;
5568 }
5569 
5570 /// PerformObjectArgumentInitialization - Perform initialization of
5571 /// the implicit object parameter for the given Method with the given
5572 /// expression.
5573 ExprResult
5574 Sema::PerformObjectArgumentInitialization(Expr *From,
5575                                           NestedNameSpecifier *Qualifier,
5576                                           NamedDecl *FoundDecl,
5577                                           CXXMethodDecl *Method) {
5578   QualType FromRecordType, DestType;
5579   QualType ImplicitParamRecordType  =
5580     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5581 
5582   Expr::Classification FromClassification;
5583   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5584     FromRecordType = PT->getPointeeType();
5585     DestType = Method->getThisType();
5586     FromClassification = Expr::Classification::makeSimpleLValue();
5587   } else {
5588     FromRecordType = From->getType();
5589     DestType = ImplicitParamRecordType;
5590     FromClassification = From->Classify(Context);
5591 
5592     // When performing member access on a prvalue, materialize a temporary.
5593     if (From->isPRValue()) {
5594       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5595                                             Method->getRefQualifier() !=
5596                                                 RefQualifierKind::RQ_RValue);
5597     }
5598   }
5599 
5600   // Note that we always use the true parent context when performing
5601   // the actual argument initialization.
5602   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5603       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5604       Method->getParent());
5605   if (ICS.isBad()) {
5606     switch (ICS.Bad.Kind) {
5607     case BadConversionSequence::bad_qualifiers: {
5608       Qualifiers FromQs = FromRecordType.getQualifiers();
5609       Qualifiers ToQs = DestType.getQualifiers();
5610       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5611       if (CVR) {
5612         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5613             << Method->getDeclName() << FromRecordType << (CVR - 1)
5614             << From->getSourceRange();
5615         Diag(Method->getLocation(), diag::note_previous_decl)
5616           << Method->getDeclName();
5617         return ExprError();
5618       }
5619       break;
5620     }
5621 
5622     case BadConversionSequence::lvalue_ref_to_rvalue:
5623     case BadConversionSequence::rvalue_ref_to_lvalue: {
5624       bool IsRValueQualified =
5625         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5626       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5627           << Method->getDeclName() << FromClassification.isRValue()
5628           << IsRValueQualified;
5629       Diag(Method->getLocation(), diag::note_previous_decl)
5630         << Method->getDeclName();
5631       return ExprError();
5632     }
5633 
5634     case BadConversionSequence::no_conversion:
5635     case BadConversionSequence::unrelated_class:
5636       break;
5637 
5638     case BadConversionSequence::too_few_initializers:
5639     case BadConversionSequence::too_many_initializers:
5640       llvm_unreachable("Lists are not objects");
5641     }
5642 
5643     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5644            << ImplicitParamRecordType << FromRecordType
5645            << From->getSourceRange();
5646   }
5647 
5648   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5649     ExprResult FromRes =
5650       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5651     if (FromRes.isInvalid())
5652       return ExprError();
5653     From = FromRes.get();
5654   }
5655 
5656   if (!Context.hasSameType(From->getType(), DestType)) {
5657     CastKind CK;
5658     QualType PteeTy = DestType->getPointeeType();
5659     LangAS DestAS =
5660         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5661     if (FromRecordType.getAddressSpace() != DestAS)
5662       CK = CK_AddressSpaceConversion;
5663     else
5664       CK = CK_NoOp;
5665     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5666   }
5667   return From;
5668 }
5669 
5670 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5671 /// expression From to bool (C++0x [conv]p3).
5672 static ImplicitConversionSequence
5673 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5674   // C++ [dcl.init]/17.8:
5675   //   - Otherwise, if the initialization is direct-initialization, the source
5676   //     type is std::nullptr_t, and the destination type is bool, the initial
5677   //     value of the object being initialized is false.
5678   if (From->getType()->isNullPtrType())
5679     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5680                                                         S.Context.BoolTy,
5681                                                         From->isGLValue());
5682 
5683   // All other direct-initialization of bool is equivalent to an implicit
5684   // conversion to bool in which explicit conversions are permitted.
5685   return TryImplicitConversion(S, From, S.Context.BoolTy,
5686                                /*SuppressUserConversions=*/false,
5687                                AllowedExplicit::Conversions,
5688                                /*InOverloadResolution=*/false,
5689                                /*CStyle=*/false,
5690                                /*AllowObjCWritebackConversion=*/false,
5691                                /*AllowObjCConversionOnExplicit=*/false);
5692 }
5693 
5694 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5695 /// of the expression From to bool (C++0x [conv]p3).
5696 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5697   if (checkPlaceholderForOverload(*this, From))
5698     return ExprError();
5699 
5700   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5701   if (!ICS.isBad())
5702     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5703 
5704   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5705     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5706            << From->getType() << From->getSourceRange();
5707   return ExprError();
5708 }
5709 
5710 /// Check that the specified conversion is permitted in a converted constant
5711 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5712 /// is acceptable.
5713 static bool CheckConvertedConstantConversions(Sema &S,
5714                                               StandardConversionSequence &SCS) {
5715   // Since we know that the target type is an integral or unscoped enumeration
5716   // type, most conversion kinds are impossible. All possible First and Third
5717   // conversions are fine.
5718   switch (SCS.Second) {
5719   case ICK_Identity:
5720   case ICK_Integral_Promotion:
5721   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5722   case ICK_Zero_Queue_Conversion:
5723     return true;
5724 
5725   case ICK_Boolean_Conversion:
5726     // Conversion from an integral or unscoped enumeration type to bool is
5727     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5728     // conversion, so we allow it in a converted constant expression.
5729     //
5730     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5731     // a lot of popular code. We should at least add a warning for this
5732     // (non-conforming) extension.
5733     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5734            SCS.getToType(2)->isBooleanType();
5735 
5736   case ICK_Pointer_Conversion:
5737   case ICK_Pointer_Member:
5738     // C++1z: null pointer conversions and null member pointer conversions are
5739     // only permitted if the source type is std::nullptr_t.
5740     return SCS.getFromType()->isNullPtrType();
5741 
5742   case ICK_Floating_Promotion:
5743   case ICK_Complex_Promotion:
5744   case ICK_Floating_Conversion:
5745   case ICK_Complex_Conversion:
5746   case ICK_Floating_Integral:
5747   case ICK_Compatible_Conversion:
5748   case ICK_Derived_To_Base:
5749   case ICK_Vector_Conversion:
5750   case ICK_SVE_Vector_Conversion:
5751   case ICK_Vector_Splat:
5752   case ICK_Complex_Real:
5753   case ICK_Block_Pointer_Conversion:
5754   case ICK_TransparentUnionConversion:
5755   case ICK_Writeback_Conversion:
5756   case ICK_Zero_Event_Conversion:
5757   case ICK_C_Only_Conversion:
5758   case ICK_Incompatible_Pointer_Conversion:
5759     return false;
5760 
5761   case ICK_Lvalue_To_Rvalue:
5762   case ICK_Array_To_Pointer:
5763   case ICK_Function_To_Pointer:
5764     llvm_unreachable("found a first conversion kind in Second");
5765 
5766   case ICK_Function_Conversion:
5767   case ICK_Qualification:
5768     llvm_unreachable("found a third conversion kind in Second");
5769 
5770   case ICK_Num_Conversion_Kinds:
5771     break;
5772   }
5773 
5774   llvm_unreachable("unknown conversion kind");
5775 }
5776 
5777 /// CheckConvertedConstantExpression - Check that the expression From is a
5778 /// converted constant expression of type T, perform the conversion and produce
5779 /// the converted expression, per C++11 [expr.const]p3.
5780 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5781                                                    QualType T, APValue &Value,
5782                                                    Sema::CCEKind CCE,
5783                                                    bool RequireInt,
5784                                                    NamedDecl *Dest) {
5785   assert(S.getLangOpts().CPlusPlus11 &&
5786          "converted constant expression outside C++11");
5787 
5788   if (checkPlaceholderForOverload(S, From))
5789     return ExprError();
5790 
5791   // C++1z [expr.const]p3:
5792   //  A converted constant expression of type T is an expression,
5793   //  implicitly converted to type T, where the converted
5794   //  expression is a constant expression and the implicit conversion
5795   //  sequence contains only [... list of conversions ...].
5796   ImplicitConversionSequence ICS =
5797       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5798           ? TryContextuallyConvertToBool(S, From)
5799           : TryCopyInitialization(S, From, T,
5800                                   /*SuppressUserConversions=*/false,
5801                                   /*InOverloadResolution=*/false,
5802                                   /*AllowObjCWritebackConversion=*/false,
5803                                   /*AllowExplicit=*/false);
5804   StandardConversionSequence *SCS = nullptr;
5805   switch (ICS.getKind()) {
5806   case ImplicitConversionSequence::StandardConversion:
5807     SCS = &ICS.Standard;
5808     break;
5809   case ImplicitConversionSequence::UserDefinedConversion:
5810     if (T->isRecordType())
5811       SCS = &ICS.UserDefined.Before;
5812     else
5813       SCS = &ICS.UserDefined.After;
5814     break;
5815   case ImplicitConversionSequence::AmbiguousConversion:
5816   case ImplicitConversionSequence::BadConversion:
5817     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5818       return S.Diag(From->getBeginLoc(),
5819                     diag::err_typecheck_converted_constant_expression)
5820              << From->getType() << From->getSourceRange() << T;
5821     return ExprError();
5822 
5823   case ImplicitConversionSequence::EllipsisConversion:
5824   case ImplicitConversionSequence::StaticObjectArgumentConversion:
5825     llvm_unreachable("bad conversion in converted constant expression");
5826   }
5827 
5828   // Check that we would only use permitted conversions.
5829   if (!CheckConvertedConstantConversions(S, *SCS)) {
5830     return S.Diag(From->getBeginLoc(),
5831                   diag::err_typecheck_converted_constant_expression_disallowed)
5832            << From->getType() << From->getSourceRange() << T;
5833   }
5834   // [...] and where the reference binding (if any) binds directly.
5835   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5836     return S.Diag(From->getBeginLoc(),
5837                   diag::err_typecheck_converted_constant_expression_indirect)
5838            << From->getType() << From->getSourceRange() << T;
5839   }
5840 
5841   // Usually we can simply apply the ImplicitConversionSequence we formed
5842   // earlier, but that's not guaranteed to work when initializing an object of
5843   // class type.
5844   ExprResult Result;
5845   if (T->isRecordType()) {
5846     assert(CCE == Sema::CCEK_TemplateArg &&
5847            "unexpected class type converted constant expr");
5848     Result = S.PerformCopyInitialization(
5849         InitializedEntity::InitializeTemplateParameter(
5850             T, cast<NonTypeTemplateParmDecl>(Dest)),
5851         SourceLocation(), From);
5852   } else {
5853     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5854   }
5855   if (Result.isInvalid())
5856     return Result;
5857 
5858   // C++2a [intro.execution]p5:
5859   //   A full-expression is [...] a constant-expression [...]
5860   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5861                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
5862                                  CCE == Sema::CCEKind::CCEK_TemplateArg);
5863   if (Result.isInvalid())
5864     return Result;
5865 
5866   // Check for a narrowing implicit conversion.
5867   bool ReturnPreNarrowingValue = false;
5868   APValue PreNarrowingValue;
5869   QualType PreNarrowingType;
5870   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5871                                 PreNarrowingType)) {
5872   case NK_Dependent_Narrowing:
5873     // Implicit conversion to a narrower type, but the expression is
5874     // value-dependent so we can't tell whether it's actually narrowing.
5875   case NK_Variable_Narrowing:
5876     // Implicit conversion to a narrower type, and the value is not a constant
5877     // expression. We'll diagnose this in a moment.
5878   case NK_Not_Narrowing:
5879     break;
5880 
5881   case NK_Constant_Narrowing:
5882     if (CCE == Sema::CCEK_ArrayBound &&
5883         PreNarrowingType->isIntegralOrEnumerationType() &&
5884         PreNarrowingValue.isInt()) {
5885       // Don't diagnose array bound narrowing here; we produce more precise
5886       // errors by allowing the un-narrowed value through.
5887       ReturnPreNarrowingValue = true;
5888       break;
5889     }
5890     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5891         << CCE << /*Constant*/ 1
5892         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5893     break;
5894 
5895   case NK_Type_Narrowing:
5896     // FIXME: It would be better to diagnose that the expression is not a
5897     // constant expression.
5898     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5899         << CCE << /*Constant*/ 0 << From->getType() << T;
5900     break;
5901   }
5902 
5903   if (Result.get()->isValueDependent()) {
5904     Value = APValue();
5905     return Result;
5906   }
5907 
5908   // Check the expression is a constant expression.
5909   SmallVector<PartialDiagnosticAt, 8> Notes;
5910   Expr::EvalResult Eval;
5911   Eval.Diag = &Notes;
5912 
5913   ConstantExprKind Kind;
5914   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5915     Kind = ConstantExprKind::ClassTemplateArgument;
5916   else if (CCE == Sema::CCEK_TemplateArg)
5917     Kind = ConstantExprKind::NonClassTemplateArgument;
5918   else
5919     Kind = ConstantExprKind::Normal;
5920 
5921   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5922       (RequireInt && !Eval.Val.isInt())) {
5923     // The expression can't be folded, so we can't keep it at this position in
5924     // the AST.
5925     Result = ExprError();
5926   } else {
5927     Value = Eval.Val;
5928 
5929     if (Notes.empty()) {
5930       // It's a constant expression.
5931       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5932       if (ReturnPreNarrowingValue)
5933         Value = std::move(PreNarrowingValue);
5934       return E;
5935     }
5936   }
5937 
5938   // It's not a constant expression. Produce an appropriate diagnostic.
5939   if (Notes.size() == 1 &&
5940       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5941     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5942   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5943                                    diag::note_constexpr_invalid_template_arg) {
5944     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5945     for (unsigned I = 0; I < Notes.size(); ++I)
5946       S.Diag(Notes[I].first, Notes[I].second);
5947   } else {
5948     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5949         << CCE << From->getSourceRange();
5950     for (unsigned I = 0; I < Notes.size(); ++I)
5951       S.Diag(Notes[I].first, Notes[I].second);
5952   }
5953   return ExprError();
5954 }
5955 
5956 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5957                                                   APValue &Value, CCEKind CCE,
5958                                                   NamedDecl *Dest) {
5959   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5960                                             Dest);
5961 }
5962 
5963 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5964                                                   llvm::APSInt &Value,
5965                                                   CCEKind CCE) {
5966   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5967 
5968   APValue V;
5969   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5970                                               /*Dest=*/nullptr);
5971   if (!R.isInvalid() && !R.get()->isValueDependent())
5972     Value = V.getInt();
5973   return R;
5974 }
5975 
5976 
5977 /// dropPointerConversions - If the given standard conversion sequence
5978 /// involves any pointer conversions, remove them.  This may change
5979 /// the result type of the conversion sequence.
5980 static void dropPointerConversion(StandardConversionSequence &SCS) {
5981   if (SCS.Second == ICK_Pointer_Conversion) {
5982     SCS.Second = ICK_Identity;
5983     SCS.Third = ICK_Identity;
5984     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5985   }
5986 }
5987 
5988 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5989 /// convert the expression From to an Objective-C pointer type.
5990 static ImplicitConversionSequence
5991 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5992   // Do an implicit conversion to 'id'.
5993   QualType Ty = S.Context.getObjCIdType();
5994   ImplicitConversionSequence ICS
5995     = TryImplicitConversion(S, From, Ty,
5996                             // FIXME: Are these flags correct?
5997                             /*SuppressUserConversions=*/false,
5998                             AllowedExplicit::Conversions,
5999                             /*InOverloadResolution=*/false,
6000                             /*CStyle=*/false,
6001                             /*AllowObjCWritebackConversion=*/false,
6002                             /*AllowObjCConversionOnExplicit=*/true);
6003 
6004   // Strip off any final conversions to 'id'.
6005   switch (ICS.getKind()) {
6006   case ImplicitConversionSequence::BadConversion:
6007   case ImplicitConversionSequence::AmbiguousConversion:
6008   case ImplicitConversionSequence::EllipsisConversion:
6009   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6010     break;
6011 
6012   case ImplicitConversionSequence::UserDefinedConversion:
6013     dropPointerConversion(ICS.UserDefined.After);
6014     break;
6015 
6016   case ImplicitConversionSequence::StandardConversion:
6017     dropPointerConversion(ICS.Standard);
6018     break;
6019   }
6020 
6021   return ICS;
6022 }
6023 
6024 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6025 /// conversion of the expression From to an Objective-C pointer type.
6026 /// Returns a valid but null ExprResult if no conversion sequence exists.
6027 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6028   if (checkPlaceholderForOverload(*this, From))
6029     return ExprError();
6030 
6031   QualType Ty = Context.getObjCIdType();
6032   ImplicitConversionSequence ICS =
6033     TryContextuallyConvertToObjCPointer(*this, From);
6034   if (!ICS.isBad())
6035     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6036   return ExprResult();
6037 }
6038 
6039 /// Determine whether the provided type is an integral type, or an enumeration
6040 /// type of a permitted flavor.
6041 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6042   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6043                                  : T->isIntegralOrUnscopedEnumerationType();
6044 }
6045 
6046 static ExprResult
6047 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6048                             Sema::ContextualImplicitConverter &Converter,
6049                             QualType T, UnresolvedSetImpl &ViableConversions) {
6050 
6051   if (Converter.Suppress)
6052     return ExprError();
6053 
6054   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6055   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6056     CXXConversionDecl *Conv =
6057         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6058     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6059     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6060   }
6061   return From;
6062 }
6063 
6064 static bool
6065 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6066                            Sema::ContextualImplicitConverter &Converter,
6067                            QualType T, bool HadMultipleCandidates,
6068                            UnresolvedSetImpl &ExplicitConversions) {
6069   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6070     DeclAccessPair Found = ExplicitConversions[0];
6071     CXXConversionDecl *Conversion =
6072         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6073 
6074     // The user probably meant to invoke the given explicit
6075     // conversion; use it.
6076     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6077     std::string TypeStr;
6078     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6079 
6080     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6081         << FixItHint::CreateInsertion(From->getBeginLoc(),
6082                                       "static_cast<" + TypeStr + ">(")
6083         << FixItHint::CreateInsertion(
6084                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6085     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6086 
6087     // If we aren't in a SFINAE context, build a call to the
6088     // explicit conversion function.
6089     if (SemaRef.isSFINAEContext())
6090       return true;
6091 
6092     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6093     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6094                                                        HadMultipleCandidates);
6095     if (Result.isInvalid())
6096       return true;
6097     // Record usage of conversion in an implicit cast.
6098     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6099                                     CK_UserDefinedConversion, Result.get(),
6100                                     nullptr, Result.get()->getValueKind(),
6101                                     SemaRef.CurFPFeatureOverrides());
6102   }
6103   return false;
6104 }
6105 
6106 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6107                              Sema::ContextualImplicitConverter &Converter,
6108                              QualType T, bool HadMultipleCandidates,
6109                              DeclAccessPair &Found) {
6110   CXXConversionDecl *Conversion =
6111       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6112   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6113 
6114   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6115   if (!Converter.SuppressConversion) {
6116     if (SemaRef.isSFINAEContext())
6117       return true;
6118 
6119     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6120         << From->getSourceRange();
6121   }
6122 
6123   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6124                                                      HadMultipleCandidates);
6125   if (Result.isInvalid())
6126     return true;
6127   // Record usage of conversion in an implicit cast.
6128   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6129                                   CK_UserDefinedConversion, Result.get(),
6130                                   nullptr, Result.get()->getValueKind(),
6131                                   SemaRef.CurFPFeatureOverrides());
6132   return false;
6133 }
6134 
6135 static ExprResult finishContextualImplicitConversion(
6136     Sema &SemaRef, SourceLocation Loc, Expr *From,
6137     Sema::ContextualImplicitConverter &Converter) {
6138   if (!Converter.match(From->getType()) && !Converter.Suppress)
6139     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6140         << From->getSourceRange();
6141 
6142   return SemaRef.DefaultLvalueConversion(From);
6143 }
6144 
6145 static void
6146 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6147                                   UnresolvedSetImpl &ViableConversions,
6148                                   OverloadCandidateSet &CandidateSet) {
6149   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6150     DeclAccessPair FoundDecl = ViableConversions[I];
6151     NamedDecl *D = FoundDecl.getDecl();
6152     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6153     if (isa<UsingShadowDecl>(D))
6154       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6155 
6156     CXXConversionDecl *Conv;
6157     FunctionTemplateDecl *ConvTemplate;
6158     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6159       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6160     else
6161       Conv = cast<CXXConversionDecl>(D);
6162 
6163     if (ConvTemplate)
6164       SemaRef.AddTemplateConversionCandidate(
6165           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6166           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6167     else
6168       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6169                                      ToType, CandidateSet,
6170                                      /*AllowObjCConversionOnExplicit=*/false,
6171                                      /*AllowExplicit*/ true);
6172   }
6173 }
6174 
6175 /// Attempt to convert the given expression to a type which is accepted
6176 /// by the given converter.
6177 ///
6178 /// This routine will attempt to convert an expression of class type to a
6179 /// type accepted by the specified converter. In C++11 and before, the class
6180 /// must have a single non-explicit conversion function converting to a matching
6181 /// type. In C++1y, there can be multiple such conversion functions, but only
6182 /// one target type.
6183 ///
6184 /// \param Loc The source location of the construct that requires the
6185 /// conversion.
6186 ///
6187 /// \param From The expression we're converting from.
6188 ///
6189 /// \param Converter Used to control and diagnose the conversion process.
6190 ///
6191 /// \returns The expression, converted to an integral or enumeration type if
6192 /// successful.
6193 ExprResult Sema::PerformContextualImplicitConversion(
6194     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6195   // We can't perform any more checking for type-dependent expressions.
6196   if (From->isTypeDependent())
6197     return From;
6198 
6199   // Process placeholders immediately.
6200   if (From->hasPlaceholderType()) {
6201     ExprResult result = CheckPlaceholderExpr(From);
6202     if (result.isInvalid())
6203       return result;
6204     From = result.get();
6205   }
6206 
6207   // If the expression already has a matching type, we're golden.
6208   QualType T = From->getType();
6209   if (Converter.match(T))
6210     return DefaultLvalueConversion(From);
6211 
6212   // FIXME: Check for missing '()' if T is a function type?
6213 
6214   // We can only perform contextual implicit conversions on objects of class
6215   // type.
6216   const RecordType *RecordTy = T->getAs<RecordType>();
6217   if (!RecordTy || !getLangOpts().CPlusPlus) {
6218     if (!Converter.Suppress)
6219       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6220     return From;
6221   }
6222 
6223   // We must have a complete class type.
6224   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6225     ContextualImplicitConverter &Converter;
6226     Expr *From;
6227 
6228     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6229         : Converter(Converter), From(From) {}
6230 
6231     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6232       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6233     }
6234   } IncompleteDiagnoser(Converter, From);
6235 
6236   if (Converter.Suppress ? !isCompleteType(Loc, T)
6237                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6238     return From;
6239 
6240   // Look for a conversion to an integral or enumeration type.
6241   UnresolvedSet<4>
6242       ViableConversions; // These are *potentially* viable in C++1y.
6243   UnresolvedSet<4> ExplicitConversions;
6244   const auto &Conversions =
6245       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6246 
6247   bool HadMultipleCandidates =
6248       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6249 
6250   // To check that there is only one target type, in C++1y:
6251   QualType ToType;
6252   bool HasUniqueTargetType = true;
6253 
6254   // Collect explicit or viable (potentially in C++1y) conversions.
6255   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6256     NamedDecl *D = (*I)->getUnderlyingDecl();
6257     CXXConversionDecl *Conversion;
6258     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6259     if (ConvTemplate) {
6260       if (getLangOpts().CPlusPlus14)
6261         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6262       else
6263         continue; // C++11 does not consider conversion operator templates(?).
6264     } else
6265       Conversion = cast<CXXConversionDecl>(D);
6266 
6267     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6268            "Conversion operator templates are considered potentially "
6269            "viable in C++1y");
6270 
6271     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6272     if (Converter.match(CurToType) || ConvTemplate) {
6273 
6274       if (Conversion->isExplicit()) {
6275         // FIXME: For C++1y, do we need this restriction?
6276         // cf. diagnoseNoViableConversion()
6277         if (!ConvTemplate)
6278           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6279       } else {
6280         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6281           if (ToType.isNull())
6282             ToType = CurToType.getUnqualifiedType();
6283           else if (HasUniqueTargetType &&
6284                    (CurToType.getUnqualifiedType() != ToType))
6285             HasUniqueTargetType = false;
6286         }
6287         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6288       }
6289     }
6290   }
6291 
6292   if (getLangOpts().CPlusPlus14) {
6293     // C++1y [conv]p6:
6294     // ... An expression e of class type E appearing in such a context
6295     // is said to be contextually implicitly converted to a specified
6296     // type T and is well-formed if and only if e can be implicitly
6297     // converted to a type T that is determined as follows: E is searched
6298     // for conversion functions whose return type is cv T or reference to
6299     // cv T such that T is allowed by the context. There shall be
6300     // exactly one such T.
6301 
6302     // If no unique T is found:
6303     if (ToType.isNull()) {
6304       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6305                                      HadMultipleCandidates,
6306                                      ExplicitConversions))
6307         return ExprError();
6308       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6309     }
6310 
6311     // If more than one unique Ts are found:
6312     if (!HasUniqueTargetType)
6313       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6314                                          ViableConversions);
6315 
6316     // If one unique T is found:
6317     // First, build a candidate set from the previously recorded
6318     // potentially viable conversions.
6319     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6320     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6321                                       CandidateSet);
6322 
6323     // Then, perform overload resolution over the candidate set.
6324     OverloadCandidateSet::iterator Best;
6325     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6326     case OR_Success: {
6327       // Apply this conversion.
6328       DeclAccessPair Found =
6329           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6330       if (recordConversion(*this, Loc, From, Converter, T,
6331                            HadMultipleCandidates, Found))
6332         return ExprError();
6333       break;
6334     }
6335     case OR_Ambiguous:
6336       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6337                                          ViableConversions);
6338     case OR_No_Viable_Function:
6339       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6340                                      HadMultipleCandidates,
6341                                      ExplicitConversions))
6342         return ExprError();
6343       [[fallthrough]];
6344     case OR_Deleted:
6345       // We'll complain below about a non-integral condition type.
6346       break;
6347     }
6348   } else {
6349     switch (ViableConversions.size()) {
6350     case 0: {
6351       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6352                                      HadMultipleCandidates,
6353                                      ExplicitConversions))
6354         return ExprError();
6355 
6356       // We'll complain below about a non-integral condition type.
6357       break;
6358     }
6359     case 1: {
6360       // Apply this conversion.
6361       DeclAccessPair Found = ViableConversions[0];
6362       if (recordConversion(*this, Loc, From, Converter, T,
6363                            HadMultipleCandidates, Found))
6364         return ExprError();
6365       break;
6366     }
6367     default:
6368       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6369                                          ViableConversions);
6370     }
6371   }
6372 
6373   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6374 }
6375 
6376 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6377 /// an acceptable non-member overloaded operator for a call whose
6378 /// arguments have types T1 (and, if non-empty, T2). This routine
6379 /// implements the check in C++ [over.match.oper]p3b2 concerning
6380 /// enumeration types.
6381 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6382                                                    FunctionDecl *Fn,
6383                                                    ArrayRef<Expr *> Args) {
6384   QualType T1 = Args[0]->getType();
6385   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6386 
6387   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6388     return true;
6389 
6390   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6391     return true;
6392 
6393   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6394   if (Proto->getNumParams() < 1)
6395     return false;
6396 
6397   if (T1->isEnumeralType()) {
6398     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6399     if (Context.hasSameUnqualifiedType(T1, ArgType))
6400       return true;
6401   }
6402 
6403   if (Proto->getNumParams() < 2)
6404     return false;
6405 
6406   if (!T2.isNull() && T2->isEnumeralType()) {
6407     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6408     if (Context.hasSameUnqualifiedType(T2, ArgType))
6409       return true;
6410   }
6411 
6412   return false;
6413 }
6414 
6415 /// AddOverloadCandidate - Adds the given function to the set of
6416 /// candidate functions, using the given function call arguments.  If
6417 /// @p SuppressUserConversions, then don't allow user-defined
6418 /// conversions via constructors or conversion operators.
6419 ///
6420 /// \param PartialOverloading true if we are performing "partial" overloading
6421 /// based on an incomplete set of function arguments. This feature is used by
6422 /// code completion.
6423 void Sema::AddOverloadCandidate(
6424     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6425     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6426     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6427     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6428     OverloadCandidateParamOrder PO) {
6429   const FunctionProtoType *Proto
6430     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6431   assert(Proto && "Functions without a prototype cannot be overloaded");
6432   assert(!Function->getDescribedFunctionTemplate() &&
6433          "Use AddTemplateOverloadCandidate for function templates");
6434 
6435   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6436     if (!isa<CXXConstructorDecl>(Method)) {
6437       // If we get here, it's because we're calling a member function
6438       // that is named without a member access expression (e.g.,
6439       // "this->f") that was either written explicitly or created
6440       // implicitly. This can happen with a qualified call to a member
6441       // function, e.g., X::f(). We use an empty type for the implied
6442       // object argument (C++ [over.call.func]p3), and the acting context
6443       // is irrelevant.
6444       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6445                          Expr::Classification::makeSimpleLValue(), Args,
6446                          CandidateSet, SuppressUserConversions,
6447                          PartialOverloading, EarlyConversions, PO);
6448       return;
6449     }
6450     // We treat a constructor like a non-member function, since its object
6451     // argument doesn't participate in overload resolution.
6452   }
6453 
6454   if (!CandidateSet.isNewCandidate(Function, PO))
6455     return;
6456 
6457   // C++11 [class.copy]p11: [DR1402]
6458   //   A defaulted move constructor that is defined as deleted is ignored by
6459   //   overload resolution.
6460   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6461   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6462       Constructor->isMoveConstructor())
6463     return;
6464 
6465   // Overload resolution is always an unevaluated context.
6466   EnterExpressionEvaluationContext Unevaluated(
6467       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6468 
6469   // C++ [over.match.oper]p3:
6470   //   if no operand has a class type, only those non-member functions in the
6471   //   lookup set that have a first parameter of type T1 or "reference to
6472   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6473   //   is a right operand) a second parameter of type T2 or "reference to
6474   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6475   //   candidate functions.
6476   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6477       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6478     return;
6479 
6480   // Add this candidate
6481   OverloadCandidate &Candidate =
6482       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6483   Candidate.FoundDecl = FoundDecl;
6484   Candidate.Function = Function;
6485   Candidate.Viable = true;
6486   Candidate.RewriteKind =
6487       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6488   Candidate.IsSurrogate = false;
6489   Candidate.IsADLCandidate = IsADLCandidate;
6490   Candidate.IgnoreObjectArgument = false;
6491   Candidate.ExplicitCallArguments = Args.size();
6492 
6493   // Explicit functions are not actually candidates at all if we're not
6494   // allowing them in this context, but keep them around so we can point
6495   // to them in diagnostics.
6496   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6497     Candidate.Viable = false;
6498     Candidate.FailureKind = ovl_fail_explicit;
6499     return;
6500   }
6501 
6502   // Functions with internal linkage are only viable in the same module unit.
6503   if (auto *MF = Function->getOwningModule()) {
6504     if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
6505         !isModuleUnitOfCurrentTU(MF)) {
6506       /// FIXME: Currently, the semantics of linkage in clang is slightly
6507       /// different from the semantics in C++ spec. In C++ spec, only names
6508       /// have linkage. So that all entities of the same should share one
6509       /// linkage. But in clang, different entities of the same could have
6510       /// different linkage.
6511       NamedDecl *ND = Function;
6512       if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6513         ND = SpecInfo->getTemplate();
6514 
6515       if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6516         Candidate.Viable = false;
6517         Candidate.FailureKind = ovl_fail_module_mismatched;
6518         return;
6519       }
6520     }
6521   }
6522 
6523   if (Function->isMultiVersion() &&
6524       ((Function->hasAttr<TargetAttr>() &&
6525         !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6526        (Function->hasAttr<TargetVersionAttr>() &&
6527         !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6528     Candidate.Viable = false;
6529     Candidate.FailureKind = ovl_non_default_multiversion_function;
6530     return;
6531   }
6532 
6533   if (Constructor) {
6534     // C++ [class.copy]p3:
6535     //   A member function template is never instantiated to perform the copy
6536     //   of a class object to an object of its class type.
6537     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6538     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6539         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6540          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6541                        ClassType))) {
6542       Candidate.Viable = false;
6543       Candidate.FailureKind = ovl_fail_illegal_constructor;
6544       return;
6545     }
6546 
6547     // C++ [over.match.funcs]p8: (proposed DR resolution)
6548     //   A constructor inherited from class type C that has a first parameter
6549     //   of type "reference to P" (including such a constructor instantiated
6550     //   from a template) is excluded from the set of candidate functions when
6551     //   constructing an object of type cv D if the argument list has exactly
6552     //   one argument and D is reference-related to P and P is reference-related
6553     //   to C.
6554     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6555     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6556         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6557       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6558       QualType C = Context.getRecordType(Constructor->getParent());
6559       QualType D = Context.getRecordType(Shadow->getParent());
6560       SourceLocation Loc = Args.front()->getExprLoc();
6561       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6562           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6563         Candidate.Viable = false;
6564         Candidate.FailureKind = ovl_fail_inhctor_slice;
6565         return;
6566       }
6567     }
6568 
6569     // Check that the constructor is capable of constructing an object in the
6570     // destination address space.
6571     if (!Qualifiers::isAddressSpaceSupersetOf(
6572             Constructor->getMethodQualifiers().getAddressSpace(),
6573             CandidateSet.getDestAS())) {
6574       Candidate.Viable = false;
6575       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6576     }
6577   }
6578 
6579   unsigned NumParams = Proto->getNumParams();
6580 
6581   // (C++ 13.3.2p2): A candidate function having fewer than m
6582   // parameters is viable only if it has an ellipsis in its parameter
6583   // list (8.3.5).
6584   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6585       !Proto->isVariadic() &&
6586       shouldEnforceArgLimit(PartialOverloading, Function)) {
6587     Candidate.Viable = false;
6588     Candidate.FailureKind = ovl_fail_too_many_arguments;
6589     return;
6590   }
6591 
6592   // (C++ 13.3.2p2): A candidate function having more than m parameters
6593   // is viable only if the (m+1)st parameter has a default argument
6594   // (8.3.6). For the purposes of overload resolution, the
6595   // parameter list is truncated on the right, so that there are
6596   // exactly m parameters.
6597   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6598   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6599     // Not enough arguments.
6600     Candidate.Viable = false;
6601     Candidate.FailureKind = ovl_fail_too_few_arguments;
6602     return;
6603   }
6604 
6605   // (CUDA B.1): Check for invalid calls between targets.
6606   if (getLangOpts().CUDA)
6607     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6608       // Skip the check for callers that are implicit members, because in this
6609       // case we may not yet know what the member's target is; the target is
6610       // inferred for the member automatically, based on the bases and fields of
6611       // the class.
6612       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6613         Candidate.Viable = false;
6614         Candidate.FailureKind = ovl_fail_bad_target;
6615         return;
6616       }
6617 
6618   if (Function->getTrailingRequiresClause()) {
6619     ConstraintSatisfaction Satisfaction;
6620     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6621                                  /*ForOverloadResolution*/ true) ||
6622         !Satisfaction.IsSatisfied) {
6623       Candidate.Viable = false;
6624       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6625       return;
6626     }
6627   }
6628 
6629   // Determine the implicit conversion sequences for each of the
6630   // arguments.
6631   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6632     unsigned ConvIdx =
6633         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6634     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6635       // We already formed a conversion sequence for this parameter during
6636       // template argument deduction.
6637     } else if (ArgIdx < NumParams) {
6638       // (C++ 13.3.2p3): for F to be a viable function, there shall
6639       // exist for each argument an implicit conversion sequence
6640       // (13.3.3.1) that converts that argument to the corresponding
6641       // parameter of F.
6642       QualType ParamType = Proto->getParamType(ArgIdx);
6643       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6644           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6645           /*InOverloadResolution=*/true,
6646           /*AllowObjCWritebackConversion=*/
6647           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6648       if (Candidate.Conversions[ConvIdx].isBad()) {
6649         Candidate.Viable = false;
6650         Candidate.FailureKind = ovl_fail_bad_conversion;
6651         return;
6652       }
6653     } else {
6654       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6655       // argument for which there is no corresponding parameter is
6656       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6657       Candidate.Conversions[ConvIdx].setEllipsis();
6658     }
6659   }
6660 
6661   if (EnableIfAttr *FailedAttr =
6662           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6663     Candidate.Viable = false;
6664     Candidate.FailureKind = ovl_fail_enable_if;
6665     Candidate.DeductionFailure.Data = FailedAttr;
6666     return;
6667   }
6668 }
6669 
6670 ObjCMethodDecl *
6671 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6672                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6673   if (Methods.size() <= 1)
6674     return nullptr;
6675 
6676   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6677     bool Match = true;
6678     ObjCMethodDecl *Method = Methods[b];
6679     unsigned NumNamedArgs = Sel.getNumArgs();
6680     // Method might have more arguments than selector indicates. This is due
6681     // to addition of c-style arguments in method.
6682     if (Method->param_size() > NumNamedArgs)
6683       NumNamedArgs = Method->param_size();
6684     if (Args.size() < NumNamedArgs)
6685       continue;
6686 
6687     for (unsigned i = 0; i < NumNamedArgs; i++) {
6688       // We can't do any type-checking on a type-dependent argument.
6689       if (Args[i]->isTypeDependent()) {
6690         Match = false;
6691         break;
6692       }
6693 
6694       ParmVarDecl *param = Method->parameters()[i];
6695       Expr *argExpr = Args[i];
6696       assert(argExpr && "SelectBestMethod(): missing expression");
6697 
6698       // Strip the unbridged-cast placeholder expression off unless it's
6699       // a consumed argument.
6700       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6701           !param->hasAttr<CFConsumedAttr>())
6702         argExpr = stripARCUnbridgedCast(argExpr);
6703 
6704       // If the parameter is __unknown_anytype, move on to the next method.
6705       if (param->getType() == Context.UnknownAnyTy) {
6706         Match = false;
6707         break;
6708       }
6709 
6710       ImplicitConversionSequence ConversionState
6711         = TryCopyInitialization(*this, argExpr, param->getType(),
6712                                 /*SuppressUserConversions*/false,
6713                                 /*InOverloadResolution=*/true,
6714                                 /*AllowObjCWritebackConversion=*/
6715                                 getLangOpts().ObjCAutoRefCount,
6716                                 /*AllowExplicit*/false);
6717       // This function looks for a reasonably-exact match, so we consider
6718       // incompatible pointer conversions to be a failure here.
6719       if (ConversionState.isBad() ||
6720           (ConversionState.isStandard() &&
6721            ConversionState.Standard.Second ==
6722                ICK_Incompatible_Pointer_Conversion)) {
6723         Match = false;
6724         break;
6725       }
6726     }
6727     // Promote additional arguments to variadic methods.
6728     if (Match && Method->isVariadic()) {
6729       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6730         if (Args[i]->isTypeDependent()) {
6731           Match = false;
6732           break;
6733         }
6734         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6735                                                           nullptr);
6736         if (Arg.isInvalid()) {
6737           Match = false;
6738           break;
6739         }
6740       }
6741     } else {
6742       // Check for extra arguments to non-variadic methods.
6743       if (Args.size() != NumNamedArgs)
6744         Match = false;
6745       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6746         // Special case when selectors have no argument. In this case, select
6747         // one with the most general result type of 'id'.
6748         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6749           QualType ReturnT = Methods[b]->getReturnType();
6750           if (ReturnT->isObjCIdType())
6751             return Methods[b];
6752         }
6753       }
6754     }
6755 
6756     if (Match)
6757       return Method;
6758   }
6759   return nullptr;
6760 }
6761 
6762 static bool convertArgsForAvailabilityChecks(
6763     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6764     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6765     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6766   if (ThisArg) {
6767     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6768     assert(!isa<CXXConstructorDecl>(Method) &&
6769            "Shouldn't have `this` for ctors!");
6770     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6771     ExprResult R = S.PerformObjectArgumentInitialization(
6772         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6773     if (R.isInvalid())
6774       return false;
6775     ConvertedThis = R.get();
6776   } else {
6777     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6778       (void)MD;
6779       assert((MissingImplicitThis || MD->isStatic() ||
6780               isa<CXXConstructorDecl>(MD)) &&
6781              "Expected `this` for non-ctor instance methods");
6782     }
6783     ConvertedThis = nullptr;
6784   }
6785 
6786   // Ignore any variadic arguments. Converting them is pointless, since the
6787   // user can't refer to them in the function condition.
6788   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6789 
6790   // Convert the arguments.
6791   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6792     ExprResult R;
6793     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6794                                         S.Context, Function->getParamDecl(I)),
6795                                     SourceLocation(), Args[I]);
6796 
6797     if (R.isInvalid())
6798       return false;
6799 
6800     ConvertedArgs.push_back(R.get());
6801   }
6802 
6803   if (Trap.hasErrorOccurred())
6804     return false;
6805 
6806   // Push default arguments if needed.
6807   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6808     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6809       ParmVarDecl *P = Function->getParamDecl(i);
6810       if (!P->hasDefaultArg())
6811         return false;
6812       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6813       if (R.isInvalid())
6814         return false;
6815       ConvertedArgs.push_back(R.get());
6816     }
6817 
6818     if (Trap.hasErrorOccurred())
6819       return false;
6820   }
6821   return true;
6822 }
6823 
6824 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6825                                   SourceLocation CallLoc,
6826                                   ArrayRef<Expr *> Args,
6827                                   bool MissingImplicitThis) {
6828   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6829   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6830     return nullptr;
6831 
6832   SFINAETrap Trap(*this);
6833   SmallVector<Expr *, 16> ConvertedArgs;
6834   // FIXME: We should look into making enable_if late-parsed.
6835   Expr *DiscardedThis;
6836   if (!convertArgsForAvailabilityChecks(
6837           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6838           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6839     return *EnableIfAttrs.begin();
6840 
6841   for (auto *EIA : EnableIfAttrs) {
6842     APValue Result;
6843     // FIXME: This doesn't consider value-dependent cases, because doing so is
6844     // very difficult. Ideally, we should handle them more gracefully.
6845     if (EIA->getCond()->isValueDependent() ||
6846         !EIA->getCond()->EvaluateWithSubstitution(
6847             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
6848       return EIA;
6849 
6850     if (!Result.isInt() || !Result.getInt().getBoolValue())
6851       return EIA;
6852   }
6853   return nullptr;
6854 }
6855 
6856 template <typename CheckFn>
6857 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6858                                         bool ArgDependent, SourceLocation Loc,
6859                                         CheckFn &&IsSuccessful) {
6860   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6861   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6862     if (ArgDependent == DIA->getArgDependent())
6863       Attrs.push_back(DIA);
6864   }
6865 
6866   // Common case: No diagnose_if attributes, so we can quit early.
6867   if (Attrs.empty())
6868     return false;
6869 
6870   auto WarningBegin = std::stable_partition(
6871       Attrs.begin(), Attrs.end(),
6872       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6873 
6874   // Note that diagnose_if attributes are late-parsed, so they appear in the
6875   // correct order (unlike enable_if attributes).
6876   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6877                                IsSuccessful);
6878   if (ErrAttr != WarningBegin) {
6879     const DiagnoseIfAttr *DIA = *ErrAttr;
6880     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6881     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6882         << DIA->getParent() << DIA->getCond()->getSourceRange();
6883     return true;
6884   }
6885 
6886   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6887     if (IsSuccessful(DIA)) {
6888       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6889       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6890           << DIA->getParent() << DIA->getCond()->getSourceRange();
6891     }
6892 
6893   return false;
6894 }
6895 
6896 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6897                                                const Expr *ThisArg,
6898                                                ArrayRef<const Expr *> Args,
6899                                                SourceLocation Loc) {
6900   return diagnoseDiagnoseIfAttrsWith(
6901       *this, Function, /*ArgDependent=*/true, Loc,
6902       [&](const DiagnoseIfAttr *DIA) {
6903         APValue Result;
6904         // It's sane to use the same Args for any redecl of this function, since
6905         // EvaluateWithSubstitution only cares about the position of each
6906         // argument in the arg list, not the ParmVarDecl* it maps to.
6907         if (!DIA->getCond()->EvaluateWithSubstitution(
6908                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6909           return false;
6910         return Result.isInt() && Result.getInt().getBoolValue();
6911       });
6912 }
6913 
6914 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6915                                                  SourceLocation Loc) {
6916   return diagnoseDiagnoseIfAttrsWith(
6917       *this, ND, /*ArgDependent=*/false, Loc,
6918       [&](const DiagnoseIfAttr *DIA) {
6919         bool Result;
6920         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6921                Result;
6922       });
6923 }
6924 
6925 /// Add all of the function declarations in the given function set to
6926 /// the overload candidate set.
6927 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6928                                  ArrayRef<Expr *> Args,
6929                                  OverloadCandidateSet &CandidateSet,
6930                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6931                                  bool SuppressUserConversions,
6932                                  bool PartialOverloading,
6933                                  bool FirstArgumentIsBase) {
6934   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6935     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6936     ArrayRef<Expr *> FunctionArgs = Args;
6937 
6938     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6939     FunctionDecl *FD =
6940         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6941 
6942     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6943       QualType ObjectType;
6944       Expr::Classification ObjectClassification;
6945       if (Args.size() > 0) {
6946         if (Expr *E = Args[0]) {
6947           // Use the explicit base to restrict the lookup:
6948           ObjectType = E->getType();
6949           // Pointers in the object arguments are implicitly dereferenced, so we
6950           // always classify them as l-values.
6951           if (!ObjectType.isNull() && ObjectType->isPointerType())
6952             ObjectClassification = Expr::Classification::makeSimpleLValue();
6953           else
6954             ObjectClassification = E->Classify(Context);
6955         } // .. else there is an implicit base.
6956         FunctionArgs = Args.slice(1);
6957       }
6958       if (FunTmpl) {
6959         AddMethodTemplateCandidate(
6960             FunTmpl, F.getPair(),
6961             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6962             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6963             FunctionArgs, CandidateSet, SuppressUserConversions,
6964             PartialOverloading);
6965       } else {
6966         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6967                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6968                            ObjectClassification, FunctionArgs, CandidateSet,
6969                            SuppressUserConversions, PartialOverloading);
6970       }
6971     } else {
6972       // This branch handles both standalone functions and static methods.
6973 
6974       // Slice the first argument (which is the base) when we access
6975       // static method as non-static.
6976       if (Args.size() > 0 &&
6977           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6978                         !isa<CXXConstructorDecl>(FD)))) {
6979         assert(cast<CXXMethodDecl>(FD)->isStatic());
6980         FunctionArgs = Args.slice(1);
6981       }
6982       if (FunTmpl) {
6983         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6984                                      ExplicitTemplateArgs, FunctionArgs,
6985                                      CandidateSet, SuppressUserConversions,
6986                                      PartialOverloading);
6987       } else {
6988         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6989                              SuppressUserConversions, PartialOverloading);
6990       }
6991     }
6992   }
6993 }
6994 
6995 /// AddMethodCandidate - Adds a named decl (which is some kind of
6996 /// method) as a method candidate to the given overload set.
6997 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6998                               Expr::Classification ObjectClassification,
6999                               ArrayRef<Expr *> Args,
7000                               OverloadCandidateSet &CandidateSet,
7001                               bool SuppressUserConversions,
7002                               OverloadCandidateParamOrder PO) {
7003   NamedDecl *Decl = FoundDecl.getDecl();
7004   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7005 
7006   if (isa<UsingShadowDecl>(Decl))
7007     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7008 
7009   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7010     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7011            "Expected a member function template");
7012     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7013                                /*ExplicitArgs*/ nullptr, ObjectType,
7014                                ObjectClassification, Args, CandidateSet,
7015                                SuppressUserConversions, false, PO);
7016   } else {
7017     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7018                        ObjectType, ObjectClassification, Args, CandidateSet,
7019                        SuppressUserConversions, false, std::nullopt, PO);
7020   }
7021 }
7022 
7023 /// AddMethodCandidate - Adds the given C++ member function to the set
7024 /// of candidate functions, using the given function call arguments
7025 /// and the object argument (@c Object). For example, in a call
7026 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7027 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7028 /// allow user-defined conversions via constructors or conversion
7029 /// operators.
7030 void
7031 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7032                          CXXRecordDecl *ActingContext, QualType ObjectType,
7033                          Expr::Classification ObjectClassification,
7034                          ArrayRef<Expr *> Args,
7035                          OverloadCandidateSet &CandidateSet,
7036                          bool SuppressUserConversions,
7037                          bool PartialOverloading,
7038                          ConversionSequenceList EarlyConversions,
7039                          OverloadCandidateParamOrder PO) {
7040   const FunctionProtoType *Proto
7041     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7042   assert(Proto && "Methods without a prototype cannot be overloaded");
7043   assert(!isa<CXXConstructorDecl>(Method) &&
7044          "Use AddOverloadCandidate for constructors");
7045 
7046   if (!CandidateSet.isNewCandidate(Method, PO))
7047     return;
7048 
7049   // C++11 [class.copy]p23: [DR1402]
7050   //   A defaulted move assignment operator that is defined as deleted is
7051   //   ignored by overload resolution.
7052   if (Method->isDefaulted() && Method->isDeleted() &&
7053       Method->isMoveAssignmentOperator())
7054     return;
7055 
7056   // Overload resolution is always an unevaluated context.
7057   EnterExpressionEvaluationContext Unevaluated(
7058       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7059 
7060   // Add this candidate
7061   OverloadCandidate &Candidate =
7062       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7063   Candidate.FoundDecl = FoundDecl;
7064   Candidate.Function = Method;
7065   Candidate.RewriteKind =
7066       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7067   Candidate.IsSurrogate = false;
7068   Candidate.IgnoreObjectArgument = false;
7069   Candidate.ExplicitCallArguments = Args.size();
7070 
7071   unsigned NumParams = Proto->getNumParams();
7072 
7073   // (C++ 13.3.2p2): A candidate function having fewer than m
7074   // parameters is viable only if it has an ellipsis in its parameter
7075   // list (8.3.5).
7076   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7077       !Proto->isVariadic() &&
7078       shouldEnforceArgLimit(PartialOverloading, Method)) {
7079     Candidate.Viable = false;
7080     Candidate.FailureKind = ovl_fail_too_many_arguments;
7081     return;
7082   }
7083 
7084   // (C++ 13.3.2p2): A candidate function having more than m parameters
7085   // is viable only if the (m+1)st parameter has a default argument
7086   // (8.3.6). For the purposes of overload resolution, the
7087   // parameter list is truncated on the right, so that there are
7088   // exactly m parameters.
7089   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
7090   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7091     // Not enough arguments.
7092     Candidate.Viable = false;
7093     Candidate.FailureKind = ovl_fail_too_few_arguments;
7094     return;
7095   }
7096 
7097   Candidate.Viable = true;
7098 
7099   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7100   if (ObjectType.isNull())
7101     Candidate.IgnoreObjectArgument = true;
7102   else if (Method->isStatic()) {
7103     // [over.best.ics.general]p8
7104     // When the parameter is the implicit object parameter of a static member
7105     // function, the implicit conversion sequence is a standard conversion
7106     // sequence that is neither better nor worse than any other standard
7107     // conversion sequence.
7108     //
7109     // This is a rule that was introduced in C++23 to support static lambdas. We
7110     // apply it retroactively because we want to support static lambdas as an
7111     // extension and it doesn't hurt previous code.
7112     Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7113   } else {
7114     // Determine the implicit conversion sequence for the object
7115     // parameter.
7116     Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7117         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7118         Method, ActingContext);
7119     if (Candidate.Conversions[FirstConvIdx].isBad()) {
7120       Candidate.Viable = false;
7121       Candidate.FailureKind = ovl_fail_bad_conversion;
7122       return;
7123     }
7124   }
7125 
7126   // (CUDA B.1): Check for invalid calls between targets.
7127   if (getLangOpts().CUDA)
7128     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7129       if (!IsAllowedCUDACall(Caller, Method)) {
7130         Candidate.Viable = false;
7131         Candidate.FailureKind = ovl_fail_bad_target;
7132         return;
7133       }
7134 
7135   if (Method->getTrailingRequiresClause()) {
7136     ConstraintSatisfaction Satisfaction;
7137     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7138                                  /*ForOverloadResolution*/ true) ||
7139         !Satisfaction.IsSatisfied) {
7140       Candidate.Viable = false;
7141       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7142       return;
7143     }
7144   }
7145 
7146   // Determine the implicit conversion sequences for each of the
7147   // arguments.
7148   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7149     unsigned ConvIdx =
7150         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7151     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7152       // We already formed a conversion sequence for this parameter during
7153       // template argument deduction.
7154     } else if (ArgIdx < NumParams) {
7155       // (C++ 13.3.2p3): for F to be a viable function, there shall
7156       // exist for each argument an implicit conversion sequence
7157       // (13.3.3.1) that converts that argument to the corresponding
7158       // parameter of F.
7159       QualType ParamType = Proto->getParamType(ArgIdx);
7160       Candidate.Conversions[ConvIdx]
7161         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7162                                 SuppressUserConversions,
7163                                 /*InOverloadResolution=*/true,
7164                                 /*AllowObjCWritebackConversion=*/
7165                                   getLangOpts().ObjCAutoRefCount);
7166       if (Candidate.Conversions[ConvIdx].isBad()) {
7167         Candidate.Viable = false;
7168         Candidate.FailureKind = ovl_fail_bad_conversion;
7169         return;
7170       }
7171     } else {
7172       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7173       // argument for which there is no corresponding parameter is
7174       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7175       Candidate.Conversions[ConvIdx].setEllipsis();
7176     }
7177   }
7178 
7179   if (EnableIfAttr *FailedAttr =
7180           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7181     Candidate.Viable = false;
7182     Candidate.FailureKind = ovl_fail_enable_if;
7183     Candidate.DeductionFailure.Data = FailedAttr;
7184     return;
7185   }
7186 
7187   if (Method->isMultiVersion() &&
7188       ((Method->hasAttr<TargetAttr>() &&
7189         !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7190        (Method->hasAttr<TargetVersionAttr>() &&
7191         !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7192     Candidate.Viable = false;
7193     Candidate.FailureKind = ovl_non_default_multiversion_function;
7194   }
7195 }
7196 
7197 /// Add a C++ member function template as a candidate to the candidate
7198 /// set, using template argument deduction to produce an appropriate member
7199 /// function template specialization.
7200 void Sema::AddMethodTemplateCandidate(
7201     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7202     CXXRecordDecl *ActingContext,
7203     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7204     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7205     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7206     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7207   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7208     return;
7209 
7210   // C++ [over.match.funcs]p7:
7211   //   In each case where a candidate is a function template, candidate
7212   //   function template specializations are generated using template argument
7213   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7214   //   candidate functions in the usual way.113) A given name can refer to one
7215   //   or more function templates and also to a set of overloaded non-template
7216   //   functions. In such a case, the candidate functions generated from each
7217   //   function template are combined with the set of non-template candidate
7218   //   functions.
7219   TemplateDeductionInfo Info(CandidateSet.getLocation());
7220   FunctionDecl *Specialization = nullptr;
7221   ConversionSequenceList Conversions;
7222   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7223           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7224           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7225             return CheckNonDependentConversions(
7226                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7227                 SuppressUserConversions, ActingContext, ObjectType,
7228                 ObjectClassification, PO);
7229           })) {
7230     OverloadCandidate &Candidate =
7231         CandidateSet.addCandidate(Conversions.size(), Conversions);
7232     Candidate.FoundDecl = FoundDecl;
7233     Candidate.Function = MethodTmpl->getTemplatedDecl();
7234     Candidate.Viable = false;
7235     Candidate.RewriteKind =
7236       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7237     Candidate.IsSurrogate = false;
7238     Candidate.IgnoreObjectArgument =
7239         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7240         ObjectType.isNull();
7241     Candidate.ExplicitCallArguments = Args.size();
7242     if (Result == TDK_NonDependentConversionFailure)
7243       Candidate.FailureKind = ovl_fail_bad_conversion;
7244     else {
7245       Candidate.FailureKind = ovl_fail_bad_deduction;
7246       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7247                                                             Info);
7248     }
7249     return;
7250   }
7251 
7252   // Add the function template specialization produced by template argument
7253   // deduction as a candidate.
7254   assert(Specialization && "Missing member function template specialization?");
7255   assert(isa<CXXMethodDecl>(Specialization) &&
7256          "Specialization is not a member function?");
7257   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7258                      ActingContext, ObjectType, ObjectClassification, Args,
7259                      CandidateSet, SuppressUserConversions, PartialOverloading,
7260                      Conversions, PO);
7261 }
7262 
7263 /// Determine whether a given function template has a simple explicit specifier
7264 /// or a non-value-dependent explicit-specification that evaluates to true.
7265 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7266   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7267 }
7268 
7269 /// Add a C++ function template specialization as a candidate
7270 /// in the candidate set, using template argument deduction to produce
7271 /// an appropriate function template specialization.
7272 void Sema::AddTemplateOverloadCandidate(
7273     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7274     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7275     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7276     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7277     OverloadCandidateParamOrder PO) {
7278   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7279     return;
7280 
7281   // If the function template has a non-dependent explicit specification,
7282   // exclude it now if appropriate; we are not permitted to perform deduction
7283   // and substitution in this case.
7284   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7285     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7286     Candidate.FoundDecl = FoundDecl;
7287     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7288     Candidate.Viable = false;
7289     Candidate.FailureKind = ovl_fail_explicit;
7290     return;
7291   }
7292 
7293   // C++ [over.match.funcs]p7:
7294   //   In each case where a candidate is a function template, candidate
7295   //   function template specializations are generated using template argument
7296   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7297   //   candidate functions in the usual way.113) A given name can refer to one
7298   //   or more function templates and also to a set of overloaded non-template
7299   //   functions. In such a case, the candidate functions generated from each
7300   //   function template are combined with the set of non-template candidate
7301   //   functions.
7302   TemplateDeductionInfo Info(CandidateSet.getLocation());
7303   FunctionDecl *Specialization = nullptr;
7304   ConversionSequenceList Conversions;
7305   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7306           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7307           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7308             return CheckNonDependentConversions(
7309                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7310                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7311           })) {
7312     OverloadCandidate &Candidate =
7313         CandidateSet.addCandidate(Conversions.size(), Conversions);
7314     Candidate.FoundDecl = FoundDecl;
7315     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7316     Candidate.Viable = false;
7317     Candidate.RewriteKind =
7318       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7319     Candidate.IsSurrogate = false;
7320     Candidate.IsADLCandidate = IsADLCandidate;
7321     // Ignore the object argument if there is one, since we don't have an object
7322     // type.
7323     Candidate.IgnoreObjectArgument =
7324         isa<CXXMethodDecl>(Candidate.Function) &&
7325         !isa<CXXConstructorDecl>(Candidate.Function);
7326     Candidate.ExplicitCallArguments = Args.size();
7327     if (Result == TDK_NonDependentConversionFailure)
7328       Candidate.FailureKind = ovl_fail_bad_conversion;
7329     else {
7330       Candidate.FailureKind = ovl_fail_bad_deduction;
7331       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7332                                                             Info);
7333     }
7334     return;
7335   }
7336 
7337   // Add the function template specialization produced by template argument
7338   // deduction as a candidate.
7339   assert(Specialization && "Missing function template specialization?");
7340   AddOverloadCandidate(
7341       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7342       PartialOverloading, AllowExplicit,
7343       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7344 }
7345 
7346 /// Check that implicit conversion sequences can be formed for each argument
7347 /// whose corresponding parameter has a non-dependent type, per DR1391's
7348 /// [temp.deduct.call]p10.
7349 bool Sema::CheckNonDependentConversions(
7350     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7351     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7352     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7353     CXXRecordDecl *ActingContext, QualType ObjectType,
7354     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7355   // FIXME: The cases in which we allow explicit conversions for constructor
7356   // arguments never consider calling a constructor template. It's not clear
7357   // that is correct.
7358   const bool AllowExplicit = false;
7359 
7360   auto *FD = FunctionTemplate->getTemplatedDecl();
7361   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7362   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7363   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7364 
7365   Conversions =
7366       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7367 
7368   // Overload resolution is always an unevaluated context.
7369   EnterExpressionEvaluationContext Unevaluated(
7370       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7371 
7372   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7373   // require that, but this check should never result in a hard error, and
7374   // overload resolution is permitted to sidestep instantiations.
7375   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7376       !ObjectType.isNull()) {
7377     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7378     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7379         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7380         Method, ActingContext);
7381     if (Conversions[ConvIdx].isBad())
7382       return true;
7383   }
7384 
7385   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7386        ++I) {
7387     QualType ParamType = ParamTypes[I];
7388     if (!ParamType->isDependentType()) {
7389       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7390                              ? 0
7391                              : (ThisConversions + I);
7392       Conversions[ConvIdx]
7393         = TryCopyInitialization(*this, Args[I], ParamType,
7394                                 SuppressUserConversions,
7395                                 /*InOverloadResolution=*/true,
7396                                 /*AllowObjCWritebackConversion=*/
7397                                   getLangOpts().ObjCAutoRefCount,
7398                                 AllowExplicit);
7399       if (Conversions[ConvIdx].isBad())
7400         return true;
7401     }
7402   }
7403 
7404   return false;
7405 }
7406 
7407 /// Determine whether this is an allowable conversion from the result
7408 /// of an explicit conversion operator to the expected type, per C++
7409 /// [over.match.conv]p1 and [over.match.ref]p1.
7410 ///
7411 /// \param ConvType The return type of the conversion function.
7412 ///
7413 /// \param ToType The type we are converting to.
7414 ///
7415 /// \param AllowObjCPointerConversion Allow a conversion from one
7416 /// Objective-C pointer to another.
7417 ///
7418 /// \returns true if the conversion is allowable, false otherwise.
7419 static bool isAllowableExplicitConversion(Sema &S,
7420                                           QualType ConvType, QualType ToType,
7421                                           bool AllowObjCPointerConversion) {
7422   QualType ToNonRefType = ToType.getNonReferenceType();
7423 
7424   // Easy case: the types are the same.
7425   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7426     return true;
7427 
7428   // Allow qualification conversions.
7429   bool ObjCLifetimeConversion;
7430   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7431                                   ObjCLifetimeConversion))
7432     return true;
7433 
7434   // If we're not allowed to consider Objective-C pointer conversions,
7435   // we're done.
7436   if (!AllowObjCPointerConversion)
7437     return false;
7438 
7439   // Is this an Objective-C pointer conversion?
7440   bool IncompatibleObjC = false;
7441   QualType ConvertedType;
7442   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7443                                    IncompatibleObjC);
7444 }
7445 
7446 /// AddConversionCandidate - Add a C++ conversion function as a
7447 /// candidate in the candidate set (C++ [over.match.conv],
7448 /// C++ [over.match.copy]). From is the expression we're converting from,
7449 /// and ToType is the type that we're eventually trying to convert to
7450 /// (which may or may not be the same type as the type that the
7451 /// conversion function produces).
7452 void Sema::AddConversionCandidate(
7453     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7454     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7455     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7456     bool AllowExplicit, bool AllowResultConversion) {
7457   assert(!Conversion->getDescribedFunctionTemplate() &&
7458          "Conversion function templates use AddTemplateConversionCandidate");
7459   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7460   if (!CandidateSet.isNewCandidate(Conversion))
7461     return;
7462 
7463   // If the conversion function has an undeduced return type, trigger its
7464   // deduction now.
7465   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7466     if (DeduceReturnType(Conversion, From->getExprLoc()))
7467       return;
7468     ConvType = Conversion->getConversionType().getNonReferenceType();
7469   }
7470 
7471   // If we don't allow any conversion of the result type, ignore conversion
7472   // functions that don't convert to exactly (possibly cv-qualified) T.
7473   if (!AllowResultConversion &&
7474       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7475     return;
7476 
7477   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7478   // operator is only a candidate if its return type is the target type or
7479   // can be converted to the target type with a qualification conversion.
7480   //
7481   // FIXME: Include such functions in the candidate list and explain why we
7482   // can't select them.
7483   if (Conversion->isExplicit() &&
7484       !isAllowableExplicitConversion(*this, ConvType, ToType,
7485                                      AllowObjCConversionOnExplicit))
7486     return;
7487 
7488   // Overload resolution is always an unevaluated context.
7489   EnterExpressionEvaluationContext Unevaluated(
7490       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7491 
7492   // Add this candidate
7493   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7494   Candidate.FoundDecl = FoundDecl;
7495   Candidate.Function = Conversion;
7496   Candidate.IsSurrogate = false;
7497   Candidate.IgnoreObjectArgument = false;
7498   Candidate.FinalConversion.setAsIdentityConversion();
7499   Candidate.FinalConversion.setFromType(ConvType);
7500   Candidate.FinalConversion.setAllToTypes(ToType);
7501   Candidate.Viable = true;
7502   Candidate.ExplicitCallArguments = 1;
7503 
7504   // Explicit functions are not actually candidates at all if we're not
7505   // allowing them in this context, but keep them around so we can point
7506   // to them in diagnostics.
7507   if (!AllowExplicit && Conversion->isExplicit()) {
7508     Candidate.Viable = false;
7509     Candidate.FailureKind = ovl_fail_explicit;
7510     return;
7511   }
7512 
7513   // C++ [over.match.funcs]p4:
7514   //   For conversion functions, the function is considered to be a member of
7515   //   the class of the implicit implied object argument for the purpose of
7516   //   defining the type of the implicit object parameter.
7517   //
7518   // Determine the implicit conversion sequence for the implicit
7519   // object parameter.
7520   QualType ImplicitParamType = From->getType();
7521   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7522     ImplicitParamType = FromPtrType->getPointeeType();
7523   CXXRecordDecl *ConversionContext
7524     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7525 
7526   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7527       *this, CandidateSet.getLocation(), From->getType(),
7528       From->Classify(Context), Conversion, ConversionContext);
7529 
7530   if (Candidate.Conversions[0].isBad()) {
7531     Candidate.Viable = false;
7532     Candidate.FailureKind = ovl_fail_bad_conversion;
7533     return;
7534   }
7535 
7536   if (Conversion->getTrailingRequiresClause()) {
7537     ConstraintSatisfaction Satisfaction;
7538     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7539         !Satisfaction.IsSatisfied) {
7540       Candidate.Viable = false;
7541       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7542       return;
7543     }
7544   }
7545 
7546   // We won't go through a user-defined type conversion function to convert a
7547   // derived to base as such conversions are given Conversion Rank. They only
7548   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7549   QualType FromCanon
7550     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7551   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7552   if (FromCanon == ToCanon ||
7553       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7554     Candidate.Viable = false;
7555     Candidate.FailureKind = ovl_fail_trivial_conversion;
7556     return;
7557   }
7558 
7559   // To determine what the conversion from the result of calling the
7560   // conversion function to the type we're eventually trying to
7561   // convert to (ToType), we need to synthesize a call to the
7562   // conversion function and attempt copy initialization from it. This
7563   // makes sure that we get the right semantics with respect to
7564   // lvalues/rvalues and the type. Fortunately, we can allocate this
7565   // call on the stack and we don't need its arguments to be
7566   // well-formed.
7567   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7568                             VK_LValue, From->getBeginLoc());
7569   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7570                                 Context.getPointerType(Conversion->getType()),
7571                                 CK_FunctionToPointerDecay, &ConversionRef,
7572                                 VK_PRValue, FPOptionsOverride());
7573 
7574   QualType ConversionType = Conversion->getConversionType();
7575   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7576     Candidate.Viable = false;
7577     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7578     return;
7579   }
7580 
7581   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7582 
7583   // Note that it is safe to allocate CallExpr on the stack here because
7584   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7585   // allocator).
7586   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7587 
7588   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7589   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7590       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7591 
7592   ImplicitConversionSequence ICS =
7593       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7594                             /*SuppressUserConversions=*/true,
7595                             /*InOverloadResolution=*/false,
7596                             /*AllowObjCWritebackConversion=*/false);
7597 
7598   switch (ICS.getKind()) {
7599   case ImplicitConversionSequence::StandardConversion:
7600     Candidate.FinalConversion = ICS.Standard;
7601 
7602     // C++ [over.ics.user]p3:
7603     //   If the user-defined conversion is specified by a specialization of a
7604     //   conversion function template, the second standard conversion sequence
7605     //   shall have exact match rank.
7606     if (Conversion->getPrimaryTemplate() &&
7607         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7608       Candidate.Viable = false;
7609       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7610       return;
7611     }
7612 
7613     // C++0x [dcl.init.ref]p5:
7614     //    In the second case, if the reference is an rvalue reference and
7615     //    the second standard conversion sequence of the user-defined
7616     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7617     //    program is ill-formed.
7618     if (ToType->isRValueReferenceType() &&
7619         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7620       Candidate.Viable = false;
7621       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7622       return;
7623     }
7624     break;
7625 
7626   case ImplicitConversionSequence::BadConversion:
7627     Candidate.Viable = false;
7628     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7629     return;
7630 
7631   default:
7632     llvm_unreachable(
7633            "Can only end up with a standard conversion sequence or failure");
7634   }
7635 
7636   if (EnableIfAttr *FailedAttr =
7637           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7638     Candidate.Viable = false;
7639     Candidate.FailureKind = ovl_fail_enable_if;
7640     Candidate.DeductionFailure.Data = FailedAttr;
7641     return;
7642   }
7643 
7644   if (Conversion->isMultiVersion() &&
7645       ((Conversion->hasAttr<TargetAttr>() &&
7646         !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
7647        (Conversion->hasAttr<TargetVersionAttr>() &&
7648         !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7649     Candidate.Viable = false;
7650     Candidate.FailureKind = ovl_non_default_multiversion_function;
7651   }
7652 }
7653 
7654 /// Adds a conversion function template specialization
7655 /// candidate to the overload set, using template argument deduction
7656 /// to deduce the template arguments of the conversion function
7657 /// template from the type that we are converting to (C++
7658 /// [temp.deduct.conv]).
7659 void Sema::AddTemplateConversionCandidate(
7660     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7661     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7662     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7663     bool AllowExplicit, bool AllowResultConversion) {
7664   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7665          "Only conversion function templates permitted here");
7666 
7667   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7668     return;
7669 
7670   // If the function template has a non-dependent explicit specification,
7671   // exclude it now if appropriate; we are not permitted to perform deduction
7672   // and substitution in this case.
7673   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7674     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7675     Candidate.FoundDecl = FoundDecl;
7676     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7677     Candidate.Viable = false;
7678     Candidate.FailureKind = ovl_fail_explicit;
7679     return;
7680   }
7681 
7682   TemplateDeductionInfo Info(CandidateSet.getLocation());
7683   CXXConversionDecl *Specialization = nullptr;
7684   if (TemplateDeductionResult Result
7685         = DeduceTemplateArguments(FunctionTemplate, ToType,
7686                                   Specialization, Info)) {
7687     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7688     Candidate.FoundDecl = FoundDecl;
7689     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7690     Candidate.Viable = false;
7691     Candidate.FailureKind = ovl_fail_bad_deduction;
7692     Candidate.IsSurrogate = false;
7693     Candidate.IgnoreObjectArgument = false;
7694     Candidate.ExplicitCallArguments = 1;
7695     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7696                                                           Info);
7697     return;
7698   }
7699 
7700   // Add the conversion function template specialization produced by
7701   // template argument deduction as a candidate.
7702   assert(Specialization && "Missing function template specialization?");
7703   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7704                          CandidateSet, AllowObjCConversionOnExplicit,
7705                          AllowExplicit, AllowResultConversion);
7706 }
7707 
7708 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7709 /// converts the given @c Object to a function pointer via the
7710 /// conversion function @c Conversion, and then attempts to call it
7711 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7712 /// the type of function that we'll eventually be calling.
7713 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7714                                  DeclAccessPair FoundDecl,
7715                                  CXXRecordDecl *ActingContext,
7716                                  const FunctionProtoType *Proto,
7717                                  Expr *Object,
7718                                  ArrayRef<Expr *> Args,
7719                                  OverloadCandidateSet& CandidateSet) {
7720   if (!CandidateSet.isNewCandidate(Conversion))
7721     return;
7722 
7723   // Overload resolution is always an unevaluated context.
7724   EnterExpressionEvaluationContext Unevaluated(
7725       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7726 
7727   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7728   Candidate.FoundDecl = FoundDecl;
7729   Candidate.Function = nullptr;
7730   Candidate.Surrogate = Conversion;
7731   Candidate.Viable = true;
7732   Candidate.IsSurrogate = true;
7733   Candidate.IgnoreObjectArgument = false;
7734   Candidate.ExplicitCallArguments = Args.size();
7735 
7736   // Determine the implicit conversion sequence for the implicit
7737   // object parameter.
7738   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7739       *this, CandidateSet.getLocation(), Object->getType(),
7740       Object->Classify(Context), Conversion, ActingContext);
7741   if (ObjectInit.isBad()) {
7742     Candidate.Viable = false;
7743     Candidate.FailureKind = ovl_fail_bad_conversion;
7744     Candidate.Conversions[0] = ObjectInit;
7745     return;
7746   }
7747 
7748   // The first conversion is actually a user-defined conversion whose
7749   // first conversion is ObjectInit's standard conversion (which is
7750   // effectively a reference binding). Record it as such.
7751   Candidate.Conversions[0].setUserDefined();
7752   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7753   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7754   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7755   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7756   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7757   Candidate.Conversions[0].UserDefined.After
7758     = Candidate.Conversions[0].UserDefined.Before;
7759   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7760 
7761   // Find the
7762   unsigned NumParams = Proto->getNumParams();
7763 
7764   // (C++ 13.3.2p2): A candidate function having fewer than m
7765   // parameters is viable only if it has an ellipsis in its parameter
7766   // list (8.3.5).
7767   if (Args.size() > NumParams && !Proto->isVariadic()) {
7768     Candidate.Viable = false;
7769     Candidate.FailureKind = ovl_fail_too_many_arguments;
7770     return;
7771   }
7772 
7773   // Function types don't have any default arguments, so just check if
7774   // we have enough arguments.
7775   if (Args.size() < NumParams) {
7776     // Not enough arguments.
7777     Candidate.Viable = false;
7778     Candidate.FailureKind = ovl_fail_too_few_arguments;
7779     return;
7780   }
7781 
7782   // Determine the implicit conversion sequences for each of the
7783   // arguments.
7784   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7785     if (ArgIdx < NumParams) {
7786       // (C++ 13.3.2p3): for F to be a viable function, there shall
7787       // exist for each argument an implicit conversion sequence
7788       // (13.3.3.1) that converts that argument to the corresponding
7789       // parameter of F.
7790       QualType ParamType = Proto->getParamType(ArgIdx);
7791       Candidate.Conversions[ArgIdx + 1]
7792         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7793                                 /*SuppressUserConversions=*/false,
7794                                 /*InOverloadResolution=*/false,
7795                                 /*AllowObjCWritebackConversion=*/
7796                                   getLangOpts().ObjCAutoRefCount);
7797       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7798         Candidate.Viable = false;
7799         Candidate.FailureKind = ovl_fail_bad_conversion;
7800         return;
7801       }
7802     } else {
7803       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7804       // argument for which there is no corresponding parameter is
7805       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7806       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7807     }
7808   }
7809 
7810   if (EnableIfAttr *FailedAttr =
7811           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7812     Candidate.Viable = false;
7813     Candidate.FailureKind = ovl_fail_enable_if;
7814     Candidate.DeductionFailure.Data = FailedAttr;
7815     return;
7816   }
7817 }
7818 
7819 /// Add all of the non-member operator function declarations in the given
7820 /// function set to the overload candidate set.
7821 void Sema::AddNonMemberOperatorCandidates(
7822     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7823     OverloadCandidateSet &CandidateSet,
7824     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7825   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7826     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7827     ArrayRef<Expr *> FunctionArgs = Args;
7828 
7829     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7830     FunctionDecl *FD =
7831         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7832 
7833     // Don't consider rewritten functions if we're not rewriting.
7834     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7835       continue;
7836 
7837     assert(!isa<CXXMethodDecl>(FD) &&
7838            "unqualified operator lookup found a member function");
7839 
7840     if (FunTmpl) {
7841       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7842                                    FunctionArgs, CandidateSet);
7843       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7844         AddTemplateOverloadCandidate(
7845             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7846             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7847             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7848     } else {
7849       if (ExplicitTemplateArgs)
7850         continue;
7851       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7852       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7853         AddOverloadCandidate(
7854             FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7855             false, false, true, false, ADLCallKind::NotADL, std::nullopt,
7856             OverloadCandidateParamOrder::Reversed);
7857     }
7858   }
7859 }
7860 
7861 /// Add overload candidates for overloaded operators that are
7862 /// member functions.
7863 ///
7864 /// Add the overloaded operator candidates that are member functions
7865 /// for the operator Op that was used in an operator expression such
7866 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7867 /// CandidateSet will store the added overload candidates. (C++
7868 /// [over.match.oper]).
7869 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7870                                        SourceLocation OpLoc,
7871                                        ArrayRef<Expr *> Args,
7872                                        OverloadCandidateSet &CandidateSet,
7873                                        OverloadCandidateParamOrder PO) {
7874   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7875 
7876   // C++ [over.match.oper]p3:
7877   //   For a unary operator @ with an operand of a type whose
7878   //   cv-unqualified version is T1, and for a binary operator @ with
7879   //   a left operand of a type whose cv-unqualified version is T1 and
7880   //   a right operand of a type whose cv-unqualified version is T2,
7881   //   three sets of candidate functions, designated member
7882   //   candidates, non-member candidates and built-in candidates, are
7883   //   constructed as follows:
7884   QualType T1 = Args[0]->getType();
7885 
7886   //     -- If T1 is a complete class type or a class currently being
7887   //        defined, the set of member candidates is the result of the
7888   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7889   //        the set of member candidates is empty.
7890   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7891     // Complete the type if it can be completed.
7892     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7893       return;
7894     // If the type is neither complete nor being defined, bail out now.
7895     if (!T1Rec->getDecl()->getDefinition())
7896       return;
7897 
7898     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7899     LookupQualifiedName(Operators, T1Rec->getDecl());
7900     Operators.suppressDiagnostics();
7901 
7902     for (LookupResult::iterator Oper = Operators.begin(),
7903                                 OperEnd = Operators.end();
7904          Oper != OperEnd; ++Oper) {
7905       if (Oper->getAsFunction() &&
7906           PO == OverloadCandidateParamOrder::Reversed &&
7907           !CandidateSet.getRewriteInfo().shouldAddReversed(
7908               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
7909         continue;
7910       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7911                          Args[0]->Classify(Context), Args.slice(1),
7912                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7913     }
7914   }
7915 }
7916 
7917 /// AddBuiltinCandidate - Add a candidate for a built-in
7918 /// operator. ResultTy and ParamTys are the result and parameter types
7919 /// of the built-in candidate, respectively. Args and NumArgs are the
7920 /// arguments being passed to the candidate. IsAssignmentOperator
7921 /// should be true when this built-in candidate is an assignment
7922 /// operator. NumContextualBoolArguments is the number of arguments
7923 /// (at the beginning of the argument list) that will be contextually
7924 /// converted to bool.
7925 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7926                                OverloadCandidateSet& CandidateSet,
7927                                bool IsAssignmentOperator,
7928                                unsigned NumContextualBoolArguments) {
7929   // Overload resolution is always an unevaluated context.
7930   EnterExpressionEvaluationContext Unevaluated(
7931       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7932 
7933   // Add this candidate
7934   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7935   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7936   Candidate.Function = nullptr;
7937   Candidate.IsSurrogate = false;
7938   Candidate.IgnoreObjectArgument = false;
7939   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7940 
7941   // Determine the implicit conversion sequences for each of the
7942   // arguments.
7943   Candidate.Viable = true;
7944   Candidate.ExplicitCallArguments = Args.size();
7945   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7946     // C++ [over.match.oper]p4:
7947     //   For the built-in assignment operators, conversions of the
7948     //   left operand are restricted as follows:
7949     //     -- no temporaries are introduced to hold the left operand, and
7950     //     -- no user-defined conversions are applied to the left
7951     //        operand to achieve a type match with the left-most
7952     //        parameter of a built-in candidate.
7953     //
7954     // We block these conversions by turning off user-defined
7955     // conversions, since that is the only way that initialization of
7956     // a reference to a non-class type can occur from something that
7957     // is not of the same type.
7958     if (ArgIdx < NumContextualBoolArguments) {
7959       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7960              "Contextual conversion to bool requires bool type");
7961       Candidate.Conversions[ArgIdx]
7962         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7963     } else {
7964       Candidate.Conversions[ArgIdx]
7965         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7966                                 ArgIdx == 0 && IsAssignmentOperator,
7967                                 /*InOverloadResolution=*/false,
7968                                 /*AllowObjCWritebackConversion=*/
7969                                   getLangOpts().ObjCAutoRefCount);
7970     }
7971     if (Candidate.Conversions[ArgIdx].isBad()) {
7972       Candidate.Viable = false;
7973       Candidate.FailureKind = ovl_fail_bad_conversion;
7974       break;
7975     }
7976   }
7977 }
7978 
7979 namespace {
7980 
7981 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7982 /// candidate operator functions for built-in operators (C++
7983 /// [over.built]). The types are separated into pointer types and
7984 /// enumeration types.
7985 class BuiltinCandidateTypeSet  {
7986   /// TypeSet - A set of types.
7987   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7988                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7989 
7990   /// PointerTypes - The set of pointer types that will be used in the
7991   /// built-in candidates.
7992   TypeSet PointerTypes;
7993 
7994   /// MemberPointerTypes - The set of member pointer types that will be
7995   /// used in the built-in candidates.
7996   TypeSet MemberPointerTypes;
7997 
7998   /// EnumerationTypes - The set of enumeration types that will be
7999   /// used in the built-in candidates.
8000   TypeSet EnumerationTypes;
8001 
8002   /// The set of vector types that will be used in the built-in
8003   /// candidates.
8004   TypeSet VectorTypes;
8005 
8006   /// The set of matrix types that will be used in the built-in
8007   /// candidates.
8008   TypeSet MatrixTypes;
8009 
8010   /// A flag indicating non-record types are viable candidates
8011   bool HasNonRecordTypes;
8012 
8013   /// A flag indicating whether either arithmetic or enumeration types
8014   /// were present in the candidate set.
8015   bool HasArithmeticOrEnumeralTypes;
8016 
8017   /// A flag indicating whether the nullptr type was present in the
8018   /// candidate set.
8019   bool HasNullPtrType;
8020 
8021   /// Sema - The semantic analysis instance where we are building the
8022   /// candidate type set.
8023   Sema &SemaRef;
8024 
8025   /// Context - The AST context in which we will build the type sets.
8026   ASTContext &Context;
8027 
8028   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8029                                                const Qualifiers &VisibleQuals);
8030   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8031 
8032 public:
8033   /// iterator - Iterates through the types that are part of the set.
8034   typedef TypeSet::iterator iterator;
8035 
8036   BuiltinCandidateTypeSet(Sema &SemaRef)
8037     : HasNonRecordTypes(false),
8038       HasArithmeticOrEnumeralTypes(false),
8039       HasNullPtrType(false),
8040       SemaRef(SemaRef),
8041       Context(SemaRef.Context) { }
8042 
8043   void AddTypesConvertedFrom(QualType Ty,
8044                              SourceLocation Loc,
8045                              bool AllowUserConversions,
8046                              bool AllowExplicitConversions,
8047                              const Qualifiers &VisibleTypeConversionsQuals);
8048 
8049   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8050   llvm::iterator_range<iterator> member_pointer_types() {
8051     return MemberPointerTypes;
8052   }
8053   llvm::iterator_range<iterator> enumeration_types() {
8054     return EnumerationTypes;
8055   }
8056   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8057   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8058 
8059   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8060   bool hasNonRecordTypes() { return HasNonRecordTypes; }
8061   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8062   bool hasNullPtrType() const { return HasNullPtrType; }
8063 };
8064 
8065 } // end anonymous namespace
8066 
8067 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8068 /// the set of pointer types along with any more-qualified variants of
8069 /// that type. For example, if @p Ty is "int const *", this routine
8070 /// will add "int const *", "int const volatile *", "int const
8071 /// restrict *", and "int const volatile restrict *" to the set of
8072 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8073 /// false otherwise.
8074 ///
8075 /// FIXME: what to do about extended qualifiers?
8076 bool
8077 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8078                                              const Qualifiers &VisibleQuals) {
8079 
8080   // Insert this type.
8081   if (!PointerTypes.insert(Ty))
8082     return false;
8083 
8084   QualType PointeeTy;
8085   const PointerType *PointerTy = Ty->getAs<PointerType>();
8086   bool buildObjCPtr = false;
8087   if (!PointerTy) {
8088     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8089     PointeeTy = PTy->getPointeeType();
8090     buildObjCPtr = true;
8091   } else {
8092     PointeeTy = PointerTy->getPointeeType();
8093   }
8094 
8095   // Don't add qualified variants of arrays. For one, they're not allowed
8096   // (the qualifier would sink to the element type), and for another, the
8097   // only overload situation where it matters is subscript or pointer +- int,
8098   // and those shouldn't have qualifier variants anyway.
8099   if (PointeeTy->isArrayType())
8100     return true;
8101 
8102   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8103   bool hasVolatile = VisibleQuals.hasVolatile();
8104   bool hasRestrict = VisibleQuals.hasRestrict();
8105 
8106   // Iterate through all strict supersets of BaseCVR.
8107   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8108     if ((CVR | BaseCVR) != CVR) continue;
8109     // Skip over volatile if no volatile found anywhere in the types.
8110     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8111 
8112     // Skip over restrict if no restrict found anywhere in the types, or if
8113     // the type cannot be restrict-qualified.
8114     if ((CVR & Qualifiers::Restrict) &&
8115         (!hasRestrict ||
8116          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8117       continue;
8118 
8119     // Build qualified pointee type.
8120     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8121 
8122     // Build qualified pointer type.
8123     QualType QPointerTy;
8124     if (!buildObjCPtr)
8125       QPointerTy = Context.getPointerType(QPointeeTy);
8126     else
8127       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8128 
8129     // Insert qualified pointer type.
8130     PointerTypes.insert(QPointerTy);
8131   }
8132 
8133   return true;
8134 }
8135 
8136 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8137 /// to the set of pointer types along with any more-qualified variants of
8138 /// that type. For example, if @p Ty is "int const *", this routine
8139 /// will add "int const *", "int const volatile *", "int const
8140 /// restrict *", and "int const volatile restrict *" to the set of
8141 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8142 /// false otherwise.
8143 ///
8144 /// FIXME: what to do about extended qualifiers?
8145 bool
8146 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8147     QualType Ty) {
8148   // Insert this type.
8149   if (!MemberPointerTypes.insert(Ty))
8150     return false;
8151 
8152   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8153   assert(PointerTy && "type was not a member pointer type!");
8154 
8155   QualType PointeeTy = PointerTy->getPointeeType();
8156   // Don't add qualified variants of arrays. For one, they're not allowed
8157   // (the qualifier would sink to the element type), and for another, the
8158   // only overload situation where it matters is subscript or pointer +- int,
8159   // and those shouldn't have qualifier variants anyway.
8160   if (PointeeTy->isArrayType())
8161     return true;
8162   const Type *ClassTy = PointerTy->getClass();
8163 
8164   // Iterate through all strict supersets of the pointee type's CVR
8165   // qualifiers.
8166   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8167   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8168     if ((CVR | BaseCVR) != CVR) continue;
8169 
8170     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8171     MemberPointerTypes.insert(
8172       Context.getMemberPointerType(QPointeeTy, ClassTy));
8173   }
8174 
8175   return true;
8176 }
8177 
8178 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8179 /// Ty can be implicit converted to the given set of @p Types. We're
8180 /// primarily interested in pointer types and enumeration types. We also
8181 /// take member pointer types, for the conditional operator.
8182 /// AllowUserConversions is true if we should look at the conversion
8183 /// functions of a class type, and AllowExplicitConversions if we
8184 /// should also include the explicit conversion functions of a class
8185 /// type.
8186 void
8187 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8188                                                SourceLocation Loc,
8189                                                bool AllowUserConversions,
8190                                                bool AllowExplicitConversions,
8191                                                const Qualifiers &VisibleQuals) {
8192   // Only deal with canonical types.
8193   Ty = Context.getCanonicalType(Ty);
8194 
8195   // Look through reference types; they aren't part of the type of an
8196   // expression for the purposes of conversions.
8197   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8198     Ty = RefTy->getPointeeType();
8199 
8200   // If we're dealing with an array type, decay to the pointer.
8201   if (Ty->isArrayType())
8202     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8203 
8204   // Otherwise, we don't care about qualifiers on the type.
8205   Ty = Ty.getLocalUnqualifiedType();
8206 
8207   // Flag if we ever add a non-record type.
8208   const RecordType *TyRec = Ty->getAs<RecordType>();
8209   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8210 
8211   // Flag if we encounter an arithmetic type.
8212   HasArithmeticOrEnumeralTypes =
8213     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8214 
8215   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8216     PointerTypes.insert(Ty);
8217   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8218     // Insert our type, and its more-qualified variants, into the set
8219     // of types.
8220     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8221       return;
8222   } else if (Ty->isMemberPointerType()) {
8223     // Member pointers are far easier, since the pointee can't be converted.
8224     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8225       return;
8226   } else if (Ty->isEnumeralType()) {
8227     HasArithmeticOrEnumeralTypes = true;
8228     EnumerationTypes.insert(Ty);
8229   } else if (Ty->isVectorType()) {
8230     // We treat vector types as arithmetic types in many contexts as an
8231     // extension.
8232     HasArithmeticOrEnumeralTypes = true;
8233     VectorTypes.insert(Ty);
8234   } else if (Ty->isMatrixType()) {
8235     // Similar to vector types, we treat vector types as arithmetic types in
8236     // many contexts as an extension.
8237     HasArithmeticOrEnumeralTypes = true;
8238     MatrixTypes.insert(Ty);
8239   } else if (Ty->isNullPtrType()) {
8240     HasNullPtrType = true;
8241   } else if (AllowUserConversions && TyRec) {
8242     // No conversion functions in incomplete types.
8243     if (!SemaRef.isCompleteType(Loc, Ty))
8244       return;
8245 
8246     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8247     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8248       if (isa<UsingShadowDecl>(D))
8249         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8250 
8251       // Skip conversion function templates; they don't tell us anything
8252       // about which builtin types we can convert to.
8253       if (isa<FunctionTemplateDecl>(D))
8254         continue;
8255 
8256       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8257       if (AllowExplicitConversions || !Conv->isExplicit()) {
8258         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8259                               VisibleQuals);
8260       }
8261     }
8262   }
8263 }
8264 /// Helper function for adjusting address spaces for the pointer or reference
8265 /// operands of builtin operators depending on the argument.
8266 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8267                                                         Expr *Arg) {
8268   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8269 }
8270 
8271 /// Helper function for AddBuiltinOperatorCandidates() that adds
8272 /// the volatile- and non-volatile-qualified assignment operators for the
8273 /// given type to the candidate set.
8274 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8275                                                    QualType T,
8276                                                    ArrayRef<Expr *> Args,
8277                                     OverloadCandidateSet &CandidateSet) {
8278   QualType ParamTypes[2];
8279 
8280   // T& operator=(T&, T)
8281   ParamTypes[0] = S.Context.getLValueReferenceType(
8282       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8283   ParamTypes[1] = T;
8284   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8285                         /*IsAssignmentOperator=*/true);
8286 
8287   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8288     // volatile T& operator=(volatile T&, T)
8289     ParamTypes[0] = S.Context.getLValueReferenceType(
8290         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8291                                                 Args[0]));
8292     ParamTypes[1] = T;
8293     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8294                           /*IsAssignmentOperator=*/true);
8295   }
8296 }
8297 
8298 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8299 /// if any, found in visible type conversion functions found in ArgExpr's type.
8300 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8301     Qualifiers VRQuals;
8302     const RecordType *TyRec;
8303     if (const MemberPointerType *RHSMPType =
8304         ArgExpr->getType()->getAs<MemberPointerType>())
8305       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8306     else
8307       TyRec = ArgExpr->getType()->getAs<RecordType>();
8308     if (!TyRec) {
8309       // Just to be safe, assume the worst case.
8310       VRQuals.addVolatile();
8311       VRQuals.addRestrict();
8312       return VRQuals;
8313     }
8314 
8315     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8316     if (!ClassDecl->hasDefinition())
8317       return VRQuals;
8318 
8319     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8320       if (isa<UsingShadowDecl>(D))
8321         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8322       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8323         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8324         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8325           CanTy = ResTypeRef->getPointeeType();
8326         // Need to go down the pointer/mempointer chain and add qualifiers
8327         // as see them.
8328         bool done = false;
8329         while (!done) {
8330           if (CanTy.isRestrictQualified())
8331             VRQuals.addRestrict();
8332           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8333             CanTy = ResTypePtr->getPointeeType();
8334           else if (const MemberPointerType *ResTypeMPtr =
8335                 CanTy->getAs<MemberPointerType>())
8336             CanTy = ResTypeMPtr->getPointeeType();
8337           else
8338             done = true;
8339           if (CanTy.isVolatileQualified())
8340             VRQuals.addVolatile();
8341           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8342             return VRQuals;
8343         }
8344       }
8345     }
8346     return VRQuals;
8347 }
8348 
8349 // Note: We're currently only handling qualifiers that are meaningful for the
8350 // LHS of compound assignment overloading.
8351 static void forAllQualifierCombinationsImpl(
8352     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8353     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8354   // _Atomic
8355   if (Available.hasAtomic()) {
8356     Available.removeAtomic();
8357     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8358     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8359     return;
8360   }
8361 
8362   // volatile
8363   if (Available.hasVolatile()) {
8364     Available.removeVolatile();
8365     assert(!Applied.hasVolatile());
8366     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8367                                     Callback);
8368     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8369     return;
8370   }
8371 
8372   Callback(Applied);
8373 }
8374 
8375 static void forAllQualifierCombinations(
8376     QualifiersAndAtomic Quals,
8377     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8378   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8379                                          Callback);
8380 }
8381 
8382 static QualType makeQualifiedLValueReferenceType(QualType Base,
8383                                                  QualifiersAndAtomic Quals,
8384                                                  Sema &S) {
8385   if (Quals.hasAtomic())
8386     Base = S.Context.getAtomicType(Base);
8387   if (Quals.hasVolatile())
8388     Base = S.Context.getVolatileType(Base);
8389   return S.Context.getLValueReferenceType(Base);
8390 }
8391 
8392 namespace {
8393 
8394 /// Helper class to manage the addition of builtin operator overload
8395 /// candidates. It provides shared state and utility methods used throughout
8396 /// the process, as well as a helper method to add each group of builtin
8397 /// operator overloads from the standard to a candidate set.
8398 class BuiltinOperatorOverloadBuilder {
8399   // Common instance state available to all overload candidate addition methods.
8400   Sema &S;
8401   ArrayRef<Expr *> Args;
8402   QualifiersAndAtomic VisibleTypeConversionsQuals;
8403   bool HasArithmeticOrEnumeralCandidateType;
8404   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8405   OverloadCandidateSet &CandidateSet;
8406 
8407   static constexpr int ArithmeticTypesCap = 24;
8408   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8409 
8410   // Define some indices used to iterate over the arithmetic types in
8411   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8412   // types are that preserved by promotion (C++ [over.built]p2).
8413   unsigned FirstIntegralType,
8414            LastIntegralType;
8415   unsigned FirstPromotedIntegralType,
8416            LastPromotedIntegralType;
8417   unsigned FirstPromotedArithmeticType,
8418            LastPromotedArithmeticType;
8419   unsigned NumArithmeticTypes;
8420 
8421   void InitArithmeticTypes() {
8422     // Start of promoted types.
8423     FirstPromotedArithmeticType = 0;
8424     ArithmeticTypes.push_back(S.Context.FloatTy);
8425     ArithmeticTypes.push_back(S.Context.DoubleTy);
8426     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8427     if (S.Context.getTargetInfo().hasFloat128Type())
8428       ArithmeticTypes.push_back(S.Context.Float128Ty);
8429     if (S.Context.getTargetInfo().hasIbm128Type())
8430       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8431 
8432     // Start of integral types.
8433     FirstIntegralType = ArithmeticTypes.size();
8434     FirstPromotedIntegralType = ArithmeticTypes.size();
8435     ArithmeticTypes.push_back(S.Context.IntTy);
8436     ArithmeticTypes.push_back(S.Context.LongTy);
8437     ArithmeticTypes.push_back(S.Context.LongLongTy);
8438     if (S.Context.getTargetInfo().hasInt128Type() ||
8439         (S.Context.getAuxTargetInfo() &&
8440          S.Context.getAuxTargetInfo()->hasInt128Type()))
8441       ArithmeticTypes.push_back(S.Context.Int128Ty);
8442     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8443     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8444     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8445     if (S.Context.getTargetInfo().hasInt128Type() ||
8446         (S.Context.getAuxTargetInfo() &&
8447          S.Context.getAuxTargetInfo()->hasInt128Type()))
8448       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8449     LastPromotedIntegralType = ArithmeticTypes.size();
8450     LastPromotedArithmeticType = ArithmeticTypes.size();
8451     // End of promoted types.
8452 
8453     ArithmeticTypes.push_back(S.Context.BoolTy);
8454     ArithmeticTypes.push_back(S.Context.CharTy);
8455     ArithmeticTypes.push_back(S.Context.WCharTy);
8456     if (S.Context.getLangOpts().Char8)
8457       ArithmeticTypes.push_back(S.Context.Char8Ty);
8458     ArithmeticTypes.push_back(S.Context.Char16Ty);
8459     ArithmeticTypes.push_back(S.Context.Char32Ty);
8460     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8461     ArithmeticTypes.push_back(S.Context.ShortTy);
8462     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8463     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8464     LastIntegralType = ArithmeticTypes.size();
8465     NumArithmeticTypes = ArithmeticTypes.size();
8466     // End of integral types.
8467     // FIXME: What about complex? What about half?
8468 
8469     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8470            "Enough inline storage for all arithmetic types.");
8471   }
8472 
8473   /// Helper method to factor out the common pattern of adding overloads
8474   /// for '++' and '--' builtin operators.
8475   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8476                                            bool HasVolatile,
8477                                            bool HasRestrict) {
8478     QualType ParamTypes[2] = {
8479       S.Context.getLValueReferenceType(CandidateTy),
8480       S.Context.IntTy
8481     };
8482 
8483     // Non-volatile version.
8484     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8485 
8486     // Use a heuristic to reduce number of builtin candidates in the set:
8487     // add volatile version only if there are conversions to a volatile type.
8488     if (HasVolatile) {
8489       ParamTypes[0] =
8490         S.Context.getLValueReferenceType(
8491           S.Context.getVolatileType(CandidateTy));
8492       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8493     }
8494 
8495     // Add restrict version only if there are conversions to a restrict type
8496     // and our candidate type is a non-restrict-qualified pointer.
8497     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8498         !CandidateTy.isRestrictQualified()) {
8499       ParamTypes[0]
8500         = S.Context.getLValueReferenceType(
8501             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8502       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8503 
8504       if (HasVolatile) {
8505         ParamTypes[0]
8506           = S.Context.getLValueReferenceType(
8507               S.Context.getCVRQualifiedType(CandidateTy,
8508                                             (Qualifiers::Volatile |
8509                                              Qualifiers::Restrict)));
8510         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8511       }
8512     }
8513 
8514   }
8515 
8516   /// Helper to add an overload candidate for a binary builtin with types \p L
8517   /// and \p R.
8518   void AddCandidate(QualType L, QualType R) {
8519     QualType LandR[2] = {L, R};
8520     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8521   }
8522 
8523 public:
8524   BuiltinOperatorOverloadBuilder(
8525     Sema &S, ArrayRef<Expr *> Args,
8526     QualifiersAndAtomic VisibleTypeConversionsQuals,
8527     bool HasArithmeticOrEnumeralCandidateType,
8528     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8529     OverloadCandidateSet &CandidateSet)
8530     : S(S), Args(Args),
8531       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8532       HasArithmeticOrEnumeralCandidateType(
8533         HasArithmeticOrEnumeralCandidateType),
8534       CandidateTypes(CandidateTypes),
8535       CandidateSet(CandidateSet) {
8536 
8537     InitArithmeticTypes();
8538   }
8539 
8540   // Increment is deprecated for bool since C++17.
8541   //
8542   // C++ [over.built]p3:
8543   //
8544   //   For every pair (T, VQ), where T is an arithmetic type other
8545   //   than bool, and VQ is either volatile or empty, there exist
8546   //   candidate operator functions of the form
8547   //
8548   //       VQ T&      operator++(VQ T&);
8549   //       T          operator++(VQ T&, int);
8550   //
8551   // C++ [over.built]p4:
8552   //
8553   //   For every pair (T, VQ), where T is an arithmetic type other
8554   //   than bool, and VQ is either volatile or empty, there exist
8555   //   candidate operator functions of the form
8556   //
8557   //       VQ T&      operator--(VQ T&);
8558   //       T          operator--(VQ T&, int);
8559   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8560     if (!HasArithmeticOrEnumeralCandidateType)
8561       return;
8562 
8563     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8564       const auto TypeOfT = ArithmeticTypes[Arith];
8565       if (TypeOfT == S.Context.BoolTy) {
8566         if (Op == OO_MinusMinus)
8567           continue;
8568         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8569           continue;
8570       }
8571       addPlusPlusMinusMinusStyleOverloads(
8572         TypeOfT,
8573         VisibleTypeConversionsQuals.hasVolatile(),
8574         VisibleTypeConversionsQuals.hasRestrict());
8575     }
8576   }
8577 
8578   // C++ [over.built]p5:
8579   //
8580   //   For every pair (T, VQ), where T is a cv-qualified or
8581   //   cv-unqualified object type, and VQ is either volatile or
8582   //   empty, there exist candidate operator functions of the form
8583   //
8584   //       T*VQ&      operator++(T*VQ&);
8585   //       T*VQ&      operator--(T*VQ&);
8586   //       T*         operator++(T*VQ&, int);
8587   //       T*         operator--(T*VQ&, int);
8588   void addPlusPlusMinusMinusPointerOverloads() {
8589     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8590       // Skip pointer types that aren't pointers to object types.
8591       if (!PtrTy->getPointeeType()->isObjectType())
8592         continue;
8593 
8594       addPlusPlusMinusMinusStyleOverloads(
8595           PtrTy,
8596           (!PtrTy.isVolatileQualified() &&
8597            VisibleTypeConversionsQuals.hasVolatile()),
8598           (!PtrTy.isRestrictQualified() &&
8599            VisibleTypeConversionsQuals.hasRestrict()));
8600     }
8601   }
8602 
8603   // C++ [over.built]p6:
8604   //   For every cv-qualified or cv-unqualified object type T, there
8605   //   exist candidate operator functions of the form
8606   //
8607   //       T&         operator*(T*);
8608   //
8609   // C++ [over.built]p7:
8610   //   For every function type T that does not have cv-qualifiers or a
8611   //   ref-qualifier, there exist candidate operator functions of the form
8612   //       T&         operator*(T*);
8613   void addUnaryStarPointerOverloads() {
8614     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8615       QualType PointeeTy = ParamTy->getPointeeType();
8616       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8617         continue;
8618 
8619       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8620         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8621           continue;
8622 
8623       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8624     }
8625   }
8626 
8627   // C++ [over.built]p9:
8628   //  For every promoted arithmetic type T, there exist candidate
8629   //  operator functions of the form
8630   //
8631   //       T         operator+(T);
8632   //       T         operator-(T);
8633   void addUnaryPlusOrMinusArithmeticOverloads() {
8634     if (!HasArithmeticOrEnumeralCandidateType)
8635       return;
8636 
8637     for (unsigned Arith = FirstPromotedArithmeticType;
8638          Arith < LastPromotedArithmeticType; ++Arith) {
8639       QualType ArithTy = ArithmeticTypes[Arith];
8640       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8641     }
8642 
8643     // Extension: We also add these operators for vector types.
8644     for (QualType VecTy : CandidateTypes[0].vector_types())
8645       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8646   }
8647 
8648   // C++ [over.built]p8:
8649   //   For every type T, there exist candidate operator functions of
8650   //   the form
8651   //
8652   //       T*         operator+(T*);
8653   void addUnaryPlusPointerOverloads() {
8654     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8655       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8656   }
8657 
8658   // C++ [over.built]p10:
8659   //   For every promoted integral type T, there exist candidate
8660   //   operator functions of the form
8661   //
8662   //        T         operator~(T);
8663   void addUnaryTildePromotedIntegralOverloads() {
8664     if (!HasArithmeticOrEnumeralCandidateType)
8665       return;
8666 
8667     for (unsigned Int = FirstPromotedIntegralType;
8668          Int < LastPromotedIntegralType; ++Int) {
8669       QualType IntTy = ArithmeticTypes[Int];
8670       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8671     }
8672 
8673     // Extension: We also add this operator for vector types.
8674     for (QualType VecTy : CandidateTypes[0].vector_types())
8675       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8676   }
8677 
8678   // C++ [over.match.oper]p16:
8679   //   For every pointer to member type T or type std::nullptr_t, there
8680   //   exist candidate operator functions of the form
8681   //
8682   //        bool operator==(T,T);
8683   //        bool operator!=(T,T);
8684   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8685     /// Set of (canonical) types that we've already handled.
8686     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8687 
8688     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8689       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8690         // Don't add the same builtin candidate twice.
8691         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8692           continue;
8693 
8694         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8695         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8696       }
8697 
8698       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8699         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8700         if (AddedTypes.insert(NullPtrTy).second) {
8701           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8702           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8703         }
8704       }
8705     }
8706   }
8707 
8708   // C++ [over.built]p15:
8709   //
8710   //   For every T, where T is an enumeration type or a pointer type,
8711   //   there exist candidate operator functions of the form
8712   //
8713   //        bool       operator<(T, T);
8714   //        bool       operator>(T, T);
8715   //        bool       operator<=(T, T);
8716   //        bool       operator>=(T, T);
8717   //        bool       operator==(T, T);
8718   //        bool       operator!=(T, T);
8719   //           R       operator<=>(T, T)
8720   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8721     // C++ [over.match.oper]p3:
8722     //   [...]the built-in candidates include all of the candidate operator
8723     //   functions defined in 13.6 that, compared to the given operator, [...]
8724     //   do not have the same parameter-type-list as any non-template non-member
8725     //   candidate.
8726     //
8727     // Note that in practice, this only affects enumeration types because there
8728     // aren't any built-in candidates of record type, and a user-defined operator
8729     // must have an operand of record or enumeration type. Also, the only other
8730     // overloaded operator with enumeration arguments, operator=,
8731     // cannot be overloaded for enumeration types, so this is the only place
8732     // where we must suppress candidates like this.
8733     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8734       UserDefinedBinaryOperators;
8735 
8736     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8737       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8738         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8739                                          CEnd = CandidateSet.end();
8740              C != CEnd; ++C) {
8741           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8742             continue;
8743 
8744           if (C->Function->isFunctionTemplateSpecialization())
8745             continue;
8746 
8747           // We interpret "same parameter-type-list" as applying to the
8748           // "synthesized candidate, with the order of the two parameters
8749           // reversed", not to the original function.
8750           bool Reversed = C->isReversed();
8751           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8752                                         ->getType()
8753                                         .getUnqualifiedType();
8754           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8755                                          ->getType()
8756                                          .getUnqualifiedType();
8757 
8758           // Skip if either parameter isn't of enumeral type.
8759           if (!FirstParamType->isEnumeralType() ||
8760               !SecondParamType->isEnumeralType())
8761             continue;
8762 
8763           // Add this operator to the set of known user-defined operators.
8764           UserDefinedBinaryOperators.insert(
8765             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8766                            S.Context.getCanonicalType(SecondParamType)));
8767         }
8768       }
8769     }
8770 
8771     /// Set of (canonical) types that we've already handled.
8772     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8773 
8774     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8775       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8776         // Don't add the same builtin candidate twice.
8777         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8778           continue;
8779         if (IsSpaceship && PtrTy->isFunctionPointerType())
8780           continue;
8781 
8782         QualType ParamTypes[2] = {PtrTy, PtrTy};
8783         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8784       }
8785       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8786         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8787 
8788         // Don't add the same builtin candidate twice, or if a user defined
8789         // candidate exists.
8790         if (!AddedTypes.insert(CanonType).second ||
8791             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8792                                                             CanonType)))
8793           continue;
8794         QualType ParamTypes[2] = {EnumTy, EnumTy};
8795         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8796       }
8797     }
8798   }
8799 
8800   // C++ [over.built]p13:
8801   //
8802   //   For every cv-qualified or cv-unqualified object type T
8803   //   there exist candidate operator functions of the form
8804   //
8805   //      T*         operator+(T*, ptrdiff_t);
8806   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8807   //      T*         operator-(T*, ptrdiff_t);
8808   //      T*         operator+(ptrdiff_t, T*);
8809   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8810   //
8811   // C++ [over.built]p14:
8812   //
8813   //   For every T, where T is a pointer to object type, there
8814   //   exist candidate operator functions of the form
8815   //
8816   //      ptrdiff_t  operator-(T, T);
8817   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8818     /// Set of (canonical) types that we've already handled.
8819     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8820 
8821     for (int Arg = 0; Arg < 2; ++Arg) {
8822       QualType AsymmetricParamTypes[2] = {
8823         S.Context.getPointerDiffType(),
8824         S.Context.getPointerDiffType(),
8825       };
8826       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8827         QualType PointeeTy = PtrTy->getPointeeType();
8828         if (!PointeeTy->isObjectType())
8829           continue;
8830 
8831         AsymmetricParamTypes[Arg] = PtrTy;
8832         if (Arg == 0 || Op == OO_Plus) {
8833           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8834           // T* operator+(ptrdiff_t, T*);
8835           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8836         }
8837         if (Op == OO_Minus) {
8838           // ptrdiff_t operator-(T, T);
8839           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8840             continue;
8841 
8842           QualType ParamTypes[2] = {PtrTy, PtrTy};
8843           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8844         }
8845       }
8846     }
8847   }
8848 
8849   // C++ [over.built]p12:
8850   //
8851   //   For every pair of promoted arithmetic types L and R, there
8852   //   exist candidate operator functions of the form
8853   //
8854   //        LR         operator*(L, R);
8855   //        LR         operator/(L, R);
8856   //        LR         operator+(L, R);
8857   //        LR         operator-(L, R);
8858   //        bool       operator<(L, R);
8859   //        bool       operator>(L, R);
8860   //        bool       operator<=(L, R);
8861   //        bool       operator>=(L, R);
8862   //        bool       operator==(L, R);
8863   //        bool       operator!=(L, R);
8864   //
8865   //   where LR is the result of the usual arithmetic conversions
8866   //   between types L and R.
8867   //
8868   // C++ [over.built]p24:
8869   //
8870   //   For every pair of promoted arithmetic types L and R, there exist
8871   //   candidate operator functions of the form
8872   //
8873   //        LR       operator?(bool, L, R);
8874   //
8875   //   where LR is the result of the usual arithmetic conversions
8876   //   between types L and R.
8877   // Our candidates ignore the first parameter.
8878   void addGenericBinaryArithmeticOverloads() {
8879     if (!HasArithmeticOrEnumeralCandidateType)
8880       return;
8881 
8882     for (unsigned Left = FirstPromotedArithmeticType;
8883          Left < LastPromotedArithmeticType; ++Left) {
8884       for (unsigned Right = FirstPromotedArithmeticType;
8885            Right < LastPromotedArithmeticType; ++Right) {
8886         QualType LandR[2] = { ArithmeticTypes[Left],
8887                               ArithmeticTypes[Right] };
8888         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8889       }
8890     }
8891 
8892     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8893     // conditional operator for vector types.
8894     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8895       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8896         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8897         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8898       }
8899   }
8900 
8901   /// Add binary operator overloads for each candidate matrix type M1, M2:
8902   ///  * (M1, M1) -> M1
8903   ///  * (M1, M1.getElementType()) -> M1
8904   ///  * (M2.getElementType(), M2) -> M2
8905   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8906   void addMatrixBinaryArithmeticOverloads() {
8907     if (!HasArithmeticOrEnumeralCandidateType)
8908       return;
8909 
8910     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8911       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8912       AddCandidate(M1, M1);
8913     }
8914 
8915     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8916       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8917       if (!CandidateTypes[0].containsMatrixType(M2))
8918         AddCandidate(M2, M2);
8919     }
8920   }
8921 
8922   // C++2a [over.built]p14:
8923   //
8924   //   For every integral type T there exists a candidate operator function
8925   //   of the form
8926   //
8927   //        std::strong_ordering operator<=>(T, T)
8928   //
8929   // C++2a [over.built]p15:
8930   //
8931   //   For every pair of floating-point types L and R, there exists a candidate
8932   //   operator function of the form
8933   //
8934   //       std::partial_ordering operator<=>(L, R);
8935   //
8936   // FIXME: The current specification for integral types doesn't play nice with
8937   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8938   // comparisons. Under the current spec this can lead to ambiguity during
8939   // overload resolution. For example:
8940   //
8941   //   enum A : int {a};
8942   //   auto x = (a <=> (long)42);
8943   //
8944   //   error: call is ambiguous for arguments 'A' and 'long'.
8945   //   note: candidate operator<=>(int, int)
8946   //   note: candidate operator<=>(long, long)
8947   //
8948   // To avoid this error, this function deviates from the specification and adds
8949   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8950   // arithmetic types (the same as the generic relational overloads).
8951   //
8952   // For now this function acts as a placeholder.
8953   void addThreeWayArithmeticOverloads() {
8954     addGenericBinaryArithmeticOverloads();
8955   }
8956 
8957   // C++ [over.built]p17:
8958   //
8959   //   For every pair of promoted integral types L and R, there
8960   //   exist candidate operator functions of the form
8961   //
8962   //      LR         operator%(L, R);
8963   //      LR         operator&(L, R);
8964   //      LR         operator^(L, R);
8965   //      LR         operator|(L, R);
8966   //      L          operator<<(L, R);
8967   //      L          operator>>(L, R);
8968   //
8969   //   where LR is the result of the usual arithmetic conversions
8970   //   between types L and R.
8971   void addBinaryBitwiseArithmeticOverloads() {
8972     if (!HasArithmeticOrEnumeralCandidateType)
8973       return;
8974 
8975     for (unsigned Left = FirstPromotedIntegralType;
8976          Left < LastPromotedIntegralType; ++Left) {
8977       for (unsigned Right = FirstPromotedIntegralType;
8978            Right < LastPromotedIntegralType; ++Right) {
8979         QualType LandR[2] = { ArithmeticTypes[Left],
8980                               ArithmeticTypes[Right] };
8981         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8982       }
8983     }
8984   }
8985 
8986   // C++ [over.built]p20:
8987   //
8988   //   For every pair (T, VQ), where T is an enumeration or
8989   //   pointer to member type and VQ is either volatile or
8990   //   empty, there exist candidate operator functions of the form
8991   //
8992   //        VQ T&      operator=(VQ T&, T);
8993   void addAssignmentMemberPointerOrEnumeralOverloads() {
8994     /// Set of (canonical) types that we've already handled.
8995     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8996 
8997     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8998       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8999         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9000           continue;
9001 
9002         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9003       }
9004 
9005       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9006         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9007           continue;
9008 
9009         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9010       }
9011     }
9012   }
9013 
9014   // C++ [over.built]p19:
9015   //
9016   //   For every pair (T, VQ), where T is any type and VQ is either
9017   //   volatile or empty, there exist candidate operator functions
9018   //   of the form
9019   //
9020   //        T*VQ&      operator=(T*VQ&, T*);
9021   //
9022   // C++ [over.built]p21:
9023   //
9024   //   For every pair (T, VQ), where T is a cv-qualified or
9025   //   cv-unqualified object type and VQ is either volatile or
9026   //   empty, there exist candidate operator functions of the form
9027   //
9028   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9029   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
9030   void addAssignmentPointerOverloads(bool isEqualOp) {
9031     /// Set of (canonical) types that we've already handled.
9032     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9033 
9034     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9035       // If this is operator=, keep track of the builtin candidates we added.
9036       if (isEqualOp)
9037         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9038       else if (!PtrTy->getPointeeType()->isObjectType())
9039         continue;
9040 
9041       // non-volatile version
9042       QualType ParamTypes[2] = {
9043           S.Context.getLValueReferenceType(PtrTy),
9044           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9045       };
9046       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9047                             /*IsAssignmentOperator=*/ isEqualOp);
9048 
9049       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9050                           VisibleTypeConversionsQuals.hasVolatile();
9051       if (NeedVolatile) {
9052         // volatile version
9053         ParamTypes[0] =
9054             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9055         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9056                               /*IsAssignmentOperator=*/isEqualOp);
9057       }
9058 
9059       if (!PtrTy.isRestrictQualified() &&
9060           VisibleTypeConversionsQuals.hasRestrict()) {
9061         // restrict version
9062         ParamTypes[0] =
9063             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9064         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9065                               /*IsAssignmentOperator=*/isEqualOp);
9066 
9067         if (NeedVolatile) {
9068           // volatile restrict version
9069           ParamTypes[0] =
9070               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9071                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9072           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9073                                 /*IsAssignmentOperator=*/isEqualOp);
9074         }
9075       }
9076     }
9077 
9078     if (isEqualOp) {
9079       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9080         // Make sure we don't add the same candidate twice.
9081         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9082           continue;
9083 
9084         QualType ParamTypes[2] = {
9085             S.Context.getLValueReferenceType(PtrTy),
9086             PtrTy,
9087         };
9088 
9089         // non-volatile version
9090         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9091                               /*IsAssignmentOperator=*/true);
9092 
9093         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9094                             VisibleTypeConversionsQuals.hasVolatile();
9095         if (NeedVolatile) {
9096           // volatile version
9097           ParamTypes[0] = S.Context.getLValueReferenceType(
9098               S.Context.getVolatileType(PtrTy));
9099           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9100                                 /*IsAssignmentOperator=*/true);
9101         }
9102 
9103         if (!PtrTy.isRestrictQualified() &&
9104             VisibleTypeConversionsQuals.hasRestrict()) {
9105           // restrict version
9106           ParamTypes[0] = S.Context.getLValueReferenceType(
9107               S.Context.getRestrictType(PtrTy));
9108           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9109                                 /*IsAssignmentOperator=*/true);
9110 
9111           if (NeedVolatile) {
9112             // volatile restrict version
9113             ParamTypes[0] =
9114                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9115                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9116             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9117                                   /*IsAssignmentOperator=*/true);
9118           }
9119         }
9120       }
9121     }
9122   }
9123 
9124   // C++ [over.built]p18:
9125   //
9126   //   For every triple (L, VQ, R), where L is an arithmetic type,
9127   //   VQ is either volatile or empty, and R is a promoted
9128   //   arithmetic type, there exist candidate operator functions of
9129   //   the form
9130   //
9131   //        VQ L&      operator=(VQ L&, R);
9132   //        VQ L&      operator*=(VQ L&, R);
9133   //        VQ L&      operator/=(VQ L&, R);
9134   //        VQ L&      operator+=(VQ L&, R);
9135   //        VQ L&      operator-=(VQ L&, R);
9136   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9137     if (!HasArithmeticOrEnumeralCandidateType)
9138       return;
9139 
9140     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9141       for (unsigned Right = FirstPromotedArithmeticType;
9142            Right < LastPromotedArithmeticType; ++Right) {
9143         QualType ParamTypes[2];
9144         ParamTypes[1] = ArithmeticTypes[Right];
9145         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9146             S, ArithmeticTypes[Left], Args[0]);
9147 
9148         forAllQualifierCombinations(
9149             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9150               ParamTypes[0] =
9151                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9152               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9153                                     /*IsAssignmentOperator=*/isEqualOp);
9154             });
9155       }
9156     }
9157 
9158     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9159     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9160       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9161         QualType ParamTypes[2];
9162         ParamTypes[1] = Vec2Ty;
9163         // Add this built-in operator as a candidate (VQ is empty).
9164         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9165         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9166                               /*IsAssignmentOperator=*/isEqualOp);
9167 
9168         // Add this built-in operator as a candidate (VQ is 'volatile').
9169         if (VisibleTypeConversionsQuals.hasVolatile()) {
9170           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9171           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9172           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9173                                 /*IsAssignmentOperator=*/isEqualOp);
9174         }
9175       }
9176   }
9177 
9178   // C++ [over.built]p22:
9179   //
9180   //   For every triple (L, VQ, R), where L is an integral type, VQ
9181   //   is either volatile or empty, and R is a promoted integral
9182   //   type, there exist candidate operator functions of the form
9183   //
9184   //        VQ L&       operator%=(VQ L&, R);
9185   //        VQ L&       operator<<=(VQ L&, R);
9186   //        VQ L&       operator>>=(VQ L&, R);
9187   //        VQ L&       operator&=(VQ L&, R);
9188   //        VQ L&       operator^=(VQ L&, R);
9189   //        VQ L&       operator|=(VQ L&, R);
9190   void addAssignmentIntegralOverloads() {
9191     if (!HasArithmeticOrEnumeralCandidateType)
9192       return;
9193 
9194     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9195       for (unsigned Right = FirstPromotedIntegralType;
9196            Right < LastPromotedIntegralType; ++Right) {
9197         QualType ParamTypes[2];
9198         ParamTypes[1] = ArithmeticTypes[Right];
9199         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9200             S, ArithmeticTypes[Left], Args[0]);
9201 
9202         forAllQualifierCombinations(
9203             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9204               ParamTypes[0] =
9205                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9206               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9207             });
9208       }
9209     }
9210   }
9211 
9212   // C++ [over.operator]p23:
9213   //
9214   //   There also exist candidate operator functions of the form
9215   //
9216   //        bool        operator!(bool);
9217   //        bool        operator&&(bool, bool);
9218   //        bool        operator||(bool, bool);
9219   void addExclaimOverload() {
9220     QualType ParamTy = S.Context.BoolTy;
9221     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9222                           /*IsAssignmentOperator=*/false,
9223                           /*NumContextualBoolArguments=*/1);
9224   }
9225   void addAmpAmpOrPipePipeOverload() {
9226     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9227     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9228                           /*IsAssignmentOperator=*/false,
9229                           /*NumContextualBoolArguments=*/2);
9230   }
9231 
9232   // C++ [over.built]p13:
9233   //
9234   //   For every cv-qualified or cv-unqualified object type T there
9235   //   exist candidate operator functions of the form
9236   //
9237   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9238   //        T&         operator[](T*, ptrdiff_t);
9239   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9240   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9241   //        T&         operator[](ptrdiff_t, T*);
9242   void addSubscriptOverloads() {
9243     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9244       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9245       QualType PointeeType = PtrTy->getPointeeType();
9246       if (!PointeeType->isObjectType())
9247         continue;
9248 
9249       // T& operator[](T*, ptrdiff_t)
9250       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9251     }
9252 
9253     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9254       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9255       QualType PointeeType = PtrTy->getPointeeType();
9256       if (!PointeeType->isObjectType())
9257         continue;
9258 
9259       // T& operator[](ptrdiff_t, T*)
9260       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9261     }
9262   }
9263 
9264   // C++ [over.built]p11:
9265   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9266   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9267   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9268   //    there exist candidate operator functions of the form
9269   //
9270   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9271   //
9272   //    where CV12 is the union of CV1 and CV2.
9273   void addArrowStarOverloads() {
9274     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9275       QualType C1Ty = PtrTy;
9276       QualType C1;
9277       QualifierCollector Q1;
9278       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9279       if (!isa<RecordType>(C1))
9280         continue;
9281       // heuristic to reduce number of builtin candidates in the set.
9282       // Add volatile/restrict version only if there are conversions to a
9283       // volatile/restrict type.
9284       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9285         continue;
9286       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9287         continue;
9288       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9289         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9290         QualType C2 = QualType(mptr->getClass(), 0);
9291         C2 = C2.getUnqualifiedType();
9292         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9293           break;
9294         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9295         // build CV12 T&
9296         QualType T = mptr->getPointeeType();
9297         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9298             T.isVolatileQualified())
9299           continue;
9300         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9301             T.isRestrictQualified())
9302           continue;
9303         T = Q1.apply(S.Context, T);
9304         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9305       }
9306     }
9307   }
9308 
9309   // Note that we don't consider the first argument, since it has been
9310   // contextually converted to bool long ago. The candidates below are
9311   // therefore added as binary.
9312   //
9313   // C++ [over.built]p25:
9314   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9315   //   enumeration type, there exist candidate operator functions of the form
9316   //
9317   //        T        operator?(bool, T, T);
9318   //
9319   void addConditionalOperatorOverloads() {
9320     /// Set of (canonical) types that we've already handled.
9321     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9322 
9323     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9324       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9325         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9326           continue;
9327 
9328         QualType ParamTypes[2] = {PtrTy, PtrTy};
9329         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9330       }
9331 
9332       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9333         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9334           continue;
9335 
9336         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9337         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9338       }
9339 
9340       if (S.getLangOpts().CPlusPlus11) {
9341         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9342           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9343             continue;
9344 
9345           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9346             continue;
9347 
9348           QualType ParamTypes[2] = {EnumTy, EnumTy};
9349           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9350         }
9351       }
9352     }
9353   }
9354 };
9355 
9356 } // end anonymous namespace
9357 
9358 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9359 /// operator overloads to the candidate set (C++ [over.built]), based
9360 /// on the operator @p Op and the arguments given. For example, if the
9361 /// operator is a binary '+', this routine might add "int
9362 /// operator+(int, int)" to cover integer addition.
9363 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9364                                         SourceLocation OpLoc,
9365                                         ArrayRef<Expr *> Args,
9366                                         OverloadCandidateSet &CandidateSet) {
9367   // Find all of the types that the arguments can convert to, but only
9368   // if the operator we're looking at has built-in operator candidates
9369   // that make use of these types. Also record whether we encounter non-record
9370   // candidate types or either arithmetic or enumeral candidate types.
9371   QualifiersAndAtomic VisibleTypeConversionsQuals;
9372   VisibleTypeConversionsQuals.addConst();
9373   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9374     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9375     if (Args[ArgIdx]->getType()->isAtomicType())
9376       VisibleTypeConversionsQuals.addAtomic();
9377   }
9378 
9379   bool HasNonRecordCandidateType = false;
9380   bool HasArithmeticOrEnumeralCandidateType = false;
9381   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9382   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9383     CandidateTypes.emplace_back(*this);
9384     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9385                                                  OpLoc,
9386                                                  true,
9387                                                  (Op == OO_Exclaim ||
9388                                                   Op == OO_AmpAmp ||
9389                                                   Op == OO_PipePipe),
9390                                                  VisibleTypeConversionsQuals);
9391     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9392         CandidateTypes[ArgIdx].hasNonRecordTypes();
9393     HasArithmeticOrEnumeralCandidateType =
9394         HasArithmeticOrEnumeralCandidateType ||
9395         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9396   }
9397 
9398   // Exit early when no non-record types have been added to the candidate set
9399   // for any of the arguments to the operator.
9400   //
9401   // We can't exit early for !, ||, or &&, since there we have always have
9402   // 'bool' overloads.
9403   if (!HasNonRecordCandidateType &&
9404       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9405     return;
9406 
9407   // Setup an object to manage the common state for building overloads.
9408   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9409                                            VisibleTypeConversionsQuals,
9410                                            HasArithmeticOrEnumeralCandidateType,
9411                                            CandidateTypes, CandidateSet);
9412 
9413   // Dispatch over the operation to add in only those overloads which apply.
9414   switch (Op) {
9415   case OO_None:
9416   case NUM_OVERLOADED_OPERATORS:
9417     llvm_unreachable("Expected an overloaded operator");
9418 
9419   case OO_New:
9420   case OO_Delete:
9421   case OO_Array_New:
9422   case OO_Array_Delete:
9423   case OO_Call:
9424     llvm_unreachable(
9425                     "Special operators don't use AddBuiltinOperatorCandidates");
9426 
9427   case OO_Comma:
9428   case OO_Arrow:
9429   case OO_Coawait:
9430     // C++ [over.match.oper]p3:
9431     //   -- For the operator ',', the unary operator '&', the
9432     //      operator '->', or the operator 'co_await', the
9433     //      built-in candidates set is empty.
9434     break;
9435 
9436   case OO_Plus: // '+' is either unary or binary
9437     if (Args.size() == 1)
9438       OpBuilder.addUnaryPlusPointerOverloads();
9439     [[fallthrough]];
9440 
9441   case OO_Minus: // '-' is either unary or binary
9442     if (Args.size() == 1) {
9443       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9444     } else {
9445       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9446       OpBuilder.addGenericBinaryArithmeticOverloads();
9447       OpBuilder.addMatrixBinaryArithmeticOverloads();
9448     }
9449     break;
9450 
9451   case OO_Star: // '*' is either unary or binary
9452     if (Args.size() == 1)
9453       OpBuilder.addUnaryStarPointerOverloads();
9454     else {
9455       OpBuilder.addGenericBinaryArithmeticOverloads();
9456       OpBuilder.addMatrixBinaryArithmeticOverloads();
9457     }
9458     break;
9459 
9460   case OO_Slash:
9461     OpBuilder.addGenericBinaryArithmeticOverloads();
9462     break;
9463 
9464   case OO_PlusPlus:
9465   case OO_MinusMinus:
9466     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9467     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9468     break;
9469 
9470   case OO_EqualEqual:
9471   case OO_ExclaimEqual:
9472     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9473     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9474     OpBuilder.addGenericBinaryArithmeticOverloads();
9475     break;
9476 
9477   case OO_Less:
9478   case OO_Greater:
9479   case OO_LessEqual:
9480   case OO_GreaterEqual:
9481     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9482     OpBuilder.addGenericBinaryArithmeticOverloads();
9483     break;
9484 
9485   case OO_Spaceship:
9486     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9487     OpBuilder.addThreeWayArithmeticOverloads();
9488     break;
9489 
9490   case OO_Percent:
9491   case OO_Caret:
9492   case OO_Pipe:
9493   case OO_LessLess:
9494   case OO_GreaterGreater:
9495     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9496     break;
9497 
9498   case OO_Amp: // '&' is either unary or binary
9499     if (Args.size() == 1)
9500       // C++ [over.match.oper]p3:
9501       //   -- For the operator ',', the unary operator '&', or the
9502       //      operator '->', the built-in candidates set is empty.
9503       break;
9504 
9505     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9506     break;
9507 
9508   case OO_Tilde:
9509     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9510     break;
9511 
9512   case OO_Equal:
9513     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9514     [[fallthrough]];
9515 
9516   case OO_PlusEqual:
9517   case OO_MinusEqual:
9518     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9519     [[fallthrough]];
9520 
9521   case OO_StarEqual:
9522   case OO_SlashEqual:
9523     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9524     break;
9525 
9526   case OO_PercentEqual:
9527   case OO_LessLessEqual:
9528   case OO_GreaterGreaterEqual:
9529   case OO_AmpEqual:
9530   case OO_CaretEqual:
9531   case OO_PipeEqual:
9532     OpBuilder.addAssignmentIntegralOverloads();
9533     break;
9534 
9535   case OO_Exclaim:
9536     OpBuilder.addExclaimOverload();
9537     break;
9538 
9539   case OO_AmpAmp:
9540   case OO_PipePipe:
9541     OpBuilder.addAmpAmpOrPipePipeOverload();
9542     break;
9543 
9544   case OO_Subscript:
9545     if (Args.size() == 2)
9546       OpBuilder.addSubscriptOverloads();
9547     break;
9548 
9549   case OO_ArrowStar:
9550     OpBuilder.addArrowStarOverloads();
9551     break;
9552 
9553   case OO_Conditional:
9554     OpBuilder.addConditionalOperatorOverloads();
9555     OpBuilder.addGenericBinaryArithmeticOverloads();
9556     break;
9557   }
9558 }
9559 
9560 /// Add function candidates found via argument-dependent lookup
9561 /// to the set of overloading candidates.
9562 ///
9563 /// This routine performs argument-dependent name lookup based on the
9564 /// given function name (which may also be an operator name) and adds
9565 /// all of the overload candidates found by ADL to the overload
9566 /// candidate set (C++ [basic.lookup.argdep]).
9567 void
9568 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9569                                            SourceLocation Loc,
9570                                            ArrayRef<Expr *> Args,
9571                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9572                                            OverloadCandidateSet& CandidateSet,
9573                                            bool PartialOverloading) {
9574   ADLResult Fns;
9575 
9576   // FIXME: This approach for uniquing ADL results (and removing
9577   // redundant candidates from the set) relies on pointer-equality,
9578   // which means we need to key off the canonical decl.  However,
9579   // always going back to the canonical decl might not get us the
9580   // right set of default arguments.  What default arguments are
9581   // we supposed to consider on ADL candidates, anyway?
9582 
9583   // FIXME: Pass in the explicit template arguments?
9584   ArgumentDependentLookup(Name, Loc, Args, Fns);
9585 
9586   // Erase all of the candidates we already knew about.
9587   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9588                                    CandEnd = CandidateSet.end();
9589        Cand != CandEnd; ++Cand)
9590     if (Cand->Function) {
9591       Fns.erase(Cand->Function);
9592       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9593         Fns.erase(FunTmpl);
9594     }
9595 
9596   // For each of the ADL candidates we found, add it to the overload
9597   // set.
9598   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9599     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9600 
9601     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9602       if (ExplicitTemplateArgs)
9603         continue;
9604 
9605       AddOverloadCandidate(
9606           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9607           PartialOverloading, /*AllowExplicit=*/true,
9608           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9609       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9610         AddOverloadCandidate(
9611             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9612             /*SuppressUserConversions=*/false, PartialOverloading,
9613             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9614             ADLCallKind::UsesADL, std::nullopt,
9615             OverloadCandidateParamOrder::Reversed);
9616       }
9617     } else {
9618       auto *FTD = cast<FunctionTemplateDecl>(*I);
9619       AddTemplateOverloadCandidate(
9620           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9621           /*SuppressUserConversions=*/false, PartialOverloading,
9622           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9623       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9624               *this, Args, FTD->getTemplatedDecl())) {
9625         AddTemplateOverloadCandidate(
9626             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9627             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9628             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9629             OverloadCandidateParamOrder::Reversed);
9630       }
9631     }
9632   }
9633 }
9634 
9635 namespace {
9636 enum class Comparison { Equal, Better, Worse };
9637 }
9638 
9639 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9640 /// overload resolution.
9641 ///
9642 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9643 /// Cand1's first N enable_if attributes have precisely the same conditions as
9644 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9645 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9646 ///
9647 /// Note that you can have a pair of candidates such that Cand1's enable_if
9648 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9649 /// worse than Cand1's.
9650 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9651                                        const FunctionDecl *Cand2) {
9652   // Common case: One (or both) decls don't have enable_if attrs.
9653   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9654   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9655   if (!Cand1Attr || !Cand2Attr) {
9656     if (Cand1Attr == Cand2Attr)
9657       return Comparison::Equal;
9658     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9659   }
9660 
9661   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9662   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9663 
9664   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9665   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9666     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9667     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9668 
9669     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9670     // has fewer enable_if attributes than Cand2, and vice versa.
9671     if (!Cand1A)
9672       return Comparison::Worse;
9673     if (!Cand2A)
9674       return Comparison::Better;
9675 
9676     Cand1ID.clear();
9677     Cand2ID.clear();
9678 
9679     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9680     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9681     if (Cand1ID != Cand2ID)
9682       return Comparison::Worse;
9683   }
9684 
9685   return Comparison::Equal;
9686 }
9687 
9688 static Comparison
9689 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9690                               const OverloadCandidate &Cand2) {
9691   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9692       !Cand2.Function->isMultiVersion())
9693     return Comparison::Equal;
9694 
9695   // If both are invalid, they are equal. If one of them is invalid, the other
9696   // is better.
9697   if (Cand1.Function->isInvalidDecl()) {
9698     if (Cand2.Function->isInvalidDecl())
9699       return Comparison::Equal;
9700     return Comparison::Worse;
9701   }
9702   if (Cand2.Function->isInvalidDecl())
9703     return Comparison::Better;
9704 
9705   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9706   // cpu_dispatch, else arbitrarily based on the identifiers.
9707   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9708   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9709   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9710   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9711 
9712   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9713     return Comparison::Equal;
9714 
9715   if (Cand1CPUDisp && !Cand2CPUDisp)
9716     return Comparison::Better;
9717   if (Cand2CPUDisp && !Cand1CPUDisp)
9718     return Comparison::Worse;
9719 
9720   if (Cand1CPUSpec && Cand2CPUSpec) {
9721     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9722       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9723                  ? Comparison::Better
9724                  : Comparison::Worse;
9725 
9726     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9727         FirstDiff = std::mismatch(
9728             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9729             Cand2CPUSpec->cpus_begin(),
9730             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9731               return LHS->getName() == RHS->getName();
9732             });
9733 
9734     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9735            "Two different cpu-specific versions should not have the same "
9736            "identifier list, otherwise they'd be the same decl!");
9737     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9738                ? Comparison::Better
9739                : Comparison::Worse;
9740   }
9741   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9742 }
9743 
9744 /// Compute the type of the implicit object parameter for the given function,
9745 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
9746 /// null QualType if there is a 'matches anything' implicit object parameter.
9747 static std::optional<QualType>
9748 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
9749   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9750     return std::nullopt;
9751 
9752   auto *M = cast<CXXMethodDecl>(F);
9753   // Static member functions' object parameters match all types.
9754   if (M->isStatic())
9755     return QualType();
9756 
9757   QualType T = M->getThisObjectType();
9758   if (M->getRefQualifier() == RQ_RValue)
9759     return Context.getRValueReferenceType(T);
9760   return Context.getLValueReferenceType(T);
9761 }
9762 
9763 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9764                                    const FunctionDecl *F2, unsigned NumParams) {
9765   if (declaresSameEntity(F1, F2))
9766     return true;
9767 
9768   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9769     if (First) {
9770       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
9771         return *T;
9772     }
9773     assert(I < F->getNumParams());
9774     return F->getParamDecl(I++)->getType();
9775   };
9776 
9777   unsigned I1 = 0, I2 = 0;
9778   for (unsigned I = 0; I != NumParams; ++I) {
9779     QualType T1 = NextParam(F1, I1, I == 0);
9780     QualType T2 = NextParam(F2, I2, I == 0);
9781     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9782     if (!Context.hasSameUnqualifiedType(T1, T2))
9783       return false;
9784   }
9785   return true;
9786 }
9787 
9788 /// We're allowed to use constraints partial ordering only if the candidates
9789 /// have the same parameter types:
9790 /// [over.match.best]p2.6
9791 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9792 /// and F1 is more constrained than F2 [...]
9793 static bool sameFunctionParameterTypeLists(Sema &S,
9794                                           const OverloadCandidate &Cand1,
9795                                           const OverloadCandidate &Cand2) {
9796   if (Cand1.Function && Cand2.Function) {
9797     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9798     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9799     if (PT1->getNumParams() == PT2->getNumParams() &&
9800         PT1->isVariadic() == PT2->isVariadic() &&
9801         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9802                                      Cand1.isReversed() ^ Cand2.isReversed()))
9803       return true;
9804   }
9805   return false;
9806 }
9807 
9808 /// isBetterOverloadCandidate - Determines whether the first overload
9809 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9810 bool clang::isBetterOverloadCandidate(
9811     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9812     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9813   // Define viable functions to be better candidates than non-viable
9814   // functions.
9815   if (!Cand2.Viable)
9816     return Cand1.Viable;
9817   else if (!Cand1.Viable)
9818     return false;
9819 
9820   // [CUDA] A function with 'never' preference is marked not viable, therefore
9821   // is never shown up here. The worst preference shown up here is 'wrong side',
9822   // e.g. an H function called by a HD function in device compilation. This is
9823   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9824   // function which is called only by an H function. A deferred diagnostic will
9825   // be triggered if it is emitted. However a wrong-sided function is still
9826   // a viable candidate here.
9827   //
9828   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9829   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9830   // can be emitted, Cand1 is not better than Cand2. This rule should have
9831   // precedence over other rules.
9832   //
9833   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9834   // other rules should be used to determine which is better. This is because
9835   // host/device based overloading resolution is mostly for determining
9836   // viability of a function. If two functions are both viable, other factors
9837   // should take precedence in preference, e.g. the standard-defined preferences
9838   // like argument conversion ranks or enable_if partial-ordering. The
9839   // preference for pass-object-size parameters is probably most similar to a
9840   // type-based-overloading decision and so should take priority.
9841   //
9842   // If other rules cannot determine which is better, CUDA preference will be
9843   // used again to determine which is better.
9844   //
9845   // TODO: Currently IdentifyCUDAPreference does not return correct values
9846   // for functions called in global variable initializers due to missing
9847   // correct context about device/host. Therefore we can only enforce this
9848   // rule when there is a caller. We should enforce this rule for functions
9849   // in global variable initializers once proper context is added.
9850   //
9851   // TODO: We can only enable the hostness based overloading resolution when
9852   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9853   // overloading resolution diagnostics.
9854   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9855       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9856     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9857       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9858       bool IsCand1ImplicitHD =
9859           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9860       bool IsCand2ImplicitHD =
9861           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9862       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9863       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9864       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9865       // The implicit HD function may be a function in a system header which
9866       // is forced by pragma. In device compilation, if we prefer HD candidates
9867       // over wrong-sided candidates, overloading resolution may change, which
9868       // may result in non-deferrable diagnostics. As a workaround, we let
9869       // implicit HD candidates take equal preference as wrong-sided candidates.
9870       // This will preserve the overloading resolution.
9871       // TODO: We still need special handling of implicit HD functions since
9872       // they may incur other diagnostics to be deferred. We should make all
9873       // host/device related diagnostics deferrable and remove special handling
9874       // of implicit HD functions.
9875       auto EmitThreshold =
9876           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9877            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9878               ? Sema::CFP_Never
9879               : Sema::CFP_WrongSide;
9880       auto Cand1Emittable = P1 > EmitThreshold;
9881       auto Cand2Emittable = P2 > EmitThreshold;
9882       if (Cand1Emittable && !Cand2Emittable)
9883         return true;
9884       if (!Cand1Emittable && Cand2Emittable)
9885         return false;
9886     }
9887   }
9888 
9889   // C++ [over.match.best]p1: (Changed in C++2b)
9890   //
9891   //   -- if F is a static member function, ICS1(F) is defined such
9892   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9893   //      any function G, and, symmetrically, ICS1(G) is neither
9894   //      better nor worse than ICS1(F).
9895   unsigned StartArg = 0;
9896   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9897     StartArg = 1;
9898 
9899   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9900     // We don't allow incompatible pointer conversions in C++.
9901     if (!S.getLangOpts().CPlusPlus)
9902       return ICS.isStandard() &&
9903              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9904 
9905     // The only ill-formed conversion we allow in C++ is the string literal to
9906     // char* conversion, which is only considered ill-formed after C++11.
9907     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9908            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9909   };
9910 
9911   // Define functions that don't require ill-formed conversions for a given
9912   // argument to be better candidates than functions that do.
9913   unsigned NumArgs = Cand1.Conversions.size();
9914   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9915   bool HasBetterConversion = false;
9916   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9917     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9918     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9919     if (Cand1Bad != Cand2Bad) {
9920       if (Cand1Bad)
9921         return false;
9922       HasBetterConversion = true;
9923     }
9924   }
9925 
9926   if (HasBetterConversion)
9927     return true;
9928 
9929   // C++ [over.match.best]p1:
9930   //   A viable function F1 is defined to be a better function than another
9931   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9932   //   conversion sequence than ICSi(F2), and then...
9933   bool HasWorseConversion = false;
9934   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9935     switch (CompareImplicitConversionSequences(S, Loc,
9936                                                Cand1.Conversions[ArgIdx],
9937                                                Cand2.Conversions[ArgIdx])) {
9938     case ImplicitConversionSequence::Better:
9939       // Cand1 has a better conversion sequence.
9940       HasBetterConversion = true;
9941       break;
9942 
9943     case ImplicitConversionSequence::Worse:
9944       if (Cand1.Function && Cand2.Function &&
9945           Cand1.isReversed() != Cand2.isReversed() &&
9946           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9947                                  NumArgs)) {
9948         // Work around large-scale breakage caused by considering reversed
9949         // forms of operator== in C++20:
9950         //
9951         // When comparing a function against a reversed function with the same
9952         // parameter types, if we have a better conversion for one argument and
9953         // a worse conversion for the other, the implicit conversion sequences
9954         // are treated as being equally good.
9955         //
9956         // This prevents a comparison function from being considered ambiguous
9957         // with a reversed form that is written in the same way.
9958         //
9959         // We diagnose this as an extension from CreateOverloadedBinOp.
9960         HasWorseConversion = true;
9961         break;
9962       }
9963 
9964       // Cand1 can't be better than Cand2.
9965       return false;
9966 
9967     case ImplicitConversionSequence::Indistinguishable:
9968       // Do nothing.
9969       break;
9970     }
9971   }
9972 
9973   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9974   //       ICSj(F2), or, if not that,
9975   if (HasBetterConversion && !HasWorseConversion)
9976     return true;
9977 
9978   //   -- the context is an initialization by user-defined conversion
9979   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9980   //      from the return type of F1 to the destination type (i.e.,
9981   //      the type of the entity being initialized) is a better
9982   //      conversion sequence than the standard conversion sequence
9983   //      from the return type of F2 to the destination type.
9984   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9985       Cand1.Function && Cand2.Function &&
9986       isa<CXXConversionDecl>(Cand1.Function) &&
9987       isa<CXXConversionDecl>(Cand2.Function)) {
9988     // First check whether we prefer one of the conversion functions over the
9989     // other. This only distinguishes the results in non-standard, extension
9990     // cases such as the conversion from a lambda closure type to a function
9991     // pointer or block.
9992     ImplicitConversionSequence::CompareKind Result =
9993         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9994     if (Result == ImplicitConversionSequence::Indistinguishable)
9995       Result = CompareStandardConversionSequences(S, Loc,
9996                                                   Cand1.FinalConversion,
9997                                                   Cand2.FinalConversion);
9998 
9999     if (Result != ImplicitConversionSequence::Indistinguishable)
10000       return Result == ImplicitConversionSequence::Better;
10001 
10002     // FIXME: Compare kind of reference binding if conversion functions
10003     // convert to a reference type used in direct reference binding, per
10004     // C++14 [over.match.best]p1 section 2 bullet 3.
10005   }
10006 
10007   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10008   // as combined with the resolution to CWG issue 243.
10009   //
10010   // When the context is initialization by constructor ([over.match.ctor] or
10011   // either phase of [over.match.list]), a constructor is preferred over
10012   // a conversion function.
10013   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10014       Cand1.Function && Cand2.Function &&
10015       isa<CXXConstructorDecl>(Cand1.Function) !=
10016           isa<CXXConstructorDecl>(Cand2.Function))
10017     return isa<CXXConstructorDecl>(Cand1.Function);
10018 
10019   //    -- F1 is a non-template function and F2 is a function template
10020   //       specialization, or, if not that,
10021   bool Cand1IsSpecialization = Cand1.Function &&
10022                                Cand1.Function->getPrimaryTemplate();
10023   bool Cand2IsSpecialization = Cand2.Function &&
10024                                Cand2.Function->getPrimaryTemplate();
10025   if (Cand1IsSpecialization != Cand2IsSpecialization)
10026     return Cand2IsSpecialization;
10027 
10028   //   -- F1 and F2 are function template specializations, and the function
10029   //      template for F1 is more specialized than the template for F2
10030   //      according to the partial ordering rules described in 14.5.5.2, or,
10031   //      if not that,
10032   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10033     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10034             Cand1.Function->getPrimaryTemplate(),
10035             Cand2.Function->getPrimaryTemplate(), Loc,
10036             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10037                                                    : TPOC_Call,
10038             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
10039             Cand1.isReversed() ^ Cand2.isReversed()))
10040       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10041   }
10042 
10043   //   -— F1 and F2 are non-template functions with the same
10044   //      parameter-type-lists, and F1 is more constrained than F2 [...],
10045   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10046       sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10047     FunctionDecl *Function1 = Cand1.Function;
10048     FunctionDecl *Function2 = Cand2.Function;
10049     if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10050       Function1 = MF;
10051     if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10052       Function2 = MF;
10053 
10054     const Expr *RC1 = Function1->getTrailingRequiresClause();
10055     const Expr *RC2 = Function2->getTrailingRequiresClause();
10056     if (RC1 && RC2) {
10057       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10058       if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10059                                    AtLeastAsConstrained1) ||
10060           S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10061                                    AtLeastAsConstrained2))
10062         return false;
10063       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10064         return AtLeastAsConstrained1;
10065     } else if (RC1 || RC2) {
10066       return RC1 != nullptr;
10067     }
10068   }
10069 
10070   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10071   //      class B of D, and for all arguments the corresponding parameters of
10072   //      F1 and F2 have the same type.
10073   // FIXME: Implement the "all parameters have the same type" check.
10074   bool Cand1IsInherited =
10075       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10076   bool Cand2IsInherited =
10077       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10078   if (Cand1IsInherited != Cand2IsInherited)
10079     return Cand2IsInherited;
10080   else if (Cand1IsInherited) {
10081     assert(Cand2IsInherited);
10082     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10083     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10084     if (Cand1Class->isDerivedFrom(Cand2Class))
10085       return true;
10086     if (Cand2Class->isDerivedFrom(Cand1Class))
10087       return false;
10088     // Inherited from sibling base classes: still ambiguous.
10089   }
10090 
10091   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10092   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10093   //      with reversed order of parameters and F1 is not
10094   //
10095   // We rank reversed + different operator as worse than just reversed, but
10096   // that comparison can never happen, because we only consider reversing for
10097   // the maximally-rewritten operator (== or <=>).
10098   if (Cand1.RewriteKind != Cand2.RewriteKind)
10099     return Cand1.RewriteKind < Cand2.RewriteKind;
10100 
10101   // Check C++17 tie-breakers for deduction guides.
10102   {
10103     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10104     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10105     if (Guide1 && Guide2) {
10106       //  -- F1 is generated from a deduction-guide and F2 is not
10107       if (Guide1->isImplicit() != Guide2->isImplicit())
10108         return Guide2->isImplicit();
10109 
10110       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10111       if (Guide1->isCopyDeductionCandidate())
10112         return true;
10113     }
10114   }
10115 
10116   // Check for enable_if value-based overload resolution.
10117   if (Cand1.Function && Cand2.Function) {
10118     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10119     if (Cmp != Comparison::Equal)
10120       return Cmp == Comparison::Better;
10121   }
10122 
10123   bool HasPS1 = Cand1.Function != nullptr &&
10124                 functionHasPassObjectSizeParams(Cand1.Function);
10125   bool HasPS2 = Cand2.Function != nullptr &&
10126                 functionHasPassObjectSizeParams(Cand2.Function);
10127   if (HasPS1 != HasPS2 && HasPS1)
10128     return true;
10129 
10130   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10131   if (MV == Comparison::Better)
10132     return true;
10133   if (MV == Comparison::Worse)
10134     return false;
10135 
10136   // If other rules cannot determine which is better, CUDA preference is used
10137   // to determine which is better.
10138   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10139     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10140     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10141            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10142   }
10143 
10144   // General member function overloading is handled above, so this only handles
10145   // constructors with address spaces.
10146   // This only handles address spaces since C++ has no other
10147   // qualifier that can be used with constructors.
10148   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10149   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10150   if (CD1 && CD2) {
10151     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10152     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10153     if (AS1 != AS2) {
10154       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10155         return true;
10156       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10157         return false;
10158     }
10159   }
10160 
10161   return false;
10162 }
10163 
10164 /// Determine whether two declarations are "equivalent" for the purposes of
10165 /// name lookup and overload resolution. This applies when the same internal/no
10166 /// linkage entity is defined by two modules (probably by textually including
10167 /// the same header). In such a case, we don't consider the declarations to
10168 /// declare the same entity, but we also don't want lookups with both
10169 /// declarations visible to be ambiguous in some cases (this happens when using
10170 /// a modularized libstdc++).
10171 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10172                                                   const NamedDecl *B) {
10173   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10174   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10175   if (!VA || !VB)
10176     return false;
10177 
10178   // The declarations must be declaring the same name as an internal linkage
10179   // entity in different modules.
10180   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10181           VB->getDeclContext()->getRedeclContext()) ||
10182       getOwningModule(VA) == getOwningModule(VB) ||
10183       VA->isExternallyVisible() || VB->isExternallyVisible())
10184     return false;
10185 
10186   // Check that the declarations appear to be equivalent.
10187   //
10188   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10189   // For constants and functions, we should check the initializer or body is
10190   // the same. For non-constant variables, we shouldn't allow it at all.
10191   if (Context.hasSameType(VA->getType(), VB->getType()))
10192     return true;
10193 
10194   // Enum constants within unnamed enumerations will have different types, but
10195   // may still be similar enough to be interchangeable for our purposes.
10196   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10197     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10198       // Only handle anonymous enums. If the enumerations were named and
10199       // equivalent, they would have been merged to the same type.
10200       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10201       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10202       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10203           !Context.hasSameType(EnumA->getIntegerType(),
10204                                EnumB->getIntegerType()))
10205         return false;
10206       // Allow this only if the value is the same for both enumerators.
10207       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10208     }
10209   }
10210 
10211   // Nothing else is sufficiently similar.
10212   return false;
10213 }
10214 
10215 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10216     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10217   assert(D && "Unknown declaration");
10218   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10219 
10220   Module *M = getOwningModule(D);
10221   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10222       << !M << (M ? M->getFullModuleName() : "");
10223 
10224   for (auto *E : Equiv) {
10225     Module *M = getOwningModule(E);
10226     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10227         << !M << (M ? M->getFullModuleName() : "");
10228   }
10229 }
10230 
10231 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10232   return FailureKind == ovl_fail_bad_deduction &&
10233          DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10234          static_cast<CNSInfo *>(DeductionFailure.Data)
10235              ->Satisfaction.ContainsErrors;
10236 }
10237 
10238 /// Computes the best viable function (C++ 13.3.3)
10239 /// within an overload candidate set.
10240 ///
10241 /// \param Loc The location of the function name (or operator symbol) for
10242 /// which overload resolution occurs.
10243 ///
10244 /// \param Best If overload resolution was successful or found a deleted
10245 /// function, \p Best points to the candidate function found.
10246 ///
10247 /// \returns The result of overload resolution.
10248 OverloadingResult
10249 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10250                                          iterator &Best) {
10251   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10252   std::transform(begin(), end(), std::back_inserter(Candidates),
10253                  [](OverloadCandidate &Cand) { return &Cand; });
10254 
10255   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10256   // are accepted by both clang and NVCC. However, during a particular
10257   // compilation mode only one call variant is viable. We need to
10258   // exclude non-viable overload candidates from consideration based
10259   // only on their host/device attributes. Specifically, if one
10260   // candidate call is WrongSide and the other is SameSide, we ignore
10261   // the WrongSide candidate.
10262   // We only need to remove wrong-sided candidates here if
10263   // -fgpu-exclude-wrong-side-overloads is off. When
10264   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10265   // uniformly in isBetterOverloadCandidate.
10266   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10267     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10268     bool ContainsSameSideCandidate =
10269         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10270           // Check viable function only.
10271           return Cand->Viable && Cand->Function &&
10272                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10273                      Sema::CFP_SameSide;
10274         });
10275     if (ContainsSameSideCandidate) {
10276       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10277         // Check viable function only to avoid unnecessary data copying/moving.
10278         return Cand->Viable && Cand->Function &&
10279                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10280                    Sema::CFP_WrongSide;
10281       };
10282       llvm::erase_if(Candidates, IsWrongSideCandidate);
10283     }
10284   }
10285 
10286   // Find the best viable function.
10287   Best = end();
10288   for (auto *Cand : Candidates) {
10289     Cand->Best = false;
10290     if (Cand->Viable) {
10291       if (Best == end() ||
10292           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10293         Best = Cand;
10294     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10295       // This candidate has constraint that we were unable to evaluate because
10296       // it referenced an expression that contained an error. Rather than fall
10297       // back onto a potentially unintended candidate (made worse by
10298       // subsuming constraints), treat this as 'no viable candidate'.
10299       Best = end();
10300       return OR_No_Viable_Function;
10301     }
10302   }
10303 
10304   // If we didn't find any viable functions, abort.
10305   if (Best == end())
10306     return OR_No_Viable_Function;
10307 
10308   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10309 
10310   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10311   PendingBest.push_back(&*Best);
10312   Best->Best = true;
10313 
10314   // Make sure that this function is better than every other viable
10315   // function. If not, we have an ambiguity.
10316   while (!PendingBest.empty()) {
10317     auto *Curr = PendingBest.pop_back_val();
10318     for (auto *Cand : Candidates) {
10319       if (Cand->Viable && !Cand->Best &&
10320           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10321         PendingBest.push_back(Cand);
10322         Cand->Best = true;
10323 
10324         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10325                                                      Curr->Function))
10326           EquivalentCands.push_back(Cand->Function);
10327         else
10328           Best = end();
10329       }
10330     }
10331   }
10332 
10333   // If we found more than one best candidate, this is ambiguous.
10334   if (Best == end())
10335     return OR_Ambiguous;
10336 
10337   // Best is the best viable function.
10338   if (Best->Function && Best->Function->isDeleted())
10339     return OR_Deleted;
10340 
10341   if (!EquivalentCands.empty())
10342     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10343                                                     EquivalentCands);
10344 
10345   return OR_Success;
10346 }
10347 
10348 namespace {
10349 
10350 enum OverloadCandidateKind {
10351   oc_function,
10352   oc_method,
10353   oc_reversed_binary_operator,
10354   oc_constructor,
10355   oc_implicit_default_constructor,
10356   oc_implicit_copy_constructor,
10357   oc_implicit_move_constructor,
10358   oc_implicit_copy_assignment,
10359   oc_implicit_move_assignment,
10360   oc_implicit_equality_comparison,
10361   oc_inherited_constructor
10362 };
10363 
10364 enum OverloadCandidateSelect {
10365   ocs_non_template,
10366   ocs_template,
10367   ocs_described_template,
10368 };
10369 
10370 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10371 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10372                           OverloadCandidateRewriteKind CRK,
10373                           std::string &Description) {
10374 
10375   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10376   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10377     isTemplate = true;
10378     Description = S.getTemplateArgumentBindingsText(
10379         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10380   }
10381 
10382   OverloadCandidateSelect Select = [&]() {
10383     if (!Description.empty())
10384       return ocs_described_template;
10385     return isTemplate ? ocs_template : ocs_non_template;
10386   }();
10387 
10388   OverloadCandidateKind Kind = [&]() {
10389     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10390       return oc_implicit_equality_comparison;
10391 
10392     if (CRK & CRK_Reversed)
10393       return oc_reversed_binary_operator;
10394 
10395     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10396       if (!Ctor->isImplicit()) {
10397         if (isa<ConstructorUsingShadowDecl>(Found))
10398           return oc_inherited_constructor;
10399         else
10400           return oc_constructor;
10401       }
10402 
10403       if (Ctor->isDefaultConstructor())
10404         return oc_implicit_default_constructor;
10405 
10406       if (Ctor->isMoveConstructor())
10407         return oc_implicit_move_constructor;
10408 
10409       assert(Ctor->isCopyConstructor() &&
10410              "unexpected sort of implicit constructor");
10411       return oc_implicit_copy_constructor;
10412     }
10413 
10414     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10415       // This actually gets spelled 'candidate function' for now, but
10416       // it doesn't hurt to split it out.
10417       if (!Meth->isImplicit())
10418         return oc_method;
10419 
10420       if (Meth->isMoveAssignmentOperator())
10421         return oc_implicit_move_assignment;
10422 
10423       if (Meth->isCopyAssignmentOperator())
10424         return oc_implicit_copy_assignment;
10425 
10426       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10427       return oc_method;
10428     }
10429 
10430     return oc_function;
10431   }();
10432 
10433   return std::make_pair(Kind, Select);
10434 }
10435 
10436 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10437   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10438   // set.
10439   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10440     S.Diag(FoundDecl->getLocation(),
10441            diag::note_ovl_candidate_inherited_constructor)
10442       << Shadow->getNominatedBaseClass();
10443 }
10444 
10445 } // end anonymous namespace
10446 
10447 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10448                                     const FunctionDecl *FD) {
10449   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10450     bool AlwaysTrue;
10451     if (EnableIf->getCond()->isValueDependent() ||
10452         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10453       return false;
10454     if (!AlwaysTrue)
10455       return false;
10456   }
10457   return true;
10458 }
10459 
10460 /// Returns true if we can take the address of the function.
10461 ///
10462 /// \param Complain - If true, we'll emit a diagnostic
10463 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10464 ///   we in overload resolution?
10465 /// \param Loc - The location of the statement we're complaining about. Ignored
10466 ///   if we're not complaining, or if we're in overload resolution.
10467 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10468                                               bool Complain,
10469                                               bool InOverloadResolution,
10470                                               SourceLocation Loc) {
10471   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10472     if (Complain) {
10473       if (InOverloadResolution)
10474         S.Diag(FD->getBeginLoc(),
10475                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10476       else
10477         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10478     }
10479     return false;
10480   }
10481 
10482   if (FD->getTrailingRequiresClause()) {
10483     ConstraintSatisfaction Satisfaction;
10484     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10485       return false;
10486     if (!Satisfaction.IsSatisfied) {
10487       if (Complain) {
10488         if (InOverloadResolution) {
10489           SmallString<128> TemplateArgString;
10490           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10491             TemplateArgString += " ";
10492             TemplateArgString += S.getTemplateArgumentBindingsText(
10493                 FunTmpl->getTemplateParameters(),
10494                 *FD->getTemplateSpecializationArgs());
10495           }
10496 
10497           S.Diag(FD->getBeginLoc(),
10498                  diag::note_ovl_candidate_unsatisfied_constraints)
10499               << TemplateArgString;
10500         } else
10501           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10502               << FD;
10503         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10504       }
10505       return false;
10506     }
10507   }
10508 
10509   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10510     return P->hasAttr<PassObjectSizeAttr>();
10511   });
10512   if (I == FD->param_end())
10513     return true;
10514 
10515   if (Complain) {
10516     // Add one to ParamNo because it's user-facing
10517     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10518     if (InOverloadResolution)
10519       S.Diag(FD->getLocation(),
10520              diag::note_ovl_candidate_has_pass_object_size_params)
10521           << ParamNo;
10522     else
10523       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10524           << FD << ParamNo;
10525   }
10526   return false;
10527 }
10528 
10529 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10530                                                const FunctionDecl *FD) {
10531   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10532                                            /*InOverloadResolution=*/true,
10533                                            /*Loc=*/SourceLocation());
10534 }
10535 
10536 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10537                                              bool Complain,
10538                                              SourceLocation Loc) {
10539   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10540                                              /*InOverloadResolution=*/false,
10541                                              Loc);
10542 }
10543 
10544 // Don't print candidates other than the one that matches the calling
10545 // convention of the call operator, since that is guaranteed to exist.
10546 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10547   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10548 
10549   if (!ConvD)
10550     return false;
10551   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10552   if (!RD->isLambda())
10553     return false;
10554 
10555   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10556   CallingConv CallOpCC =
10557       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10558   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10559   CallingConv ConvToCC =
10560       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10561 
10562   return ConvToCC != CallOpCC;
10563 }
10564 
10565 // Notes the location of an overload candidate.
10566 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10567                                  OverloadCandidateRewriteKind RewriteKind,
10568                                  QualType DestType, bool TakingAddress) {
10569   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10570     return;
10571   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10572       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10573     return;
10574   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
10575       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
10576     return;
10577   if (shouldSkipNotingLambdaConversionDecl(Fn))
10578     return;
10579 
10580   std::string FnDesc;
10581   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10582       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10583   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10584                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10585                          << Fn << FnDesc;
10586 
10587   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10588   Diag(Fn->getLocation(), PD);
10589   MaybeEmitInheritedConstructorNote(*this, Found);
10590 }
10591 
10592 static void
10593 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10594   // Perhaps the ambiguity was caused by two atomic constraints that are
10595   // 'identical' but not equivalent:
10596   //
10597   // void foo() requires (sizeof(T) > 4) { } // #1
10598   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10599   //
10600   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10601   // #2 to subsume #1, but these constraint are not considered equivalent
10602   // according to the subsumption rules because they are not the same
10603   // source-level construct. This behavior is quite confusing and we should try
10604   // to help the user figure out what happened.
10605 
10606   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10607   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10608   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10609     if (!I->Function)
10610       continue;
10611     SmallVector<const Expr *, 3> AC;
10612     if (auto *Template = I->Function->getPrimaryTemplate())
10613       Template->getAssociatedConstraints(AC);
10614     else
10615       I->Function->getAssociatedConstraints(AC);
10616     if (AC.empty())
10617       continue;
10618     if (FirstCand == nullptr) {
10619       FirstCand = I->Function;
10620       FirstAC = AC;
10621     } else if (SecondCand == nullptr) {
10622       SecondCand = I->Function;
10623       SecondAC = AC;
10624     } else {
10625       // We have more than one pair of constrained functions - this check is
10626       // expensive and we'd rather not try to diagnose it.
10627       return;
10628     }
10629   }
10630   if (!SecondCand)
10631     return;
10632   // The diagnostic can only happen if there are associated constraints on
10633   // both sides (there needs to be some identical atomic constraint).
10634   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10635                                                       SecondCand, SecondAC))
10636     // Just show the user one diagnostic, they'll probably figure it out
10637     // from here.
10638     return;
10639 }
10640 
10641 // Notes the location of all overload candidates designated through
10642 // OverloadedExpr
10643 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10644                                      bool TakingAddress) {
10645   assert(OverloadedExpr->getType() == Context.OverloadTy);
10646 
10647   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10648   OverloadExpr *OvlExpr = Ovl.Expression;
10649 
10650   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10651                             IEnd = OvlExpr->decls_end();
10652        I != IEnd; ++I) {
10653     if (FunctionTemplateDecl *FunTmpl =
10654                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10655       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10656                             TakingAddress);
10657     } else if (FunctionDecl *Fun
10658                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10659       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10660     }
10661   }
10662 }
10663 
10664 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10665 /// "lead" diagnostic; it will be given two arguments, the source and
10666 /// target types of the conversion.
10667 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10668                                  Sema &S,
10669                                  SourceLocation CaretLoc,
10670                                  const PartialDiagnostic &PDiag) const {
10671   S.Diag(CaretLoc, PDiag)
10672     << Ambiguous.getFromType() << Ambiguous.getToType();
10673   unsigned CandsShown = 0;
10674   AmbiguousConversionSequence::const_iterator I, E;
10675   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10676     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10677       break;
10678     ++CandsShown;
10679     S.NoteOverloadCandidate(I->first, I->second);
10680   }
10681   S.Diags.overloadCandidatesShown(CandsShown);
10682   if (I != E)
10683     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10684 }
10685 
10686 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10687                                   unsigned I, bool TakingCandidateAddress) {
10688   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10689   assert(Conv.isBad());
10690   assert(Cand->Function && "for now, candidate must be a function");
10691   FunctionDecl *Fn = Cand->Function;
10692 
10693   // There's a conversion slot for the object argument if this is a
10694   // non-constructor method.  Note that 'I' corresponds the
10695   // conversion-slot index.
10696   bool isObjectArgument = false;
10697   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10698     if (I == 0)
10699       isObjectArgument = true;
10700     else
10701       I--;
10702   }
10703 
10704   std::string FnDesc;
10705   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10706       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10707                                 FnDesc);
10708 
10709   Expr *FromExpr = Conv.Bad.FromExpr;
10710   QualType FromTy = Conv.Bad.getFromType();
10711   QualType ToTy = Conv.Bad.getToType();
10712 
10713   if (FromTy == S.Context.OverloadTy) {
10714     assert(FromExpr && "overload set argument came from implicit argument?");
10715     Expr *E = FromExpr->IgnoreParens();
10716     if (isa<UnaryOperator>(E))
10717       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10718     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10719 
10720     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10721         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10722         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10723         << Name << I + 1;
10724     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10725     return;
10726   }
10727 
10728   // Do some hand-waving analysis to see if the non-viability is due
10729   // to a qualifier mismatch.
10730   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10731   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10732   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10733     CToTy = RT->getPointeeType();
10734   else {
10735     // TODO: detect and diagnose the full richness of const mismatches.
10736     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10737       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10738         CFromTy = FromPT->getPointeeType();
10739         CToTy = ToPT->getPointeeType();
10740       }
10741   }
10742 
10743   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10744       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10745     Qualifiers FromQs = CFromTy.getQualifiers();
10746     Qualifiers ToQs = CToTy.getQualifiers();
10747 
10748     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10749       if (isObjectArgument)
10750         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10751             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10752             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10753             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10754       else
10755         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10756             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10757             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10758             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10759             << ToTy->isReferenceType() << I + 1;
10760       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10761       return;
10762     }
10763 
10764     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10765       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10766           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10767           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10768           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10769           << (unsigned)isObjectArgument << I + 1;
10770       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10771       return;
10772     }
10773 
10774     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10775       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10776           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10777           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10778           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10779           << (unsigned)isObjectArgument << I + 1;
10780       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10781       return;
10782     }
10783 
10784     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10785       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10786           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10787           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10788           << FromQs.hasUnaligned() << I + 1;
10789       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10790       return;
10791     }
10792 
10793     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10794     assert(CVR && "expected qualifiers mismatch");
10795 
10796     if (isObjectArgument) {
10797       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10798           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10799           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10800           << (CVR - 1);
10801     } else {
10802       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10803           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10804           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10805           << (CVR - 1) << I + 1;
10806     }
10807     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10808     return;
10809   }
10810 
10811   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10812       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10813     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10814         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10815         << (unsigned)isObjectArgument << I + 1
10816         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10817         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10818     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10819     return;
10820   }
10821 
10822   // Special diagnostic for failure to convert an initializer list, since
10823   // telling the user that it has type void is not useful.
10824   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10825     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10826         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10827         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10828         << ToTy << (unsigned)isObjectArgument << I + 1
10829         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10830             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10831                 ? 2
10832                 : 0);
10833     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10834     return;
10835   }
10836 
10837   // Diagnose references or pointers to incomplete types differently,
10838   // since it's far from impossible that the incompleteness triggered
10839   // the failure.
10840   QualType TempFromTy = FromTy.getNonReferenceType();
10841   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10842     TempFromTy = PTy->getPointeeType();
10843   if (TempFromTy->isIncompleteType()) {
10844     // Emit the generic diagnostic and, optionally, add the hints to it.
10845     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10846         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10847         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10848         << ToTy << (unsigned)isObjectArgument << I + 1
10849         << (unsigned)(Cand->Fix.Kind);
10850 
10851     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10852     return;
10853   }
10854 
10855   // Diagnose base -> derived pointer conversions.
10856   unsigned BaseToDerivedConversion = 0;
10857   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10858     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10859       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10860                                                FromPtrTy->getPointeeType()) &&
10861           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10862           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10863           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10864                           FromPtrTy->getPointeeType()))
10865         BaseToDerivedConversion = 1;
10866     }
10867   } else if (const ObjCObjectPointerType *FromPtrTy
10868                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10869     if (const ObjCObjectPointerType *ToPtrTy
10870                                         = ToTy->getAs<ObjCObjectPointerType>())
10871       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10872         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10873           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10874                                                 FromPtrTy->getPointeeType()) &&
10875               FromIface->isSuperClassOf(ToIface))
10876             BaseToDerivedConversion = 2;
10877   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10878     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10879         !FromTy->isIncompleteType() &&
10880         !ToRefTy->getPointeeType()->isIncompleteType() &&
10881         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10882       BaseToDerivedConversion = 3;
10883     }
10884   }
10885 
10886   if (BaseToDerivedConversion) {
10887     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10888         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10889         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10890         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10891     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10892     return;
10893   }
10894 
10895   if (isa<ObjCObjectPointerType>(CFromTy) &&
10896       isa<PointerType>(CToTy)) {
10897       Qualifiers FromQs = CFromTy.getQualifiers();
10898       Qualifiers ToQs = CToTy.getQualifiers();
10899       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10900         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10901             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10902             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10903             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10904         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10905         return;
10906       }
10907   }
10908 
10909   if (TakingCandidateAddress &&
10910       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10911     return;
10912 
10913   // Emit the generic diagnostic and, optionally, add the hints to it.
10914   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10915   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10916         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10917         << ToTy << (unsigned)isObjectArgument << I + 1
10918         << (unsigned)(Cand->Fix.Kind);
10919 
10920   // Check that location of Fn is not in system header.
10921   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
10922     // If we can fix the conversion, suggest the FixIts.
10923     for (const FixItHint &HI : Cand->Fix.Hints)
10924         FDiag << HI;
10925   }
10926 
10927   S.Diag(Fn->getLocation(), FDiag);
10928 
10929   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10930 }
10931 
10932 /// Additional arity mismatch diagnosis specific to a function overload
10933 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10934 /// over a candidate in any candidate set.
10935 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10936                                unsigned NumArgs) {
10937   FunctionDecl *Fn = Cand->Function;
10938   unsigned MinParams = Fn->getMinRequiredArguments();
10939 
10940   // With invalid overloaded operators, it's possible that we think we
10941   // have an arity mismatch when in fact it looks like we have the
10942   // right number of arguments, because only overloaded operators have
10943   // the weird behavior of overloading member and non-member functions.
10944   // Just don't report anything.
10945   if (Fn->isInvalidDecl() &&
10946       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10947     return true;
10948 
10949   if (NumArgs < MinParams) {
10950     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10951            (Cand->FailureKind == ovl_fail_bad_deduction &&
10952             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10953   } else {
10954     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10955            (Cand->FailureKind == ovl_fail_bad_deduction &&
10956             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10957   }
10958 
10959   return false;
10960 }
10961 
10962 /// General arity mismatch diagnosis over a candidate in a candidate set.
10963 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10964                                   unsigned NumFormalArgs) {
10965   assert(isa<FunctionDecl>(D) &&
10966       "The templated declaration should at least be a function"
10967       " when diagnosing bad template argument deduction due to too many"
10968       " or too few arguments");
10969 
10970   FunctionDecl *Fn = cast<FunctionDecl>(D);
10971 
10972   // TODO: treat calls to a missing default constructor as a special case
10973   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10974   unsigned MinParams = Fn->getMinRequiredArguments();
10975 
10976   // at least / at most / exactly
10977   unsigned mode, modeCount;
10978   if (NumFormalArgs < MinParams) {
10979     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10980         FnTy->isTemplateVariadic())
10981       mode = 0; // "at least"
10982     else
10983       mode = 2; // "exactly"
10984     modeCount = MinParams;
10985   } else {
10986     if (MinParams != FnTy->getNumParams())
10987       mode = 1; // "at most"
10988     else
10989       mode = 2; // "exactly"
10990     modeCount = FnTy->getNumParams();
10991   }
10992 
10993   std::string Description;
10994   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10995       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10996 
10997   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10998     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10999         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11000         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
11001   else
11002     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11003         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11004         << Description << mode << modeCount << NumFormalArgs;
11005 
11006   MaybeEmitInheritedConstructorNote(S, Found);
11007 }
11008 
11009 /// Arity mismatch diagnosis specific to a function overload candidate.
11010 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11011                                   unsigned NumFormalArgs) {
11012   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11013     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11014 }
11015 
11016 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11017   if (TemplateDecl *TD = Templated->getDescribedTemplate())
11018     return TD;
11019   llvm_unreachable("Unsupported: Getting the described template declaration"
11020                    " for bad deduction diagnosis");
11021 }
11022 
11023 /// Diagnose a failed template-argument deduction.
11024 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11025                                  DeductionFailureInfo &DeductionFailure,
11026                                  unsigned NumArgs,
11027                                  bool TakingCandidateAddress) {
11028   TemplateParameter Param = DeductionFailure.getTemplateParameter();
11029   NamedDecl *ParamD;
11030   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11031   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11032   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11033   switch (DeductionFailure.Result) {
11034   case Sema::TDK_Success:
11035     llvm_unreachable("TDK_success while diagnosing bad deduction");
11036 
11037   case Sema::TDK_Incomplete: {
11038     assert(ParamD && "no parameter found for incomplete deduction result");
11039     S.Diag(Templated->getLocation(),
11040            diag::note_ovl_candidate_incomplete_deduction)
11041         << ParamD->getDeclName();
11042     MaybeEmitInheritedConstructorNote(S, Found);
11043     return;
11044   }
11045 
11046   case Sema::TDK_IncompletePack: {
11047     assert(ParamD && "no parameter found for incomplete deduction result");
11048     S.Diag(Templated->getLocation(),
11049            diag::note_ovl_candidate_incomplete_deduction_pack)
11050         << ParamD->getDeclName()
11051         << (DeductionFailure.getFirstArg()->pack_size() + 1)
11052         << *DeductionFailure.getFirstArg();
11053     MaybeEmitInheritedConstructorNote(S, Found);
11054     return;
11055   }
11056 
11057   case Sema::TDK_Underqualified: {
11058     assert(ParamD && "no parameter found for bad qualifiers deduction result");
11059     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11060 
11061     QualType Param = DeductionFailure.getFirstArg()->getAsType();
11062 
11063     // Param will have been canonicalized, but it should just be a
11064     // qualified version of ParamD, so move the qualifiers to that.
11065     QualifierCollector Qs;
11066     Qs.strip(Param);
11067     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11068     assert(S.Context.hasSameType(Param, NonCanonParam));
11069 
11070     // Arg has also been canonicalized, but there's nothing we can do
11071     // about that.  It also doesn't matter as much, because it won't
11072     // have any template parameters in it (because deduction isn't
11073     // done on dependent types).
11074     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11075 
11076     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11077         << ParamD->getDeclName() << Arg << NonCanonParam;
11078     MaybeEmitInheritedConstructorNote(S, Found);
11079     return;
11080   }
11081 
11082   case Sema::TDK_Inconsistent: {
11083     assert(ParamD && "no parameter found for inconsistent deduction result");
11084     int which = 0;
11085     if (isa<TemplateTypeParmDecl>(ParamD))
11086       which = 0;
11087     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11088       // Deduction might have failed because we deduced arguments of two
11089       // different types for a non-type template parameter.
11090       // FIXME: Use a different TDK value for this.
11091       QualType T1 =
11092           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11093       QualType T2 =
11094           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11095       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11096         S.Diag(Templated->getLocation(),
11097                diag::note_ovl_candidate_inconsistent_deduction_types)
11098           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11099           << *DeductionFailure.getSecondArg() << T2;
11100         MaybeEmitInheritedConstructorNote(S, Found);
11101         return;
11102       }
11103 
11104       which = 1;
11105     } else {
11106       which = 2;
11107     }
11108 
11109     // Tweak the diagnostic if the problem is that we deduced packs of
11110     // different arities. We'll print the actual packs anyway in case that
11111     // includes additional useful information.
11112     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11113         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11114         DeductionFailure.getFirstArg()->pack_size() !=
11115             DeductionFailure.getSecondArg()->pack_size()) {
11116       which = 3;
11117     }
11118 
11119     S.Diag(Templated->getLocation(),
11120            diag::note_ovl_candidate_inconsistent_deduction)
11121         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11122         << *DeductionFailure.getSecondArg();
11123     MaybeEmitInheritedConstructorNote(S, Found);
11124     return;
11125   }
11126 
11127   case Sema::TDK_InvalidExplicitArguments:
11128     assert(ParamD && "no parameter found for invalid explicit arguments");
11129     if (ParamD->getDeclName())
11130       S.Diag(Templated->getLocation(),
11131              diag::note_ovl_candidate_explicit_arg_mismatch_named)
11132           << ParamD->getDeclName();
11133     else {
11134       int index = 0;
11135       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11136         index = TTP->getIndex();
11137       else if (NonTypeTemplateParmDecl *NTTP
11138                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11139         index = NTTP->getIndex();
11140       else
11141         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11142       S.Diag(Templated->getLocation(),
11143              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11144           << (index + 1);
11145     }
11146     MaybeEmitInheritedConstructorNote(S, Found);
11147     return;
11148 
11149   case Sema::TDK_ConstraintsNotSatisfied: {
11150     // Format the template argument list into the argument string.
11151     SmallString<128> TemplateArgString;
11152     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11153     TemplateArgString = " ";
11154     TemplateArgString += S.getTemplateArgumentBindingsText(
11155         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11156     if (TemplateArgString.size() == 1)
11157       TemplateArgString.clear();
11158     S.Diag(Templated->getLocation(),
11159            diag::note_ovl_candidate_unsatisfied_constraints)
11160         << TemplateArgString;
11161 
11162     S.DiagnoseUnsatisfiedConstraint(
11163         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11164     return;
11165   }
11166   case Sema::TDK_TooManyArguments:
11167   case Sema::TDK_TooFewArguments:
11168     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11169     return;
11170 
11171   case Sema::TDK_InstantiationDepth:
11172     S.Diag(Templated->getLocation(),
11173            diag::note_ovl_candidate_instantiation_depth);
11174     MaybeEmitInheritedConstructorNote(S, Found);
11175     return;
11176 
11177   case Sema::TDK_SubstitutionFailure: {
11178     // Format the template argument list into the argument string.
11179     SmallString<128> TemplateArgString;
11180     if (TemplateArgumentList *Args =
11181             DeductionFailure.getTemplateArgumentList()) {
11182       TemplateArgString = " ";
11183       TemplateArgString += S.getTemplateArgumentBindingsText(
11184           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11185       if (TemplateArgString.size() == 1)
11186         TemplateArgString.clear();
11187     }
11188 
11189     // If this candidate was disabled by enable_if, say so.
11190     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11191     if (PDiag && PDiag->second.getDiagID() ==
11192           diag::err_typename_nested_not_found_enable_if) {
11193       // FIXME: Use the source range of the condition, and the fully-qualified
11194       //        name of the enable_if template. These are both present in PDiag.
11195       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11196         << "'enable_if'" << TemplateArgString;
11197       return;
11198     }
11199 
11200     // We found a specific requirement that disabled the enable_if.
11201     if (PDiag && PDiag->second.getDiagID() ==
11202         diag::err_typename_nested_not_found_requirement) {
11203       S.Diag(Templated->getLocation(),
11204              diag::note_ovl_candidate_disabled_by_requirement)
11205         << PDiag->second.getStringArg(0) << TemplateArgString;
11206       return;
11207     }
11208 
11209     // Format the SFINAE diagnostic into the argument string.
11210     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11211     //        formatted message in another diagnostic.
11212     SmallString<128> SFINAEArgString;
11213     SourceRange R;
11214     if (PDiag) {
11215       SFINAEArgString = ": ";
11216       R = SourceRange(PDiag->first, PDiag->first);
11217       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11218     }
11219 
11220     S.Diag(Templated->getLocation(),
11221            diag::note_ovl_candidate_substitution_failure)
11222         << TemplateArgString << SFINAEArgString << R;
11223     MaybeEmitInheritedConstructorNote(S, Found);
11224     return;
11225   }
11226 
11227   case Sema::TDK_DeducedMismatch:
11228   case Sema::TDK_DeducedMismatchNested: {
11229     // Format the template argument list into the argument string.
11230     SmallString<128> TemplateArgString;
11231     if (TemplateArgumentList *Args =
11232             DeductionFailure.getTemplateArgumentList()) {
11233       TemplateArgString = " ";
11234       TemplateArgString += S.getTemplateArgumentBindingsText(
11235           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11236       if (TemplateArgString.size() == 1)
11237         TemplateArgString.clear();
11238     }
11239 
11240     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11241         << (*DeductionFailure.getCallArgIndex() + 1)
11242         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11243         << TemplateArgString
11244         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11245     break;
11246   }
11247 
11248   case Sema::TDK_NonDeducedMismatch: {
11249     // FIXME: Provide a source location to indicate what we couldn't match.
11250     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11251     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11252     if (FirstTA.getKind() == TemplateArgument::Template &&
11253         SecondTA.getKind() == TemplateArgument::Template) {
11254       TemplateName FirstTN = FirstTA.getAsTemplate();
11255       TemplateName SecondTN = SecondTA.getAsTemplate();
11256       if (FirstTN.getKind() == TemplateName::Template &&
11257           SecondTN.getKind() == TemplateName::Template) {
11258         if (FirstTN.getAsTemplateDecl()->getName() ==
11259             SecondTN.getAsTemplateDecl()->getName()) {
11260           // FIXME: This fixes a bad diagnostic where both templates are named
11261           // the same.  This particular case is a bit difficult since:
11262           // 1) It is passed as a string to the diagnostic printer.
11263           // 2) The diagnostic printer only attempts to find a better
11264           //    name for types, not decls.
11265           // Ideally, this should folded into the diagnostic printer.
11266           S.Diag(Templated->getLocation(),
11267                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11268               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11269           return;
11270         }
11271       }
11272     }
11273 
11274     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11275         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11276       return;
11277 
11278     // FIXME: For generic lambda parameters, check if the function is a lambda
11279     // call operator, and if so, emit a prettier and more informative
11280     // diagnostic that mentions 'auto' and lambda in addition to
11281     // (or instead of?) the canonical template type parameters.
11282     S.Diag(Templated->getLocation(),
11283            diag::note_ovl_candidate_non_deduced_mismatch)
11284         << FirstTA << SecondTA;
11285     return;
11286   }
11287   // TODO: diagnose these individually, then kill off
11288   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11289   case Sema::TDK_MiscellaneousDeductionFailure:
11290     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11291     MaybeEmitInheritedConstructorNote(S, Found);
11292     return;
11293   case Sema::TDK_CUDATargetMismatch:
11294     S.Diag(Templated->getLocation(),
11295            diag::note_cuda_ovl_candidate_target_mismatch);
11296     return;
11297   }
11298 }
11299 
11300 /// Diagnose a failed template-argument deduction, for function calls.
11301 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11302                                  unsigned NumArgs,
11303                                  bool TakingCandidateAddress) {
11304   unsigned TDK = Cand->DeductionFailure.Result;
11305   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11306     if (CheckArityMismatch(S, Cand, NumArgs))
11307       return;
11308   }
11309   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11310                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11311 }
11312 
11313 /// CUDA: diagnose an invalid call across targets.
11314 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11315   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11316   FunctionDecl *Callee = Cand->Function;
11317 
11318   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11319                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11320 
11321   std::string FnDesc;
11322   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11323       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11324                                 Cand->getRewriteKind(), FnDesc);
11325 
11326   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11327       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11328       << FnDesc /* Ignored */
11329       << CalleeTarget << CallerTarget;
11330 
11331   // This could be an implicit constructor for which we could not infer the
11332   // target due to a collsion. Diagnose that case.
11333   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11334   if (Meth != nullptr && Meth->isImplicit()) {
11335     CXXRecordDecl *ParentClass = Meth->getParent();
11336     Sema::CXXSpecialMember CSM;
11337 
11338     switch (FnKindPair.first) {
11339     default:
11340       return;
11341     case oc_implicit_default_constructor:
11342       CSM = Sema::CXXDefaultConstructor;
11343       break;
11344     case oc_implicit_copy_constructor:
11345       CSM = Sema::CXXCopyConstructor;
11346       break;
11347     case oc_implicit_move_constructor:
11348       CSM = Sema::CXXMoveConstructor;
11349       break;
11350     case oc_implicit_copy_assignment:
11351       CSM = Sema::CXXCopyAssignment;
11352       break;
11353     case oc_implicit_move_assignment:
11354       CSM = Sema::CXXMoveAssignment;
11355       break;
11356     };
11357 
11358     bool ConstRHS = false;
11359     if (Meth->getNumParams()) {
11360       if (const ReferenceType *RT =
11361               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11362         ConstRHS = RT->getPointeeType().isConstQualified();
11363       }
11364     }
11365 
11366     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11367                                               /* ConstRHS */ ConstRHS,
11368                                               /* Diagnose */ true);
11369   }
11370 }
11371 
11372 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11373   FunctionDecl *Callee = Cand->Function;
11374   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11375 
11376   S.Diag(Callee->getLocation(),
11377          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11378       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11379 }
11380 
11381 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11382   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11383   assert(ES.isExplicit() && "not an explicit candidate");
11384 
11385   unsigned Kind;
11386   switch (Cand->Function->getDeclKind()) {
11387   case Decl::Kind::CXXConstructor:
11388     Kind = 0;
11389     break;
11390   case Decl::Kind::CXXConversion:
11391     Kind = 1;
11392     break;
11393   case Decl::Kind::CXXDeductionGuide:
11394     Kind = Cand->Function->isImplicit() ? 0 : 2;
11395     break;
11396   default:
11397     llvm_unreachable("invalid Decl");
11398   }
11399 
11400   // Note the location of the first (in-class) declaration; a redeclaration
11401   // (particularly an out-of-class definition) will typically lack the
11402   // 'explicit' specifier.
11403   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11404   FunctionDecl *First = Cand->Function->getFirstDecl();
11405   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11406     First = Pattern->getFirstDecl();
11407 
11408   S.Diag(First->getLocation(),
11409          diag::note_ovl_candidate_explicit)
11410       << Kind << (ES.getExpr() ? 1 : 0)
11411       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11412 }
11413 
11414 /// Generates a 'note' diagnostic for an overload candidate.  We've
11415 /// already generated a primary error at the call site.
11416 ///
11417 /// It really does need to be a single diagnostic with its caret
11418 /// pointed at the candidate declaration.  Yes, this creates some
11419 /// major challenges of technical writing.  Yes, this makes pointing
11420 /// out problems with specific arguments quite awkward.  It's still
11421 /// better than generating twenty screens of text for every failed
11422 /// overload.
11423 ///
11424 /// It would be great to be able to express per-candidate problems
11425 /// more richly for those diagnostic clients that cared, but we'd
11426 /// still have to be just as careful with the default diagnostics.
11427 /// \param CtorDestAS Addr space of object being constructed (for ctor
11428 /// candidates only).
11429 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11430                                   unsigned NumArgs,
11431                                   bool TakingCandidateAddress,
11432                                   LangAS CtorDestAS = LangAS::Default) {
11433   FunctionDecl *Fn = Cand->Function;
11434   if (shouldSkipNotingLambdaConversionDecl(Fn))
11435     return;
11436 
11437   // There is no physical candidate declaration to point to for OpenCL builtins.
11438   // Except for failed conversions, the notes are identical for each candidate,
11439   // so do not generate such notes.
11440   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11441       Cand->FailureKind != ovl_fail_bad_conversion)
11442     return;
11443 
11444   // Note deleted candidates, but only if they're viable.
11445   if (Cand->Viable) {
11446     if (Fn->isDeleted()) {
11447       std::string FnDesc;
11448       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11449           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11450                                     Cand->getRewriteKind(), FnDesc);
11451 
11452       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11453           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11454           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11455       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11456       return;
11457     }
11458 
11459     // We don't really have anything else to say about viable candidates.
11460     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11461     return;
11462   }
11463 
11464   switch (Cand->FailureKind) {
11465   case ovl_fail_too_many_arguments:
11466   case ovl_fail_too_few_arguments:
11467     return DiagnoseArityMismatch(S, Cand, NumArgs);
11468 
11469   case ovl_fail_bad_deduction:
11470     return DiagnoseBadDeduction(S, Cand, NumArgs,
11471                                 TakingCandidateAddress);
11472 
11473   case ovl_fail_illegal_constructor: {
11474     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11475       << (Fn->getPrimaryTemplate() ? 1 : 0);
11476     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11477     return;
11478   }
11479 
11480   case ovl_fail_object_addrspace_mismatch: {
11481     Qualifiers QualsForPrinting;
11482     QualsForPrinting.setAddressSpace(CtorDestAS);
11483     S.Diag(Fn->getLocation(),
11484            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11485         << QualsForPrinting;
11486     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11487     return;
11488   }
11489 
11490   case ovl_fail_trivial_conversion:
11491   case ovl_fail_bad_final_conversion:
11492   case ovl_fail_final_conversion_not_exact:
11493     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11494 
11495   case ovl_fail_bad_conversion: {
11496     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11497     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11498       if (Cand->Conversions[I].isBad())
11499         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11500 
11501     // FIXME: this currently happens when we're called from SemaInit
11502     // when user-conversion overload fails.  Figure out how to handle
11503     // those conditions and diagnose them well.
11504     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11505   }
11506 
11507   case ovl_fail_bad_target:
11508     return DiagnoseBadTarget(S, Cand);
11509 
11510   case ovl_fail_enable_if:
11511     return DiagnoseFailedEnableIfAttr(S, Cand);
11512 
11513   case ovl_fail_explicit:
11514     return DiagnoseFailedExplicitSpec(S, Cand);
11515 
11516   case ovl_fail_inhctor_slice:
11517     // It's generally not interesting to note copy/move constructors here.
11518     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11519       return;
11520     S.Diag(Fn->getLocation(),
11521            diag::note_ovl_candidate_inherited_constructor_slice)
11522       << (Fn->getPrimaryTemplate() ? 1 : 0)
11523       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11524     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11525     return;
11526 
11527   case ovl_fail_addr_not_available: {
11528     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11529     (void)Available;
11530     assert(!Available);
11531     break;
11532   }
11533   case ovl_non_default_multiversion_function:
11534     // Do nothing, these should simply be ignored.
11535     break;
11536 
11537   case ovl_fail_constraints_not_satisfied: {
11538     std::string FnDesc;
11539     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11540         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11541                                   Cand->getRewriteKind(), FnDesc);
11542 
11543     S.Diag(Fn->getLocation(),
11544            diag::note_ovl_candidate_constraints_not_satisfied)
11545         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11546         << FnDesc /* Ignored */;
11547     ConstraintSatisfaction Satisfaction;
11548     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11549       break;
11550     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11551   }
11552   }
11553 }
11554 
11555 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11556   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11557     return;
11558 
11559   // Desugar the type of the surrogate down to a function type,
11560   // retaining as many typedefs as possible while still showing
11561   // the function type (and, therefore, its parameter types).
11562   QualType FnType = Cand->Surrogate->getConversionType();
11563   bool isLValueReference = false;
11564   bool isRValueReference = false;
11565   bool isPointer = false;
11566   if (const LValueReferenceType *FnTypeRef =
11567         FnType->getAs<LValueReferenceType>()) {
11568     FnType = FnTypeRef->getPointeeType();
11569     isLValueReference = true;
11570   } else if (const RValueReferenceType *FnTypeRef =
11571                FnType->getAs<RValueReferenceType>()) {
11572     FnType = FnTypeRef->getPointeeType();
11573     isRValueReference = true;
11574   }
11575   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11576     FnType = FnTypePtr->getPointeeType();
11577     isPointer = true;
11578   }
11579   // Desugar down to a function type.
11580   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11581   // Reconstruct the pointer/reference as appropriate.
11582   if (isPointer) FnType = S.Context.getPointerType(FnType);
11583   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11584   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11585 
11586   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11587     << FnType;
11588 }
11589 
11590 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11591                                          SourceLocation OpLoc,
11592                                          OverloadCandidate *Cand) {
11593   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11594   std::string TypeStr("operator");
11595   TypeStr += Opc;
11596   TypeStr += "(";
11597   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11598   if (Cand->Conversions.size() == 1) {
11599     TypeStr += ")";
11600     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11601   } else {
11602     TypeStr += ", ";
11603     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11604     TypeStr += ")";
11605     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11606   }
11607 }
11608 
11609 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11610                                          OverloadCandidate *Cand) {
11611   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11612     if (ICS.isBad()) break; // all meaningless after first invalid
11613     if (!ICS.isAmbiguous()) continue;
11614 
11615     ICS.DiagnoseAmbiguousConversion(
11616         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11617   }
11618 }
11619 
11620 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11621   if (Cand->Function)
11622     return Cand->Function->getLocation();
11623   if (Cand->IsSurrogate)
11624     return Cand->Surrogate->getLocation();
11625   return SourceLocation();
11626 }
11627 
11628 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11629   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11630   case Sema::TDK_Success:
11631   case Sema::TDK_NonDependentConversionFailure:
11632   case Sema::TDK_AlreadyDiagnosed:
11633     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11634 
11635   case Sema::TDK_Invalid:
11636   case Sema::TDK_Incomplete:
11637   case Sema::TDK_IncompletePack:
11638     return 1;
11639 
11640   case Sema::TDK_Underqualified:
11641   case Sema::TDK_Inconsistent:
11642     return 2;
11643 
11644   case Sema::TDK_SubstitutionFailure:
11645   case Sema::TDK_DeducedMismatch:
11646   case Sema::TDK_ConstraintsNotSatisfied:
11647   case Sema::TDK_DeducedMismatchNested:
11648   case Sema::TDK_NonDeducedMismatch:
11649   case Sema::TDK_MiscellaneousDeductionFailure:
11650   case Sema::TDK_CUDATargetMismatch:
11651     return 3;
11652 
11653   case Sema::TDK_InstantiationDepth:
11654     return 4;
11655 
11656   case Sema::TDK_InvalidExplicitArguments:
11657     return 5;
11658 
11659   case Sema::TDK_TooManyArguments:
11660   case Sema::TDK_TooFewArguments:
11661     return 6;
11662   }
11663   llvm_unreachable("Unhandled deduction result");
11664 }
11665 
11666 namespace {
11667 struct CompareOverloadCandidatesForDisplay {
11668   Sema &S;
11669   SourceLocation Loc;
11670   size_t NumArgs;
11671   OverloadCandidateSet::CandidateSetKind CSK;
11672 
11673   CompareOverloadCandidatesForDisplay(
11674       Sema &S, SourceLocation Loc, size_t NArgs,
11675       OverloadCandidateSet::CandidateSetKind CSK)
11676       : S(S), NumArgs(NArgs), CSK(CSK) {}
11677 
11678   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11679     // If there are too many or too few arguments, that's the high-order bit we
11680     // want to sort by, even if the immediate failure kind was something else.
11681     if (C->FailureKind == ovl_fail_too_many_arguments ||
11682         C->FailureKind == ovl_fail_too_few_arguments)
11683       return static_cast<OverloadFailureKind>(C->FailureKind);
11684 
11685     if (C->Function) {
11686       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11687         return ovl_fail_too_many_arguments;
11688       if (NumArgs < C->Function->getMinRequiredArguments())
11689         return ovl_fail_too_few_arguments;
11690     }
11691 
11692     return static_cast<OverloadFailureKind>(C->FailureKind);
11693   }
11694 
11695   bool operator()(const OverloadCandidate *L,
11696                   const OverloadCandidate *R) {
11697     // Fast-path this check.
11698     if (L == R) return false;
11699 
11700     // Order first by viability.
11701     if (L->Viable) {
11702       if (!R->Viable) return true;
11703 
11704       // TODO: introduce a tri-valued comparison for overload
11705       // candidates.  Would be more worthwhile if we had a sort
11706       // that could exploit it.
11707       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11708         return true;
11709       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11710         return false;
11711     } else if (R->Viable)
11712       return false;
11713 
11714     assert(L->Viable == R->Viable);
11715 
11716     // Criteria by which we can sort non-viable candidates:
11717     if (!L->Viable) {
11718       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11719       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11720 
11721       // 1. Arity mismatches come after other candidates.
11722       if (LFailureKind == ovl_fail_too_many_arguments ||
11723           LFailureKind == ovl_fail_too_few_arguments) {
11724         if (RFailureKind == ovl_fail_too_many_arguments ||
11725             RFailureKind == ovl_fail_too_few_arguments) {
11726           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11727           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11728           if (LDist == RDist) {
11729             if (LFailureKind == RFailureKind)
11730               // Sort non-surrogates before surrogates.
11731               return !L->IsSurrogate && R->IsSurrogate;
11732             // Sort candidates requiring fewer parameters than there were
11733             // arguments given after candidates requiring more parameters
11734             // than there were arguments given.
11735             return LFailureKind == ovl_fail_too_many_arguments;
11736           }
11737           return LDist < RDist;
11738         }
11739         return false;
11740       }
11741       if (RFailureKind == ovl_fail_too_many_arguments ||
11742           RFailureKind == ovl_fail_too_few_arguments)
11743         return true;
11744 
11745       // 2. Bad conversions come first and are ordered by the number
11746       // of bad conversions and quality of good conversions.
11747       if (LFailureKind == ovl_fail_bad_conversion) {
11748         if (RFailureKind != ovl_fail_bad_conversion)
11749           return true;
11750 
11751         // The conversion that can be fixed with a smaller number of changes,
11752         // comes first.
11753         unsigned numLFixes = L->Fix.NumConversionsFixed;
11754         unsigned numRFixes = R->Fix.NumConversionsFixed;
11755         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11756         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11757         if (numLFixes != numRFixes) {
11758           return numLFixes < numRFixes;
11759         }
11760 
11761         // If there's any ordering between the defined conversions...
11762         // FIXME: this might not be transitive.
11763         assert(L->Conversions.size() == R->Conversions.size());
11764 
11765         int leftBetter = 0;
11766         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11767         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11768           switch (CompareImplicitConversionSequences(S, Loc,
11769                                                      L->Conversions[I],
11770                                                      R->Conversions[I])) {
11771           case ImplicitConversionSequence::Better:
11772             leftBetter++;
11773             break;
11774 
11775           case ImplicitConversionSequence::Worse:
11776             leftBetter--;
11777             break;
11778 
11779           case ImplicitConversionSequence::Indistinguishable:
11780             break;
11781           }
11782         }
11783         if (leftBetter > 0) return true;
11784         if (leftBetter < 0) return false;
11785 
11786       } else if (RFailureKind == ovl_fail_bad_conversion)
11787         return false;
11788 
11789       if (LFailureKind == ovl_fail_bad_deduction) {
11790         if (RFailureKind != ovl_fail_bad_deduction)
11791           return true;
11792 
11793         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11794           return RankDeductionFailure(L->DeductionFailure)
11795                < RankDeductionFailure(R->DeductionFailure);
11796       } else if (RFailureKind == ovl_fail_bad_deduction)
11797         return false;
11798 
11799       // TODO: others?
11800     }
11801 
11802     // Sort everything else by location.
11803     SourceLocation LLoc = GetLocationForCandidate(L);
11804     SourceLocation RLoc = GetLocationForCandidate(R);
11805 
11806     // Put candidates without locations (e.g. builtins) at the end.
11807     if (LLoc.isInvalid()) return false;
11808     if (RLoc.isInvalid()) return true;
11809 
11810     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11811   }
11812 };
11813 }
11814 
11815 /// CompleteNonViableCandidate - Normally, overload resolution only
11816 /// computes up to the first bad conversion. Produces the FixIt set if
11817 /// possible.
11818 static void
11819 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11820                            ArrayRef<Expr *> Args,
11821                            OverloadCandidateSet::CandidateSetKind CSK) {
11822   assert(!Cand->Viable);
11823 
11824   // Don't do anything on failures other than bad conversion.
11825   if (Cand->FailureKind != ovl_fail_bad_conversion)
11826     return;
11827 
11828   // We only want the FixIts if all the arguments can be corrected.
11829   bool Unfixable = false;
11830   // Use a implicit copy initialization to check conversion fixes.
11831   Cand->Fix.setConversionChecker(TryCopyInitialization);
11832 
11833   // Attempt to fix the bad conversion.
11834   unsigned ConvCount = Cand->Conversions.size();
11835   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11836        ++ConvIdx) {
11837     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11838     if (Cand->Conversions[ConvIdx].isInitialized() &&
11839         Cand->Conversions[ConvIdx].isBad()) {
11840       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11841       break;
11842     }
11843   }
11844 
11845   // FIXME: this should probably be preserved from the overload
11846   // operation somehow.
11847   bool SuppressUserConversions = false;
11848 
11849   unsigned ConvIdx = 0;
11850   unsigned ArgIdx = 0;
11851   ArrayRef<QualType> ParamTypes;
11852   bool Reversed = Cand->isReversed();
11853 
11854   if (Cand->IsSurrogate) {
11855     QualType ConvType
11856       = Cand->Surrogate->getConversionType().getNonReferenceType();
11857     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11858       ConvType = ConvPtrType->getPointeeType();
11859     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11860     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11861     ConvIdx = 1;
11862   } else if (Cand->Function) {
11863     ParamTypes =
11864         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11865     if (isa<CXXMethodDecl>(Cand->Function) &&
11866         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11867       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11868       ConvIdx = 1;
11869       if (CSK == OverloadCandidateSet::CSK_Operator &&
11870           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11871           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11872               OO_Subscript)
11873         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11874         ArgIdx = 1;
11875     }
11876   } else {
11877     // Builtin operator.
11878     assert(ConvCount <= 3);
11879     ParamTypes = Cand->BuiltinParamTypes;
11880   }
11881 
11882   // Fill in the rest of the conversions.
11883   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11884        ConvIdx != ConvCount;
11885        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11886     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11887     if (Cand->Conversions[ConvIdx].isInitialized()) {
11888       // We've already checked this conversion.
11889     } else if (ParamIdx < ParamTypes.size()) {
11890       if (ParamTypes[ParamIdx]->isDependentType())
11891         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11892             Args[ArgIdx]->getType());
11893       else {
11894         Cand->Conversions[ConvIdx] =
11895             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11896                                   SuppressUserConversions,
11897                                   /*InOverloadResolution=*/true,
11898                                   /*AllowObjCWritebackConversion=*/
11899                                   S.getLangOpts().ObjCAutoRefCount);
11900         // Store the FixIt in the candidate if it exists.
11901         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11902           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11903       }
11904     } else
11905       Cand->Conversions[ConvIdx].setEllipsis();
11906   }
11907 }
11908 
11909 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11910     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11911     SourceLocation OpLoc,
11912     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11913   // Sort the candidates by viability and position.  Sorting directly would
11914   // be prohibitive, so we make a set of pointers and sort those.
11915   SmallVector<OverloadCandidate*, 32> Cands;
11916   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11917   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11918     if (!Filter(*Cand))
11919       continue;
11920     switch (OCD) {
11921     case OCD_AllCandidates:
11922       if (!Cand->Viable) {
11923         if (!Cand->Function && !Cand->IsSurrogate) {
11924           // This a non-viable builtin candidate.  We do not, in general,
11925           // want to list every possible builtin candidate.
11926           continue;
11927         }
11928         CompleteNonViableCandidate(S, Cand, Args, Kind);
11929       }
11930       break;
11931 
11932     case OCD_ViableCandidates:
11933       if (!Cand->Viable)
11934         continue;
11935       break;
11936 
11937     case OCD_AmbiguousCandidates:
11938       if (!Cand->Best)
11939         continue;
11940       break;
11941     }
11942 
11943     Cands.push_back(Cand);
11944   }
11945 
11946   llvm::stable_sort(
11947       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11948 
11949   return Cands;
11950 }
11951 
11952 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11953                                             SourceLocation OpLoc) {
11954   bool DeferHint = false;
11955   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11956     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11957     // host device candidates.
11958     auto WrongSidedCands =
11959         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11960           return (Cand.Viable == false &&
11961                   Cand.FailureKind == ovl_fail_bad_target) ||
11962                  (Cand.Function &&
11963                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11964                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11965         });
11966     DeferHint = !WrongSidedCands.empty();
11967   }
11968   return DeferHint;
11969 }
11970 
11971 /// When overload resolution fails, prints diagnostic messages containing the
11972 /// candidates in the candidate set.
11973 void OverloadCandidateSet::NoteCandidates(
11974     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11975     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11976     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11977 
11978   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11979 
11980   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11981 
11982   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11983 
11984   if (OCD == OCD_AmbiguousCandidates)
11985     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11986 }
11987 
11988 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11989                                           ArrayRef<OverloadCandidate *> Cands,
11990                                           StringRef Opc, SourceLocation OpLoc) {
11991   bool ReportedAmbiguousConversions = false;
11992 
11993   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11994   unsigned CandsShown = 0;
11995   auto I = Cands.begin(), E = Cands.end();
11996   for (; I != E; ++I) {
11997     OverloadCandidate *Cand = *I;
11998 
11999     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12000         ShowOverloads == Ovl_Best) {
12001       break;
12002     }
12003     ++CandsShown;
12004 
12005     if (Cand->Function)
12006       NoteFunctionCandidate(S, Cand, Args.size(),
12007                             /*TakingCandidateAddress=*/false, DestAS);
12008     else if (Cand->IsSurrogate)
12009       NoteSurrogateCandidate(S, Cand);
12010     else {
12011       assert(Cand->Viable &&
12012              "Non-viable built-in candidates are not added to Cands.");
12013       // Generally we only see ambiguities including viable builtin
12014       // operators if overload resolution got screwed up by an
12015       // ambiguous user-defined conversion.
12016       //
12017       // FIXME: It's quite possible for different conversions to see
12018       // different ambiguities, though.
12019       if (!ReportedAmbiguousConversions) {
12020         NoteAmbiguousUserConversions(S, OpLoc, Cand);
12021         ReportedAmbiguousConversions = true;
12022       }
12023 
12024       // If this is a viable builtin, print it.
12025       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12026     }
12027   }
12028 
12029   // Inform S.Diags that we've shown an overload set with N elements.  This may
12030   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12031   S.Diags.overloadCandidatesShown(CandsShown);
12032 
12033   if (I != E)
12034     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12035            shouldDeferDiags(S, Args, OpLoc))
12036         << int(E - I);
12037 }
12038 
12039 static SourceLocation
12040 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12041   return Cand->Specialization ? Cand->Specialization->getLocation()
12042                               : SourceLocation();
12043 }
12044 
12045 namespace {
12046 struct CompareTemplateSpecCandidatesForDisplay {
12047   Sema &S;
12048   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12049 
12050   bool operator()(const TemplateSpecCandidate *L,
12051                   const TemplateSpecCandidate *R) {
12052     // Fast-path this check.
12053     if (L == R)
12054       return false;
12055 
12056     // Assuming that both candidates are not matches...
12057 
12058     // Sort by the ranking of deduction failures.
12059     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12060       return RankDeductionFailure(L->DeductionFailure) <
12061              RankDeductionFailure(R->DeductionFailure);
12062 
12063     // Sort everything else by location.
12064     SourceLocation LLoc = GetLocationForCandidate(L);
12065     SourceLocation RLoc = GetLocationForCandidate(R);
12066 
12067     // Put candidates without locations (e.g. builtins) at the end.
12068     if (LLoc.isInvalid())
12069       return false;
12070     if (RLoc.isInvalid())
12071       return true;
12072 
12073     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12074   }
12075 };
12076 }
12077 
12078 /// Diagnose a template argument deduction failure.
12079 /// We are treating these failures as overload failures due to bad
12080 /// deductions.
12081 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12082                                                  bool ForTakingAddress) {
12083   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12084                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12085 }
12086 
12087 void TemplateSpecCandidateSet::destroyCandidates() {
12088   for (iterator i = begin(), e = end(); i != e; ++i) {
12089     i->DeductionFailure.Destroy();
12090   }
12091 }
12092 
12093 void TemplateSpecCandidateSet::clear() {
12094   destroyCandidates();
12095   Candidates.clear();
12096 }
12097 
12098 /// NoteCandidates - When no template specialization match is found, prints
12099 /// diagnostic messages containing the non-matching specializations that form
12100 /// the candidate set.
12101 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12102 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12103 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12104   // Sort the candidates by position (assuming no candidate is a match).
12105   // Sorting directly would be prohibitive, so we make a set of pointers
12106   // and sort those.
12107   SmallVector<TemplateSpecCandidate *, 32> Cands;
12108   Cands.reserve(size());
12109   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12110     if (Cand->Specialization)
12111       Cands.push_back(Cand);
12112     // Otherwise, this is a non-matching builtin candidate.  We do not,
12113     // in general, want to list every possible builtin candidate.
12114   }
12115 
12116   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12117 
12118   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12119   // for generalization purposes (?).
12120   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12121 
12122   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12123   unsigned CandsShown = 0;
12124   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12125     TemplateSpecCandidate *Cand = *I;
12126 
12127     // Set an arbitrary limit on the number of candidates we'll spam
12128     // the user with.  FIXME: This limit should depend on details of the
12129     // candidate list.
12130     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12131       break;
12132     ++CandsShown;
12133 
12134     assert(Cand->Specialization &&
12135            "Non-matching built-in candidates are not added to Cands.");
12136     Cand->NoteDeductionFailure(S, ForTakingAddress);
12137   }
12138 
12139   if (I != E)
12140     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12141 }
12142 
12143 // [PossiblyAFunctionType]  -->   [Return]
12144 // NonFunctionType --> NonFunctionType
12145 // R (A) --> R(A)
12146 // R (*)(A) --> R (A)
12147 // R (&)(A) --> R (A)
12148 // R (S::*)(A) --> R (A)
12149 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12150   QualType Ret = PossiblyAFunctionType;
12151   if (const PointerType *ToTypePtr =
12152     PossiblyAFunctionType->getAs<PointerType>())
12153     Ret = ToTypePtr->getPointeeType();
12154   else if (const ReferenceType *ToTypeRef =
12155     PossiblyAFunctionType->getAs<ReferenceType>())
12156     Ret = ToTypeRef->getPointeeType();
12157   else if (const MemberPointerType *MemTypePtr =
12158     PossiblyAFunctionType->getAs<MemberPointerType>())
12159     Ret = MemTypePtr->getPointeeType();
12160   Ret =
12161     Context.getCanonicalType(Ret).getUnqualifiedType();
12162   return Ret;
12163 }
12164 
12165 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12166                                  bool Complain = true) {
12167   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12168       S.DeduceReturnType(FD, Loc, Complain))
12169     return true;
12170 
12171   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12172   if (S.getLangOpts().CPlusPlus17 &&
12173       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12174       !S.ResolveExceptionSpec(Loc, FPT))
12175     return true;
12176 
12177   return false;
12178 }
12179 
12180 namespace {
12181 // A helper class to help with address of function resolution
12182 // - allows us to avoid passing around all those ugly parameters
12183 class AddressOfFunctionResolver {
12184   Sema& S;
12185   Expr* SourceExpr;
12186   const QualType& TargetType;
12187   QualType TargetFunctionType; // Extracted function type from target type
12188 
12189   bool Complain;
12190   //DeclAccessPair& ResultFunctionAccessPair;
12191   ASTContext& Context;
12192 
12193   bool TargetTypeIsNonStaticMemberFunction;
12194   bool FoundNonTemplateFunction;
12195   bool StaticMemberFunctionFromBoundPointer;
12196   bool HasComplained;
12197 
12198   OverloadExpr::FindResult OvlExprInfo;
12199   OverloadExpr *OvlExpr;
12200   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12201   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12202   TemplateSpecCandidateSet FailedCandidates;
12203 
12204 public:
12205   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12206                             const QualType &TargetType, bool Complain)
12207       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12208         Complain(Complain), Context(S.getASTContext()),
12209         TargetTypeIsNonStaticMemberFunction(
12210             !!TargetType->getAs<MemberPointerType>()),
12211         FoundNonTemplateFunction(false),
12212         StaticMemberFunctionFromBoundPointer(false),
12213         HasComplained(false),
12214         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12215         OvlExpr(OvlExprInfo.Expression),
12216         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12217     ExtractUnqualifiedFunctionTypeFromTargetType();
12218 
12219     if (TargetFunctionType->isFunctionType()) {
12220       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12221         if (!UME->isImplicitAccess() &&
12222             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12223           StaticMemberFunctionFromBoundPointer = true;
12224     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12225       DeclAccessPair dap;
12226       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12227               OvlExpr, false, &dap)) {
12228         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12229           if (!Method->isStatic()) {
12230             // If the target type is a non-function type and the function found
12231             // is a non-static member function, pretend as if that was the
12232             // target, it's the only possible type to end up with.
12233             TargetTypeIsNonStaticMemberFunction = true;
12234 
12235             // And skip adding the function if its not in the proper form.
12236             // We'll diagnose this due to an empty set of functions.
12237             if (!OvlExprInfo.HasFormOfMemberPointer)
12238               return;
12239           }
12240 
12241         Matches.push_back(std::make_pair(dap, Fn));
12242       }
12243       return;
12244     }
12245 
12246     if (OvlExpr->hasExplicitTemplateArgs())
12247       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12248 
12249     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12250       // C++ [over.over]p4:
12251       //   If more than one function is selected, [...]
12252       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12253         if (FoundNonTemplateFunction)
12254           EliminateAllTemplateMatches();
12255         else
12256           EliminateAllExceptMostSpecializedTemplate();
12257       }
12258     }
12259 
12260     if (S.getLangOpts().CUDA && Matches.size() > 1)
12261       EliminateSuboptimalCudaMatches();
12262   }
12263 
12264   bool hasComplained() const { return HasComplained; }
12265 
12266 private:
12267   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12268     QualType Discard;
12269     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12270            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12271   }
12272 
12273   /// \return true if A is considered a better overload candidate for the
12274   /// desired type than B.
12275   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12276     // If A doesn't have exactly the correct type, we don't want to classify it
12277     // as "better" than anything else. This way, the user is required to
12278     // disambiguate for us if there are multiple candidates and no exact match.
12279     return candidateHasExactlyCorrectType(A) &&
12280            (!candidateHasExactlyCorrectType(B) ||
12281             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12282   }
12283 
12284   /// \return true if we were able to eliminate all but one overload candidate,
12285   /// false otherwise.
12286   bool eliminiateSuboptimalOverloadCandidates() {
12287     // Same algorithm as overload resolution -- one pass to pick the "best",
12288     // another pass to be sure that nothing is better than the best.
12289     auto Best = Matches.begin();
12290     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12291       if (isBetterCandidate(I->second, Best->second))
12292         Best = I;
12293 
12294     const FunctionDecl *BestFn = Best->second;
12295     auto IsBestOrInferiorToBest = [this, BestFn](
12296         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12297       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12298     };
12299 
12300     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12301     // option, so we can potentially give the user a better error
12302     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12303       return false;
12304     Matches[0] = *Best;
12305     Matches.resize(1);
12306     return true;
12307   }
12308 
12309   bool isTargetTypeAFunction() const {
12310     return TargetFunctionType->isFunctionType();
12311   }
12312 
12313   // [ToType]     [Return]
12314 
12315   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12316   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12317   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12318   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12319     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12320   }
12321 
12322   // return true if any matching specializations were found
12323   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12324                                    const DeclAccessPair& CurAccessFunPair) {
12325     if (CXXMethodDecl *Method
12326               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12327       // Skip non-static function templates when converting to pointer, and
12328       // static when converting to member pointer.
12329       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12330         return false;
12331     }
12332     else if (TargetTypeIsNonStaticMemberFunction)
12333       return false;
12334 
12335     // C++ [over.over]p2:
12336     //   If the name is a function template, template argument deduction is
12337     //   done (14.8.2.2), and if the argument deduction succeeds, the
12338     //   resulting template argument list is used to generate a single
12339     //   function template specialization, which is added to the set of
12340     //   overloaded functions considered.
12341     FunctionDecl *Specialization = nullptr;
12342     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12343     if (Sema::TemplateDeductionResult Result
12344           = S.DeduceTemplateArguments(FunctionTemplate,
12345                                       &OvlExplicitTemplateArgs,
12346                                       TargetFunctionType, Specialization,
12347                                       Info, /*IsAddressOfFunction*/true)) {
12348       // Make a note of the failed deduction for diagnostics.
12349       FailedCandidates.addCandidate()
12350           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12351                MakeDeductionFailureInfo(Context, Result, Info));
12352       return false;
12353     }
12354 
12355     // Template argument deduction ensures that we have an exact match or
12356     // compatible pointer-to-function arguments that would be adjusted by ICS.
12357     // This function template specicalization works.
12358     assert(S.isSameOrCompatibleFunctionType(
12359               Context.getCanonicalType(Specialization->getType()),
12360               Context.getCanonicalType(TargetFunctionType)));
12361 
12362     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12363       return false;
12364 
12365     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12366     return true;
12367   }
12368 
12369   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12370                                       const DeclAccessPair& CurAccessFunPair) {
12371     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12372       // Skip non-static functions when converting to pointer, and static
12373       // when converting to member pointer.
12374       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12375         return false;
12376     }
12377     else if (TargetTypeIsNonStaticMemberFunction)
12378       return false;
12379 
12380     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12381       if (S.getLangOpts().CUDA)
12382         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12383           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12384             return false;
12385       if (FunDecl->isMultiVersion()) {
12386         const auto *TA = FunDecl->getAttr<TargetAttr>();
12387         if (TA && !TA->isDefaultVersion())
12388           return false;
12389         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12390         if (TVA && !TVA->isDefaultVersion())
12391           return false;
12392       }
12393 
12394       // If any candidate has a placeholder return type, trigger its deduction
12395       // now.
12396       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12397                                Complain)) {
12398         HasComplained |= Complain;
12399         return false;
12400       }
12401 
12402       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12403         return false;
12404 
12405       // If we're in C, we need to support types that aren't exactly identical.
12406       if (!S.getLangOpts().CPlusPlus ||
12407           candidateHasExactlyCorrectType(FunDecl)) {
12408         Matches.push_back(std::make_pair(
12409             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12410         FoundNonTemplateFunction = true;
12411         return true;
12412       }
12413     }
12414 
12415     return false;
12416   }
12417 
12418   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12419     bool Ret = false;
12420 
12421     // If the overload expression doesn't have the form of a pointer to
12422     // member, don't try to convert it to a pointer-to-member type.
12423     if (IsInvalidFormOfPointerToMemberFunction())
12424       return false;
12425 
12426     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12427                                E = OvlExpr->decls_end();
12428          I != E; ++I) {
12429       // Look through any using declarations to find the underlying function.
12430       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12431 
12432       // C++ [over.over]p3:
12433       //   Non-member functions and static member functions match
12434       //   targets of type "pointer-to-function" or "reference-to-function."
12435       //   Nonstatic member functions match targets of
12436       //   type "pointer-to-member-function."
12437       // Note that according to DR 247, the containing class does not matter.
12438       if (FunctionTemplateDecl *FunctionTemplate
12439                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12440         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12441           Ret = true;
12442       }
12443       // If we have explicit template arguments supplied, skip non-templates.
12444       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12445                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12446         Ret = true;
12447     }
12448     assert(Ret || Matches.empty());
12449     return Ret;
12450   }
12451 
12452   void EliminateAllExceptMostSpecializedTemplate() {
12453     //   [...] and any given function template specialization F1 is
12454     //   eliminated if the set contains a second function template
12455     //   specialization whose function template is more specialized
12456     //   than the function template of F1 according to the partial
12457     //   ordering rules of 14.5.5.2.
12458 
12459     // The algorithm specified above is quadratic. We instead use a
12460     // two-pass algorithm (similar to the one used to identify the
12461     // best viable function in an overload set) that identifies the
12462     // best function template (if it exists).
12463 
12464     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12465     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12466       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12467 
12468     // TODO: It looks like FailedCandidates does not serve much purpose
12469     // here, since the no_viable diagnostic has index 0.
12470     UnresolvedSetIterator Result = S.getMostSpecialized(
12471         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12472         SourceExpr->getBeginLoc(), S.PDiag(),
12473         S.PDiag(diag::err_addr_ovl_ambiguous)
12474             << Matches[0].second->getDeclName(),
12475         S.PDiag(diag::note_ovl_candidate)
12476             << (unsigned)oc_function << (unsigned)ocs_described_template,
12477         Complain, TargetFunctionType);
12478 
12479     if (Result != MatchesCopy.end()) {
12480       // Make it the first and only element
12481       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12482       Matches[0].second = cast<FunctionDecl>(*Result);
12483       Matches.resize(1);
12484     } else
12485       HasComplained |= Complain;
12486   }
12487 
12488   void EliminateAllTemplateMatches() {
12489     //   [...] any function template specializations in the set are
12490     //   eliminated if the set also contains a non-template function, [...]
12491     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12492       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12493         ++I;
12494       else {
12495         Matches[I] = Matches[--N];
12496         Matches.resize(N);
12497       }
12498     }
12499   }
12500 
12501   void EliminateSuboptimalCudaMatches() {
12502     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12503                                Matches);
12504   }
12505 
12506 public:
12507   void ComplainNoMatchesFound() const {
12508     assert(Matches.empty());
12509     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12510         << OvlExpr->getName() << TargetFunctionType
12511         << OvlExpr->getSourceRange();
12512     if (FailedCandidates.empty())
12513       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12514                                   /*TakingAddress=*/true);
12515     else {
12516       // We have some deduction failure messages. Use them to diagnose
12517       // the function templates, and diagnose the non-template candidates
12518       // normally.
12519       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12520                                  IEnd = OvlExpr->decls_end();
12521            I != IEnd; ++I)
12522         if (FunctionDecl *Fun =
12523                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12524           if (!functionHasPassObjectSizeParams(Fun))
12525             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12526                                     /*TakingAddress=*/true);
12527       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12528     }
12529   }
12530 
12531   bool IsInvalidFormOfPointerToMemberFunction() const {
12532     return TargetTypeIsNonStaticMemberFunction &&
12533       !OvlExprInfo.HasFormOfMemberPointer;
12534   }
12535 
12536   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12537       // TODO: Should we condition this on whether any functions might
12538       // have matched, or is it more appropriate to do that in callers?
12539       // TODO: a fixit wouldn't hurt.
12540       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12541         << TargetType << OvlExpr->getSourceRange();
12542   }
12543 
12544   bool IsStaticMemberFunctionFromBoundPointer() const {
12545     return StaticMemberFunctionFromBoundPointer;
12546   }
12547 
12548   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12549     S.Diag(OvlExpr->getBeginLoc(),
12550            diag::err_invalid_form_pointer_member_function)
12551         << OvlExpr->getSourceRange();
12552   }
12553 
12554   void ComplainOfInvalidConversion() const {
12555     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12556         << OvlExpr->getName() << TargetType;
12557   }
12558 
12559   void ComplainMultipleMatchesFound() const {
12560     assert(Matches.size() > 1);
12561     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12562         << OvlExpr->getName() << OvlExpr->getSourceRange();
12563     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12564                                 /*TakingAddress=*/true);
12565   }
12566 
12567   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12568 
12569   int getNumMatches() const { return Matches.size(); }
12570 
12571   FunctionDecl* getMatchingFunctionDecl() const {
12572     if (Matches.size() != 1) return nullptr;
12573     return Matches[0].second;
12574   }
12575 
12576   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12577     if (Matches.size() != 1) return nullptr;
12578     return &Matches[0].first;
12579   }
12580 };
12581 }
12582 
12583 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12584 /// an overloaded function (C++ [over.over]), where @p From is an
12585 /// expression with overloaded function type and @p ToType is the type
12586 /// we're trying to resolve to. For example:
12587 ///
12588 /// @code
12589 /// int f(double);
12590 /// int f(int);
12591 ///
12592 /// int (*pfd)(double) = f; // selects f(double)
12593 /// @endcode
12594 ///
12595 /// This routine returns the resulting FunctionDecl if it could be
12596 /// resolved, and NULL otherwise. When @p Complain is true, this
12597 /// routine will emit diagnostics if there is an error.
12598 FunctionDecl *
12599 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12600                                          QualType TargetType,
12601                                          bool Complain,
12602                                          DeclAccessPair &FoundResult,
12603                                          bool *pHadMultipleCandidates) {
12604   assert(AddressOfExpr->getType() == Context.OverloadTy);
12605 
12606   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12607                                      Complain);
12608   int NumMatches = Resolver.getNumMatches();
12609   FunctionDecl *Fn = nullptr;
12610   bool ShouldComplain = Complain && !Resolver.hasComplained();
12611   if (NumMatches == 0 && ShouldComplain) {
12612     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12613       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12614     else
12615       Resolver.ComplainNoMatchesFound();
12616   }
12617   else if (NumMatches > 1 && ShouldComplain)
12618     Resolver.ComplainMultipleMatchesFound();
12619   else if (NumMatches == 1) {
12620     Fn = Resolver.getMatchingFunctionDecl();
12621     assert(Fn);
12622     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12623       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12624     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12625     if (Complain) {
12626       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12627         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12628       else
12629         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12630     }
12631   }
12632 
12633   if (pHadMultipleCandidates)
12634     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12635   return Fn;
12636 }
12637 
12638 /// Given an expression that refers to an overloaded function, try to
12639 /// resolve that function to a single function that can have its address taken.
12640 /// This will modify `Pair` iff it returns non-null.
12641 ///
12642 /// This routine can only succeed if from all of the candidates in the overload
12643 /// set for SrcExpr that can have their addresses taken, there is one candidate
12644 /// that is more constrained than the rest.
12645 FunctionDecl *
12646 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12647   OverloadExpr::FindResult R = OverloadExpr::find(E);
12648   OverloadExpr *Ovl = R.Expression;
12649   bool IsResultAmbiguous = false;
12650   FunctionDecl *Result = nullptr;
12651   DeclAccessPair DAP;
12652   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12653 
12654   auto CheckMoreConstrained = [&](FunctionDecl *FD1,
12655                                   FunctionDecl *FD2) -> std::optional<bool> {
12656     if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
12657       FD1 = MF;
12658     if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
12659       FD2 = MF;
12660     SmallVector<const Expr *, 1> AC1, AC2;
12661     FD1->getAssociatedConstraints(AC1);
12662     FD2->getAssociatedConstraints(AC2);
12663     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12664     if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12665       return std::nullopt;
12666     if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12667       return std::nullopt;
12668     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12669       return std::nullopt;
12670     return AtLeastAsConstrained1;
12671   };
12672 
12673   // Don't use the AddressOfResolver because we're specifically looking for
12674   // cases where we have one overload candidate that lacks
12675   // enable_if/pass_object_size/...
12676   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12677     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12678     if (!FD)
12679       return nullptr;
12680 
12681     if (!checkAddressOfFunctionIsAvailable(FD))
12682       continue;
12683 
12684     // We have more than one result - see if it is more constrained than the
12685     // previous one.
12686     if (Result) {
12687       std::optional<bool> MoreConstrainedThanPrevious =
12688           CheckMoreConstrained(FD, Result);
12689       if (!MoreConstrainedThanPrevious) {
12690         IsResultAmbiguous = true;
12691         AmbiguousDecls.push_back(FD);
12692         continue;
12693       }
12694       if (!*MoreConstrainedThanPrevious)
12695         continue;
12696       // FD is more constrained - replace Result with it.
12697     }
12698     IsResultAmbiguous = false;
12699     DAP = I.getPair();
12700     Result = FD;
12701   }
12702 
12703   if (IsResultAmbiguous)
12704     return nullptr;
12705 
12706   if (Result) {
12707     SmallVector<const Expr *, 1> ResultAC;
12708     // We skipped over some ambiguous declarations which might be ambiguous with
12709     // the selected result.
12710     for (FunctionDecl *Skipped : AmbiguousDecls)
12711       if (!CheckMoreConstrained(Skipped, Result))
12712         return nullptr;
12713     Pair = DAP;
12714   }
12715   return Result;
12716 }
12717 
12718 /// Given an overloaded function, tries to turn it into a non-overloaded
12719 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12720 /// will perform access checks, diagnose the use of the resultant decl, and, if
12721 /// requested, potentially perform a function-to-pointer decay.
12722 ///
12723 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12724 /// Otherwise, returns true. This may emit diagnostics and return true.
12725 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12726     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
12727   Expr *E = SrcExpr.get();
12728   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12729 
12730   DeclAccessPair DAP;
12731   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12732   if (!Found || Found->isCPUDispatchMultiVersion() ||
12733       Found->isCPUSpecificMultiVersion())
12734     return false;
12735 
12736   // Emitting multiple diagnostics for a function that is both inaccessible and
12737   // unavailable is consistent with our behavior elsewhere. So, always check
12738   // for both.
12739   DiagnoseUseOfDecl(Found, E->getExprLoc());
12740   CheckAddressOfMemberAccess(E, DAP);
12741   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12742   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
12743     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12744   else
12745     SrcExpr = Fixed;
12746   return true;
12747 }
12748 
12749 /// Given an expression that refers to an overloaded function, try to
12750 /// resolve that overloaded function expression down to a single function.
12751 ///
12752 /// This routine can only resolve template-ids that refer to a single function
12753 /// template, where that template-id refers to a single template whose template
12754 /// arguments are either provided by the template-id or have defaults,
12755 /// as described in C++0x [temp.arg.explicit]p3.
12756 ///
12757 /// If no template-ids are found, no diagnostics are emitted and NULL is
12758 /// returned.
12759 FunctionDecl *
12760 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12761                                                   bool Complain,
12762                                                   DeclAccessPair *FoundResult) {
12763   // C++ [over.over]p1:
12764   //   [...] [Note: any redundant set of parentheses surrounding the
12765   //   overloaded function name is ignored (5.1). ]
12766   // C++ [over.over]p1:
12767   //   [...] The overloaded function name can be preceded by the &
12768   //   operator.
12769 
12770   // If we didn't actually find any template-ids, we're done.
12771   if (!ovl->hasExplicitTemplateArgs())
12772     return nullptr;
12773 
12774   TemplateArgumentListInfo ExplicitTemplateArgs;
12775   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12776   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12777 
12778   // Look through all of the overloaded functions, searching for one
12779   // whose type matches exactly.
12780   FunctionDecl *Matched = nullptr;
12781   for (UnresolvedSetIterator I = ovl->decls_begin(),
12782          E = ovl->decls_end(); I != E; ++I) {
12783     // C++0x [temp.arg.explicit]p3:
12784     //   [...] In contexts where deduction is done and fails, or in contexts
12785     //   where deduction is not done, if a template argument list is
12786     //   specified and it, along with any default template arguments,
12787     //   identifies a single function template specialization, then the
12788     //   template-id is an lvalue for the function template specialization.
12789     FunctionTemplateDecl *FunctionTemplate
12790       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12791 
12792     // C++ [over.over]p2:
12793     //   If the name is a function template, template argument deduction is
12794     //   done (14.8.2.2), and if the argument deduction succeeds, the
12795     //   resulting template argument list is used to generate a single
12796     //   function template specialization, which is added to the set of
12797     //   overloaded functions considered.
12798     FunctionDecl *Specialization = nullptr;
12799     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12800     if (TemplateDeductionResult Result
12801           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12802                                     Specialization, Info,
12803                                     /*IsAddressOfFunction*/true)) {
12804       // Make a note of the failed deduction for diagnostics.
12805       // TODO: Actually use the failed-deduction info?
12806       FailedCandidates.addCandidate()
12807           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12808                MakeDeductionFailureInfo(Context, Result, Info));
12809       continue;
12810     }
12811 
12812     assert(Specialization && "no specialization and no error?");
12813 
12814     // Multiple matches; we can't resolve to a single declaration.
12815     if (Matched) {
12816       if (Complain) {
12817         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12818           << ovl->getName();
12819         NoteAllOverloadCandidates(ovl);
12820       }
12821       return nullptr;
12822     }
12823 
12824     Matched = Specialization;
12825     if (FoundResult) *FoundResult = I.getPair();
12826   }
12827 
12828   if (Matched &&
12829       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12830     return nullptr;
12831 
12832   return Matched;
12833 }
12834 
12835 // Resolve and fix an overloaded expression that can be resolved
12836 // because it identifies a single function template specialization.
12837 //
12838 // Last three arguments should only be supplied if Complain = true
12839 //
12840 // Return true if it was logically possible to so resolve the
12841 // expression, regardless of whether or not it succeeded.  Always
12842 // returns true if 'complain' is set.
12843 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12844     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
12845     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
12846     unsigned DiagIDForComplaining) {
12847   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12848 
12849   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12850 
12851   DeclAccessPair found;
12852   ExprResult SingleFunctionExpression;
12853   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12854                            ovl.Expression, /*complain*/ false, &found)) {
12855     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12856       SrcExpr = ExprError();
12857       return true;
12858     }
12859 
12860     // It is only correct to resolve to an instance method if we're
12861     // resolving a form that's permitted to be a pointer to member.
12862     // Otherwise we'll end up making a bound member expression, which
12863     // is illegal in all the contexts we resolve like this.
12864     if (!ovl.HasFormOfMemberPointer &&
12865         isa<CXXMethodDecl>(fn) &&
12866         cast<CXXMethodDecl>(fn)->isInstance()) {
12867       if (!complain) return false;
12868 
12869       Diag(ovl.Expression->getExprLoc(),
12870            diag::err_bound_member_function)
12871         << 0 << ovl.Expression->getSourceRange();
12872 
12873       // TODO: I believe we only end up here if there's a mix of
12874       // static and non-static candidates (otherwise the expression
12875       // would have 'bound member' type, not 'overload' type).
12876       // Ideally we would note which candidate was chosen and why
12877       // the static candidates were rejected.
12878       SrcExpr = ExprError();
12879       return true;
12880     }
12881 
12882     // Fix the expression to refer to 'fn'.
12883     SingleFunctionExpression =
12884         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12885 
12886     // If desired, do function-to-pointer decay.
12887     if (doFunctionPointerConversion) {
12888       SingleFunctionExpression =
12889         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12890       if (SingleFunctionExpression.isInvalid()) {
12891         SrcExpr = ExprError();
12892         return true;
12893       }
12894     }
12895   }
12896 
12897   if (!SingleFunctionExpression.isUsable()) {
12898     if (complain) {
12899       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12900         << ovl.Expression->getName()
12901         << DestTypeForComplaining
12902         << OpRangeForComplaining
12903         << ovl.Expression->getQualifierLoc().getSourceRange();
12904       NoteAllOverloadCandidates(SrcExpr.get());
12905 
12906       SrcExpr = ExprError();
12907       return true;
12908     }
12909 
12910     return false;
12911   }
12912 
12913   SrcExpr = SingleFunctionExpression;
12914   return true;
12915 }
12916 
12917 /// Add a single candidate to the overload set.
12918 static void AddOverloadedCallCandidate(Sema &S,
12919                                        DeclAccessPair FoundDecl,
12920                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12921                                        ArrayRef<Expr *> Args,
12922                                        OverloadCandidateSet &CandidateSet,
12923                                        bool PartialOverloading,
12924                                        bool KnownValid) {
12925   NamedDecl *Callee = FoundDecl.getDecl();
12926   if (isa<UsingShadowDecl>(Callee))
12927     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12928 
12929   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12930     if (ExplicitTemplateArgs) {
12931       assert(!KnownValid && "Explicit template arguments?");
12932       return;
12933     }
12934     // Prevent ill-formed function decls to be added as overload candidates.
12935     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12936       return;
12937 
12938     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12939                            /*SuppressUserConversions=*/false,
12940                            PartialOverloading);
12941     return;
12942   }
12943 
12944   if (FunctionTemplateDecl *FuncTemplate
12945       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12946     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12947                                    ExplicitTemplateArgs, Args, CandidateSet,
12948                                    /*SuppressUserConversions=*/false,
12949                                    PartialOverloading);
12950     return;
12951   }
12952 
12953   assert(!KnownValid && "unhandled case in overloaded call candidate");
12954 }
12955 
12956 /// Add the overload candidates named by callee and/or found by argument
12957 /// dependent lookup to the given overload set.
12958 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12959                                        ArrayRef<Expr *> Args,
12960                                        OverloadCandidateSet &CandidateSet,
12961                                        bool PartialOverloading) {
12962 
12963 #ifndef NDEBUG
12964   // Verify that ArgumentDependentLookup is consistent with the rules
12965   // in C++0x [basic.lookup.argdep]p3:
12966   //
12967   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12968   //   and let Y be the lookup set produced by argument dependent
12969   //   lookup (defined as follows). If X contains
12970   //
12971   //     -- a declaration of a class member, or
12972   //
12973   //     -- a block-scope function declaration that is not a
12974   //        using-declaration, or
12975   //
12976   //     -- a declaration that is neither a function or a function
12977   //        template
12978   //
12979   //   then Y is empty.
12980 
12981   if (ULE->requiresADL()) {
12982     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12983            E = ULE->decls_end(); I != E; ++I) {
12984       assert(!(*I)->getDeclContext()->isRecord());
12985       assert(isa<UsingShadowDecl>(*I) ||
12986              !(*I)->getDeclContext()->isFunctionOrMethod());
12987       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12988     }
12989   }
12990 #endif
12991 
12992   // It would be nice to avoid this copy.
12993   TemplateArgumentListInfo TABuffer;
12994   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12995   if (ULE->hasExplicitTemplateArgs()) {
12996     ULE->copyTemplateArgumentsInto(TABuffer);
12997     ExplicitTemplateArgs = &TABuffer;
12998   }
12999 
13000   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13001          E = ULE->decls_end(); I != E; ++I)
13002     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13003                                CandidateSet, PartialOverloading,
13004                                /*KnownValid*/ true);
13005 
13006   if (ULE->requiresADL())
13007     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13008                                          Args, ExplicitTemplateArgs,
13009                                          CandidateSet, PartialOverloading);
13010 }
13011 
13012 /// Add the call candidates from the given set of lookup results to the given
13013 /// overload set. Non-function lookup results are ignored.
13014 void Sema::AddOverloadedCallCandidates(
13015     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13016     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13017   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13018     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13019                                CandidateSet, false, /*KnownValid*/ false);
13020 }
13021 
13022 /// Determine whether a declaration with the specified name could be moved into
13023 /// a different namespace.
13024 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13025   switch (Name.getCXXOverloadedOperator()) {
13026   case OO_New: case OO_Array_New:
13027   case OO_Delete: case OO_Array_Delete:
13028     return false;
13029 
13030   default:
13031     return true;
13032   }
13033 }
13034 
13035 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13036 /// template, where the non-dependent name was declared after the template
13037 /// was defined. This is common in code written for a compilers which do not
13038 /// correctly implement two-stage name lookup.
13039 ///
13040 /// Returns true if a viable candidate was found and a diagnostic was issued.
13041 static bool DiagnoseTwoPhaseLookup(
13042     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13043     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13044     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13045     CXXRecordDecl **FoundInClass = nullptr) {
13046   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13047     return false;
13048 
13049   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13050     if (DC->isTransparentContext())
13051       continue;
13052 
13053     SemaRef.LookupQualifiedName(R, DC);
13054 
13055     if (!R.empty()) {
13056       R.suppressDiagnostics();
13057 
13058       OverloadCandidateSet Candidates(FnLoc, CSK);
13059       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13060                                           Candidates);
13061 
13062       OverloadCandidateSet::iterator Best;
13063       OverloadingResult OR =
13064           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13065 
13066       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13067         // We either found non-function declarations or a best viable function
13068         // at class scope. A class-scope lookup result disables ADL. Don't
13069         // look past this, but let the caller know that we found something that
13070         // either is, or might be, usable in this class.
13071         if (FoundInClass) {
13072           *FoundInClass = RD;
13073           if (OR == OR_Success) {
13074             R.clear();
13075             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13076             R.resolveKind();
13077           }
13078         }
13079         return false;
13080       }
13081 
13082       if (OR != OR_Success) {
13083         // There wasn't a unique best function or function template.
13084         return false;
13085       }
13086 
13087       // Find the namespaces where ADL would have looked, and suggest
13088       // declaring the function there instead.
13089       Sema::AssociatedNamespaceSet AssociatedNamespaces;
13090       Sema::AssociatedClassSet AssociatedClasses;
13091       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13092                                                  AssociatedNamespaces,
13093                                                  AssociatedClasses);
13094       Sema::AssociatedNamespaceSet SuggestedNamespaces;
13095       if (canBeDeclaredInNamespace(R.getLookupName())) {
13096         DeclContext *Std = SemaRef.getStdNamespace();
13097         for (Sema::AssociatedNamespaceSet::iterator
13098                it = AssociatedNamespaces.begin(),
13099                end = AssociatedNamespaces.end(); it != end; ++it) {
13100           // Never suggest declaring a function within namespace 'std'.
13101           if (Std && Std->Encloses(*it))
13102             continue;
13103 
13104           // Never suggest declaring a function within a namespace with a
13105           // reserved name, like __gnu_cxx.
13106           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13107           if (NS &&
13108               NS->getQualifiedNameAsString().find("__") != std::string::npos)
13109             continue;
13110 
13111           SuggestedNamespaces.insert(*it);
13112         }
13113       }
13114 
13115       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13116         << R.getLookupName();
13117       if (SuggestedNamespaces.empty()) {
13118         SemaRef.Diag(Best->Function->getLocation(),
13119                      diag::note_not_found_by_two_phase_lookup)
13120           << R.getLookupName() << 0;
13121       } else if (SuggestedNamespaces.size() == 1) {
13122         SemaRef.Diag(Best->Function->getLocation(),
13123                      diag::note_not_found_by_two_phase_lookup)
13124           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13125       } else {
13126         // FIXME: It would be useful to list the associated namespaces here,
13127         // but the diagnostics infrastructure doesn't provide a way to produce
13128         // a localized representation of a list of items.
13129         SemaRef.Diag(Best->Function->getLocation(),
13130                      diag::note_not_found_by_two_phase_lookup)
13131           << R.getLookupName() << 2;
13132       }
13133 
13134       // Try to recover by calling this function.
13135       return true;
13136     }
13137 
13138     R.clear();
13139   }
13140 
13141   return false;
13142 }
13143 
13144 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13145 /// template, where the non-dependent operator was declared after the template
13146 /// was defined.
13147 ///
13148 /// Returns true if a viable candidate was found and a diagnostic was issued.
13149 static bool
13150 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13151                                SourceLocation OpLoc,
13152                                ArrayRef<Expr *> Args) {
13153   DeclarationName OpName =
13154     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13155   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13156   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13157                                 OverloadCandidateSet::CSK_Operator,
13158                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13159 }
13160 
13161 namespace {
13162 class BuildRecoveryCallExprRAII {
13163   Sema &SemaRef;
13164   Sema::SatisfactionStackResetRAII SatStack;
13165 
13166 public:
13167   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13168     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13169     SemaRef.IsBuildingRecoveryCallExpr = true;
13170   }
13171 
13172   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13173 };
13174 }
13175 
13176 /// Attempts to recover from a call where no functions were found.
13177 ///
13178 /// This function will do one of three things:
13179 ///  * Diagnose, recover, and return a recovery expression.
13180 ///  * Diagnose, fail to recover, and return ExprError().
13181 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13182 ///    expected to diagnose as appropriate.
13183 static ExprResult
13184 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13185                       UnresolvedLookupExpr *ULE,
13186                       SourceLocation LParenLoc,
13187                       MutableArrayRef<Expr *> Args,
13188                       SourceLocation RParenLoc,
13189                       bool EmptyLookup, bool AllowTypoCorrection) {
13190   // Do not try to recover if it is already building a recovery call.
13191   // This stops infinite loops for template instantiations like
13192   //
13193   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13194   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13195   if (SemaRef.IsBuildingRecoveryCallExpr)
13196     return ExprResult();
13197   BuildRecoveryCallExprRAII RCE(SemaRef);
13198 
13199   CXXScopeSpec SS;
13200   SS.Adopt(ULE->getQualifierLoc());
13201   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13202 
13203   TemplateArgumentListInfo TABuffer;
13204   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13205   if (ULE->hasExplicitTemplateArgs()) {
13206     ULE->copyTemplateArgumentsInto(TABuffer);
13207     ExplicitTemplateArgs = &TABuffer;
13208   }
13209 
13210   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13211                  Sema::LookupOrdinaryName);
13212   CXXRecordDecl *FoundInClass = nullptr;
13213   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13214                              OverloadCandidateSet::CSK_Normal,
13215                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13216     // OK, diagnosed a two-phase lookup issue.
13217   } else if (EmptyLookup) {
13218     // Try to recover from an empty lookup with typo correction.
13219     R.clear();
13220     NoTypoCorrectionCCC NoTypoValidator{};
13221     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13222                                                 ExplicitTemplateArgs != nullptr,
13223                                                 dyn_cast<MemberExpr>(Fn));
13224     CorrectionCandidateCallback &Validator =
13225         AllowTypoCorrection
13226             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13227             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13228     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13229                                     Args))
13230       return ExprError();
13231   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13232     // We found a usable declaration of the name in a dependent base of some
13233     // enclosing class.
13234     // FIXME: We should also explain why the candidates found by name lookup
13235     // were not viable.
13236     if (SemaRef.DiagnoseDependentMemberLookup(R))
13237       return ExprError();
13238   } else {
13239     // We had viable candidates and couldn't recover; let the caller diagnose
13240     // this.
13241     return ExprResult();
13242   }
13243 
13244   // If we get here, we should have issued a diagnostic and formed a recovery
13245   // lookup result.
13246   assert(!R.empty() && "lookup results empty despite recovery");
13247 
13248   // If recovery created an ambiguity, just bail out.
13249   if (R.isAmbiguous()) {
13250     R.suppressDiagnostics();
13251     return ExprError();
13252   }
13253 
13254   // Build an implicit member call if appropriate.  Just drop the
13255   // casts and such from the call, we don't really care.
13256   ExprResult NewFn = ExprError();
13257   if ((*R.begin())->isCXXClassMember())
13258     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13259                                                     ExplicitTemplateArgs, S);
13260   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13261     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13262                                         ExplicitTemplateArgs);
13263   else
13264     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13265 
13266   if (NewFn.isInvalid())
13267     return ExprError();
13268 
13269   // This shouldn't cause an infinite loop because we're giving it
13270   // an expression with viable lookup results, which should never
13271   // end up here.
13272   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13273                                MultiExprArg(Args.data(), Args.size()),
13274                                RParenLoc);
13275 }
13276 
13277 /// Constructs and populates an OverloadedCandidateSet from
13278 /// the given function.
13279 /// \returns true when an the ExprResult output parameter has been set.
13280 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13281                                   UnresolvedLookupExpr *ULE,
13282                                   MultiExprArg Args,
13283                                   SourceLocation RParenLoc,
13284                                   OverloadCandidateSet *CandidateSet,
13285                                   ExprResult *Result) {
13286 #ifndef NDEBUG
13287   if (ULE->requiresADL()) {
13288     // To do ADL, we must have found an unqualified name.
13289     assert(!ULE->getQualifier() && "qualified name with ADL");
13290 
13291     // We don't perform ADL for implicit declarations of builtins.
13292     // Verify that this was correctly set up.
13293     FunctionDecl *F;
13294     if (ULE->decls_begin() != ULE->decls_end() &&
13295         ULE->decls_begin() + 1 == ULE->decls_end() &&
13296         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13297         F->getBuiltinID() && F->isImplicit())
13298       llvm_unreachable("performing ADL for builtin");
13299 
13300     // We don't perform ADL in C.
13301     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13302   }
13303 #endif
13304 
13305   UnbridgedCastsSet UnbridgedCasts;
13306   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13307     *Result = ExprError();
13308     return true;
13309   }
13310 
13311   // Add the functions denoted by the callee to the set of candidate
13312   // functions, including those from argument-dependent lookup.
13313   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13314 
13315   if (getLangOpts().MSVCCompat &&
13316       CurContext->isDependentContext() && !isSFINAEContext() &&
13317       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13318 
13319     OverloadCandidateSet::iterator Best;
13320     if (CandidateSet->empty() ||
13321         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13322             OR_No_Viable_Function) {
13323       // In Microsoft mode, if we are inside a template class member function
13324       // then create a type dependent CallExpr. The goal is to postpone name
13325       // lookup to instantiation time to be able to search into type dependent
13326       // base classes.
13327       CallExpr *CE =
13328           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13329                            RParenLoc, CurFPFeatureOverrides());
13330       CE->markDependentForPostponedNameLookup();
13331       *Result = CE;
13332       return true;
13333     }
13334   }
13335 
13336   if (CandidateSet->empty())
13337     return false;
13338 
13339   UnbridgedCasts.restore();
13340   return false;
13341 }
13342 
13343 // Guess at what the return type for an unresolvable overload should be.
13344 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13345                                    OverloadCandidateSet::iterator *Best) {
13346   std::optional<QualType> Result;
13347   // Adjust Type after seeing a candidate.
13348   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13349     if (!Candidate.Function)
13350       return;
13351     if (Candidate.Function->isInvalidDecl())
13352       return;
13353     QualType T = Candidate.Function->getReturnType();
13354     if (T.isNull())
13355       return;
13356     if (!Result)
13357       Result = T;
13358     else if (Result != T)
13359       Result = QualType();
13360   };
13361 
13362   // Look for an unambiguous type from a progressively larger subset.
13363   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13364   //
13365   // First, consider only the best candidate.
13366   if (Best && *Best != CS.end())
13367     ConsiderCandidate(**Best);
13368   // Next, consider only viable candidates.
13369   if (!Result)
13370     for (const auto &C : CS)
13371       if (C.Viable)
13372         ConsiderCandidate(C);
13373   // Finally, consider all candidates.
13374   if (!Result)
13375     for (const auto &C : CS)
13376       ConsiderCandidate(C);
13377 
13378   if (!Result)
13379     return QualType();
13380   auto Value = *Result;
13381   if (Value.isNull() || Value->isUndeducedType())
13382     return QualType();
13383   return Value;
13384 }
13385 
13386 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13387 /// the completed call expression. If overload resolution fails, emits
13388 /// diagnostics and returns ExprError()
13389 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13390                                            UnresolvedLookupExpr *ULE,
13391                                            SourceLocation LParenLoc,
13392                                            MultiExprArg Args,
13393                                            SourceLocation RParenLoc,
13394                                            Expr *ExecConfig,
13395                                            OverloadCandidateSet *CandidateSet,
13396                                            OverloadCandidateSet::iterator *Best,
13397                                            OverloadingResult OverloadResult,
13398                                            bool AllowTypoCorrection) {
13399   switch (OverloadResult) {
13400   case OR_Success: {
13401     FunctionDecl *FDecl = (*Best)->Function;
13402     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13403     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13404       return ExprError();
13405     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13406     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13407                                          ExecConfig, /*IsExecConfig=*/false,
13408                                          (*Best)->IsADLCandidate);
13409   }
13410 
13411   case OR_No_Viable_Function: {
13412     // Try to recover by looking for viable functions which the user might
13413     // have meant to call.
13414     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13415                                                 Args, RParenLoc,
13416                                                 CandidateSet->empty(),
13417                                                 AllowTypoCorrection);
13418     if (Recovery.isInvalid() || Recovery.isUsable())
13419       return Recovery;
13420 
13421     // If the user passes in a function that we can't take the address of, we
13422     // generally end up emitting really bad error messages. Here, we attempt to
13423     // emit better ones.
13424     for (const Expr *Arg : Args) {
13425       if (!Arg->getType()->isFunctionType())
13426         continue;
13427       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13428         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13429         if (FD &&
13430             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13431                                                        Arg->getExprLoc()))
13432           return ExprError();
13433       }
13434     }
13435 
13436     CandidateSet->NoteCandidates(
13437         PartialDiagnosticAt(
13438             Fn->getBeginLoc(),
13439             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13440                 << ULE->getName() << Fn->getSourceRange()),
13441         SemaRef, OCD_AllCandidates, Args);
13442     break;
13443   }
13444 
13445   case OR_Ambiguous:
13446     CandidateSet->NoteCandidates(
13447         PartialDiagnosticAt(Fn->getBeginLoc(),
13448                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13449                                 << ULE->getName() << Fn->getSourceRange()),
13450         SemaRef, OCD_AmbiguousCandidates, Args);
13451     break;
13452 
13453   case OR_Deleted: {
13454     CandidateSet->NoteCandidates(
13455         PartialDiagnosticAt(Fn->getBeginLoc(),
13456                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13457                                 << ULE->getName() << Fn->getSourceRange()),
13458         SemaRef, OCD_AllCandidates, Args);
13459 
13460     // We emitted an error for the unavailable/deleted function call but keep
13461     // the call in the AST.
13462     FunctionDecl *FDecl = (*Best)->Function;
13463     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13464     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13465                                          ExecConfig, /*IsExecConfig=*/false,
13466                                          (*Best)->IsADLCandidate);
13467   }
13468   }
13469 
13470   // Overload resolution failed, try to recover.
13471   SmallVector<Expr *, 8> SubExprs = {Fn};
13472   SubExprs.append(Args.begin(), Args.end());
13473   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13474                                     chooseRecoveryType(*CandidateSet, Best));
13475 }
13476 
13477 static void markUnaddressableCandidatesUnviable(Sema &S,
13478                                                 OverloadCandidateSet &CS) {
13479   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13480     if (I->Viable &&
13481         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13482       I->Viable = false;
13483       I->FailureKind = ovl_fail_addr_not_available;
13484     }
13485   }
13486 }
13487 
13488 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13489 /// (which eventually refers to the declaration Func) and the call
13490 /// arguments Args/NumArgs, attempt to resolve the function call down
13491 /// to a specific function. If overload resolution succeeds, returns
13492 /// the call expression produced by overload resolution.
13493 /// Otherwise, emits diagnostics and returns ExprError.
13494 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13495                                          UnresolvedLookupExpr *ULE,
13496                                          SourceLocation LParenLoc,
13497                                          MultiExprArg Args,
13498                                          SourceLocation RParenLoc,
13499                                          Expr *ExecConfig,
13500                                          bool AllowTypoCorrection,
13501                                          bool CalleesAddressIsTaken) {
13502   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13503                                     OverloadCandidateSet::CSK_Normal);
13504   ExprResult result;
13505 
13506   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13507                              &result))
13508     return result;
13509 
13510   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13511   // functions that aren't addressible are considered unviable.
13512   if (CalleesAddressIsTaken)
13513     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13514 
13515   OverloadCandidateSet::iterator Best;
13516   OverloadingResult OverloadResult =
13517       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13518 
13519   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13520                                   ExecConfig, &CandidateSet, &Best,
13521                                   OverloadResult, AllowTypoCorrection);
13522 }
13523 
13524 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13525   return Functions.size() > 1 ||
13526          (Functions.size() == 1 &&
13527           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13528 }
13529 
13530 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13531                                             NestedNameSpecifierLoc NNSLoc,
13532                                             DeclarationNameInfo DNI,
13533                                             const UnresolvedSetImpl &Fns,
13534                                             bool PerformADL) {
13535   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13536                                       PerformADL, IsOverloaded(Fns),
13537                                       Fns.begin(), Fns.end());
13538 }
13539 
13540 /// Create a unary operation that may resolve to an overloaded
13541 /// operator.
13542 ///
13543 /// \param OpLoc The location of the operator itself (e.g., '*').
13544 ///
13545 /// \param Opc The UnaryOperatorKind that describes this operator.
13546 ///
13547 /// \param Fns The set of non-member functions that will be
13548 /// considered by overload resolution. The caller needs to build this
13549 /// set based on the context using, e.g.,
13550 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13551 /// set should not contain any member functions; those will be added
13552 /// by CreateOverloadedUnaryOp().
13553 ///
13554 /// \param Input The input argument.
13555 ExprResult
13556 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13557                               const UnresolvedSetImpl &Fns,
13558                               Expr *Input, bool PerformADL) {
13559   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13560   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13561   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13562   // TODO: provide better source location info.
13563   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13564 
13565   if (checkPlaceholderForOverload(*this, Input))
13566     return ExprError();
13567 
13568   Expr *Args[2] = { Input, nullptr };
13569   unsigned NumArgs = 1;
13570 
13571   // For post-increment and post-decrement, add the implicit '0' as
13572   // the second argument, so that we know this is a post-increment or
13573   // post-decrement.
13574   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13575     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13576     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13577                                      SourceLocation());
13578     NumArgs = 2;
13579   }
13580 
13581   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13582 
13583   if (Input->isTypeDependent()) {
13584     if (Fns.empty())
13585       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13586                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13587                                    CurFPFeatureOverrides());
13588 
13589     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13590     ExprResult Fn = CreateUnresolvedLookupExpr(
13591         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13592     if (Fn.isInvalid())
13593       return ExprError();
13594     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13595                                        Context.DependentTy, VK_PRValue, OpLoc,
13596                                        CurFPFeatureOverrides());
13597   }
13598 
13599   // Build an empty overload set.
13600   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13601 
13602   // Add the candidates from the given function set.
13603   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13604 
13605   // Add operator candidates that are member functions.
13606   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13607 
13608   // Add candidates from ADL.
13609   if (PerformADL) {
13610     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13611                                          /*ExplicitTemplateArgs*/nullptr,
13612                                          CandidateSet);
13613   }
13614 
13615   // Add builtin operator candidates.
13616   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13617 
13618   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13619 
13620   // Perform overload resolution.
13621   OverloadCandidateSet::iterator Best;
13622   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13623   case OR_Success: {
13624     // We found a built-in operator or an overloaded operator.
13625     FunctionDecl *FnDecl = Best->Function;
13626 
13627     if (FnDecl) {
13628       Expr *Base = nullptr;
13629       // We matched an overloaded operator. Build a call to that
13630       // operator.
13631 
13632       // Convert the arguments.
13633       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13634         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13635 
13636         ExprResult InputRes =
13637           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13638                                               Best->FoundDecl, Method);
13639         if (InputRes.isInvalid())
13640           return ExprError();
13641         Base = Input = InputRes.get();
13642       } else {
13643         // Convert the arguments.
13644         ExprResult InputInit
13645           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13646                                                       Context,
13647                                                       FnDecl->getParamDecl(0)),
13648                                       SourceLocation(),
13649                                       Input);
13650         if (InputInit.isInvalid())
13651           return ExprError();
13652         Input = InputInit.get();
13653       }
13654 
13655       // Build the actual expression node.
13656       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13657                                                 Base, HadMultipleCandidates,
13658                                                 OpLoc);
13659       if (FnExpr.isInvalid())
13660         return ExprError();
13661 
13662       // Determine the result type.
13663       QualType ResultTy = FnDecl->getReturnType();
13664       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13665       ResultTy = ResultTy.getNonLValueExprType(Context);
13666 
13667       Args[0] = Input;
13668       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13669           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13670           CurFPFeatureOverrides(), Best->IsADLCandidate);
13671 
13672       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13673         return ExprError();
13674 
13675       if (CheckFunctionCall(FnDecl, TheCall,
13676                             FnDecl->getType()->castAs<FunctionProtoType>()))
13677         return ExprError();
13678       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13679     } else {
13680       // We matched a built-in operator. Convert the arguments, then
13681       // break out so that we will build the appropriate built-in
13682       // operator node.
13683       ExprResult InputRes = PerformImplicitConversion(
13684           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13685           CCK_ForBuiltinOverloadedOp);
13686       if (InputRes.isInvalid())
13687         return ExprError();
13688       Input = InputRes.get();
13689       break;
13690     }
13691   }
13692 
13693   case OR_No_Viable_Function:
13694     // This is an erroneous use of an operator which can be overloaded by
13695     // a non-member function. Check for non-member operators which were
13696     // defined too late to be candidates.
13697     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13698       // FIXME: Recover by calling the found function.
13699       return ExprError();
13700 
13701     // No viable function; fall through to handling this as a
13702     // built-in operator, which will produce an error message for us.
13703     break;
13704 
13705   case OR_Ambiguous:
13706     CandidateSet.NoteCandidates(
13707         PartialDiagnosticAt(OpLoc,
13708                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13709                                 << UnaryOperator::getOpcodeStr(Opc)
13710                                 << Input->getType() << Input->getSourceRange()),
13711         *this, OCD_AmbiguousCandidates, ArgsArray,
13712         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13713     return ExprError();
13714 
13715   case OR_Deleted:
13716     CandidateSet.NoteCandidates(
13717         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13718                                        << UnaryOperator::getOpcodeStr(Opc)
13719                                        << Input->getSourceRange()),
13720         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13721         OpLoc);
13722     return ExprError();
13723   }
13724 
13725   // Either we found no viable overloaded operator or we matched a
13726   // built-in operator. In either case, fall through to trying to
13727   // build a built-in operation.
13728   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13729 }
13730 
13731 /// Perform lookup for an overloaded binary operator.
13732 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13733                                  OverloadedOperatorKind Op,
13734                                  const UnresolvedSetImpl &Fns,
13735                                  ArrayRef<Expr *> Args, bool PerformADL) {
13736   SourceLocation OpLoc = CandidateSet.getLocation();
13737 
13738   OverloadedOperatorKind ExtraOp =
13739       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13740           ? getRewrittenOverloadedOperator(Op)
13741           : OO_None;
13742 
13743   // Add the candidates from the given function set. This also adds the
13744   // rewritten candidates using these functions if necessary.
13745   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13746 
13747   // Add operator candidates that are member functions.
13748   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13749   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
13750     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13751                                 OverloadCandidateParamOrder::Reversed);
13752 
13753   // In C++20, also add any rewritten member candidates.
13754   if (ExtraOp) {
13755     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13756     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
13757       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13758                                   CandidateSet,
13759                                   OverloadCandidateParamOrder::Reversed);
13760   }
13761 
13762   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13763   // performed for an assignment operator (nor for operator[] nor operator->,
13764   // which don't get here).
13765   if (Op != OO_Equal && PerformADL) {
13766     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13767     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13768                                          /*ExplicitTemplateArgs*/ nullptr,
13769                                          CandidateSet);
13770     if (ExtraOp) {
13771       DeclarationName ExtraOpName =
13772           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13773       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13774                                            /*ExplicitTemplateArgs*/ nullptr,
13775                                            CandidateSet);
13776     }
13777   }
13778 
13779   // Add builtin operator candidates.
13780   //
13781   // FIXME: We don't add any rewritten candidates here. This is strictly
13782   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13783   // resulting in our selecting a rewritten builtin candidate. For example:
13784   //
13785   //   enum class E { e };
13786   //   bool operator!=(E, E) requires false;
13787   //   bool k = E::e != E::e;
13788   //
13789   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13790   // it seems unreasonable to consider rewritten builtin candidates. A core
13791   // issue has been filed proposing to removed this requirement.
13792   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13793 }
13794 
13795 /// Create a binary operation that may resolve to an overloaded
13796 /// operator.
13797 ///
13798 /// \param OpLoc The location of the operator itself (e.g., '+').
13799 ///
13800 /// \param Opc The BinaryOperatorKind that describes this operator.
13801 ///
13802 /// \param Fns The set of non-member functions that will be
13803 /// considered by overload resolution. The caller needs to build this
13804 /// set based on the context using, e.g.,
13805 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13806 /// set should not contain any member functions; those will be added
13807 /// by CreateOverloadedBinOp().
13808 ///
13809 /// \param LHS Left-hand argument.
13810 /// \param RHS Right-hand argument.
13811 /// \param PerformADL Whether to consider operator candidates found by ADL.
13812 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13813 ///        C++20 operator rewrites.
13814 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13815 ///        the function in question. Such a function is never a candidate in
13816 ///        our overload resolution. This also enables synthesizing a three-way
13817 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13818 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13819                                        BinaryOperatorKind Opc,
13820                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13821                                        Expr *RHS, bool PerformADL,
13822                                        bool AllowRewrittenCandidates,
13823                                        FunctionDecl *DefaultedFn) {
13824   Expr *Args[2] = { LHS, RHS };
13825   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13826 
13827   if (!getLangOpts().CPlusPlus20)
13828     AllowRewrittenCandidates = false;
13829 
13830   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13831 
13832   // If either side is type-dependent, create an appropriate dependent
13833   // expression.
13834   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13835     if (Fns.empty()) {
13836       // If there are no functions to store, just build a dependent
13837       // BinaryOperator or CompoundAssignment.
13838       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13839         return CompoundAssignOperator::Create(
13840             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13841             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13842             Context.DependentTy);
13843       return BinaryOperator::Create(
13844           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13845           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13846     }
13847 
13848     // FIXME: save results of ADL from here?
13849     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13850     // TODO: provide better source location info in DNLoc component.
13851     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13852     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13853     ExprResult Fn = CreateUnresolvedLookupExpr(
13854         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13855     if (Fn.isInvalid())
13856       return ExprError();
13857     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13858                                        Context.DependentTy, VK_PRValue, OpLoc,
13859                                        CurFPFeatureOverrides());
13860   }
13861 
13862   // Always do placeholder-like conversions on the RHS.
13863   if (checkPlaceholderForOverload(*this, Args[1]))
13864     return ExprError();
13865 
13866   // Do placeholder-like conversion on the LHS; note that we should
13867   // not get here with a PseudoObject LHS.
13868   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13869   if (checkPlaceholderForOverload(*this, Args[0]))
13870     return ExprError();
13871 
13872   // If this is the assignment operator, we only perform overload resolution
13873   // if the left-hand side is a class or enumeration type. This is actually
13874   // a hack. The standard requires that we do overload resolution between the
13875   // various built-in candidates, but as DR507 points out, this can lead to
13876   // problems. So we do it this way, which pretty much follows what GCC does.
13877   // Note that we go the traditional code path for compound assignment forms.
13878   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13879     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13880 
13881   // If this is the .* operator, which is not overloadable, just
13882   // create a built-in binary operator.
13883   if (Opc == BO_PtrMemD)
13884     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13885 
13886   // Build the overload set.
13887   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
13888                                     OverloadCandidateSet::OperatorRewriteInfo(
13889                                         Op, OpLoc, AllowRewrittenCandidates));
13890   if (DefaultedFn)
13891     CandidateSet.exclude(DefaultedFn);
13892   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13893 
13894   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13895 
13896   // Perform overload resolution.
13897   OverloadCandidateSet::iterator Best;
13898   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13899     case OR_Success: {
13900       // We found a built-in operator or an overloaded operator.
13901       FunctionDecl *FnDecl = Best->Function;
13902 
13903       bool IsReversed = Best->isReversed();
13904       if (IsReversed)
13905         std::swap(Args[0], Args[1]);
13906 
13907       if (FnDecl) {
13908         Expr *Base = nullptr;
13909         // We matched an overloaded operator. Build a call to that
13910         // operator.
13911 
13912         OverloadedOperatorKind ChosenOp =
13913             FnDecl->getDeclName().getCXXOverloadedOperator();
13914 
13915         // C++2a [over.match.oper]p9:
13916         //   If a rewritten operator== candidate is selected by overload
13917         //   resolution for an operator@, its return type shall be cv bool
13918         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13919             !FnDecl->getReturnType()->isBooleanType()) {
13920           bool IsExtension =
13921               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13922           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13923                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13924               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13925               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13926           Diag(FnDecl->getLocation(), diag::note_declared_at);
13927           if (!IsExtension)
13928             return ExprError();
13929         }
13930 
13931         if (AllowRewrittenCandidates && !IsReversed &&
13932             CandidateSet.getRewriteInfo().isReversible()) {
13933           // We could have reversed this operator, but didn't. Check if some
13934           // reversed form was a viable candidate, and if so, if it had a
13935           // better conversion for either parameter. If so, this call is
13936           // formally ambiguous, and allowing it is an extension.
13937           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13938           for (OverloadCandidate &Cand : CandidateSet) {
13939             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13940                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13941               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13942                 if (CompareImplicitConversionSequences(
13943                         *this, OpLoc, Cand.Conversions[ArgIdx],
13944                         Best->Conversions[ArgIdx]) ==
13945                     ImplicitConversionSequence::Better) {
13946                   AmbiguousWith.push_back(Cand.Function);
13947                   break;
13948                 }
13949               }
13950             }
13951           }
13952 
13953           if (!AmbiguousWith.empty()) {
13954             bool AmbiguousWithSelf =
13955                 AmbiguousWith.size() == 1 &&
13956                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13957             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13958                 << BinaryOperator::getOpcodeStr(Opc)
13959                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13960                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13961             if (AmbiguousWithSelf) {
13962               Diag(FnDecl->getLocation(),
13963                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13964               // Mark member== const or provide matching != to disallow reversed
13965               // args. Eg.
13966               // struct S { bool operator==(const S&); };
13967               // S()==S();
13968               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
13969                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
13970                     !MD->isConst() &&
13971                     Context.hasSameUnqualifiedType(
13972                         MD->getThisObjectType(),
13973                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
13974                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
13975                                                    Args[0]->getType()) &&
13976                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
13977                                                    Args[1]->getType()))
13978                   Diag(FnDecl->getLocation(),
13979                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
13980             } else {
13981               Diag(FnDecl->getLocation(),
13982                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13983               for (auto *F : AmbiguousWith)
13984                 Diag(F->getLocation(),
13985                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13986             }
13987           }
13988         }
13989 
13990         // Convert the arguments.
13991         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13992           // Best->Access is only meaningful for class members.
13993           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13994 
13995           ExprResult Arg1 =
13996             PerformCopyInitialization(
13997               InitializedEntity::InitializeParameter(Context,
13998                                                      FnDecl->getParamDecl(0)),
13999               SourceLocation(), Args[1]);
14000           if (Arg1.isInvalid())
14001             return ExprError();
14002 
14003           ExprResult Arg0 =
14004             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14005                                                 Best->FoundDecl, Method);
14006           if (Arg0.isInvalid())
14007             return ExprError();
14008           Base = Args[0] = Arg0.getAs<Expr>();
14009           Args[1] = RHS = Arg1.getAs<Expr>();
14010         } else {
14011           // Convert the arguments.
14012           ExprResult Arg0 = PerformCopyInitialization(
14013             InitializedEntity::InitializeParameter(Context,
14014                                                    FnDecl->getParamDecl(0)),
14015             SourceLocation(), Args[0]);
14016           if (Arg0.isInvalid())
14017             return ExprError();
14018 
14019           ExprResult Arg1 =
14020             PerformCopyInitialization(
14021               InitializedEntity::InitializeParameter(Context,
14022                                                      FnDecl->getParamDecl(1)),
14023               SourceLocation(), Args[1]);
14024           if (Arg1.isInvalid())
14025             return ExprError();
14026           Args[0] = LHS = Arg0.getAs<Expr>();
14027           Args[1] = RHS = Arg1.getAs<Expr>();
14028         }
14029 
14030         // Build the actual expression node.
14031         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14032                                                   Best->FoundDecl, Base,
14033                                                   HadMultipleCandidates, OpLoc);
14034         if (FnExpr.isInvalid())
14035           return ExprError();
14036 
14037         // Determine the result type.
14038         QualType ResultTy = FnDecl->getReturnType();
14039         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14040         ResultTy = ResultTy.getNonLValueExprType(Context);
14041 
14042         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14043             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14044             CurFPFeatureOverrides(), Best->IsADLCandidate);
14045 
14046         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14047                                 FnDecl))
14048           return ExprError();
14049 
14050         ArrayRef<const Expr *> ArgsArray(Args, 2);
14051         const Expr *ImplicitThis = nullptr;
14052         // Cut off the implicit 'this'.
14053         if (isa<CXXMethodDecl>(FnDecl)) {
14054           ImplicitThis = ArgsArray[0];
14055           ArgsArray = ArgsArray.slice(1);
14056         }
14057 
14058         // Check for a self move.
14059         if (Op == OO_Equal)
14060           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14061 
14062         if (ImplicitThis) {
14063           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14064           QualType ThisTypeFromDecl = Context.getPointerType(
14065               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
14066 
14067           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14068                             ThisTypeFromDecl);
14069         }
14070 
14071         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14072                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14073                   VariadicDoesNotApply);
14074 
14075         ExprResult R = MaybeBindToTemporary(TheCall);
14076         if (R.isInvalid())
14077           return ExprError();
14078 
14079         R = CheckForImmediateInvocation(R, FnDecl);
14080         if (R.isInvalid())
14081           return ExprError();
14082 
14083         // For a rewritten candidate, we've already reversed the arguments
14084         // if needed. Perform the rest of the rewrite now.
14085         if ((Best->RewriteKind & CRK_DifferentOperator) ||
14086             (Op == OO_Spaceship && IsReversed)) {
14087           if (Op == OO_ExclaimEqual) {
14088             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14089             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14090           } else {
14091             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14092             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14093             Expr *ZeroLiteral =
14094                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14095 
14096             Sema::CodeSynthesisContext Ctx;
14097             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14098             Ctx.Entity = FnDecl;
14099             pushCodeSynthesisContext(Ctx);
14100 
14101             R = CreateOverloadedBinOp(
14102                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14103                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14104                 /*AllowRewrittenCandidates=*/false);
14105 
14106             popCodeSynthesisContext();
14107           }
14108           if (R.isInvalid())
14109             return ExprError();
14110         } else {
14111           assert(ChosenOp == Op && "unexpected operator name");
14112         }
14113 
14114         // Make a note in the AST if we did any rewriting.
14115         if (Best->RewriteKind != CRK_None)
14116           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14117 
14118         return R;
14119       } else {
14120         // We matched a built-in operator. Convert the arguments, then
14121         // break out so that we will build the appropriate built-in
14122         // operator node.
14123         ExprResult ArgsRes0 = PerformImplicitConversion(
14124             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14125             AA_Passing, CCK_ForBuiltinOverloadedOp);
14126         if (ArgsRes0.isInvalid())
14127           return ExprError();
14128         Args[0] = ArgsRes0.get();
14129 
14130         ExprResult ArgsRes1 = PerformImplicitConversion(
14131             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14132             AA_Passing, CCK_ForBuiltinOverloadedOp);
14133         if (ArgsRes1.isInvalid())
14134           return ExprError();
14135         Args[1] = ArgsRes1.get();
14136         break;
14137       }
14138     }
14139 
14140     case OR_No_Viable_Function: {
14141       // C++ [over.match.oper]p9:
14142       //   If the operator is the operator , [...] and there are no
14143       //   viable functions, then the operator is assumed to be the
14144       //   built-in operator and interpreted according to clause 5.
14145       if (Opc == BO_Comma)
14146         break;
14147 
14148       // When defaulting an 'operator<=>', we can try to synthesize a three-way
14149       // compare result using '==' and '<'.
14150       if (DefaultedFn && Opc == BO_Cmp) {
14151         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14152                                                           Args[1], DefaultedFn);
14153         if (E.isInvalid() || E.isUsable())
14154           return E;
14155       }
14156 
14157       // For class as left operand for assignment or compound assignment
14158       // operator do not fall through to handling in built-in, but report that
14159       // no overloaded assignment operator found
14160       ExprResult Result = ExprError();
14161       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14162       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14163                                                    Args, OpLoc);
14164       DeferDiagsRAII DDR(*this,
14165                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14166       if (Args[0]->getType()->isRecordType() &&
14167           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14168         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14169              << BinaryOperator::getOpcodeStr(Opc)
14170              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14171         if (Args[0]->getType()->isIncompleteType()) {
14172           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14173             << Args[0]->getType()
14174             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14175         }
14176       } else {
14177         // This is an erroneous use of an operator which can be overloaded by
14178         // a non-member function. Check for non-member operators which were
14179         // defined too late to be candidates.
14180         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14181           // FIXME: Recover by calling the found function.
14182           return ExprError();
14183 
14184         // No viable function; try to create a built-in operation, which will
14185         // produce an error. Then, show the non-viable candidates.
14186         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14187       }
14188       assert(Result.isInvalid() &&
14189              "C++ binary operator overloading is missing candidates!");
14190       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14191       return Result;
14192     }
14193 
14194     case OR_Ambiguous:
14195       CandidateSet.NoteCandidates(
14196           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14197                                          << BinaryOperator::getOpcodeStr(Opc)
14198                                          << Args[0]->getType()
14199                                          << Args[1]->getType()
14200                                          << Args[0]->getSourceRange()
14201                                          << Args[1]->getSourceRange()),
14202           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14203           OpLoc);
14204       return ExprError();
14205 
14206     case OR_Deleted:
14207       if (isImplicitlyDeleted(Best->Function)) {
14208         FunctionDecl *DeletedFD = Best->Function;
14209         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14210         if (DFK.isSpecialMember()) {
14211           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14212             << Args[0]->getType() << DFK.asSpecialMember();
14213         } else {
14214           assert(DFK.isComparison());
14215           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14216             << Args[0]->getType() << DeletedFD;
14217         }
14218 
14219         // The user probably meant to call this special member. Just
14220         // explain why it's deleted.
14221         NoteDeletedFunction(DeletedFD);
14222         return ExprError();
14223       }
14224       CandidateSet.NoteCandidates(
14225           PartialDiagnosticAt(
14226               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14227                          << getOperatorSpelling(Best->Function->getDeclName()
14228                                                     .getCXXOverloadedOperator())
14229                          << Args[0]->getSourceRange()
14230                          << Args[1]->getSourceRange()),
14231           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14232           OpLoc);
14233       return ExprError();
14234   }
14235 
14236   // We matched a built-in operator; build it.
14237   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14238 }
14239 
14240 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14241     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14242     FunctionDecl *DefaultedFn) {
14243   const ComparisonCategoryInfo *Info =
14244       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14245   // If we're not producing a known comparison category type, we can't
14246   // synthesize a three-way comparison. Let the caller diagnose this.
14247   if (!Info)
14248     return ExprResult((Expr*)nullptr);
14249 
14250   // If we ever want to perform this synthesis more generally, we will need to
14251   // apply the temporary materialization conversion to the operands.
14252   assert(LHS->isGLValue() && RHS->isGLValue() &&
14253          "cannot use prvalue expressions more than once");
14254   Expr *OrigLHS = LHS;
14255   Expr *OrigRHS = RHS;
14256 
14257   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14258   // each of them multiple times below.
14259   LHS = new (Context)
14260       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14261                       LHS->getObjectKind(), LHS);
14262   RHS = new (Context)
14263       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14264                       RHS->getObjectKind(), RHS);
14265 
14266   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14267                                         DefaultedFn);
14268   if (Eq.isInvalid())
14269     return ExprError();
14270 
14271   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14272                                           true, DefaultedFn);
14273   if (Less.isInvalid())
14274     return ExprError();
14275 
14276   ExprResult Greater;
14277   if (Info->isPartial()) {
14278     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14279                                     DefaultedFn);
14280     if (Greater.isInvalid())
14281       return ExprError();
14282   }
14283 
14284   // Form the list of comparisons we're going to perform.
14285   struct Comparison {
14286     ExprResult Cmp;
14287     ComparisonCategoryResult Result;
14288   } Comparisons[4] =
14289   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14290                           : ComparisonCategoryResult::Equivalent},
14291     {Less, ComparisonCategoryResult::Less},
14292     {Greater, ComparisonCategoryResult::Greater},
14293     {ExprResult(), ComparisonCategoryResult::Unordered},
14294   };
14295 
14296   int I = Info->isPartial() ? 3 : 2;
14297 
14298   // Combine the comparisons with suitable conditional expressions.
14299   ExprResult Result;
14300   for (; I >= 0; --I) {
14301     // Build a reference to the comparison category constant.
14302     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14303     // FIXME: Missing a constant for a comparison category. Diagnose this?
14304     if (!VI)
14305       return ExprResult((Expr*)nullptr);
14306     ExprResult ThisResult =
14307         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14308     if (ThisResult.isInvalid())
14309       return ExprError();
14310 
14311     // Build a conditional unless this is the final case.
14312     if (Result.get()) {
14313       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14314                                   ThisResult.get(), Result.get());
14315       if (Result.isInvalid())
14316         return ExprError();
14317     } else {
14318       Result = ThisResult;
14319     }
14320   }
14321 
14322   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14323   // bind the OpaqueValueExprs before they're (repeatedly) used.
14324   Expr *SyntacticForm = BinaryOperator::Create(
14325       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14326       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14327       CurFPFeatureOverrides());
14328   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14329   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14330 }
14331 
14332 static bool PrepareArgumentsForCallToObjectOfClassType(
14333     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14334     MultiExprArg Args, SourceLocation LParenLoc) {
14335 
14336   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14337   unsigned NumParams = Proto->getNumParams();
14338   unsigned NumArgsSlots =
14339       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14340   // Build the full argument list for the method call (the implicit object
14341   // parameter is placed at the beginning of the list).
14342   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14343   bool IsError = false;
14344   // Initialize the implicit object parameter.
14345   // Check the argument types.
14346   for (unsigned i = 0; i != NumParams; i++) {
14347     Expr *Arg;
14348     if (i < Args.size()) {
14349       Arg = Args[i];
14350       ExprResult InputInit =
14351           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14352                                           S.Context, Method->getParamDecl(i)),
14353                                       SourceLocation(), Arg);
14354       IsError |= InputInit.isInvalid();
14355       Arg = InputInit.getAs<Expr>();
14356     } else {
14357       ExprResult DefArg =
14358           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14359       if (DefArg.isInvalid()) {
14360         IsError = true;
14361         break;
14362       }
14363       Arg = DefArg.getAs<Expr>();
14364     }
14365 
14366     MethodArgs.push_back(Arg);
14367   }
14368   return IsError;
14369 }
14370 
14371 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14372                                                     SourceLocation RLoc,
14373                                                     Expr *Base,
14374                                                     MultiExprArg ArgExpr) {
14375   SmallVector<Expr *, 2> Args;
14376   Args.push_back(Base);
14377   for (auto *e : ArgExpr) {
14378     Args.push_back(e);
14379   }
14380   DeclarationName OpName =
14381       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14382 
14383   SourceRange Range = ArgExpr.empty()
14384                           ? SourceRange{}
14385                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14386                                         ArgExpr.back()->getEndLoc());
14387 
14388   // If either side is type-dependent, create an appropriate dependent
14389   // expression.
14390   if (Expr::hasAnyTypeDependentArguments(Args)) {
14391 
14392     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14393     // CHECKME: no 'operator' keyword?
14394     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14395     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14396     ExprResult Fn = CreateUnresolvedLookupExpr(
14397         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14398     if (Fn.isInvalid())
14399       return ExprError();
14400     // Can't add any actual overloads yet
14401 
14402     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14403                                        Context.DependentTy, VK_PRValue, RLoc,
14404                                        CurFPFeatureOverrides());
14405   }
14406 
14407   // Handle placeholders
14408   UnbridgedCastsSet UnbridgedCasts;
14409   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14410     return ExprError();
14411   }
14412   // Build an empty overload set.
14413   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14414 
14415   // Subscript can only be overloaded as a member function.
14416 
14417   // Add operator candidates that are member functions.
14418   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14419 
14420   // Add builtin operator candidates.
14421   if (Args.size() == 2)
14422     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14423 
14424   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14425 
14426   // Perform overload resolution.
14427   OverloadCandidateSet::iterator Best;
14428   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14429     case OR_Success: {
14430       // We found a built-in operator or an overloaded operator.
14431       FunctionDecl *FnDecl = Best->Function;
14432 
14433       if (FnDecl) {
14434         // We matched an overloaded operator. Build a call to that
14435         // operator.
14436 
14437         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14438 
14439         // Convert the arguments.
14440         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14441         SmallVector<Expr *, 2> MethodArgs;
14442 
14443         // Handle 'this' parameter if the selected function is not static.
14444         if (Method->isInstance()) {
14445           ExprResult Arg0 = PerformObjectArgumentInitialization(
14446               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14447           if (Arg0.isInvalid())
14448             return ExprError();
14449 
14450           MethodArgs.push_back(Arg0.get());
14451         }
14452 
14453         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14454             *this, MethodArgs, Method, ArgExpr, LLoc);
14455         if (IsError)
14456           return ExprError();
14457 
14458         // Build the actual expression node.
14459         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14460         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14461         ExprResult FnExpr = CreateFunctionRefExpr(
14462             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14463             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14464         if (FnExpr.isInvalid())
14465           return ExprError();
14466 
14467         // Determine the result type
14468         QualType ResultTy = FnDecl->getReturnType();
14469         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14470         ResultTy = ResultTy.getNonLValueExprType(Context);
14471 
14472         CallExpr *TheCall;
14473         if (Method->isInstance())
14474           TheCall = CXXOperatorCallExpr::Create(
14475               Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK,
14476               RLoc, CurFPFeatureOverrides());
14477         else
14478           TheCall =
14479               CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
14480                                RLoc, CurFPFeatureOverrides());
14481 
14482         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14483           return ExprError();
14484 
14485         if (CheckFunctionCall(Method, TheCall,
14486                               Method->getType()->castAs<FunctionProtoType>()))
14487           return ExprError();
14488 
14489         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14490                                            FnDecl);
14491       } else {
14492         // We matched a built-in operator. Convert the arguments, then
14493         // break out so that we will build the appropriate built-in
14494         // operator node.
14495         ExprResult ArgsRes0 = PerformImplicitConversion(
14496             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14497             AA_Passing, CCK_ForBuiltinOverloadedOp);
14498         if (ArgsRes0.isInvalid())
14499           return ExprError();
14500         Args[0] = ArgsRes0.get();
14501 
14502         ExprResult ArgsRes1 = PerformImplicitConversion(
14503             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14504             AA_Passing, CCK_ForBuiltinOverloadedOp);
14505         if (ArgsRes1.isInvalid())
14506           return ExprError();
14507         Args[1] = ArgsRes1.get();
14508 
14509         break;
14510       }
14511     }
14512 
14513     case OR_No_Viable_Function: {
14514       PartialDiagnostic PD =
14515           CandidateSet.empty()
14516               ? (PDiag(diag::err_ovl_no_oper)
14517                  << Args[0]->getType() << /*subscript*/ 0
14518                  << Args[0]->getSourceRange() << Range)
14519               : (PDiag(diag::err_ovl_no_viable_subscript)
14520                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14521       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14522                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14523       return ExprError();
14524     }
14525 
14526     case OR_Ambiguous:
14527       if (Args.size() == 2) {
14528         CandidateSet.NoteCandidates(
14529             PartialDiagnosticAt(
14530                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14531                           << "[]" << Args[0]->getType() << Args[1]->getType()
14532                           << Args[0]->getSourceRange() << Range),
14533             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14534       } else {
14535         CandidateSet.NoteCandidates(
14536             PartialDiagnosticAt(LLoc,
14537                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14538                                     << Args[0]->getType()
14539                                     << Args[0]->getSourceRange() << Range),
14540             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14541       }
14542       return ExprError();
14543 
14544     case OR_Deleted:
14545       CandidateSet.NoteCandidates(
14546           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14547                                         << "[]" << Args[0]->getSourceRange()
14548                                         << Range),
14549           *this, OCD_AllCandidates, Args, "[]", LLoc);
14550       return ExprError();
14551     }
14552 
14553   // We matched a built-in operator; build it.
14554   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14555 }
14556 
14557 /// BuildCallToMemberFunction - Build a call to a member
14558 /// function. MemExpr is the expression that refers to the member
14559 /// function (and includes the object parameter), Args/NumArgs are the
14560 /// arguments to the function call (not including the object
14561 /// parameter). The caller needs to validate that the member
14562 /// expression refers to a non-static member function or an overloaded
14563 /// member function.
14564 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14565                                            SourceLocation LParenLoc,
14566                                            MultiExprArg Args,
14567                                            SourceLocation RParenLoc,
14568                                            Expr *ExecConfig, bool IsExecConfig,
14569                                            bool AllowRecovery) {
14570   assert(MemExprE->getType() == Context.BoundMemberTy ||
14571          MemExprE->getType() == Context.OverloadTy);
14572 
14573   // Dig out the member expression. This holds both the object
14574   // argument and the member function we're referring to.
14575   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14576 
14577   // Determine whether this is a call to a pointer-to-member function.
14578   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14579     assert(op->getType() == Context.BoundMemberTy);
14580     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14581 
14582     QualType fnType =
14583       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14584 
14585     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14586     QualType resultType = proto->getCallResultType(Context);
14587     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14588 
14589     // Check that the object type isn't more qualified than the
14590     // member function we're calling.
14591     Qualifiers funcQuals = proto->getMethodQuals();
14592 
14593     QualType objectType = op->getLHS()->getType();
14594     if (op->getOpcode() == BO_PtrMemI)
14595       objectType = objectType->castAs<PointerType>()->getPointeeType();
14596     Qualifiers objectQuals = objectType.getQualifiers();
14597 
14598     Qualifiers difference = objectQuals - funcQuals;
14599     difference.removeObjCGCAttr();
14600     difference.removeAddressSpace();
14601     if (difference) {
14602       std::string qualsString = difference.getAsString();
14603       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14604         << fnType.getUnqualifiedType()
14605         << qualsString
14606         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14607     }
14608 
14609     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14610         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14611         CurFPFeatureOverrides(), proto->getNumParams());
14612 
14613     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14614                             call, nullptr))
14615       return ExprError();
14616 
14617     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14618       return ExprError();
14619 
14620     if (CheckOtherCall(call, proto))
14621       return ExprError();
14622 
14623     return MaybeBindToTemporary(call);
14624   }
14625 
14626   // We only try to build a recovery expr at this level if we can preserve
14627   // the return type, otherwise we return ExprError() and let the caller
14628   // recover.
14629   auto BuildRecoveryExpr = [&](QualType Type) {
14630     if (!AllowRecovery)
14631       return ExprError();
14632     std::vector<Expr *> SubExprs = {MemExprE};
14633     llvm::append_range(SubExprs, Args);
14634     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14635                               Type);
14636   };
14637   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14638     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14639                             RParenLoc, CurFPFeatureOverrides());
14640 
14641   UnbridgedCastsSet UnbridgedCasts;
14642   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14643     return ExprError();
14644 
14645   MemberExpr *MemExpr;
14646   CXXMethodDecl *Method = nullptr;
14647   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14648   NestedNameSpecifier *Qualifier = nullptr;
14649   if (isa<MemberExpr>(NakedMemExpr)) {
14650     MemExpr = cast<MemberExpr>(NakedMemExpr);
14651     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14652     FoundDecl = MemExpr->getFoundDecl();
14653     Qualifier = MemExpr->getQualifier();
14654     UnbridgedCasts.restore();
14655   } else {
14656     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14657     Qualifier = UnresExpr->getQualifier();
14658 
14659     QualType ObjectType = UnresExpr->getBaseType();
14660     Expr::Classification ObjectClassification
14661       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14662                             : UnresExpr->getBase()->Classify(Context);
14663 
14664     // Add overload candidates
14665     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14666                                       OverloadCandidateSet::CSK_Normal);
14667 
14668     // FIXME: avoid copy.
14669     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14670     if (UnresExpr->hasExplicitTemplateArgs()) {
14671       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14672       TemplateArgs = &TemplateArgsBuffer;
14673     }
14674 
14675     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14676            E = UnresExpr->decls_end(); I != E; ++I) {
14677 
14678       NamedDecl *Func = *I;
14679       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14680       if (isa<UsingShadowDecl>(Func))
14681         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14682 
14683 
14684       // Microsoft supports direct constructor calls.
14685       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14686         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14687                              CandidateSet,
14688                              /*SuppressUserConversions*/ false);
14689       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14690         // If explicit template arguments were provided, we can't call a
14691         // non-template member function.
14692         if (TemplateArgs)
14693           continue;
14694 
14695         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14696                            ObjectClassification, Args, CandidateSet,
14697                            /*SuppressUserConversions=*/false);
14698       } else {
14699         AddMethodTemplateCandidate(
14700             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14701             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14702             /*SuppressUserConversions=*/false);
14703       }
14704     }
14705 
14706     DeclarationName DeclName = UnresExpr->getMemberName();
14707 
14708     UnbridgedCasts.restore();
14709 
14710     OverloadCandidateSet::iterator Best;
14711     bool Succeeded = false;
14712     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14713                                             Best)) {
14714     case OR_Success:
14715       Method = cast<CXXMethodDecl>(Best->Function);
14716       FoundDecl = Best->FoundDecl;
14717       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14718       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14719         break;
14720       // If FoundDecl is different from Method (such as if one is a template
14721       // and the other a specialization), make sure DiagnoseUseOfDecl is
14722       // called on both.
14723       // FIXME: This would be more comprehensively addressed by modifying
14724       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14725       // being used.
14726       if (Method != FoundDecl.getDecl() &&
14727           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
14728         break;
14729       Succeeded = true;
14730       break;
14731 
14732     case OR_No_Viable_Function:
14733       CandidateSet.NoteCandidates(
14734           PartialDiagnosticAt(
14735               UnresExpr->getMemberLoc(),
14736               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14737                   << DeclName << MemExprE->getSourceRange()),
14738           *this, OCD_AllCandidates, Args);
14739       break;
14740     case OR_Ambiguous:
14741       CandidateSet.NoteCandidates(
14742           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14743                               PDiag(diag::err_ovl_ambiguous_member_call)
14744                                   << DeclName << MemExprE->getSourceRange()),
14745           *this, OCD_AmbiguousCandidates, Args);
14746       break;
14747     case OR_Deleted:
14748       CandidateSet.NoteCandidates(
14749           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14750                               PDiag(diag::err_ovl_deleted_member_call)
14751                                   << DeclName << MemExprE->getSourceRange()),
14752           *this, OCD_AllCandidates, Args);
14753       break;
14754     }
14755     // Overload resolution fails, try to recover.
14756     if (!Succeeded)
14757       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14758 
14759     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14760 
14761     // If overload resolution picked a static member, build a
14762     // non-member call based on that function.
14763     if (Method->isStatic()) {
14764       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14765                                    ExecConfig, IsExecConfig);
14766     }
14767 
14768     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14769   }
14770 
14771   QualType ResultType = Method->getReturnType();
14772   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14773   ResultType = ResultType.getNonLValueExprType(Context);
14774 
14775   assert(Method && "Member call to something that isn't a method?");
14776   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14777   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14778       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14779       CurFPFeatureOverrides(), Proto->getNumParams());
14780 
14781   // Check for a valid return type.
14782   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14783                           TheCall, Method))
14784     return BuildRecoveryExpr(ResultType);
14785 
14786   // Convert the object argument (for a non-static member function call).
14787   // We only need to do this if there was actually an overload; otherwise
14788   // it was done at lookup.
14789   if (!Method->isStatic()) {
14790     ExprResult ObjectArg =
14791       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14792                                           FoundDecl, Method);
14793     if (ObjectArg.isInvalid())
14794       return ExprError();
14795     MemExpr->setBase(ObjectArg.get());
14796   }
14797 
14798   // Convert the rest of the arguments
14799   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14800                               RParenLoc))
14801     return BuildRecoveryExpr(ResultType);
14802 
14803   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14804 
14805   if (CheckFunctionCall(Method, TheCall, Proto))
14806     return ExprError();
14807 
14808   // In the case the method to call was not selected by the overloading
14809   // resolution process, we still need to handle the enable_if attribute. Do
14810   // that here, so it will not hide previous -- and more relevant -- errors.
14811   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14812     if (const EnableIfAttr *Attr =
14813             CheckEnableIf(Method, LParenLoc, Args, true)) {
14814       Diag(MemE->getMemberLoc(),
14815            diag::err_ovl_no_viable_member_function_in_call)
14816           << Method << Method->getSourceRange();
14817       Diag(Method->getLocation(),
14818            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14819           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14820       return ExprError();
14821     }
14822   }
14823 
14824   if ((isa<CXXConstructorDecl>(CurContext) ||
14825        isa<CXXDestructorDecl>(CurContext)) &&
14826       TheCall->getMethodDecl()->isPure()) {
14827     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14828 
14829     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14830         MemExpr->performsVirtualDispatch(getLangOpts())) {
14831       Diag(MemExpr->getBeginLoc(),
14832            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14833           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14834           << MD->getParent();
14835 
14836       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14837       if (getLangOpts().AppleKext)
14838         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14839             << MD->getParent() << MD->getDeclName();
14840     }
14841   }
14842 
14843   if (CXXDestructorDecl *DD =
14844           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14845     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14846     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14847     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14848                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14849                          MemExpr->getMemberLoc());
14850   }
14851 
14852   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14853                                      TheCall->getMethodDecl());
14854 }
14855 
14856 /// BuildCallToObjectOfClassType - Build a call to an object of class
14857 /// type (C++ [over.call.object]), which can end up invoking an
14858 /// overloaded function call operator (@c operator()) or performing a
14859 /// user-defined conversion on the object argument.
14860 ExprResult
14861 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14862                                    SourceLocation LParenLoc,
14863                                    MultiExprArg Args,
14864                                    SourceLocation RParenLoc) {
14865   if (checkPlaceholderForOverload(*this, Obj))
14866     return ExprError();
14867   ExprResult Object = Obj;
14868 
14869   UnbridgedCastsSet UnbridgedCasts;
14870   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14871     return ExprError();
14872 
14873   assert(Object.get()->getType()->isRecordType() &&
14874          "Requires object type argument");
14875 
14876   // C++ [over.call.object]p1:
14877   //  If the primary-expression E in the function call syntax
14878   //  evaluates to a class object of type "cv T", then the set of
14879   //  candidate functions includes at least the function call
14880   //  operators of T. The function call operators of T are obtained by
14881   //  ordinary lookup of the name operator() in the context of
14882   //  (E).operator().
14883   OverloadCandidateSet CandidateSet(LParenLoc,
14884                                     OverloadCandidateSet::CSK_Operator);
14885   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14886 
14887   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14888                           diag::err_incomplete_object_call, Object.get()))
14889     return true;
14890 
14891   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14892   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14893   LookupQualifiedName(R, Record->getDecl());
14894   R.suppressDiagnostics();
14895 
14896   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14897        Oper != OperEnd; ++Oper) {
14898     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14899                        Object.get()->Classify(Context), Args, CandidateSet,
14900                        /*SuppressUserConversion=*/false);
14901   }
14902 
14903   // C++ [over.call.object]p2:
14904   //   In addition, for each (non-explicit in C++0x) conversion function
14905   //   declared in T of the form
14906   //
14907   //        operator conversion-type-id () cv-qualifier;
14908   //
14909   //   where cv-qualifier is the same cv-qualification as, or a
14910   //   greater cv-qualification than, cv, and where conversion-type-id
14911   //   denotes the type "pointer to function of (P1,...,Pn) returning
14912   //   R", or the type "reference to pointer to function of
14913   //   (P1,...,Pn) returning R", or the type "reference to function
14914   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14915   //   is also considered as a candidate function. Similarly,
14916   //   surrogate call functions are added to the set of candidate
14917   //   functions for each conversion function declared in an
14918   //   accessible base class provided the function is not hidden
14919   //   within T by another intervening declaration.
14920   const auto &Conversions =
14921       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14922   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14923     NamedDecl *D = *I;
14924     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14925     if (isa<UsingShadowDecl>(D))
14926       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14927 
14928     // Skip over templated conversion functions; they aren't
14929     // surrogates.
14930     if (isa<FunctionTemplateDecl>(D))
14931       continue;
14932 
14933     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14934     if (!Conv->isExplicit()) {
14935       // Strip the reference type (if any) and then the pointer type (if
14936       // any) to get down to what might be a function type.
14937       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14938       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14939         ConvType = ConvPtrType->getPointeeType();
14940 
14941       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14942       {
14943         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14944                               Object.get(), Args, CandidateSet);
14945       }
14946     }
14947   }
14948 
14949   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14950 
14951   // Perform overload resolution.
14952   OverloadCandidateSet::iterator Best;
14953   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14954                                           Best)) {
14955   case OR_Success:
14956     // Overload resolution succeeded; we'll build the appropriate call
14957     // below.
14958     break;
14959 
14960   case OR_No_Viable_Function: {
14961     PartialDiagnostic PD =
14962         CandidateSet.empty()
14963             ? (PDiag(diag::err_ovl_no_oper)
14964                << Object.get()->getType() << /*call*/ 1
14965                << Object.get()->getSourceRange())
14966             : (PDiag(diag::err_ovl_no_viable_object_call)
14967                << Object.get()->getType() << Object.get()->getSourceRange());
14968     CandidateSet.NoteCandidates(
14969         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14970         OCD_AllCandidates, Args);
14971     break;
14972   }
14973   case OR_Ambiguous:
14974     CandidateSet.NoteCandidates(
14975         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14976                             PDiag(diag::err_ovl_ambiguous_object_call)
14977                                 << Object.get()->getType()
14978                                 << Object.get()->getSourceRange()),
14979         *this, OCD_AmbiguousCandidates, Args);
14980     break;
14981 
14982   case OR_Deleted:
14983     CandidateSet.NoteCandidates(
14984         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14985                             PDiag(diag::err_ovl_deleted_object_call)
14986                                 << Object.get()->getType()
14987                                 << Object.get()->getSourceRange()),
14988         *this, OCD_AllCandidates, Args);
14989     break;
14990   }
14991 
14992   if (Best == CandidateSet.end())
14993     return true;
14994 
14995   UnbridgedCasts.restore();
14996 
14997   if (Best->Function == nullptr) {
14998     // Since there is no function declaration, this is one of the
14999     // surrogate candidates. Dig out the conversion function.
15000     CXXConversionDecl *Conv
15001       = cast<CXXConversionDecl>(
15002                          Best->Conversions[0].UserDefined.ConversionFunction);
15003 
15004     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15005                               Best->FoundDecl);
15006     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15007       return ExprError();
15008     assert(Conv == Best->FoundDecl.getDecl() &&
15009              "Found Decl & conversion-to-functionptr should be same, right?!");
15010     // We selected one of the surrogate functions that converts the
15011     // object parameter to a function pointer. Perform the conversion
15012     // on the object argument, then let BuildCallExpr finish the job.
15013 
15014     // Create an implicit member expr to refer to the conversion operator.
15015     // and then call it.
15016     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15017                                              Conv, HadMultipleCandidates);
15018     if (Call.isInvalid())
15019       return ExprError();
15020     // Record usage of conversion in an implicit cast.
15021     Call = ImplicitCastExpr::Create(
15022         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15023         nullptr, VK_PRValue, CurFPFeatureOverrides());
15024 
15025     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15026   }
15027 
15028   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15029 
15030   // We found an overloaded operator(). Build a CXXOperatorCallExpr
15031   // that calls this method, using Object for the implicit object
15032   // parameter and passing along the remaining arguments.
15033   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15034 
15035   // An error diagnostic has already been printed when parsing the declaration.
15036   if (Method->isInvalidDecl())
15037     return ExprError();
15038 
15039   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15040   unsigned NumParams = Proto->getNumParams();
15041 
15042   DeclarationNameInfo OpLocInfo(
15043                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15044   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15045   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15046                                            Obj, HadMultipleCandidates,
15047                                            OpLocInfo.getLoc(),
15048                                            OpLocInfo.getInfo());
15049   if (NewFn.isInvalid())
15050     return true;
15051 
15052   SmallVector<Expr *, 8> MethodArgs;
15053   MethodArgs.reserve(NumParams + 1);
15054 
15055   bool IsError = false;
15056 
15057   // Initialize the implicit object parameter if needed.
15058   // Since C++2b, this could also be a call to a static call operator
15059   // which we emit as a regular CallExpr.
15060   if (Method->isInstance()) {
15061     ExprResult ObjRes = PerformObjectArgumentInitialization(
15062         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15063     if (ObjRes.isInvalid())
15064       IsError = true;
15065     else
15066       Object = ObjRes;
15067     MethodArgs.push_back(Object.get());
15068   }
15069 
15070   IsError |= PrepareArgumentsForCallToObjectOfClassType(
15071       *this, MethodArgs, Method, Args, LParenLoc);
15072 
15073   // If this is a variadic call, handle args passed through "...".
15074   if (Proto->isVariadic()) {
15075     // Promote the arguments (C99 6.5.2.2p7).
15076     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15077       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15078                                                         nullptr);
15079       IsError |= Arg.isInvalid();
15080       MethodArgs.push_back(Arg.get());
15081     }
15082   }
15083 
15084   if (IsError)
15085     return true;
15086 
15087   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15088 
15089   // Once we've built TheCall, all of the expressions are properly owned.
15090   QualType ResultTy = Method->getReturnType();
15091   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15092   ResultTy = ResultTy.getNonLValueExprType(Context);
15093 
15094   CallExpr *TheCall;
15095   if (Method->isInstance())
15096     TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
15097                                           MethodArgs, ResultTy, VK, RParenLoc,
15098                                           CurFPFeatureOverrides());
15099   else
15100     TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
15101                                RParenLoc, CurFPFeatureOverrides());
15102 
15103   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15104     return true;
15105 
15106   if (CheckFunctionCall(Method, TheCall, Proto))
15107     return true;
15108 
15109   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15110 }
15111 
15112 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15113 ///  (if one exists), where @c Base is an expression of class type and
15114 /// @c Member is the name of the member we're trying to find.
15115 ExprResult
15116 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15117                                bool *NoArrowOperatorFound) {
15118   assert(Base->getType()->isRecordType() &&
15119          "left-hand side must have class type");
15120 
15121   if (checkPlaceholderForOverload(*this, Base))
15122     return ExprError();
15123 
15124   SourceLocation Loc = Base->getExprLoc();
15125 
15126   // C++ [over.ref]p1:
15127   //
15128   //   [...] An expression x->m is interpreted as (x.operator->())->m
15129   //   for a class object x of type T if T::operator->() exists and if
15130   //   the operator is selected as the best match function by the
15131   //   overload resolution mechanism (13.3).
15132   DeclarationName OpName =
15133     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15134   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15135 
15136   if (RequireCompleteType(Loc, Base->getType(),
15137                           diag::err_typecheck_incomplete_tag, Base))
15138     return ExprError();
15139 
15140   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15141   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15142   R.suppressDiagnostics();
15143 
15144   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15145        Oper != OperEnd; ++Oper) {
15146     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15147                        std::nullopt, CandidateSet,
15148                        /*SuppressUserConversion=*/false);
15149   }
15150 
15151   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15152 
15153   // Perform overload resolution.
15154   OverloadCandidateSet::iterator Best;
15155   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15156   case OR_Success:
15157     // Overload resolution succeeded; we'll build the call below.
15158     break;
15159 
15160   case OR_No_Viable_Function: {
15161     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15162     if (CandidateSet.empty()) {
15163       QualType BaseType = Base->getType();
15164       if (NoArrowOperatorFound) {
15165         // Report this specific error to the caller instead of emitting a
15166         // diagnostic, as requested.
15167         *NoArrowOperatorFound = true;
15168         return ExprError();
15169       }
15170       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15171         << BaseType << Base->getSourceRange();
15172       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15173         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15174           << FixItHint::CreateReplacement(OpLoc, ".");
15175       }
15176     } else
15177       Diag(OpLoc, diag::err_ovl_no_viable_oper)
15178         << "operator->" << Base->getSourceRange();
15179     CandidateSet.NoteCandidates(*this, Base, Cands);
15180     return ExprError();
15181   }
15182   case OR_Ambiguous:
15183     CandidateSet.NoteCandidates(
15184         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15185                                        << "->" << Base->getType()
15186                                        << Base->getSourceRange()),
15187         *this, OCD_AmbiguousCandidates, Base);
15188     return ExprError();
15189 
15190   case OR_Deleted:
15191     CandidateSet.NoteCandidates(
15192         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15193                                        << "->" << Base->getSourceRange()),
15194         *this, OCD_AllCandidates, Base);
15195     return ExprError();
15196   }
15197 
15198   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15199 
15200   // Convert the object parameter.
15201   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15202   ExprResult BaseResult =
15203     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15204                                         Best->FoundDecl, Method);
15205   if (BaseResult.isInvalid())
15206     return ExprError();
15207   Base = BaseResult.get();
15208 
15209   // Build the operator call.
15210   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15211                                             Base, HadMultipleCandidates, OpLoc);
15212   if (FnExpr.isInvalid())
15213     return ExprError();
15214 
15215   QualType ResultTy = Method->getReturnType();
15216   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15217   ResultTy = ResultTy.getNonLValueExprType(Context);
15218   CXXOperatorCallExpr *TheCall =
15219       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15220                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15221 
15222   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15223     return ExprError();
15224 
15225   if (CheckFunctionCall(Method, TheCall,
15226                         Method->getType()->castAs<FunctionProtoType>()))
15227     return ExprError();
15228 
15229   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15230 }
15231 
15232 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15233 /// a literal operator described by the provided lookup results.
15234 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15235                                           DeclarationNameInfo &SuffixInfo,
15236                                           ArrayRef<Expr*> Args,
15237                                           SourceLocation LitEndLoc,
15238                                        TemplateArgumentListInfo *TemplateArgs) {
15239   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15240 
15241   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15242                                     OverloadCandidateSet::CSK_Normal);
15243   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15244                                  TemplateArgs);
15245 
15246   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15247 
15248   // Perform overload resolution. This will usually be trivial, but might need
15249   // to perform substitutions for a literal operator template.
15250   OverloadCandidateSet::iterator Best;
15251   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15252   case OR_Success:
15253   case OR_Deleted:
15254     break;
15255 
15256   case OR_No_Viable_Function:
15257     CandidateSet.NoteCandidates(
15258         PartialDiagnosticAt(UDSuffixLoc,
15259                             PDiag(diag::err_ovl_no_viable_function_in_call)
15260                                 << R.getLookupName()),
15261         *this, OCD_AllCandidates, Args);
15262     return ExprError();
15263 
15264   case OR_Ambiguous:
15265     CandidateSet.NoteCandidates(
15266         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15267                                                 << R.getLookupName()),
15268         *this, OCD_AmbiguousCandidates, Args);
15269     return ExprError();
15270   }
15271 
15272   FunctionDecl *FD = Best->Function;
15273   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15274                                         nullptr, HadMultipleCandidates,
15275                                         SuffixInfo.getLoc(),
15276                                         SuffixInfo.getInfo());
15277   if (Fn.isInvalid())
15278     return true;
15279 
15280   // Check the argument types. This should almost always be a no-op, except
15281   // that array-to-pointer decay is applied to string literals.
15282   Expr *ConvArgs[2];
15283   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15284     ExprResult InputInit = PerformCopyInitialization(
15285       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15286       SourceLocation(), Args[ArgIdx]);
15287     if (InputInit.isInvalid())
15288       return true;
15289     ConvArgs[ArgIdx] = InputInit.get();
15290   }
15291 
15292   QualType ResultTy = FD->getReturnType();
15293   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15294   ResultTy = ResultTy.getNonLValueExprType(Context);
15295 
15296   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15297       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
15298       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15299 
15300   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15301     return ExprError();
15302 
15303   if (CheckFunctionCall(FD, UDL, nullptr))
15304     return ExprError();
15305 
15306   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15307 }
15308 
15309 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15310 /// given LookupResult is non-empty, it is assumed to describe a member which
15311 /// will be invoked. Otherwise, the function will be found via argument
15312 /// dependent lookup.
15313 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15314 /// otherwise CallExpr is set to ExprError() and some non-success value
15315 /// is returned.
15316 Sema::ForRangeStatus
15317 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15318                                 SourceLocation RangeLoc,
15319                                 const DeclarationNameInfo &NameInfo,
15320                                 LookupResult &MemberLookup,
15321                                 OverloadCandidateSet *CandidateSet,
15322                                 Expr *Range, ExprResult *CallExpr) {
15323   Scope *S = nullptr;
15324 
15325   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15326   if (!MemberLookup.empty()) {
15327     ExprResult MemberRef =
15328         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15329                                  /*IsPtr=*/false, CXXScopeSpec(),
15330                                  /*TemplateKWLoc=*/SourceLocation(),
15331                                  /*FirstQualifierInScope=*/nullptr,
15332                                  MemberLookup,
15333                                  /*TemplateArgs=*/nullptr, S);
15334     if (MemberRef.isInvalid()) {
15335       *CallExpr = ExprError();
15336       return FRS_DiagnosticIssued;
15337     }
15338     *CallExpr =
15339         BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
15340     if (CallExpr->isInvalid()) {
15341       *CallExpr = ExprError();
15342       return FRS_DiagnosticIssued;
15343     }
15344   } else {
15345     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15346                                                 NestedNameSpecifierLoc(),
15347                                                 NameInfo, UnresolvedSet<0>());
15348     if (FnR.isInvalid())
15349       return FRS_DiagnosticIssued;
15350     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15351 
15352     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15353                                                     CandidateSet, CallExpr);
15354     if (CandidateSet->empty() || CandidateSetError) {
15355       *CallExpr = ExprError();
15356       return FRS_NoViableFunction;
15357     }
15358     OverloadCandidateSet::iterator Best;
15359     OverloadingResult OverloadResult =
15360         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15361 
15362     if (OverloadResult == OR_No_Viable_Function) {
15363       *CallExpr = ExprError();
15364       return FRS_NoViableFunction;
15365     }
15366     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15367                                          Loc, nullptr, CandidateSet, &Best,
15368                                          OverloadResult,
15369                                          /*AllowTypoCorrection=*/false);
15370     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15371       *CallExpr = ExprError();
15372       return FRS_DiagnosticIssued;
15373     }
15374   }
15375   return FRS_Success;
15376 }
15377 
15378 
15379 /// FixOverloadedFunctionReference - E is an expression that refers to
15380 /// a C++ overloaded function (possibly with some parentheses and
15381 /// perhaps a '&' around it). We have resolved the overloaded function
15382 /// to the function declaration Fn, so patch up the expression E to
15383 /// refer (possibly indirectly) to Fn. Returns the new expr.
15384 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15385                                            FunctionDecl *Fn) {
15386   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15387     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15388                                                    Found, Fn);
15389     if (SubExpr == PE->getSubExpr())
15390       return PE;
15391 
15392     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15393   }
15394 
15395   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15396     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15397                                                    Found, Fn);
15398     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15399                                SubExpr->getType()) &&
15400            "Implicit cast type cannot be determined from overload");
15401     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15402     if (SubExpr == ICE->getSubExpr())
15403       return ICE;
15404 
15405     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15406                                     SubExpr, nullptr, ICE->getValueKind(),
15407                                     CurFPFeatureOverrides());
15408   }
15409 
15410   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15411     if (!GSE->isResultDependent()) {
15412       Expr *SubExpr =
15413           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15414       if (SubExpr == GSE->getResultExpr())
15415         return GSE;
15416 
15417       // Replace the resulting type information before rebuilding the generic
15418       // selection expression.
15419       ArrayRef<Expr *> A = GSE->getAssocExprs();
15420       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15421       unsigned ResultIdx = GSE->getResultIndex();
15422       AssocExprs[ResultIdx] = SubExpr;
15423 
15424       return GenericSelectionExpr::Create(
15425           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15426           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15427           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15428           ResultIdx);
15429     }
15430     // Rather than fall through to the unreachable, return the original generic
15431     // selection expression.
15432     return GSE;
15433   }
15434 
15435   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15436     assert(UnOp->getOpcode() == UO_AddrOf &&
15437            "Can only take the address of an overloaded function");
15438     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15439       if (Method->isStatic()) {
15440         // Do nothing: static member functions aren't any different
15441         // from non-member functions.
15442       } else {
15443         // Fix the subexpression, which really has to be an
15444         // UnresolvedLookupExpr holding an overloaded member function
15445         // or template.
15446         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15447                                                        Found, Fn);
15448         if (SubExpr == UnOp->getSubExpr())
15449           return UnOp;
15450 
15451         assert(isa<DeclRefExpr>(SubExpr)
15452                && "fixed to something other than a decl ref");
15453         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15454                && "fixed to a member ref with no nested name qualifier");
15455 
15456         // We have taken the address of a pointer to member
15457         // function. Perform the computation here so that we get the
15458         // appropriate pointer to member type.
15459         QualType ClassType
15460           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15461         QualType MemPtrType
15462           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15463         // Under the MS ABI, lock down the inheritance model now.
15464         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15465           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15466 
15467         return UnaryOperator::Create(
15468             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15469             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15470       }
15471     }
15472     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15473                                                    Found, Fn);
15474     if (SubExpr == UnOp->getSubExpr())
15475       return UnOp;
15476 
15477     // FIXME: This can't currently fail, but in principle it could.
15478     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15479         .get();
15480   }
15481 
15482   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15483     // FIXME: avoid copy.
15484     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15485     if (ULE->hasExplicitTemplateArgs()) {
15486       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15487       TemplateArgs = &TemplateArgsBuffer;
15488     }
15489 
15490     QualType Type = Fn->getType();
15491     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15492 
15493     // FIXME: Duplicated from BuildDeclarationNameExpr.
15494     if (unsigned BID = Fn->getBuiltinID()) {
15495       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15496         Type = Context.BuiltinFnTy;
15497         ValueKind = VK_PRValue;
15498       }
15499     }
15500 
15501     DeclRefExpr *DRE = BuildDeclRefExpr(
15502         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15503         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15504     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15505     return DRE;
15506   }
15507 
15508   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15509     // FIXME: avoid copy.
15510     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15511     if (MemExpr->hasExplicitTemplateArgs()) {
15512       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15513       TemplateArgs = &TemplateArgsBuffer;
15514     }
15515 
15516     Expr *Base;
15517 
15518     // If we're filling in a static method where we used to have an
15519     // implicit member access, rewrite to a simple decl ref.
15520     if (MemExpr->isImplicitAccess()) {
15521       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15522         DeclRefExpr *DRE = BuildDeclRefExpr(
15523             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15524             MemExpr->getQualifierLoc(), Found.getDecl(),
15525             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15526         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15527         return DRE;
15528       } else {
15529         SourceLocation Loc = MemExpr->getMemberLoc();
15530         if (MemExpr->getQualifier())
15531           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15532         Base =
15533             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15534       }
15535     } else
15536       Base = MemExpr->getBase();
15537 
15538     ExprValueKind valueKind;
15539     QualType type;
15540     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15541       valueKind = VK_LValue;
15542       type = Fn->getType();
15543     } else {
15544       valueKind = VK_PRValue;
15545       type = Context.BoundMemberTy;
15546     }
15547 
15548     return BuildMemberExpr(
15549         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15550         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15551         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15552         type, valueKind, OK_Ordinary, TemplateArgs);
15553   }
15554 
15555   llvm_unreachable("Invalid reference to overloaded function");
15556 }
15557 
15558 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15559                                                 DeclAccessPair Found,
15560                                                 FunctionDecl *Fn) {
15561   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15562 }
15563 
15564 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15565                                   FunctionDecl *Function) {
15566   if (!PartialOverloading || !Function)
15567     return true;
15568   if (Function->isVariadic())
15569     return false;
15570   if (const auto *Proto =
15571           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15572     if (Proto->isTemplateVariadic())
15573       return false;
15574   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15575     if (const auto *Proto =
15576             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15577       if (Proto->isTemplateVariadic())
15578         return false;
15579   return true;
15580 }
15581