xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/OperatorKinds.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/Support/Casting.h"
42 #include <algorithm>
43 #include <cstdlib>
44 #include <optional>
45 
46 using namespace clang;
47 using namespace sema;
48 
49 using AllowedExplicit = Sema::AllowedExplicit;
50 
51 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
52   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
53     return P->hasAttr<PassObjectSizeAttr>();
54   });
55 }
56 
57 /// A convenience routine for creating a decayed reference to a function.
58 static ExprResult CreateFunctionRefExpr(
59     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
60     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
61     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
62   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
63     return ExprError();
64   // If FoundDecl is different from Fn (such as if one is a template
65   // and the other a specialization), make sure DiagnoseUseOfDecl is
66   // called on both.
67   // FIXME: This would be more comprehensively addressed by modifying
68   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
69   // being used.
70   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
71     return ExprError();
72   DeclRefExpr *DRE = new (S.Context)
73       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
74   if (HadMultipleCandidates)
75     DRE->setHadMultipleCandidates(true);
76 
77   S.MarkDeclRefReferenced(DRE, Base);
78   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
79     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
80       S.ResolveExceptionSpec(Loc, FPT);
81       DRE->setType(Fn->getType());
82     }
83   }
84   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
85                              CK_FunctionToPointerDecay);
86 }
87 
88 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
89                                  bool InOverloadResolution,
90                                  StandardConversionSequence &SCS,
91                                  bool CStyle,
92                                  bool AllowObjCWritebackConversion);
93 
94 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
95                                                  QualType &ToType,
96                                                  bool InOverloadResolution,
97                                                  StandardConversionSequence &SCS,
98                                                  bool CStyle);
99 static OverloadingResult
100 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
101                         UserDefinedConversionSequence& User,
102                         OverloadCandidateSet& Conversions,
103                         AllowedExplicit AllowExplicit,
104                         bool AllowObjCConversionOnExplicit);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
108                                    const StandardConversionSequence& SCS1,
109                                    const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareQualificationConversions(Sema &S,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 static ImplicitConversionSequence::CompareKind
117 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
118                                 const StandardConversionSequence& SCS1,
119                                 const StandardConversionSequence& SCS2);
120 
121 /// GetConversionRank - Retrieve the implicit conversion rank
122 /// corresponding to the given implicit conversion kind.
123 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
124   static const ImplicitConversionRank
125     Rank[] = {
126     ICR_Exact_Match,
127     ICR_Exact_Match,
128     ICR_Exact_Match,
129     ICR_Exact_Match,
130     ICR_Exact_Match,
131     ICR_Exact_Match,
132     ICR_Promotion,
133     ICR_Promotion,
134     ICR_Promotion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Conversion,
146     ICR_Conversion,
147     ICR_OCL_Scalar_Widening,
148     ICR_Complex_Real_Conversion,
149     ICR_Conversion,
150     ICR_Conversion,
151     ICR_Writeback_Conversion,
152     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
153                      // it was omitted by the patch that added
154                      // ICK_Zero_Event_Conversion
155     ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
156                      // it was omitted by the patch that added
157                      // ICK_Zero_Queue_Conversion
158     ICR_C_Conversion,
159     ICR_C_Conversion_Extension
160   };
161   static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
162   return Rank[(int)Kind];
163 }
164 
165 /// GetImplicitConversionName - Return the name of this kind of
166 /// implicit conversion.
167 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
168   static const char* const Name[] = {
169     "No conversion",
170     "Lvalue-to-rvalue",
171     "Array-to-pointer",
172     "Function-to-pointer",
173     "Function pointer conversion",
174     "Qualification",
175     "Integral promotion",
176     "Floating point promotion",
177     "Complex promotion",
178     "Integral conversion",
179     "Floating conversion",
180     "Complex conversion",
181     "Floating-integral conversion",
182     "Pointer conversion",
183     "Pointer-to-member conversion",
184     "Boolean conversion",
185     "Compatible-types conversion",
186     "Derived-to-base conversion",
187     "Vector conversion",
188     "SVE Vector conversion",
189     "RVV Vector conversion",
190     "Vector splat",
191     "Complex-real conversion",
192     "Block Pointer conversion",
193     "Transparent Union Conversion",
194     "Writeback conversion",
195     "OpenCL Zero Event Conversion",
196     "OpenCL Zero Queue Conversion",
197     "C specific type conversion",
198     "Incompatible pointer conversion"
199   };
200   static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
201   return Name[Kind];
202 }
203 
204 /// StandardConversionSequence - Set the standard conversion
205 /// sequence to the identity conversion.
206 void StandardConversionSequence::setAsIdentityConversion() {
207   First = ICK_Identity;
208   Second = ICK_Identity;
209   Third = ICK_Identity;
210   DeprecatedStringLiteralToCharPtr = false;
211   QualificationIncludesObjCLifetime = false;
212   ReferenceBinding = false;
213   DirectBinding = false;
214   IsLvalueReference = true;
215   BindsToFunctionLvalue = false;
216   BindsToRvalue = false;
217   BindsImplicitObjectArgumentWithoutRefQualifier = false;
218   ObjCLifetimeConversionBinding = false;
219   CopyConstructor = nullptr;
220 }
221 
222 /// getRank - Retrieve the rank of this standard conversion sequence
223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224 /// implicit conversions.
225 ImplicitConversionRank StandardConversionSequence::getRank() const {
226   ImplicitConversionRank Rank = ICR_Exact_Match;
227   if  (GetConversionRank(First) > Rank)
228     Rank = GetConversionRank(First);
229   if  (GetConversionRank(Second) > Rank)
230     Rank = GetConversionRank(Second);
231   if  (GetConversionRank(Third) > Rank)
232     Rank = GetConversionRank(Third);
233   return Rank;
234 }
235 
236 /// isPointerConversionToBool - Determines whether this conversion is
237 /// a conversion of a pointer or pointer-to-member to bool. This is
238 /// used as part of the ranking of standard conversion sequences
239 /// (C++ 13.3.3.2p4).
240 bool StandardConversionSequence::isPointerConversionToBool() const {
241   // Note that FromType has not necessarily been transformed by the
242   // array-to-pointer or function-to-pointer implicit conversions, so
243   // check for their presence as well as checking whether FromType is
244   // a pointer.
245   if (getToType(1)->isBooleanType() &&
246       (getFromType()->isPointerType() ||
247        getFromType()->isMemberPointerType() ||
248        getFromType()->isObjCObjectPointerType() ||
249        getFromType()->isBlockPointerType() ||
250        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
251     return true;
252 
253   return false;
254 }
255 
256 /// isPointerConversionToVoidPointer - Determines whether this
257 /// conversion is a conversion of a pointer to a void pointer. This is
258 /// used as part of the ranking of standard conversion sequences (C++
259 /// 13.3.3.2p4).
260 bool
261 StandardConversionSequence::
262 isPointerConversionToVoidPointer(ASTContext& Context) const {
263   QualType FromType = getFromType();
264   QualType ToType = getToType(1);
265 
266   // Note that FromType has not necessarily been transformed by the
267   // array-to-pointer implicit conversion, so check for its presence
268   // and redo the conversion to get a pointer.
269   if (First == ICK_Array_To_Pointer)
270     FromType = Context.getArrayDecayedType(FromType);
271 
272   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
273     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
274       return ToPtrType->getPointeeType()->isVoidType();
275 
276   return false;
277 }
278 
279 /// Skip any implicit casts which could be either part of a narrowing conversion
280 /// or after one in an implicit conversion.
281 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
282                                              const Expr *Converted) {
283   // We can have cleanups wrapping the converted expression; these need to be
284   // preserved so that destructors run if necessary.
285   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
286     Expr *Inner =
287         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
288     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
289                                     EWC->getObjects());
290   }
291 
292   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
293     switch (ICE->getCastKind()) {
294     case CK_NoOp:
295     case CK_IntegralCast:
296     case CK_IntegralToBoolean:
297     case CK_IntegralToFloating:
298     case CK_BooleanToSignedIntegral:
299     case CK_FloatingToIntegral:
300     case CK_FloatingToBoolean:
301     case CK_FloatingCast:
302       Converted = ICE->getSubExpr();
303       continue;
304 
305     default:
306       return Converted;
307     }
308   }
309 
310   return Converted;
311 }
312 
313 /// Check if this standard conversion sequence represents a narrowing
314 /// conversion, according to C++11 [dcl.init.list]p7.
315 ///
316 /// \param Ctx  The AST context.
317 /// \param Converted  The result of applying this standard conversion sequence.
318 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
319 ///        value of the expression prior to the narrowing conversion.
320 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
321 ///        type of the expression prior to the narrowing conversion.
322 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
323 ///        from floating point types to integral types should be ignored.
324 NarrowingKind StandardConversionSequence::getNarrowingKind(
325     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
326     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
327   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
328 
329   // C++11 [dcl.init.list]p7:
330   //   A narrowing conversion is an implicit conversion ...
331   QualType FromType = getToType(0);
332   QualType ToType = getToType(1);
333 
334   // A conversion to an enumeration type is narrowing if the conversion to
335   // the underlying type is narrowing. This only arises for expressions of
336   // the form 'Enum{init}'.
337   if (auto *ET = ToType->getAs<EnumType>())
338     ToType = ET->getDecl()->getIntegerType();
339 
340   switch (Second) {
341   // 'bool' is an integral type; dispatch to the right place to handle it.
342   case ICK_Boolean_Conversion:
343     if (FromType->isRealFloatingType())
344       goto FloatingIntegralConversion;
345     if (FromType->isIntegralOrUnscopedEnumerationType())
346       goto IntegralConversion;
347     // -- from a pointer type or pointer-to-member type to bool, or
348     return NK_Type_Narrowing;
349 
350   // -- from a floating-point type to an integer type, or
351   //
352   // -- from an integer type or unscoped enumeration type to a floating-point
353   //    type, except where the source is a constant expression and the actual
354   //    value after conversion will fit into the target type and will produce
355   //    the original value when converted back to the original type, or
356   case ICK_Floating_Integral:
357   FloatingIntegralConversion:
358     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
359       return NK_Type_Narrowing;
360     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
361                ToType->isRealFloatingType()) {
362       if (IgnoreFloatToIntegralConversion)
363         return NK_Not_Narrowing;
364       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
365       assert(Initializer && "Unknown conversion expression");
366 
367       // If it's value-dependent, we can't tell whether it's narrowing.
368       if (Initializer->isValueDependent())
369         return NK_Dependent_Narrowing;
370 
371       if (std::optional<llvm::APSInt> IntConstantValue =
372               Initializer->getIntegerConstantExpr(Ctx)) {
373         // Convert the integer to the floating type.
374         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
375         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
376                                 llvm::APFloat::rmNearestTiesToEven);
377         // And back.
378         llvm::APSInt ConvertedValue = *IntConstantValue;
379         bool ignored;
380         Result.convertToInteger(ConvertedValue,
381                                 llvm::APFloat::rmTowardZero, &ignored);
382         // If the resulting value is different, this was a narrowing conversion.
383         if (*IntConstantValue != ConvertedValue) {
384           ConstantValue = APValue(*IntConstantValue);
385           ConstantType = Initializer->getType();
386           return NK_Constant_Narrowing;
387         }
388       } else {
389         // Variables are always narrowings.
390         return NK_Variable_Narrowing;
391       }
392     }
393     return NK_Not_Narrowing;
394 
395   // -- from long double to double or float, or from double to float, except
396   //    where the source is a constant expression and the actual value after
397   //    conversion is within the range of values that can be represented (even
398   //    if it cannot be represented exactly), or
399   case ICK_Floating_Conversion:
400     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
401         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
402       // FromType is larger than ToType.
403       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 
405       // If it's value-dependent, we can't tell whether it's narrowing.
406       if (Initializer->isValueDependent())
407         return NK_Dependent_Narrowing;
408 
409       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
410         // Constant!
411         assert(ConstantValue.isFloat());
412         llvm::APFloat FloatVal = ConstantValue.getFloat();
413         // Convert the source value into the target type.
414         bool ignored;
415         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
416           Ctx.getFloatTypeSemantics(ToType),
417           llvm::APFloat::rmNearestTiesToEven, &ignored);
418         // If there was no overflow, the source value is within the range of
419         // values that can be represented.
420         if (ConvertStatus & llvm::APFloat::opOverflow) {
421           ConstantType = Initializer->getType();
422           return NK_Constant_Narrowing;
423         }
424       } else {
425         return NK_Variable_Narrowing;
426       }
427     }
428     return NK_Not_Narrowing;
429 
430   // -- from an integer type or unscoped enumeration type to an integer type
431   //    that cannot represent all the values of the original type, except where
432   //    the source is a constant expression and the actual value after
433   //    conversion will fit into the target type and will produce the original
434   //    value when converted back to the original type.
435   case ICK_Integral_Conversion:
436   IntegralConversion: {
437     assert(FromType->isIntegralOrUnscopedEnumerationType());
438     assert(ToType->isIntegralOrUnscopedEnumerationType());
439     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
440     const unsigned FromWidth = Ctx.getIntWidth(FromType);
441     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
442     const unsigned ToWidth = Ctx.getIntWidth(ToType);
443 
444     if (FromWidth > ToWidth ||
445         (FromWidth == ToWidth && FromSigned != ToSigned) ||
446         (FromSigned && !ToSigned)) {
447       // Not all values of FromType can be represented in ToType.
448       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
449 
450       // If it's value-dependent, we can't tell whether it's narrowing.
451       if (Initializer->isValueDependent())
452         return NK_Dependent_Narrowing;
453 
454       std::optional<llvm::APSInt> OptInitializerValue;
455       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
456         // Such conversions on variables are always narrowing.
457         return NK_Variable_Narrowing;
458       }
459       llvm::APSInt &InitializerValue = *OptInitializerValue;
460       bool Narrowing = false;
461       if (FromWidth < ToWidth) {
462         // Negative -> unsigned is narrowing. Otherwise, more bits is never
463         // narrowing.
464         if (InitializerValue.isSigned() && InitializerValue.isNegative())
465           Narrowing = true;
466       } else {
467         // Add a bit to the InitializerValue so we don't have to worry about
468         // signed vs. unsigned comparisons.
469         InitializerValue = InitializerValue.extend(
470           InitializerValue.getBitWidth() + 1);
471         // Convert the initializer to and from the target width and signed-ness.
472         llvm::APSInt ConvertedValue = InitializerValue;
473         ConvertedValue = ConvertedValue.trunc(ToWidth);
474         ConvertedValue.setIsSigned(ToSigned);
475         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
476         ConvertedValue.setIsSigned(InitializerValue.isSigned());
477         // If the result is different, this was a narrowing conversion.
478         if (ConvertedValue != InitializerValue)
479           Narrowing = true;
480       }
481       if (Narrowing) {
482         ConstantType = Initializer->getType();
483         ConstantValue = APValue(InitializerValue);
484         return NK_Constant_Narrowing;
485       }
486     }
487     return NK_Not_Narrowing;
488   }
489 
490   default:
491     // Other kinds of conversions are not narrowings.
492     return NK_Not_Narrowing;
493   }
494 }
495 
496 /// dump - Print this standard conversion sequence to standard
497 /// error. Useful for debugging overloading issues.
498 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
499   raw_ostream &OS = llvm::errs();
500   bool PrintedSomething = false;
501   if (First != ICK_Identity) {
502     OS << GetImplicitConversionName(First);
503     PrintedSomething = true;
504   }
505 
506   if (Second != ICK_Identity) {
507     if (PrintedSomething) {
508       OS << " -> ";
509     }
510     OS << GetImplicitConversionName(Second);
511 
512     if (CopyConstructor) {
513       OS << " (by copy constructor)";
514     } else if (DirectBinding) {
515       OS << " (direct reference binding)";
516     } else if (ReferenceBinding) {
517       OS << " (reference binding)";
518     }
519     PrintedSomething = true;
520   }
521 
522   if (Third != ICK_Identity) {
523     if (PrintedSomething) {
524       OS << " -> ";
525     }
526     OS << GetImplicitConversionName(Third);
527     PrintedSomething = true;
528   }
529 
530   if (!PrintedSomething) {
531     OS << "No conversions required";
532   }
533 }
534 
535 /// dump - Print this user-defined conversion sequence to standard
536 /// error. Useful for debugging overloading issues.
537 void UserDefinedConversionSequence::dump() const {
538   raw_ostream &OS = llvm::errs();
539   if (Before.First || Before.Second || Before.Third) {
540     Before.dump();
541     OS << " -> ";
542   }
543   if (ConversionFunction)
544     OS << '\'' << *ConversionFunction << '\'';
545   else
546     OS << "aggregate initialization";
547   if (After.First || After.Second || After.Third) {
548     OS << " -> ";
549     After.dump();
550   }
551 }
552 
553 /// dump - Print this implicit conversion sequence to standard
554 /// error. Useful for debugging overloading issues.
555 void ImplicitConversionSequence::dump() const {
556   raw_ostream &OS = llvm::errs();
557   if (hasInitializerListContainerType())
558     OS << "Worst list element conversion: ";
559   switch (ConversionKind) {
560   case StandardConversion:
561     OS << "Standard conversion: ";
562     Standard.dump();
563     break;
564   case UserDefinedConversion:
565     OS << "User-defined conversion: ";
566     UserDefined.dump();
567     break;
568   case EllipsisConversion:
569     OS << "Ellipsis conversion";
570     break;
571   case AmbiguousConversion:
572     OS << "Ambiguous conversion";
573     break;
574   case BadConversion:
575     OS << "Bad conversion";
576     break;
577   }
578 
579   OS << "\n";
580 }
581 
582 void AmbiguousConversionSequence::construct() {
583   new (&conversions()) ConversionSet();
584 }
585 
586 void AmbiguousConversionSequence::destruct() {
587   conversions().~ConversionSet();
588 }
589 
590 void
591 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
592   FromTypePtr = O.FromTypePtr;
593   ToTypePtr = O.ToTypePtr;
594   new (&conversions()) ConversionSet(O.conversions());
595 }
596 
597 namespace {
598   // Structure used by DeductionFailureInfo to store
599   // template argument information.
600   struct DFIArguments {
601     TemplateArgument FirstArg;
602     TemplateArgument SecondArg;
603   };
604   // Structure used by DeductionFailureInfo to store
605   // template parameter and template argument information.
606   struct DFIParamWithArguments : DFIArguments {
607     TemplateParameter Param;
608   };
609   // Structure used by DeductionFailureInfo to store template argument
610   // information and the index of the problematic call argument.
611   struct DFIDeducedMismatchArgs : DFIArguments {
612     TemplateArgumentList *TemplateArgs;
613     unsigned CallArgIndex;
614   };
615   // Structure used by DeductionFailureInfo to store information about
616   // unsatisfied constraints.
617   struct CNSInfo {
618     TemplateArgumentList *TemplateArgs;
619     ConstraintSatisfaction Satisfaction;
620   };
621 }
622 
623 /// Convert from Sema's representation of template deduction information
624 /// to the form used in overload-candidate information.
625 DeductionFailureInfo
626 clang::MakeDeductionFailureInfo(ASTContext &Context,
627                                 Sema::TemplateDeductionResult TDK,
628                                 TemplateDeductionInfo &Info) {
629   DeductionFailureInfo Result;
630   Result.Result = static_cast<unsigned>(TDK);
631   Result.HasDiagnostic = false;
632   switch (TDK) {
633   case Sema::TDK_Invalid:
634   case Sema::TDK_InstantiationDepth:
635   case Sema::TDK_TooManyArguments:
636   case Sema::TDK_TooFewArguments:
637   case Sema::TDK_MiscellaneousDeductionFailure:
638   case Sema::TDK_CUDATargetMismatch:
639     Result.Data = nullptr;
640     break;
641 
642   case Sema::TDK_Incomplete:
643   case Sema::TDK_InvalidExplicitArguments:
644     Result.Data = Info.Param.getOpaqueValue();
645     break;
646 
647   case Sema::TDK_DeducedMismatch:
648   case Sema::TDK_DeducedMismatchNested: {
649     // FIXME: Should allocate from normal heap so that we can free this later.
650     auto *Saved = new (Context) DFIDeducedMismatchArgs;
651     Saved->FirstArg = Info.FirstArg;
652     Saved->SecondArg = Info.SecondArg;
653     Saved->TemplateArgs = Info.takeSugared();
654     Saved->CallArgIndex = Info.CallArgIndex;
655     Result.Data = Saved;
656     break;
657   }
658 
659   case Sema::TDK_NonDeducedMismatch: {
660     // FIXME: Should allocate from normal heap so that we can free this later.
661     DFIArguments *Saved = new (Context) DFIArguments;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_IncompletePack:
669     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
670   case Sema::TDK_Inconsistent:
671   case Sema::TDK_Underqualified: {
672     // FIXME: Should allocate from normal heap so that we can free this later.
673     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
674     Saved->Param = Info.Param;
675     Saved->FirstArg = Info.FirstArg;
676     Saved->SecondArg = Info.SecondArg;
677     Result.Data = Saved;
678     break;
679   }
680 
681   case Sema::TDK_SubstitutionFailure:
682     Result.Data = Info.takeSugared();
683     if (Info.hasSFINAEDiagnostic()) {
684       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
685           SourceLocation(), PartialDiagnostic::NullDiagnostic());
686       Info.takeSFINAEDiagnostic(*Diag);
687       Result.HasDiagnostic = true;
688     }
689     break;
690 
691   case Sema::TDK_ConstraintsNotSatisfied: {
692     CNSInfo *Saved = new (Context) CNSInfo;
693     Saved->TemplateArgs = Info.takeSugared();
694     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
695     Result.Data = Saved;
696     break;
697   }
698 
699   case Sema::TDK_Success:
700   case Sema::TDK_NonDependentConversionFailure:
701   case Sema::TDK_AlreadyDiagnosed:
702     llvm_unreachable("not a deduction failure");
703   }
704 
705   return Result;
706 }
707 
708 void DeductionFailureInfo::Destroy() {
709   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
710   case Sema::TDK_Success:
711   case Sema::TDK_Invalid:
712   case Sema::TDK_InstantiationDepth:
713   case Sema::TDK_Incomplete:
714   case Sema::TDK_TooManyArguments:
715   case Sema::TDK_TooFewArguments:
716   case Sema::TDK_InvalidExplicitArguments:
717   case Sema::TDK_CUDATargetMismatch:
718   case Sema::TDK_NonDependentConversionFailure:
719     break;
720 
721   case Sema::TDK_IncompletePack:
722   case Sema::TDK_Inconsistent:
723   case Sema::TDK_Underqualified:
724   case Sema::TDK_DeducedMismatch:
725   case Sema::TDK_DeducedMismatchNested:
726   case Sema::TDK_NonDeducedMismatch:
727     // FIXME: Destroy the data?
728     Data = nullptr;
729     break;
730 
731   case Sema::TDK_SubstitutionFailure:
732     // FIXME: Destroy the template argument list?
733     Data = nullptr;
734     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
735       Diag->~PartialDiagnosticAt();
736       HasDiagnostic = false;
737     }
738     break;
739 
740   case Sema::TDK_ConstraintsNotSatisfied:
741     // FIXME: Destroy the template argument list?
742     Data = nullptr;
743     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
744       Diag->~PartialDiagnosticAt();
745       HasDiagnostic = false;
746     }
747     break;
748 
749   // Unhandled
750   case Sema::TDK_MiscellaneousDeductionFailure:
751   case Sema::TDK_AlreadyDiagnosed:
752     break;
753   }
754 }
755 
756 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
757   if (HasDiagnostic)
758     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
759   return nullptr;
760 }
761 
762 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
763   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
764   case Sema::TDK_Success:
765   case Sema::TDK_Invalid:
766   case Sema::TDK_InstantiationDepth:
767   case Sema::TDK_TooManyArguments:
768   case Sema::TDK_TooFewArguments:
769   case Sema::TDK_SubstitutionFailure:
770   case Sema::TDK_DeducedMismatch:
771   case Sema::TDK_DeducedMismatchNested:
772   case Sema::TDK_NonDeducedMismatch:
773   case Sema::TDK_CUDATargetMismatch:
774   case Sema::TDK_NonDependentConversionFailure:
775   case Sema::TDK_ConstraintsNotSatisfied:
776     return TemplateParameter();
777 
778   case Sema::TDK_Incomplete:
779   case Sema::TDK_InvalidExplicitArguments:
780     return TemplateParameter::getFromOpaqueValue(Data);
781 
782   case Sema::TDK_IncompletePack:
783   case Sema::TDK_Inconsistent:
784   case Sema::TDK_Underqualified:
785     return static_cast<DFIParamWithArguments*>(Data)->Param;
786 
787   // Unhandled
788   case Sema::TDK_MiscellaneousDeductionFailure:
789   case Sema::TDK_AlreadyDiagnosed:
790     break;
791   }
792 
793   return TemplateParameter();
794 }
795 
796 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
797   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
798   case Sema::TDK_Success:
799   case Sema::TDK_Invalid:
800   case Sema::TDK_InstantiationDepth:
801   case Sema::TDK_TooManyArguments:
802   case Sema::TDK_TooFewArguments:
803   case Sema::TDK_Incomplete:
804   case Sema::TDK_IncompletePack:
805   case Sema::TDK_InvalidExplicitArguments:
806   case Sema::TDK_Inconsistent:
807   case Sema::TDK_Underqualified:
808   case Sema::TDK_NonDeducedMismatch:
809   case Sema::TDK_CUDATargetMismatch:
810   case Sema::TDK_NonDependentConversionFailure:
811     return nullptr;
812 
813   case Sema::TDK_DeducedMismatch:
814   case Sema::TDK_DeducedMismatchNested:
815     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
816 
817   case Sema::TDK_SubstitutionFailure:
818     return static_cast<TemplateArgumentList*>(Data);
819 
820   case Sema::TDK_ConstraintsNotSatisfied:
821     return static_cast<CNSInfo*>(Data)->TemplateArgs;
822 
823   // Unhandled
824   case Sema::TDK_MiscellaneousDeductionFailure:
825   case Sema::TDK_AlreadyDiagnosed:
826     break;
827   }
828 
829   return nullptr;
830 }
831 
832 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
833   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
834   case Sema::TDK_Success:
835   case Sema::TDK_Invalid:
836   case Sema::TDK_InstantiationDepth:
837   case Sema::TDK_Incomplete:
838   case Sema::TDK_TooManyArguments:
839   case Sema::TDK_TooFewArguments:
840   case Sema::TDK_InvalidExplicitArguments:
841   case Sema::TDK_SubstitutionFailure:
842   case Sema::TDK_CUDATargetMismatch:
843   case Sema::TDK_NonDependentConversionFailure:
844   case Sema::TDK_ConstraintsNotSatisfied:
845     return nullptr;
846 
847   case Sema::TDK_IncompletePack:
848   case Sema::TDK_Inconsistent:
849   case Sema::TDK_Underqualified:
850   case Sema::TDK_DeducedMismatch:
851   case Sema::TDK_DeducedMismatchNested:
852   case Sema::TDK_NonDeducedMismatch:
853     return &static_cast<DFIArguments*>(Data)->FirstArg;
854 
855   // Unhandled
856   case Sema::TDK_MiscellaneousDeductionFailure:
857   case Sema::TDK_AlreadyDiagnosed:
858     break;
859   }
860 
861   return nullptr;
862 }
863 
864 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
865   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
866   case Sema::TDK_Success:
867   case Sema::TDK_Invalid:
868   case Sema::TDK_InstantiationDepth:
869   case Sema::TDK_Incomplete:
870   case Sema::TDK_IncompletePack:
871   case Sema::TDK_TooManyArguments:
872   case Sema::TDK_TooFewArguments:
873   case Sema::TDK_InvalidExplicitArguments:
874   case Sema::TDK_SubstitutionFailure:
875   case Sema::TDK_CUDATargetMismatch:
876   case Sema::TDK_NonDependentConversionFailure:
877   case Sema::TDK_ConstraintsNotSatisfied:
878     return nullptr;
879 
880   case Sema::TDK_Inconsistent:
881   case Sema::TDK_Underqualified:
882   case Sema::TDK_DeducedMismatch:
883   case Sema::TDK_DeducedMismatchNested:
884   case Sema::TDK_NonDeducedMismatch:
885     return &static_cast<DFIArguments*>(Data)->SecondArg;
886 
887   // Unhandled
888   case Sema::TDK_MiscellaneousDeductionFailure:
889   case Sema::TDK_AlreadyDiagnosed:
890     break;
891   }
892 
893   return nullptr;
894 }
895 
896 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
897   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
898   case Sema::TDK_DeducedMismatch:
899   case Sema::TDK_DeducedMismatchNested:
900     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
901 
902   default:
903     return std::nullopt;
904   }
905 }
906 
907 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
908                                 const FunctionDecl *Y) {
909   if (!X || !Y)
910     return false;
911   if (X->getNumParams() != Y->getNumParams())
912     return false;
913   for (unsigned I = 0; I < X->getNumParams(); ++I)
914     if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
915                                     Y->getParamDecl(I)->getType()))
916       return false;
917   if (auto *FTX = X->getDescribedFunctionTemplate()) {
918     auto *FTY = Y->getDescribedFunctionTemplate();
919     if (!FTY)
920       return false;
921     if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
922                                          FTY->getTemplateParameters()))
923       return false;
924   }
925   return true;
926 }
927 
928 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
929                                   Expr *FirstOperand, FunctionDecl *EqFD) {
930   assert(EqFD->getOverloadedOperator() ==
931          OverloadedOperatorKind::OO_EqualEqual);
932   // C++2a [over.match.oper]p4:
933   // A non-template function or function template F named operator== is a
934   // rewrite target with first operand o unless a search for the name operator!=
935   // in the scope S from the instantiation context of the operator expression
936   // finds a function or function template that would correspond
937   // ([basic.scope.scope]) to F if its name were operator==, where S is the
938   // scope of the class type of o if F is a class member, and the namespace
939   // scope of which F is a member otherwise. A function template specialization
940   // named operator== is a rewrite target if its function template is a rewrite
941   // target.
942   DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
943       OverloadedOperatorKind::OO_ExclaimEqual);
944   if (isa<CXXMethodDecl>(EqFD)) {
945     // If F is a class member, search scope is class type of first operand.
946     QualType RHS = FirstOperand->getType();
947     auto *RHSRec = RHS->getAs<RecordType>();
948     if (!RHSRec)
949       return true;
950     LookupResult Members(S, NotEqOp, OpLoc,
951                          Sema::LookupNameKind::LookupMemberName);
952     S.LookupQualifiedName(Members, RHSRec->getDecl());
953     Members.suppressDiagnostics();
954     for (NamedDecl *Op : Members)
955       if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
956         return false;
957     return true;
958   }
959   // Otherwise the search scope is the namespace scope of which F is a member.
960   for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
961     auto *NotEqFD = Op->getAsFunction();
962     if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
963       NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
964     if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
965         declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
966                            cast<Decl>(Op->getLexicalDeclContext())))
967       return false;
968   }
969   return true;
970 }
971 
972 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
973     OverloadedOperatorKind Op) {
974   if (!AllowRewrittenCandidates)
975     return false;
976   return Op == OO_EqualEqual || Op == OO_Spaceship;
977 }
978 
979 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
980     Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
981   auto Op = FD->getOverloadedOperator();
982   if (!allowsReversed(Op))
983     return false;
984   if (Op == OverloadedOperatorKind::OO_EqualEqual) {
985     assert(OriginalArgs.size() == 2);
986     if (!shouldAddReversedEqEq(
987             S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
988       return false;
989   }
990   // Don't bother adding a reversed candidate that can never be a better
991   // match than the non-reversed version.
992   return FD->getNumParams() != 2 ||
993          !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
994                                            FD->getParamDecl(1)->getType()) ||
995          FD->hasAttr<EnableIfAttr>();
996 }
997 
998 void OverloadCandidateSet::destroyCandidates() {
999   for (iterator i = begin(), e = end(); i != e; ++i) {
1000     for (auto &C : i->Conversions)
1001       C.~ImplicitConversionSequence();
1002     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1003       i->DeductionFailure.Destroy();
1004   }
1005 }
1006 
1007 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1008   destroyCandidates();
1009   SlabAllocator.Reset();
1010   NumInlineBytesUsed = 0;
1011   Candidates.clear();
1012   Functions.clear();
1013   Kind = CSK;
1014 }
1015 
1016 namespace {
1017   class UnbridgedCastsSet {
1018     struct Entry {
1019       Expr **Addr;
1020       Expr *Saved;
1021     };
1022     SmallVector<Entry, 2> Entries;
1023 
1024   public:
1025     void save(Sema &S, Expr *&E) {
1026       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1027       Entry entry = { &E, E };
1028       Entries.push_back(entry);
1029       E = S.stripARCUnbridgedCast(E);
1030     }
1031 
1032     void restore() {
1033       for (SmallVectorImpl<Entry>::iterator
1034              i = Entries.begin(), e = Entries.end(); i != e; ++i)
1035         *i->Addr = i->Saved;
1036     }
1037   };
1038 }
1039 
1040 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1041 /// preprocessing on the given expression.
1042 ///
1043 /// \param unbridgedCasts a collection to which to add unbridged casts;
1044 ///   without this, they will be immediately diagnosed as errors
1045 ///
1046 /// Return true on unrecoverable error.
1047 static bool
1048 checkPlaceholderForOverload(Sema &S, Expr *&E,
1049                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
1050   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
1051     // We can't handle overloaded expressions here because overload
1052     // resolution might reasonably tweak them.
1053     if (placeholder->getKind() == BuiltinType::Overload) return false;
1054 
1055     // If the context potentially accepts unbridged ARC casts, strip
1056     // the unbridged cast and add it to the collection for later restoration.
1057     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1058         unbridgedCasts) {
1059       unbridgedCasts->save(S, E);
1060       return false;
1061     }
1062 
1063     // Go ahead and check everything else.
1064     ExprResult result = S.CheckPlaceholderExpr(E);
1065     if (result.isInvalid())
1066       return true;
1067 
1068     E = result.get();
1069     return false;
1070   }
1071 
1072   // Nothing to do.
1073   return false;
1074 }
1075 
1076 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1077 /// placeholders.
1078 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1079                                             UnbridgedCastsSet &unbridged) {
1080   for (unsigned i = 0, e = Args.size(); i != e; ++i)
1081     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1082       return true;
1083 
1084   return false;
1085 }
1086 
1087 /// Determine whether the given New declaration is an overload of the
1088 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1089 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1090 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1091 /// functions (or function templates) at all. When it does return Ovl_Match or
1092 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1093 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1094 /// declaration.
1095 ///
1096 /// Example: Given the following input:
1097 ///
1098 ///   void f(int, float); // #1
1099 ///   void f(int, int); // #2
1100 ///   int f(int, int); // #3
1101 ///
1102 /// When we process #1, there is no previous declaration of "f", so IsOverload
1103 /// will not be used.
1104 ///
1105 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1106 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1107 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1108 /// unchanged.
1109 ///
1110 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1111 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1112 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1113 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1114 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1115 ///
1116 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1117 /// by a using declaration. The rules for whether to hide shadow declarations
1118 /// ignore some properties which otherwise figure into a function template's
1119 /// signature.
1120 Sema::OverloadKind
1121 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1122                     NamedDecl *&Match, bool NewIsUsingDecl) {
1123   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1124          I != E; ++I) {
1125     NamedDecl *OldD = *I;
1126 
1127     bool OldIsUsingDecl = false;
1128     if (isa<UsingShadowDecl>(OldD)) {
1129       OldIsUsingDecl = true;
1130 
1131       // We can always introduce two using declarations into the same
1132       // context, even if they have identical signatures.
1133       if (NewIsUsingDecl) continue;
1134 
1135       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1136     }
1137 
1138     // A using-declaration does not conflict with another declaration
1139     // if one of them is hidden.
1140     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1141       continue;
1142 
1143     // If either declaration was introduced by a using declaration,
1144     // we'll need to use slightly different rules for matching.
1145     // Essentially, these rules are the normal rules, except that
1146     // function templates hide function templates with different
1147     // return types or template parameter lists.
1148     bool UseMemberUsingDeclRules =
1149       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1150       !New->getFriendObjectKind();
1151 
1152     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1153       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1154         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1155           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1156           continue;
1157         }
1158 
1159         if (!isa<FunctionTemplateDecl>(OldD) &&
1160             !shouldLinkPossiblyHiddenDecl(*I, New))
1161           continue;
1162 
1163         Match = *I;
1164         return Ovl_Match;
1165       }
1166 
1167       // Builtins that have custom typechecking or have a reference should
1168       // not be overloadable or redeclarable.
1169       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1170         Match = *I;
1171         return Ovl_NonFunction;
1172       }
1173     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1174       // We can overload with these, which can show up when doing
1175       // redeclaration checks for UsingDecls.
1176       assert(Old.getLookupKind() == LookupUsingDeclName);
1177     } else if (isa<TagDecl>(OldD)) {
1178       // We can always overload with tags by hiding them.
1179     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1180       // Optimistically assume that an unresolved using decl will
1181       // overload; if it doesn't, we'll have to diagnose during
1182       // template instantiation.
1183       //
1184       // Exception: if the scope is dependent and this is not a class
1185       // member, the using declaration can only introduce an enumerator.
1186       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1187         Match = *I;
1188         return Ovl_NonFunction;
1189       }
1190     } else {
1191       // (C++ 13p1):
1192       //   Only function declarations can be overloaded; object and type
1193       //   declarations cannot be overloaded.
1194       Match = *I;
1195       return Ovl_NonFunction;
1196     }
1197   }
1198 
1199   // C++ [temp.friend]p1:
1200   //   For a friend function declaration that is not a template declaration:
1201   //    -- if the name of the friend is a qualified or unqualified template-id,
1202   //       [...], otherwise
1203   //    -- if the name of the friend is a qualified-id and a matching
1204   //       non-template function is found in the specified class or namespace,
1205   //       the friend declaration refers to that function, otherwise,
1206   //    -- if the name of the friend is a qualified-id and a matching function
1207   //       template is found in the specified class or namespace, the friend
1208   //       declaration refers to the deduced specialization of that function
1209   //       template, otherwise
1210   //    -- the name shall be an unqualified-id [...]
1211   // If we get here for a qualified friend declaration, we've just reached the
1212   // third bullet. If the type of the friend is dependent, skip this lookup
1213   // until instantiation.
1214   if (New->getFriendObjectKind() && New->getQualifier() &&
1215       !New->getDescribedFunctionTemplate() &&
1216       !New->getDependentSpecializationInfo() &&
1217       !New->getType()->isDependentType()) {
1218     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1219     TemplateSpecResult.addAllDecls(Old);
1220     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1221                                             /*QualifiedFriend*/true)) {
1222       New->setInvalidDecl();
1223       return Ovl_Overload;
1224     }
1225 
1226     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1227     return Ovl_Match;
1228   }
1229 
1230   return Ovl_Overload;
1231 }
1232 
1233 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1234                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1235                       bool ConsiderRequiresClauses) {
1236   // C++ [basic.start.main]p2: This function shall not be overloaded.
1237   if (New->isMain())
1238     return false;
1239 
1240   // MSVCRT user defined entry points cannot be overloaded.
1241   if (New->isMSVCRTEntryPoint())
1242     return false;
1243 
1244   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1245   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1246 
1247   // C++ [temp.fct]p2:
1248   //   A function template can be overloaded with other function templates
1249   //   and with normal (non-template) functions.
1250   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1251     return true;
1252 
1253   // Is the function New an overload of the function Old?
1254   QualType OldQType = Context.getCanonicalType(Old->getType());
1255   QualType NewQType = Context.getCanonicalType(New->getType());
1256 
1257   // Compare the signatures (C++ 1.3.10) of the two functions to
1258   // determine whether they are overloads. If we find any mismatch
1259   // in the signature, they are overloads.
1260 
1261   // If either of these functions is a K&R-style function (no
1262   // prototype), then we consider them to have matching signatures.
1263   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1264       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1265     return false;
1266 
1267   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1268   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1269 
1270   // The signature of a function includes the types of its
1271   // parameters (C++ 1.3.10), which includes the presence or absence
1272   // of the ellipsis; see C++ DR 357).
1273   if (OldQType != NewQType &&
1274       (OldType->getNumParams() != NewType->getNumParams() ||
1275        OldType->isVariadic() != NewType->isVariadic() ||
1276        !FunctionParamTypesAreEqual(OldType, NewType)))
1277     return true;
1278 
1279   // For member-like friends, the enclosing class is part of the signature.
1280   if ((New->isMemberLikeConstrainedFriend() ||
1281        Old->isMemberLikeConstrainedFriend()) &&
1282       !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1283     return true;
1284 
1285   if (NewTemplate) {
1286     // C++ [temp.over.link]p4:
1287     //   The signature of a function template consists of its function
1288     //   signature, its return type and its template parameter list. The names
1289     //   of the template parameters are significant only for establishing the
1290     //   relationship between the template parameters and the rest of the
1291     //   signature.
1292     //
1293     // We check the return type and template parameter lists for function
1294     // templates first; the remaining checks follow.
1295     bool SameTemplateParameterList = TemplateParameterListsAreEqual(
1296         NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1297         OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch);
1298     bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),
1299                                               New->getDeclaredReturnType());
1300     // FIXME(GH58571): Match template parameter list even for non-constrained
1301     // template heads. This currently ensures that the code prior to C++20 is
1302     // not newly broken.
1303     bool ConstraintsInTemplateHead =
1304         NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1305         OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1306     // C++ [namespace.udecl]p11:
1307     //   The set of declarations named by a using-declarator that inhabits a
1308     //   class C does not include member functions and member function
1309     //   templates of a base class that "correspond" to (and thus would
1310     //   conflict with) a declaration of a function or function template in
1311     //   C.
1312     // Comparing return types is not required for the "correspond" check to
1313     // decide whether a member introduced by a shadow declaration is hidden.
1314     if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1315         !SameTemplateParameterList)
1316       return true;
1317     if (!UseMemberUsingDeclRules &&
1318         (!SameTemplateParameterList || !SameReturnType))
1319       return true;
1320   }
1321 
1322   if (ConsiderRequiresClauses) {
1323     Expr *NewRC = New->getTrailingRequiresClause(),
1324          *OldRC = Old->getTrailingRequiresClause();
1325     if ((NewRC != nullptr) != (OldRC != nullptr))
1326       return true;
1327 
1328     if (NewRC && !AreConstraintExpressionsEqual(Old, OldRC, New, NewRC))
1329         return true;
1330   }
1331 
1332   // If the function is a class member, its signature includes the
1333   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1334   //
1335   // As part of this, also check whether one of the member functions
1336   // is static, in which case they are not overloads (C++
1337   // 13.1p2). While not part of the definition of the signature,
1338   // this check is important to determine whether these functions
1339   // can be overloaded.
1340   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1341   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1342   if (OldMethod && NewMethod &&
1343       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1344     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1345       if (!UseMemberUsingDeclRules &&
1346           (OldMethod->getRefQualifier() == RQ_None ||
1347            NewMethod->getRefQualifier() == RQ_None)) {
1348         // C++20 [over.load]p2:
1349         //   - Member function declarations with the same name, the same
1350         //     parameter-type-list, and the same trailing requires-clause (if
1351         //     any), as well as member function template declarations with the
1352         //     same name, the same parameter-type-list, the same trailing
1353         //     requires-clause (if any), and the same template-head, cannot be
1354         //     overloaded if any of them, but not all, have a ref-qualifier.
1355         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1356             << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1357         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1358       }
1359       return true;
1360     }
1361 
1362     // We may not have applied the implicit const for a constexpr member
1363     // function yet (because we haven't yet resolved whether this is a static
1364     // or non-static member function). Add it now, on the assumption that this
1365     // is a redeclaration of OldMethod.
1366     auto OldQuals = OldMethod->getMethodQualifiers();
1367     auto NewQuals = NewMethod->getMethodQualifiers();
1368     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1369         !isa<CXXConstructorDecl>(NewMethod))
1370       NewQuals.addConst();
1371     // We do not allow overloading based off of '__restrict'.
1372     OldQuals.removeRestrict();
1373     NewQuals.removeRestrict();
1374     if (OldQuals != NewQuals)
1375       return true;
1376   }
1377 
1378   // Though pass_object_size is placed on parameters and takes an argument, we
1379   // consider it to be a function-level modifier for the sake of function
1380   // identity. Either the function has one or more parameters with
1381   // pass_object_size or it doesn't.
1382   if (functionHasPassObjectSizeParams(New) !=
1383       functionHasPassObjectSizeParams(Old))
1384     return true;
1385 
1386   // enable_if attributes are an order-sensitive part of the signature.
1387   for (specific_attr_iterator<EnableIfAttr>
1388          NewI = New->specific_attr_begin<EnableIfAttr>(),
1389          NewE = New->specific_attr_end<EnableIfAttr>(),
1390          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1391          OldE = Old->specific_attr_end<EnableIfAttr>();
1392        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1393     if (NewI == NewE || OldI == OldE)
1394       return true;
1395     llvm::FoldingSetNodeID NewID, OldID;
1396     NewI->getCond()->Profile(NewID, Context, true);
1397     OldI->getCond()->Profile(OldID, Context, true);
1398     if (NewID != OldID)
1399       return true;
1400   }
1401 
1402   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1403     // Don't allow overloading of destructors.  (In theory we could, but it
1404     // would be a giant change to clang.)
1405     if (!isa<CXXDestructorDecl>(New)) {
1406       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1407                          OldTarget = IdentifyCUDATarget(Old);
1408       if (NewTarget != CFT_InvalidTarget) {
1409         assert((OldTarget != CFT_InvalidTarget) &&
1410                "Unexpected invalid target.");
1411 
1412         // Allow overloading of functions with same signature and different CUDA
1413         // target attributes.
1414         if (NewTarget != OldTarget)
1415           return true;
1416       }
1417     }
1418   }
1419 
1420   // The signatures match; this is not an overload.
1421   return false;
1422 }
1423 
1424 /// Tries a user-defined conversion from From to ToType.
1425 ///
1426 /// Produces an implicit conversion sequence for when a standard conversion
1427 /// is not an option. See TryImplicitConversion for more information.
1428 static ImplicitConversionSequence
1429 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1430                          bool SuppressUserConversions,
1431                          AllowedExplicit AllowExplicit,
1432                          bool InOverloadResolution,
1433                          bool CStyle,
1434                          bool AllowObjCWritebackConversion,
1435                          bool AllowObjCConversionOnExplicit) {
1436   ImplicitConversionSequence ICS;
1437 
1438   if (SuppressUserConversions) {
1439     // We're not in the case above, so there is no conversion that
1440     // we can perform.
1441     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1442     return ICS;
1443   }
1444 
1445   // Attempt user-defined conversion.
1446   OverloadCandidateSet Conversions(From->getExprLoc(),
1447                                    OverloadCandidateSet::CSK_Normal);
1448   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1449                                   Conversions, AllowExplicit,
1450                                   AllowObjCConversionOnExplicit)) {
1451   case OR_Success:
1452   case OR_Deleted:
1453     ICS.setUserDefined();
1454     // C++ [over.ics.user]p4:
1455     //   A conversion of an expression of class type to the same class
1456     //   type is given Exact Match rank, and a conversion of an
1457     //   expression of class type to a base class of that type is
1458     //   given Conversion rank, in spite of the fact that a copy
1459     //   constructor (i.e., a user-defined conversion function) is
1460     //   called for those cases.
1461     if (CXXConstructorDecl *Constructor
1462           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1463       QualType FromCanon
1464         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1465       QualType ToCanon
1466         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1467       if (Constructor->isCopyConstructor() &&
1468           (FromCanon == ToCanon ||
1469            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1470         // Turn this into a "standard" conversion sequence, so that it
1471         // gets ranked with standard conversion sequences.
1472         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1473         ICS.setStandard();
1474         ICS.Standard.setAsIdentityConversion();
1475         ICS.Standard.setFromType(From->getType());
1476         ICS.Standard.setAllToTypes(ToType);
1477         ICS.Standard.CopyConstructor = Constructor;
1478         ICS.Standard.FoundCopyConstructor = Found;
1479         if (ToCanon != FromCanon)
1480           ICS.Standard.Second = ICK_Derived_To_Base;
1481       }
1482     }
1483     break;
1484 
1485   case OR_Ambiguous:
1486     ICS.setAmbiguous();
1487     ICS.Ambiguous.setFromType(From->getType());
1488     ICS.Ambiguous.setToType(ToType);
1489     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1490          Cand != Conversions.end(); ++Cand)
1491       if (Cand->Best)
1492         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1493     break;
1494 
1495     // Fall through.
1496   case OR_No_Viable_Function:
1497     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1498     break;
1499   }
1500 
1501   return ICS;
1502 }
1503 
1504 /// TryImplicitConversion - Attempt to perform an implicit conversion
1505 /// from the given expression (Expr) to the given type (ToType). This
1506 /// function returns an implicit conversion sequence that can be used
1507 /// to perform the initialization. Given
1508 ///
1509 ///   void f(float f);
1510 ///   void g(int i) { f(i); }
1511 ///
1512 /// this routine would produce an implicit conversion sequence to
1513 /// describe the initialization of f from i, which will be a standard
1514 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1515 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1516 //
1517 /// Note that this routine only determines how the conversion can be
1518 /// performed; it does not actually perform the conversion. As such,
1519 /// it will not produce any diagnostics if no conversion is available,
1520 /// but will instead return an implicit conversion sequence of kind
1521 /// "BadConversion".
1522 ///
1523 /// If @p SuppressUserConversions, then user-defined conversions are
1524 /// not permitted.
1525 /// If @p AllowExplicit, then explicit user-defined conversions are
1526 /// permitted.
1527 ///
1528 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1529 /// writeback conversion, which allows __autoreleasing id* parameters to
1530 /// be initialized with __strong id* or __weak id* arguments.
1531 static ImplicitConversionSequence
1532 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1533                       bool SuppressUserConversions,
1534                       AllowedExplicit AllowExplicit,
1535                       bool InOverloadResolution,
1536                       bool CStyle,
1537                       bool AllowObjCWritebackConversion,
1538                       bool AllowObjCConversionOnExplicit) {
1539   ImplicitConversionSequence ICS;
1540   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1541                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1542     ICS.setStandard();
1543     return ICS;
1544   }
1545 
1546   if (!S.getLangOpts().CPlusPlus) {
1547     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1548     return ICS;
1549   }
1550 
1551   // C++ [over.ics.user]p4:
1552   //   A conversion of an expression of class type to the same class
1553   //   type is given Exact Match rank, and a conversion of an
1554   //   expression of class type to a base class of that type is
1555   //   given Conversion rank, in spite of the fact that a copy/move
1556   //   constructor (i.e., a user-defined conversion function) is
1557   //   called for those cases.
1558   QualType FromType = From->getType();
1559   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1560       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1561        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1562     ICS.setStandard();
1563     ICS.Standard.setAsIdentityConversion();
1564     ICS.Standard.setFromType(FromType);
1565     ICS.Standard.setAllToTypes(ToType);
1566 
1567     // We don't actually check at this point whether there is a valid
1568     // copy/move constructor, since overloading just assumes that it
1569     // exists. When we actually perform initialization, we'll find the
1570     // appropriate constructor to copy the returned object, if needed.
1571     ICS.Standard.CopyConstructor = nullptr;
1572 
1573     // Determine whether this is considered a derived-to-base conversion.
1574     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1575       ICS.Standard.Second = ICK_Derived_To_Base;
1576 
1577     return ICS;
1578   }
1579 
1580   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1581                                   AllowExplicit, InOverloadResolution, CStyle,
1582                                   AllowObjCWritebackConversion,
1583                                   AllowObjCConversionOnExplicit);
1584 }
1585 
1586 ImplicitConversionSequence
1587 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1588                             bool SuppressUserConversions,
1589                             AllowedExplicit AllowExplicit,
1590                             bool InOverloadResolution,
1591                             bool CStyle,
1592                             bool AllowObjCWritebackConversion) {
1593   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1594                                  AllowExplicit, InOverloadResolution, CStyle,
1595                                  AllowObjCWritebackConversion,
1596                                  /*AllowObjCConversionOnExplicit=*/false);
1597 }
1598 
1599 /// PerformImplicitConversion - Perform an implicit conversion of the
1600 /// expression From to the type ToType. Returns the
1601 /// converted expression. Flavor is the kind of conversion we're
1602 /// performing, used in the error message. If @p AllowExplicit,
1603 /// explicit user-defined conversions are permitted.
1604 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1605                                            AssignmentAction Action,
1606                                            bool AllowExplicit) {
1607   if (checkPlaceholderForOverload(*this, From))
1608     return ExprError();
1609 
1610   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1611   bool AllowObjCWritebackConversion
1612     = getLangOpts().ObjCAutoRefCount &&
1613       (Action == AA_Passing || Action == AA_Sending);
1614   if (getLangOpts().ObjC)
1615     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1616                                       From->getType(), From);
1617   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1618       *this, From, ToType,
1619       /*SuppressUserConversions=*/false,
1620       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1621       /*InOverloadResolution=*/false,
1622       /*CStyle=*/false, AllowObjCWritebackConversion,
1623       /*AllowObjCConversionOnExplicit=*/false);
1624   return PerformImplicitConversion(From, ToType, ICS, Action);
1625 }
1626 
1627 /// Determine whether the conversion from FromType to ToType is a valid
1628 /// conversion that strips "noexcept" or "noreturn" off the nested function
1629 /// type.
1630 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1631                                 QualType &ResultTy) {
1632   if (Context.hasSameUnqualifiedType(FromType, ToType))
1633     return false;
1634 
1635   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1636   //                    or F(t noexcept) -> F(t)
1637   // where F adds one of the following at most once:
1638   //   - a pointer
1639   //   - a member pointer
1640   //   - a block pointer
1641   // Changes here need matching changes in FindCompositePointerType.
1642   CanQualType CanTo = Context.getCanonicalType(ToType);
1643   CanQualType CanFrom = Context.getCanonicalType(FromType);
1644   Type::TypeClass TyClass = CanTo->getTypeClass();
1645   if (TyClass != CanFrom->getTypeClass()) return false;
1646   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1647     if (TyClass == Type::Pointer) {
1648       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1649       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1650     } else if (TyClass == Type::BlockPointer) {
1651       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1652       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1653     } else if (TyClass == Type::MemberPointer) {
1654       auto ToMPT = CanTo.castAs<MemberPointerType>();
1655       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1656       // A function pointer conversion cannot change the class of the function.
1657       if (ToMPT->getClass() != FromMPT->getClass())
1658         return false;
1659       CanTo = ToMPT->getPointeeType();
1660       CanFrom = FromMPT->getPointeeType();
1661     } else {
1662       return false;
1663     }
1664 
1665     TyClass = CanTo->getTypeClass();
1666     if (TyClass != CanFrom->getTypeClass()) return false;
1667     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1668       return false;
1669   }
1670 
1671   const auto *FromFn = cast<FunctionType>(CanFrom);
1672   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1673 
1674   const auto *ToFn = cast<FunctionType>(CanTo);
1675   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1676 
1677   bool Changed = false;
1678 
1679   // Drop 'noreturn' if not present in target type.
1680   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1681     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1682     Changed = true;
1683   }
1684 
1685   // Drop 'noexcept' if not present in target type.
1686   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1687     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1688     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1689       FromFn = cast<FunctionType>(
1690           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1691                                                    EST_None)
1692                  .getTypePtr());
1693       Changed = true;
1694     }
1695 
1696     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1697     // only if the ExtParameterInfo lists of the two function prototypes can be
1698     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1699     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1700     bool CanUseToFPT, CanUseFromFPT;
1701     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1702                                       CanUseFromFPT, NewParamInfos) &&
1703         CanUseToFPT && !CanUseFromFPT) {
1704       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1705       ExtInfo.ExtParameterInfos =
1706           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1707       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1708                                             FromFPT->getParamTypes(), ExtInfo);
1709       FromFn = QT->getAs<FunctionType>();
1710       Changed = true;
1711     }
1712   }
1713 
1714   if (!Changed)
1715     return false;
1716 
1717   assert(QualType(FromFn, 0).isCanonical());
1718   if (QualType(FromFn, 0) != CanTo) return false;
1719 
1720   ResultTy = ToType;
1721   return true;
1722 }
1723 
1724 /// Determine whether the conversion from FromType to ToType is a valid
1725 /// vector conversion.
1726 ///
1727 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1728 /// conversion.
1729 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1730                                ImplicitConversionKind &ICK, Expr *From,
1731                                bool InOverloadResolution, bool CStyle) {
1732   // We need at least one of these types to be a vector type to have a vector
1733   // conversion.
1734   if (!ToType->isVectorType() && !FromType->isVectorType())
1735     return false;
1736 
1737   // Identical types require no conversions.
1738   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1739     return false;
1740 
1741   // There are no conversions between extended vector types, only identity.
1742   if (ToType->isExtVectorType()) {
1743     // There are no conversions between extended vector types other than the
1744     // identity conversion.
1745     if (FromType->isExtVectorType())
1746       return false;
1747 
1748     // Vector splat from any arithmetic type to a vector.
1749     if (FromType->isArithmeticType()) {
1750       ICK = ICK_Vector_Splat;
1751       return true;
1752     }
1753   }
1754 
1755   if (ToType->isSVESizelessBuiltinType() ||
1756       FromType->isSVESizelessBuiltinType())
1757     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1758         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1759       ICK = ICK_SVE_Vector_Conversion;
1760       return true;
1761     }
1762 
1763   if (ToType->isRVVSizelessBuiltinType() ||
1764       FromType->isRVVSizelessBuiltinType())
1765     if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
1766         S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
1767       ICK = ICK_RVV_Vector_Conversion;
1768       return true;
1769     }
1770 
1771   // We can perform the conversion between vector types in the following cases:
1772   // 1)vector types are equivalent AltiVec and GCC vector types
1773   // 2)lax vector conversions are permitted and the vector types are of the
1774   //   same size
1775   // 3)the destination type does not have the ARM MVE strict-polymorphism
1776   //   attribute, which inhibits lax vector conversion for overload resolution
1777   //   only
1778   if (ToType->isVectorType() && FromType->isVectorType()) {
1779     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1780         (S.isLaxVectorConversion(FromType, ToType) &&
1781          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1782       if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
1783           S.isLaxVectorConversion(FromType, ToType) &&
1784           S.anyAltivecTypes(FromType, ToType) &&
1785           !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
1786           !InOverloadResolution && !CStyle) {
1787         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1788             << FromType << ToType;
1789       }
1790       ICK = ICK_Vector_Conversion;
1791       return true;
1792     }
1793   }
1794 
1795   return false;
1796 }
1797 
1798 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1799                                 bool InOverloadResolution,
1800                                 StandardConversionSequence &SCS,
1801                                 bool CStyle);
1802 
1803 /// IsStandardConversion - Determines whether there is a standard
1804 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1805 /// expression From to the type ToType. Standard conversion sequences
1806 /// only consider non-class types; for conversions that involve class
1807 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1808 /// contain the standard conversion sequence required to perform this
1809 /// conversion and this routine will return true. Otherwise, this
1810 /// routine will return false and the value of SCS is unspecified.
1811 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1812                                  bool InOverloadResolution,
1813                                  StandardConversionSequence &SCS,
1814                                  bool CStyle,
1815                                  bool AllowObjCWritebackConversion) {
1816   QualType FromType = From->getType();
1817 
1818   // Standard conversions (C++ [conv])
1819   SCS.setAsIdentityConversion();
1820   SCS.IncompatibleObjC = false;
1821   SCS.setFromType(FromType);
1822   SCS.CopyConstructor = nullptr;
1823 
1824   // There are no standard conversions for class types in C++, so
1825   // abort early. When overloading in C, however, we do permit them.
1826   if (S.getLangOpts().CPlusPlus &&
1827       (FromType->isRecordType() || ToType->isRecordType()))
1828     return false;
1829 
1830   // The first conversion can be an lvalue-to-rvalue conversion,
1831   // array-to-pointer conversion, or function-to-pointer conversion
1832   // (C++ 4p1).
1833 
1834   if (FromType == S.Context.OverloadTy) {
1835     DeclAccessPair AccessPair;
1836     if (FunctionDecl *Fn
1837           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1838                                                  AccessPair)) {
1839       // We were able to resolve the address of the overloaded function,
1840       // so we can convert to the type of that function.
1841       FromType = Fn->getType();
1842       SCS.setFromType(FromType);
1843 
1844       // we can sometimes resolve &foo<int> regardless of ToType, so check
1845       // if the type matches (identity) or we are converting to bool
1846       if (!S.Context.hasSameUnqualifiedType(
1847                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1848         QualType resultTy;
1849         // if the function type matches except for [[noreturn]], it's ok
1850         if (!S.IsFunctionConversion(FromType,
1851               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1852           // otherwise, only a boolean conversion is standard
1853           if (!ToType->isBooleanType())
1854             return false;
1855       }
1856 
1857       // Check if the "from" expression is taking the address of an overloaded
1858       // function and recompute the FromType accordingly. Take advantage of the
1859       // fact that non-static member functions *must* have such an address-of
1860       // expression.
1861       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1862       if (Method && !Method->isStatic()) {
1863         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1864                "Non-unary operator on non-static member address");
1865         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1866                == UO_AddrOf &&
1867                "Non-address-of operator on non-static member address");
1868         const Type *ClassType
1869           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1870         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1871       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1872         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1873                UO_AddrOf &&
1874                "Non-address-of operator for overloaded function expression");
1875         FromType = S.Context.getPointerType(FromType);
1876       }
1877     } else {
1878       return false;
1879     }
1880   }
1881   // Lvalue-to-rvalue conversion (C++11 4.1):
1882   //   A glvalue (3.10) of a non-function, non-array type T can
1883   //   be converted to a prvalue.
1884   bool argIsLValue = From->isGLValue();
1885   if (argIsLValue &&
1886       !FromType->isFunctionType() && !FromType->isArrayType() &&
1887       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1888     SCS.First = ICK_Lvalue_To_Rvalue;
1889 
1890     // C11 6.3.2.1p2:
1891     //   ... if the lvalue has atomic type, the value has the non-atomic version
1892     //   of the type of the lvalue ...
1893     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1894       FromType = Atomic->getValueType();
1895 
1896     // If T is a non-class type, the type of the rvalue is the
1897     // cv-unqualified version of T. Otherwise, the type of the rvalue
1898     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1899     // just strip the qualifiers because they don't matter.
1900     FromType = FromType.getUnqualifiedType();
1901   } else if (FromType->isArrayType()) {
1902     // Array-to-pointer conversion (C++ 4.2)
1903     SCS.First = ICK_Array_To_Pointer;
1904 
1905     // An lvalue or rvalue of type "array of N T" or "array of unknown
1906     // bound of T" can be converted to an rvalue of type "pointer to
1907     // T" (C++ 4.2p1).
1908     FromType = S.Context.getArrayDecayedType(FromType);
1909 
1910     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1911       // This conversion is deprecated in C++03 (D.4)
1912       SCS.DeprecatedStringLiteralToCharPtr = true;
1913 
1914       // For the purpose of ranking in overload resolution
1915       // (13.3.3.1.1), this conversion is considered an
1916       // array-to-pointer conversion followed by a qualification
1917       // conversion (4.4). (C++ 4.2p2)
1918       SCS.Second = ICK_Identity;
1919       SCS.Third = ICK_Qualification;
1920       SCS.QualificationIncludesObjCLifetime = false;
1921       SCS.setAllToTypes(FromType);
1922       return true;
1923     }
1924   } else if (FromType->isFunctionType() && argIsLValue) {
1925     // Function-to-pointer conversion (C++ 4.3).
1926     SCS.First = ICK_Function_To_Pointer;
1927 
1928     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1929       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1930         if (!S.checkAddressOfFunctionIsAvailable(FD))
1931           return false;
1932 
1933     // An lvalue of function type T can be converted to an rvalue of
1934     // type "pointer to T." The result is a pointer to the
1935     // function. (C++ 4.3p1).
1936     FromType = S.Context.getPointerType(FromType);
1937   } else {
1938     // We don't require any conversions for the first step.
1939     SCS.First = ICK_Identity;
1940   }
1941   SCS.setToType(0, FromType);
1942 
1943   // The second conversion can be an integral promotion, floating
1944   // point promotion, integral conversion, floating point conversion,
1945   // floating-integral conversion, pointer conversion,
1946   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1947   // For overloading in C, this can also be a "compatible-type"
1948   // conversion.
1949   bool IncompatibleObjC = false;
1950   ImplicitConversionKind SecondICK = ICK_Identity;
1951   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1952     // The unqualified versions of the types are the same: there's no
1953     // conversion to do.
1954     SCS.Second = ICK_Identity;
1955   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1956     // Integral promotion (C++ 4.5).
1957     SCS.Second = ICK_Integral_Promotion;
1958     FromType = ToType.getUnqualifiedType();
1959   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1960     // Floating point promotion (C++ 4.6).
1961     SCS.Second = ICK_Floating_Promotion;
1962     FromType = ToType.getUnqualifiedType();
1963   } else if (S.IsComplexPromotion(FromType, ToType)) {
1964     // Complex promotion (Clang extension)
1965     SCS.Second = ICK_Complex_Promotion;
1966     FromType = ToType.getUnqualifiedType();
1967   } else if (ToType->isBooleanType() &&
1968              (FromType->isArithmeticType() ||
1969               FromType->isAnyPointerType() ||
1970               FromType->isBlockPointerType() ||
1971               FromType->isMemberPointerType())) {
1972     // Boolean conversions (C++ 4.12).
1973     SCS.Second = ICK_Boolean_Conversion;
1974     FromType = S.Context.BoolTy;
1975   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1976              ToType->isIntegralType(S.Context)) {
1977     // Integral conversions (C++ 4.7).
1978     SCS.Second = ICK_Integral_Conversion;
1979     FromType = ToType.getUnqualifiedType();
1980   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1981     // Complex conversions (C99 6.3.1.6)
1982     SCS.Second = ICK_Complex_Conversion;
1983     FromType = ToType.getUnqualifiedType();
1984   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1985              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1986     // Complex-real conversions (C99 6.3.1.7)
1987     SCS.Second = ICK_Complex_Real;
1988     FromType = ToType.getUnqualifiedType();
1989   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1990     // FIXME: disable conversions between long double, __ibm128 and __float128
1991     // if their representation is different until there is back end support
1992     // We of course allow this conversion if long double is really double.
1993 
1994     // Conversions between bfloat16 and float16 are currently not supported.
1995     if ((FromType->isBFloat16Type() &&
1996          (ToType->isFloat16Type() || ToType->isHalfType())) ||
1997         (ToType->isBFloat16Type() &&
1998          (FromType->isFloat16Type() || FromType->isHalfType())))
1999       return false;
2000 
2001     // Conversions between IEEE-quad and IBM-extended semantics are not
2002     // permitted.
2003     const llvm::fltSemantics &FromSem =
2004         S.Context.getFloatTypeSemantics(FromType);
2005     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2006     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2007          &ToSem == &llvm::APFloat::IEEEquad()) ||
2008         (&FromSem == &llvm::APFloat::IEEEquad() &&
2009          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2010       return false;
2011 
2012     // Floating point conversions (C++ 4.8).
2013     SCS.Second = ICK_Floating_Conversion;
2014     FromType = ToType.getUnqualifiedType();
2015   } else if ((FromType->isRealFloatingType() &&
2016               ToType->isIntegralType(S.Context)) ||
2017              (FromType->isIntegralOrUnscopedEnumerationType() &&
2018               ToType->isRealFloatingType())) {
2019 
2020     // Floating-integral conversions (C++ 4.9).
2021     SCS.Second = ICK_Floating_Integral;
2022     FromType = ToType.getUnqualifiedType();
2023   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2024     SCS.Second = ICK_Block_Pointer_Conversion;
2025   } else if (AllowObjCWritebackConversion &&
2026              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
2027     SCS.Second = ICK_Writeback_Conversion;
2028   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2029                                    FromType, IncompatibleObjC)) {
2030     // Pointer conversions (C++ 4.10).
2031     SCS.Second = ICK_Pointer_Conversion;
2032     SCS.IncompatibleObjC = IncompatibleObjC;
2033     FromType = FromType.getUnqualifiedType();
2034   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2035                                          InOverloadResolution, FromType)) {
2036     // Pointer to member conversions (4.11).
2037     SCS.Second = ICK_Pointer_Member;
2038   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
2039                                 InOverloadResolution, CStyle)) {
2040     SCS.Second = SecondICK;
2041     FromType = ToType.getUnqualifiedType();
2042   } else if (!S.getLangOpts().CPlusPlus &&
2043              S.Context.typesAreCompatible(ToType, FromType)) {
2044     // Compatible conversions (Clang extension for C function overloading)
2045     SCS.Second = ICK_Compatible_Conversion;
2046     FromType = ToType.getUnqualifiedType();
2047   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
2048                                              InOverloadResolution,
2049                                              SCS, CStyle)) {
2050     SCS.Second = ICK_TransparentUnionConversion;
2051     FromType = ToType;
2052   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2053                                  CStyle)) {
2054     // tryAtomicConversion has updated the standard conversion sequence
2055     // appropriately.
2056     return true;
2057   } else if (ToType->isEventT() &&
2058              From->isIntegerConstantExpr(S.getASTContext()) &&
2059              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2060     SCS.Second = ICK_Zero_Event_Conversion;
2061     FromType = ToType;
2062   } else if (ToType->isQueueT() &&
2063              From->isIntegerConstantExpr(S.getASTContext()) &&
2064              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2065     SCS.Second = ICK_Zero_Queue_Conversion;
2066     FromType = ToType;
2067   } else if (ToType->isSamplerT() &&
2068              From->isIntegerConstantExpr(S.getASTContext())) {
2069     SCS.Second = ICK_Compatible_Conversion;
2070     FromType = ToType;
2071   } else {
2072     // No second conversion required.
2073     SCS.Second = ICK_Identity;
2074   }
2075   SCS.setToType(1, FromType);
2076 
2077   // The third conversion can be a function pointer conversion or a
2078   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2079   bool ObjCLifetimeConversion;
2080   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2081     // Function pointer conversions (removing 'noexcept') including removal of
2082     // 'noreturn' (Clang extension).
2083     SCS.Third = ICK_Function_Conversion;
2084   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2085                                          ObjCLifetimeConversion)) {
2086     SCS.Third = ICK_Qualification;
2087     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2088     FromType = ToType;
2089   } else {
2090     // No conversion required
2091     SCS.Third = ICK_Identity;
2092   }
2093 
2094   // C++ [over.best.ics]p6:
2095   //   [...] Any difference in top-level cv-qualification is
2096   //   subsumed by the initialization itself and does not constitute
2097   //   a conversion. [...]
2098   QualType CanonFrom = S.Context.getCanonicalType(FromType);
2099   QualType CanonTo = S.Context.getCanonicalType(ToType);
2100   if (CanonFrom.getLocalUnqualifiedType()
2101                                      == CanonTo.getLocalUnqualifiedType() &&
2102       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2103     FromType = ToType;
2104     CanonFrom = CanonTo;
2105   }
2106 
2107   SCS.setToType(2, FromType);
2108 
2109   if (CanonFrom == CanonTo)
2110     return true;
2111 
2112   // If we have not converted the argument type to the parameter type,
2113   // this is a bad conversion sequence, unless we're resolving an overload in C.
2114   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2115     return false;
2116 
2117   ExprResult ER = ExprResult{From};
2118   Sema::AssignConvertType Conv =
2119       S.CheckSingleAssignmentConstraints(ToType, ER,
2120                                          /*Diagnose=*/false,
2121                                          /*DiagnoseCFAudited=*/false,
2122                                          /*ConvertRHS=*/false);
2123   ImplicitConversionKind SecondConv;
2124   switch (Conv) {
2125   case Sema::Compatible:
2126     SecondConv = ICK_C_Only_Conversion;
2127     break;
2128   // For our purposes, discarding qualifiers is just as bad as using an
2129   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2130   // qualifiers, as well.
2131   case Sema::CompatiblePointerDiscardsQualifiers:
2132   case Sema::IncompatiblePointer:
2133   case Sema::IncompatiblePointerSign:
2134     SecondConv = ICK_Incompatible_Pointer_Conversion;
2135     break;
2136   default:
2137     return false;
2138   }
2139 
2140   // First can only be an lvalue conversion, so we pretend that this was the
2141   // second conversion. First should already be valid from earlier in the
2142   // function.
2143   SCS.Second = SecondConv;
2144   SCS.setToType(1, ToType);
2145 
2146   // Third is Identity, because Second should rank us worse than any other
2147   // conversion. This could also be ICK_Qualification, but it's simpler to just
2148   // lump everything in with the second conversion, and we don't gain anything
2149   // from making this ICK_Qualification.
2150   SCS.Third = ICK_Identity;
2151   SCS.setToType(2, ToType);
2152   return true;
2153 }
2154 
2155 static bool
2156 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2157                                      QualType &ToType,
2158                                      bool InOverloadResolution,
2159                                      StandardConversionSequence &SCS,
2160                                      bool CStyle) {
2161 
2162   const RecordType *UT = ToType->getAsUnionType();
2163   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2164     return false;
2165   // The field to initialize within the transparent union.
2166   RecordDecl *UD = UT->getDecl();
2167   // It's compatible if the expression matches any of the fields.
2168   for (const auto *it : UD->fields()) {
2169     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2170                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2171       ToType = it->getType();
2172       return true;
2173     }
2174   }
2175   return false;
2176 }
2177 
2178 /// IsIntegralPromotion - Determines whether the conversion from the
2179 /// expression From (whose potentially-adjusted type is FromType) to
2180 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2181 /// sets PromotedType to the promoted type.
2182 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2183   const BuiltinType *To = ToType->getAs<BuiltinType>();
2184   // All integers are built-in.
2185   if (!To) {
2186     return false;
2187   }
2188 
2189   // An rvalue of type char, signed char, unsigned char, short int, or
2190   // unsigned short int can be converted to an rvalue of type int if
2191   // int can represent all the values of the source type; otherwise,
2192   // the source rvalue can be converted to an rvalue of type unsigned
2193   // int (C++ 4.5p1).
2194   if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2195       !FromType->isEnumeralType()) {
2196     if ( // We can promote any signed, promotable integer type to an int
2197         (FromType->isSignedIntegerType() ||
2198          // We can promote any unsigned integer type whose size is
2199          // less than int to an int.
2200          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2201       return To->getKind() == BuiltinType::Int;
2202     }
2203 
2204     return To->getKind() == BuiltinType::UInt;
2205   }
2206 
2207   // C++11 [conv.prom]p3:
2208   //   A prvalue of an unscoped enumeration type whose underlying type is not
2209   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2210   //   following types that can represent all the values of the enumeration
2211   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2212   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2213   //   long long int. If none of the types in that list can represent all the
2214   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2215   //   type can be converted to an rvalue a prvalue of the extended integer type
2216   //   with lowest integer conversion rank (4.13) greater than the rank of long
2217   //   long in which all the values of the enumeration can be represented. If
2218   //   there are two such extended types, the signed one is chosen.
2219   // C++11 [conv.prom]p4:
2220   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2221   //   can be converted to a prvalue of its underlying type. Moreover, if
2222   //   integral promotion can be applied to its underlying type, a prvalue of an
2223   //   unscoped enumeration type whose underlying type is fixed can also be
2224   //   converted to a prvalue of the promoted underlying type.
2225   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2226     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2227     // provided for a scoped enumeration.
2228     if (FromEnumType->getDecl()->isScoped())
2229       return false;
2230 
2231     // We can perform an integral promotion to the underlying type of the enum,
2232     // even if that's not the promoted type. Note that the check for promoting
2233     // the underlying type is based on the type alone, and does not consider
2234     // the bitfield-ness of the actual source expression.
2235     if (FromEnumType->getDecl()->isFixed()) {
2236       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2237       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2238              IsIntegralPromotion(nullptr, Underlying, ToType);
2239     }
2240 
2241     // We have already pre-calculated the promotion type, so this is trivial.
2242     if (ToType->isIntegerType() &&
2243         isCompleteType(From->getBeginLoc(), FromType))
2244       return Context.hasSameUnqualifiedType(
2245           ToType, FromEnumType->getDecl()->getPromotionType());
2246 
2247     // C++ [conv.prom]p5:
2248     //   If the bit-field has an enumerated type, it is treated as any other
2249     //   value of that type for promotion purposes.
2250     //
2251     // ... so do not fall through into the bit-field checks below in C++.
2252     if (getLangOpts().CPlusPlus)
2253       return false;
2254   }
2255 
2256   // C++0x [conv.prom]p2:
2257   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2258   //   to an rvalue a prvalue of the first of the following types that can
2259   //   represent all the values of its underlying type: int, unsigned int,
2260   //   long int, unsigned long int, long long int, or unsigned long long int.
2261   //   If none of the types in that list can represent all the values of its
2262   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2263   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2264   //   type.
2265   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2266       ToType->isIntegerType()) {
2267     // Determine whether the type we're converting from is signed or
2268     // unsigned.
2269     bool FromIsSigned = FromType->isSignedIntegerType();
2270     uint64_t FromSize = Context.getTypeSize(FromType);
2271 
2272     // The types we'll try to promote to, in the appropriate
2273     // order. Try each of these types.
2274     QualType PromoteTypes[6] = {
2275       Context.IntTy, Context.UnsignedIntTy,
2276       Context.LongTy, Context.UnsignedLongTy ,
2277       Context.LongLongTy, Context.UnsignedLongLongTy
2278     };
2279     for (int Idx = 0; Idx < 6; ++Idx) {
2280       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2281       if (FromSize < ToSize ||
2282           (FromSize == ToSize &&
2283            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2284         // We found the type that we can promote to. If this is the
2285         // type we wanted, we have a promotion. Otherwise, no
2286         // promotion.
2287         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2288       }
2289     }
2290   }
2291 
2292   // An rvalue for an integral bit-field (9.6) can be converted to an
2293   // rvalue of type int if int can represent all the values of the
2294   // bit-field; otherwise, it can be converted to unsigned int if
2295   // unsigned int can represent all the values of the bit-field. If
2296   // the bit-field is larger yet, no integral promotion applies to
2297   // it. If the bit-field has an enumerated type, it is treated as any
2298   // other value of that type for promotion purposes (C++ 4.5p3).
2299   // FIXME: We should delay checking of bit-fields until we actually perform the
2300   // conversion.
2301   //
2302   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2303   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2304   // bit-fields and those whose underlying type is larger than int) for GCC
2305   // compatibility.
2306   if (From) {
2307     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2308       std::optional<llvm::APSInt> BitWidth;
2309       if (FromType->isIntegralType(Context) &&
2310           (BitWidth =
2311                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2312         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2313         ToSize = Context.getTypeSize(ToType);
2314 
2315         // Are we promoting to an int from a bitfield that fits in an int?
2316         if (*BitWidth < ToSize ||
2317             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2318           return To->getKind() == BuiltinType::Int;
2319         }
2320 
2321         // Are we promoting to an unsigned int from an unsigned bitfield
2322         // that fits into an unsigned int?
2323         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2324           return To->getKind() == BuiltinType::UInt;
2325         }
2326 
2327         return false;
2328       }
2329     }
2330   }
2331 
2332   // An rvalue of type bool can be converted to an rvalue of type int,
2333   // with false becoming zero and true becoming one (C++ 4.5p4).
2334   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2335     return true;
2336   }
2337 
2338   return false;
2339 }
2340 
2341 /// IsFloatingPointPromotion - Determines whether the conversion from
2342 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2343 /// returns true and sets PromotedType to the promoted type.
2344 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2345   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2346     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2347       /// An rvalue of type float can be converted to an rvalue of type
2348       /// double. (C++ 4.6p1).
2349       if (FromBuiltin->getKind() == BuiltinType::Float &&
2350           ToBuiltin->getKind() == BuiltinType::Double)
2351         return true;
2352 
2353       // C99 6.3.1.5p1:
2354       //   When a float is promoted to double or long double, or a
2355       //   double is promoted to long double [...].
2356       if (!getLangOpts().CPlusPlus &&
2357           (FromBuiltin->getKind() == BuiltinType::Float ||
2358            FromBuiltin->getKind() == BuiltinType::Double) &&
2359           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2360            ToBuiltin->getKind() == BuiltinType::Float128 ||
2361            ToBuiltin->getKind() == BuiltinType::Ibm128))
2362         return true;
2363 
2364       // Half can be promoted to float.
2365       if (!getLangOpts().NativeHalfType &&
2366            FromBuiltin->getKind() == BuiltinType::Half &&
2367           ToBuiltin->getKind() == BuiltinType::Float)
2368         return true;
2369     }
2370 
2371   return false;
2372 }
2373 
2374 /// Determine if a conversion is a complex promotion.
2375 ///
2376 /// A complex promotion is defined as a complex -> complex conversion
2377 /// where the conversion between the underlying real types is a
2378 /// floating-point or integral promotion.
2379 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2380   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2381   if (!FromComplex)
2382     return false;
2383 
2384   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2385   if (!ToComplex)
2386     return false;
2387 
2388   return IsFloatingPointPromotion(FromComplex->getElementType(),
2389                                   ToComplex->getElementType()) ||
2390     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2391                         ToComplex->getElementType());
2392 }
2393 
2394 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2395 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2396 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2397 /// if non-empty, will be a pointer to ToType that may or may not have
2398 /// the right set of qualifiers on its pointee.
2399 ///
2400 static QualType
2401 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2402                                    QualType ToPointee, QualType ToType,
2403                                    ASTContext &Context,
2404                                    bool StripObjCLifetime = false) {
2405   assert((FromPtr->getTypeClass() == Type::Pointer ||
2406           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2407          "Invalid similarly-qualified pointer type");
2408 
2409   /// Conversions to 'id' subsume cv-qualifier conversions.
2410   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2411     return ToType.getUnqualifiedType();
2412 
2413   QualType CanonFromPointee
2414     = Context.getCanonicalType(FromPtr->getPointeeType());
2415   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2416   Qualifiers Quals = CanonFromPointee.getQualifiers();
2417 
2418   if (StripObjCLifetime)
2419     Quals.removeObjCLifetime();
2420 
2421   // Exact qualifier match -> return the pointer type we're converting to.
2422   if (CanonToPointee.getLocalQualifiers() == Quals) {
2423     // ToType is exactly what we need. Return it.
2424     if (!ToType.isNull())
2425       return ToType.getUnqualifiedType();
2426 
2427     // Build a pointer to ToPointee. It has the right qualifiers
2428     // already.
2429     if (isa<ObjCObjectPointerType>(ToType))
2430       return Context.getObjCObjectPointerType(ToPointee);
2431     return Context.getPointerType(ToPointee);
2432   }
2433 
2434   // Just build a canonical type that has the right qualifiers.
2435   QualType QualifiedCanonToPointee
2436     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2437 
2438   if (isa<ObjCObjectPointerType>(ToType))
2439     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2440   return Context.getPointerType(QualifiedCanonToPointee);
2441 }
2442 
2443 static bool isNullPointerConstantForConversion(Expr *Expr,
2444                                                bool InOverloadResolution,
2445                                                ASTContext &Context) {
2446   // Handle value-dependent integral null pointer constants correctly.
2447   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2448   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2449       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2450     return !InOverloadResolution;
2451 
2452   return Expr->isNullPointerConstant(Context,
2453                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2454                                         : Expr::NPC_ValueDependentIsNull);
2455 }
2456 
2457 /// IsPointerConversion - Determines whether the conversion of the
2458 /// expression From, which has the (possibly adjusted) type FromType,
2459 /// can be converted to the type ToType via a pointer conversion (C++
2460 /// 4.10). If so, returns true and places the converted type (that
2461 /// might differ from ToType in its cv-qualifiers at some level) into
2462 /// ConvertedType.
2463 ///
2464 /// This routine also supports conversions to and from block pointers
2465 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2466 /// pointers to interfaces. FIXME: Once we've determined the
2467 /// appropriate overloading rules for Objective-C, we may want to
2468 /// split the Objective-C checks into a different routine; however,
2469 /// GCC seems to consider all of these conversions to be pointer
2470 /// conversions, so for now they live here. IncompatibleObjC will be
2471 /// set if the conversion is an allowed Objective-C conversion that
2472 /// should result in a warning.
2473 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2474                                bool InOverloadResolution,
2475                                QualType& ConvertedType,
2476                                bool &IncompatibleObjC) {
2477   IncompatibleObjC = false;
2478   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2479                               IncompatibleObjC))
2480     return true;
2481 
2482   // Conversion from a null pointer constant to any Objective-C pointer type.
2483   if (ToType->isObjCObjectPointerType() &&
2484       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2485     ConvertedType = ToType;
2486     return true;
2487   }
2488 
2489   // Blocks: Block pointers can be converted to void*.
2490   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2491       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2492     ConvertedType = ToType;
2493     return true;
2494   }
2495   // Blocks: A null pointer constant can be converted to a block
2496   // pointer type.
2497   if (ToType->isBlockPointerType() &&
2498       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2499     ConvertedType = ToType;
2500     return true;
2501   }
2502 
2503   // If the left-hand-side is nullptr_t, the right side can be a null
2504   // pointer constant.
2505   if (ToType->isNullPtrType() &&
2506       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2507     ConvertedType = ToType;
2508     return true;
2509   }
2510 
2511   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2512   if (!ToTypePtr)
2513     return false;
2514 
2515   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2516   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2517     ConvertedType = ToType;
2518     return true;
2519   }
2520 
2521   // Beyond this point, both types need to be pointers
2522   // , including objective-c pointers.
2523   QualType ToPointeeType = ToTypePtr->getPointeeType();
2524   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2525       !getLangOpts().ObjCAutoRefCount) {
2526     ConvertedType = BuildSimilarlyQualifiedPointerType(
2527         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2528         Context);
2529     return true;
2530   }
2531   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2532   if (!FromTypePtr)
2533     return false;
2534 
2535   QualType FromPointeeType = FromTypePtr->getPointeeType();
2536 
2537   // If the unqualified pointee types are the same, this can't be a
2538   // pointer conversion, so don't do all of the work below.
2539   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2540     return false;
2541 
2542   // An rvalue of type "pointer to cv T," where T is an object type,
2543   // can be converted to an rvalue of type "pointer to cv void" (C++
2544   // 4.10p2).
2545   if (FromPointeeType->isIncompleteOrObjectType() &&
2546       ToPointeeType->isVoidType()) {
2547     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2548                                                        ToPointeeType,
2549                                                        ToType, Context,
2550                                                    /*StripObjCLifetime=*/true);
2551     return true;
2552   }
2553 
2554   // MSVC allows implicit function to void* type conversion.
2555   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2556       ToPointeeType->isVoidType()) {
2557     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2558                                                        ToPointeeType,
2559                                                        ToType, Context);
2560     return true;
2561   }
2562 
2563   // When we're overloading in C, we allow a special kind of pointer
2564   // conversion for compatible-but-not-identical pointee types.
2565   if (!getLangOpts().CPlusPlus &&
2566       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2567     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2568                                                        ToPointeeType,
2569                                                        ToType, Context);
2570     return true;
2571   }
2572 
2573   // C++ [conv.ptr]p3:
2574   //
2575   //   An rvalue of type "pointer to cv D," where D is a class type,
2576   //   can be converted to an rvalue of type "pointer to cv B," where
2577   //   B is a base class (clause 10) of D. If B is an inaccessible
2578   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2579   //   necessitates this conversion is ill-formed. The result of the
2580   //   conversion is a pointer to the base class sub-object of the
2581   //   derived class object. The null pointer value is converted to
2582   //   the null pointer value of the destination type.
2583   //
2584   // Note that we do not check for ambiguity or inaccessibility
2585   // here. That is handled by CheckPointerConversion.
2586   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2587       ToPointeeType->isRecordType() &&
2588       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2589       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2590     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2591                                                        ToPointeeType,
2592                                                        ToType, Context);
2593     return true;
2594   }
2595 
2596   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2597       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2598     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2599                                                        ToPointeeType,
2600                                                        ToType, Context);
2601     return true;
2602   }
2603 
2604   return false;
2605 }
2606 
2607 /// Adopt the given qualifiers for the given type.
2608 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2609   Qualifiers TQs = T.getQualifiers();
2610 
2611   // Check whether qualifiers already match.
2612   if (TQs == Qs)
2613     return T;
2614 
2615   if (Qs.compatiblyIncludes(TQs))
2616     return Context.getQualifiedType(T, Qs);
2617 
2618   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2619 }
2620 
2621 /// isObjCPointerConversion - Determines whether this is an
2622 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2623 /// with the same arguments and return values.
2624 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2625                                    QualType& ConvertedType,
2626                                    bool &IncompatibleObjC) {
2627   if (!getLangOpts().ObjC)
2628     return false;
2629 
2630   // The set of qualifiers on the type we're converting from.
2631   Qualifiers FromQualifiers = FromType.getQualifiers();
2632 
2633   // First, we handle all conversions on ObjC object pointer types.
2634   const ObjCObjectPointerType* ToObjCPtr =
2635     ToType->getAs<ObjCObjectPointerType>();
2636   const ObjCObjectPointerType *FromObjCPtr =
2637     FromType->getAs<ObjCObjectPointerType>();
2638 
2639   if (ToObjCPtr && FromObjCPtr) {
2640     // If the pointee types are the same (ignoring qualifications),
2641     // then this is not a pointer conversion.
2642     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2643                                        FromObjCPtr->getPointeeType()))
2644       return false;
2645 
2646     // Conversion between Objective-C pointers.
2647     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2648       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2649       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2650       if (getLangOpts().CPlusPlus && LHS && RHS &&
2651           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2652                                                 FromObjCPtr->getPointeeType()))
2653         return false;
2654       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2655                                                    ToObjCPtr->getPointeeType(),
2656                                                          ToType, Context);
2657       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2658       return true;
2659     }
2660 
2661     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2662       // Okay: this is some kind of implicit downcast of Objective-C
2663       // interfaces, which is permitted. However, we're going to
2664       // complain about it.
2665       IncompatibleObjC = true;
2666       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2667                                                    ToObjCPtr->getPointeeType(),
2668                                                          ToType, Context);
2669       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2670       return true;
2671     }
2672   }
2673   // Beyond this point, both types need to be C pointers or block pointers.
2674   QualType ToPointeeType;
2675   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2676     ToPointeeType = ToCPtr->getPointeeType();
2677   else if (const BlockPointerType *ToBlockPtr =
2678             ToType->getAs<BlockPointerType>()) {
2679     // Objective C++: We're able to convert from a pointer to any object
2680     // to a block pointer type.
2681     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2682       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2683       return true;
2684     }
2685     ToPointeeType = ToBlockPtr->getPointeeType();
2686   }
2687   else if (FromType->getAs<BlockPointerType>() &&
2688            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2689     // Objective C++: We're able to convert from a block pointer type to a
2690     // pointer to any object.
2691     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2692     return true;
2693   }
2694   else
2695     return false;
2696 
2697   QualType FromPointeeType;
2698   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2699     FromPointeeType = FromCPtr->getPointeeType();
2700   else if (const BlockPointerType *FromBlockPtr =
2701            FromType->getAs<BlockPointerType>())
2702     FromPointeeType = FromBlockPtr->getPointeeType();
2703   else
2704     return false;
2705 
2706   // If we have pointers to pointers, recursively check whether this
2707   // is an Objective-C conversion.
2708   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2709       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2710                               IncompatibleObjC)) {
2711     // We always complain about this conversion.
2712     IncompatibleObjC = true;
2713     ConvertedType = Context.getPointerType(ConvertedType);
2714     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2715     return true;
2716   }
2717   // Allow conversion of pointee being objective-c pointer to another one;
2718   // as in I* to id.
2719   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2720       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2721       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2722                               IncompatibleObjC)) {
2723 
2724     ConvertedType = Context.getPointerType(ConvertedType);
2725     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2726     return true;
2727   }
2728 
2729   // If we have pointers to functions or blocks, check whether the only
2730   // differences in the argument and result types are in Objective-C
2731   // pointer conversions. If so, we permit the conversion (but
2732   // complain about it).
2733   const FunctionProtoType *FromFunctionType
2734     = FromPointeeType->getAs<FunctionProtoType>();
2735   const FunctionProtoType *ToFunctionType
2736     = ToPointeeType->getAs<FunctionProtoType>();
2737   if (FromFunctionType && ToFunctionType) {
2738     // If the function types are exactly the same, this isn't an
2739     // Objective-C pointer conversion.
2740     if (Context.getCanonicalType(FromPointeeType)
2741           == Context.getCanonicalType(ToPointeeType))
2742       return false;
2743 
2744     // Perform the quick checks that will tell us whether these
2745     // function types are obviously different.
2746     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2747         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2748         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2749       return false;
2750 
2751     bool HasObjCConversion = false;
2752     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2753         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2754       // Okay, the types match exactly. Nothing to do.
2755     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2756                                        ToFunctionType->getReturnType(),
2757                                        ConvertedType, IncompatibleObjC)) {
2758       // Okay, we have an Objective-C pointer conversion.
2759       HasObjCConversion = true;
2760     } else {
2761       // Function types are too different. Abort.
2762       return false;
2763     }
2764 
2765     // Check argument types.
2766     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2767          ArgIdx != NumArgs; ++ArgIdx) {
2768       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2769       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2770       if (Context.getCanonicalType(FromArgType)
2771             == Context.getCanonicalType(ToArgType)) {
2772         // Okay, the types match exactly. Nothing to do.
2773       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2774                                          ConvertedType, IncompatibleObjC)) {
2775         // Okay, we have an Objective-C pointer conversion.
2776         HasObjCConversion = true;
2777       } else {
2778         // Argument types are too different. Abort.
2779         return false;
2780       }
2781     }
2782 
2783     if (HasObjCConversion) {
2784       // We had an Objective-C conversion. Allow this pointer
2785       // conversion, but complain about it.
2786       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2787       IncompatibleObjC = true;
2788       return true;
2789     }
2790   }
2791 
2792   return false;
2793 }
2794 
2795 /// Determine whether this is an Objective-C writeback conversion,
2796 /// used for parameter passing when performing automatic reference counting.
2797 ///
2798 /// \param FromType The type we're converting form.
2799 ///
2800 /// \param ToType The type we're converting to.
2801 ///
2802 /// \param ConvertedType The type that will be produced after applying
2803 /// this conversion.
2804 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2805                                      QualType &ConvertedType) {
2806   if (!getLangOpts().ObjCAutoRefCount ||
2807       Context.hasSameUnqualifiedType(FromType, ToType))
2808     return false;
2809 
2810   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2811   QualType ToPointee;
2812   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2813     ToPointee = ToPointer->getPointeeType();
2814   else
2815     return false;
2816 
2817   Qualifiers ToQuals = ToPointee.getQualifiers();
2818   if (!ToPointee->isObjCLifetimeType() ||
2819       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2820       !ToQuals.withoutObjCLifetime().empty())
2821     return false;
2822 
2823   // Argument must be a pointer to __strong to __weak.
2824   QualType FromPointee;
2825   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2826     FromPointee = FromPointer->getPointeeType();
2827   else
2828     return false;
2829 
2830   Qualifiers FromQuals = FromPointee.getQualifiers();
2831   if (!FromPointee->isObjCLifetimeType() ||
2832       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2833        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2834     return false;
2835 
2836   // Make sure that we have compatible qualifiers.
2837   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2838   if (!ToQuals.compatiblyIncludes(FromQuals))
2839     return false;
2840 
2841   // Remove qualifiers from the pointee type we're converting from; they
2842   // aren't used in the compatibility check belong, and we'll be adding back
2843   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2844   FromPointee = FromPointee.getUnqualifiedType();
2845 
2846   // The unqualified form of the pointee types must be compatible.
2847   ToPointee = ToPointee.getUnqualifiedType();
2848   bool IncompatibleObjC;
2849   if (Context.typesAreCompatible(FromPointee, ToPointee))
2850     FromPointee = ToPointee;
2851   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2852                                     IncompatibleObjC))
2853     return false;
2854 
2855   /// Construct the type we're converting to, which is a pointer to
2856   /// __autoreleasing pointee.
2857   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2858   ConvertedType = Context.getPointerType(FromPointee);
2859   return true;
2860 }
2861 
2862 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2863                                     QualType& ConvertedType) {
2864   QualType ToPointeeType;
2865   if (const BlockPointerType *ToBlockPtr =
2866         ToType->getAs<BlockPointerType>())
2867     ToPointeeType = ToBlockPtr->getPointeeType();
2868   else
2869     return false;
2870 
2871   QualType FromPointeeType;
2872   if (const BlockPointerType *FromBlockPtr =
2873       FromType->getAs<BlockPointerType>())
2874     FromPointeeType = FromBlockPtr->getPointeeType();
2875   else
2876     return false;
2877   // We have pointer to blocks, check whether the only
2878   // differences in the argument and result types are in Objective-C
2879   // pointer conversions. If so, we permit the conversion.
2880 
2881   const FunctionProtoType *FromFunctionType
2882     = FromPointeeType->getAs<FunctionProtoType>();
2883   const FunctionProtoType *ToFunctionType
2884     = ToPointeeType->getAs<FunctionProtoType>();
2885 
2886   if (!FromFunctionType || !ToFunctionType)
2887     return false;
2888 
2889   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2890     return true;
2891 
2892   // Perform the quick checks that will tell us whether these
2893   // function types are obviously different.
2894   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2895       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2896     return false;
2897 
2898   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2899   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2900   if (FromEInfo != ToEInfo)
2901     return false;
2902 
2903   bool IncompatibleObjC = false;
2904   if (Context.hasSameType(FromFunctionType->getReturnType(),
2905                           ToFunctionType->getReturnType())) {
2906     // Okay, the types match exactly. Nothing to do.
2907   } else {
2908     QualType RHS = FromFunctionType->getReturnType();
2909     QualType LHS = ToFunctionType->getReturnType();
2910     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2911         !RHS.hasQualifiers() && LHS.hasQualifiers())
2912        LHS = LHS.getUnqualifiedType();
2913 
2914      if (Context.hasSameType(RHS,LHS)) {
2915        // OK exact match.
2916      } else if (isObjCPointerConversion(RHS, LHS,
2917                                         ConvertedType, IncompatibleObjC)) {
2918      if (IncompatibleObjC)
2919        return false;
2920      // Okay, we have an Objective-C pointer conversion.
2921      }
2922      else
2923        return false;
2924    }
2925 
2926    // Check argument types.
2927    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2928         ArgIdx != NumArgs; ++ArgIdx) {
2929      IncompatibleObjC = false;
2930      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2931      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2932      if (Context.hasSameType(FromArgType, ToArgType)) {
2933        // Okay, the types match exactly. Nothing to do.
2934      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2935                                         ConvertedType, IncompatibleObjC)) {
2936        if (IncompatibleObjC)
2937          return false;
2938        // Okay, we have an Objective-C pointer conversion.
2939      } else
2940        // Argument types are too different. Abort.
2941        return false;
2942    }
2943 
2944    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2945    bool CanUseToFPT, CanUseFromFPT;
2946    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2947                                       CanUseToFPT, CanUseFromFPT,
2948                                       NewParamInfos))
2949      return false;
2950 
2951    ConvertedType = ToType;
2952    return true;
2953 }
2954 
2955 enum {
2956   ft_default,
2957   ft_different_class,
2958   ft_parameter_arity,
2959   ft_parameter_mismatch,
2960   ft_return_type,
2961   ft_qualifer_mismatch,
2962   ft_noexcept
2963 };
2964 
2965 /// Attempts to get the FunctionProtoType from a Type. Handles
2966 /// MemberFunctionPointers properly.
2967 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2968   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2969     return FPT;
2970 
2971   if (auto *MPT = FromType->getAs<MemberPointerType>())
2972     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2973 
2974   return nullptr;
2975 }
2976 
2977 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2978 /// function types.  Catches different number of parameter, mismatch in
2979 /// parameter types, and different return types.
2980 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2981                                       QualType FromType, QualType ToType) {
2982   // If either type is not valid, include no extra info.
2983   if (FromType.isNull() || ToType.isNull()) {
2984     PDiag << ft_default;
2985     return;
2986   }
2987 
2988   // Get the function type from the pointers.
2989   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2990     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2991                *ToMember = ToType->castAs<MemberPointerType>();
2992     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2993       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2994             << QualType(FromMember->getClass(), 0);
2995       return;
2996     }
2997     FromType = FromMember->getPointeeType();
2998     ToType = ToMember->getPointeeType();
2999   }
3000 
3001   if (FromType->isPointerType())
3002     FromType = FromType->getPointeeType();
3003   if (ToType->isPointerType())
3004     ToType = ToType->getPointeeType();
3005 
3006   // Remove references.
3007   FromType = FromType.getNonReferenceType();
3008   ToType = ToType.getNonReferenceType();
3009 
3010   // Don't print extra info for non-specialized template functions.
3011   if (FromType->isInstantiationDependentType() &&
3012       !FromType->getAs<TemplateSpecializationType>()) {
3013     PDiag << ft_default;
3014     return;
3015   }
3016 
3017   // No extra info for same types.
3018   if (Context.hasSameType(FromType, ToType)) {
3019     PDiag << ft_default;
3020     return;
3021   }
3022 
3023   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3024                           *ToFunction = tryGetFunctionProtoType(ToType);
3025 
3026   // Both types need to be function types.
3027   if (!FromFunction || !ToFunction) {
3028     PDiag << ft_default;
3029     return;
3030   }
3031 
3032   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3033     PDiag << ft_parameter_arity << ToFunction->getNumParams()
3034           << FromFunction->getNumParams();
3035     return;
3036   }
3037 
3038   // Handle different parameter types.
3039   unsigned ArgPos;
3040   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3041     PDiag << ft_parameter_mismatch << ArgPos + 1
3042           << ToFunction->getParamType(ArgPos)
3043           << FromFunction->getParamType(ArgPos);
3044     return;
3045   }
3046 
3047   // Handle different return type.
3048   if (!Context.hasSameType(FromFunction->getReturnType(),
3049                            ToFunction->getReturnType())) {
3050     PDiag << ft_return_type << ToFunction->getReturnType()
3051           << FromFunction->getReturnType();
3052     return;
3053   }
3054 
3055   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3056     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3057           << FromFunction->getMethodQuals();
3058     return;
3059   }
3060 
3061   // Handle exception specification differences on canonical type (in C++17
3062   // onwards).
3063   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3064           ->isNothrow() !=
3065       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3066           ->isNothrow()) {
3067     PDiag << ft_noexcept;
3068     return;
3069   }
3070 
3071   // Unable to find a difference, so add no extra info.
3072   PDiag << ft_default;
3073 }
3074 
3075 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3076 /// for equality of their parameter types. Caller has already checked that
3077 /// they have same number of parameters.  If the parameters are different,
3078 /// ArgPos will have the parameter index of the first different parameter.
3079 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3080 /// reverse order. That's useful if one of the functions is being used as a C++20
3081 /// synthesized operator overload with a reversed parameter order.
3082 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3083                                       const FunctionProtoType *NewType,
3084                                       unsigned *ArgPos, bool Reversed) {
3085   assert(OldType->getNumParams() == NewType->getNumParams() &&
3086          "Can't compare parameters of functions with different number of "
3087          "parameters!");
3088   for (size_t I = 0; I < OldType->getNumParams(); I++) {
3089     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3090     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
3091 
3092     // Ignore address spaces in pointee type. This is to disallow overloading
3093     // on __ptr32/__ptr64 address spaces.
3094     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
3095     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
3096 
3097     if (!Context.hasSameType(Old, New)) {
3098       if (ArgPos)
3099         *ArgPos = I;
3100       return false;
3101     }
3102   }
3103   return true;
3104 }
3105 
3106 /// CheckPointerConversion - Check the pointer conversion from the
3107 /// expression From to the type ToType. This routine checks for
3108 /// ambiguous or inaccessible derived-to-base pointer
3109 /// conversions for which IsPointerConversion has already returned
3110 /// true. It returns true and produces a diagnostic if there was an
3111 /// error, or returns false otherwise.
3112 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3113                                   CastKind &Kind,
3114                                   CXXCastPath& BasePath,
3115                                   bool IgnoreBaseAccess,
3116                                   bool Diagnose) {
3117   QualType FromType = From->getType();
3118   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3119 
3120   Kind = CK_BitCast;
3121 
3122   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3123       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3124           Expr::NPCK_ZeroExpression) {
3125     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3126       DiagRuntimeBehavior(From->getExprLoc(), From,
3127                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3128                             << ToType << From->getSourceRange());
3129     else if (!isUnevaluatedContext())
3130       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3131         << ToType << From->getSourceRange();
3132   }
3133   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3134     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3135       QualType FromPointeeType = FromPtrType->getPointeeType(),
3136                ToPointeeType   = ToPtrType->getPointeeType();
3137 
3138       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3139           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3140         // We must have a derived-to-base conversion. Check an
3141         // ambiguous or inaccessible conversion.
3142         unsigned InaccessibleID = 0;
3143         unsigned AmbiguousID = 0;
3144         if (Diagnose) {
3145           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3146           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3147         }
3148         if (CheckDerivedToBaseConversion(
3149                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3150                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3151                 &BasePath, IgnoreBaseAccess))
3152           return true;
3153 
3154         // The conversion was successful.
3155         Kind = CK_DerivedToBase;
3156       }
3157 
3158       if (Diagnose && !IsCStyleOrFunctionalCast &&
3159           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3160         assert(getLangOpts().MSVCCompat &&
3161                "this should only be possible with MSVCCompat!");
3162         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3163             << From->getSourceRange();
3164       }
3165     }
3166   } else if (const ObjCObjectPointerType *ToPtrType =
3167                ToType->getAs<ObjCObjectPointerType>()) {
3168     if (const ObjCObjectPointerType *FromPtrType =
3169           FromType->getAs<ObjCObjectPointerType>()) {
3170       // Objective-C++ conversions are always okay.
3171       // FIXME: We should have a different class of conversions for the
3172       // Objective-C++ implicit conversions.
3173       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3174         return false;
3175     } else if (FromType->isBlockPointerType()) {
3176       Kind = CK_BlockPointerToObjCPointerCast;
3177     } else {
3178       Kind = CK_CPointerToObjCPointerCast;
3179     }
3180   } else if (ToType->isBlockPointerType()) {
3181     if (!FromType->isBlockPointerType())
3182       Kind = CK_AnyPointerToBlockPointerCast;
3183   }
3184 
3185   // We shouldn't fall into this case unless it's valid for other
3186   // reasons.
3187   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3188     Kind = CK_NullToPointer;
3189 
3190   return false;
3191 }
3192 
3193 /// IsMemberPointerConversion - Determines whether the conversion of the
3194 /// expression From, which has the (possibly adjusted) type FromType, can be
3195 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3196 /// If so, returns true and places the converted type (that might differ from
3197 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3198 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3199                                      QualType ToType,
3200                                      bool InOverloadResolution,
3201                                      QualType &ConvertedType) {
3202   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3203   if (!ToTypePtr)
3204     return false;
3205 
3206   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3207   if (From->isNullPointerConstant(Context,
3208                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3209                                         : Expr::NPC_ValueDependentIsNull)) {
3210     ConvertedType = ToType;
3211     return true;
3212   }
3213 
3214   // Otherwise, both types have to be member pointers.
3215   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3216   if (!FromTypePtr)
3217     return false;
3218 
3219   // A pointer to member of B can be converted to a pointer to member of D,
3220   // where D is derived from B (C++ 4.11p2).
3221   QualType FromClass(FromTypePtr->getClass(), 0);
3222   QualType ToClass(ToTypePtr->getClass(), 0);
3223 
3224   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3225       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3226     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3227                                                  ToClass.getTypePtr());
3228     return true;
3229   }
3230 
3231   return false;
3232 }
3233 
3234 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3235 /// expression From to the type ToType. This routine checks for ambiguous or
3236 /// virtual or inaccessible base-to-derived member pointer conversions
3237 /// for which IsMemberPointerConversion has already returned true. It returns
3238 /// true and produces a diagnostic if there was an error, or returns false
3239 /// otherwise.
3240 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3241                                         CastKind &Kind,
3242                                         CXXCastPath &BasePath,
3243                                         bool IgnoreBaseAccess) {
3244   QualType FromType = From->getType();
3245   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3246   if (!FromPtrType) {
3247     // This must be a null pointer to member pointer conversion
3248     assert(From->isNullPointerConstant(Context,
3249                                        Expr::NPC_ValueDependentIsNull) &&
3250            "Expr must be null pointer constant!");
3251     Kind = CK_NullToMemberPointer;
3252     return false;
3253   }
3254 
3255   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3256   assert(ToPtrType && "No member pointer cast has a target type "
3257                       "that is not a member pointer.");
3258 
3259   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3260   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3261 
3262   // FIXME: What about dependent types?
3263   assert(FromClass->isRecordType() && "Pointer into non-class.");
3264   assert(ToClass->isRecordType() && "Pointer into non-class.");
3265 
3266   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3267                      /*DetectVirtual=*/true);
3268   bool DerivationOkay =
3269       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3270   assert(DerivationOkay &&
3271          "Should not have been called if derivation isn't OK.");
3272   (void)DerivationOkay;
3273 
3274   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3275                                   getUnqualifiedType())) {
3276     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3277     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3278       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3279     return true;
3280   }
3281 
3282   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3283     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3284       << FromClass << ToClass << QualType(VBase, 0)
3285       << From->getSourceRange();
3286     return true;
3287   }
3288 
3289   if (!IgnoreBaseAccess)
3290     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3291                          Paths.front(),
3292                          diag::err_downcast_from_inaccessible_base);
3293 
3294   // Must be a base to derived member conversion.
3295   BuildBasePathArray(Paths, BasePath);
3296   Kind = CK_BaseToDerivedMemberPointer;
3297   return false;
3298 }
3299 
3300 /// Determine whether the lifetime conversion between the two given
3301 /// qualifiers sets is nontrivial.
3302 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3303                                                Qualifiers ToQuals) {
3304   // Converting anything to const __unsafe_unretained is trivial.
3305   if (ToQuals.hasConst() &&
3306       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3307     return false;
3308 
3309   return true;
3310 }
3311 
3312 /// Perform a single iteration of the loop for checking if a qualification
3313 /// conversion is valid.
3314 ///
3315 /// Specifically, check whether any change between the qualifiers of \p
3316 /// FromType and \p ToType is permissible, given knowledge about whether every
3317 /// outer layer is const-qualified.
3318 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3319                                           bool CStyle, bool IsTopLevel,
3320                                           bool &PreviousToQualsIncludeConst,
3321                                           bool &ObjCLifetimeConversion) {
3322   Qualifiers FromQuals = FromType.getQualifiers();
3323   Qualifiers ToQuals = ToType.getQualifiers();
3324 
3325   // Ignore __unaligned qualifier.
3326   FromQuals.removeUnaligned();
3327 
3328   // Objective-C ARC:
3329   //   Check Objective-C lifetime conversions.
3330   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3331     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3332       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3333         ObjCLifetimeConversion = true;
3334       FromQuals.removeObjCLifetime();
3335       ToQuals.removeObjCLifetime();
3336     } else {
3337       // Qualification conversions cannot cast between different
3338       // Objective-C lifetime qualifiers.
3339       return false;
3340     }
3341   }
3342 
3343   // Allow addition/removal of GC attributes but not changing GC attributes.
3344   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3345       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3346     FromQuals.removeObjCGCAttr();
3347     ToQuals.removeObjCGCAttr();
3348   }
3349 
3350   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3351   //      2,j, and similarly for volatile.
3352   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3353     return false;
3354 
3355   // If address spaces mismatch:
3356   //  - in top level it is only valid to convert to addr space that is a
3357   //    superset in all cases apart from C-style casts where we allow
3358   //    conversions between overlapping address spaces.
3359   //  - in non-top levels it is not a valid conversion.
3360   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3361       (!IsTopLevel ||
3362        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3363          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3364     return false;
3365 
3366   //   -- if the cv 1,j and cv 2,j are different, then const is in
3367   //      every cv for 0 < k < j.
3368   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3369       !PreviousToQualsIncludeConst)
3370     return false;
3371 
3372   // The following wording is from C++20, where the result of the conversion
3373   // is T3, not T2.
3374   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3375   //      "array of unknown bound of"
3376   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3377     return false;
3378 
3379   //   -- if the resulting P3,i is different from P1,i [...], then const is
3380   //      added to every cv 3_k for 0 < k < i.
3381   if (!CStyle && FromType->isConstantArrayType() &&
3382       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3383     return false;
3384 
3385   // Keep track of whether all prior cv-qualifiers in the "to" type
3386   // include const.
3387   PreviousToQualsIncludeConst =
3388       PreviousToQualsIncludeConst && ToQuals.hasConst();
3389   return true;
3390 }
3391 
3392 /// IsQualificationConversion - Determines whether the conversion from
3393 /// an rvalue of type FromType to ToType is a qualification conversion
3394 /// (C++ 4.4).
3395 ///
3396 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3397 /// when the qualification conversion involves a change in the Objective-C
3398 /// object lifetime.
3399 bool
3400 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3401                                 bool CStyle, bool &ObjCLifetimeConversion) {
3402   FromType = Context.getCanonicalType(FromType);
3403   ToType = Context.getCanonicalType(ToType);
3404   ObjCLifetimeConversion = false;
3405 
3406   // If FromType and ToType are the same type, this is not a
3407   // qualification conversion.
3408   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3409     return false;
3410 
3411   // (C++ 4.4p4):
3412   //   A conversion can add cv-qualifiers at levels other than the first
3413   //   in multi-level pointers, subject to the following rules: [...]
3414   bool PreviousToQualsIncludeConst = true;
3415   bool UnwrappedAnyPointer = false;
3416   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3417     if (!isQualificationConversionStep(
3418             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3419             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3420       return false;
3421     UnwrappedAnyPointer = true;
3422   }
3423 
3424   // We are left with FromType and ToType being the pointee types
3425   // after unwrapping the original FromType and ToType the same number
3426   // of times. If we unwrapped any pointers, and if FromType and
3427   // ToType have the same unqualified type (since we checked
3428   // qualifiers above), then this is a qualification conversion.
3429   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3430 }
3431 
3432 /// - Determine whether this is a conversion from a scalar type to an
3433 /// atomic type.
3434 ///
3435 /// If successful, updates \c SCS's second and third steps in the conversion
3436 /// sequence to finish the conversion.
3437 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3438                                 bool InOverloadResolution,
3439                                 StandardConversionSequence &SCS,
3440                                 bool CStyle) {
3441   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3442   if (!ToAtomic)
3443     return false;
3444 
3445   StandardConversionSequence InnerSCS;
3446   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3447                             InOverloadResolution, InnerSCS,
3448                             CStyle, /*AllowObjCWritebackConversion=*/false))
3449     return false;
3450 
3451   SCS.Second = InnerSCS.Second;
3452   SCS.setToType(1, InnerSCS.getToType(1));
3453   SCS.Third = InnerSCS.Third;
3454   SCS.QualificationIncludesObjCLifetime
3455     = InnerSCS.QualificationIncludesObjCLifetime;
3456   SCS.setToType(2, InnerSCS.getToType(2));
3457   return true;
3458 }
3459 
3460 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3461                                               CXXConstructorDecl *Constructor,
3462                                               QualType Type) {
3463   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3464   if (CtorType->getNumParams() > 0) {
3465     QualType FirstArg = CtorType->getParamType(0);
3466     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3467       return true;
3468   }
3469   return false;
3470 }
3471 
3472 static OverloadingResult
3473 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3474                                        CXXRecordDecl *To,
3475                                        UserDefinedConversionSequence &User,
3476                                        OverloadCandidateSet &CandidateSet,
3477                                        bool AllowExplicit) {
3478   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3479   for (auto *D : S.LookupConstructors(To)) {
3480     auto Info = getConstructorInfo(D);
3481     if (!Info)
3482       continue;
3483 
3484     bool Usable = !Info.Constructor->isInvalidDecl() &&
3485                   S.isInitListConstructor(Info.Constructor);
3486     if (Usable) {
3487       bool SuppressUserConversions = false;
3488       if (Info.ConstructorTmpl)
3489         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3490                                        /*ExplicitArgs*/ nullptr, From,
3491                                        CandidateSet, SuppressUserConversions,
3492                                        /*PartialOverloading*/ false,
3493                                        AllowExplicit);
3494       else
3495         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3496                                CandidateSet, SuppressUserConversions,
3497                                /*PartialOverloading*/ false, AllowExplicit);
3498     }
3499   }
3500 
3501   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3502 
3503   OverloadCandidateSet::iterator Best;
3504   switch (auto Result =
3505               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3506   case OR_Deleted:
3507   case OR_Success: {
3508     // Record the standard conversion we used and the conversion function.
3509     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3510     QualType ThisType = Constructor->getThisType();
3511     // Initializer lists don't have conversions as such.
3512     User.Before.setAsIdentityConversion();
3513     User.HadMultipleCandidates = HadMultipleCandidates;
3514     User.ConversionFunction = Constructor;
3515     User.FoundConversionFunction = Best->FoundDecl;
3516     User.After.setAsIdentityConversion();
3517     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3518     User.After.setAllToTypes(ToType);
3519     return Result;
3520   }
3521 
3522   case OR_No_Viable_Function:
3523     return OR_No_Viable_Function;
3524   case OR_Ambiguous:
3525     return OR_Ambiguous;
3526   }
3527 
3528   llvm_unreachable("Invalid OverloadResult!");
3529 }
3530 
3531 /// Determines whether there is a user-defined conversion sequence
3532 /// (C++ [over.ics.user]) that converts expression From to the type
3533 /// ToType. If such a conversion exists, User will contain the
3534 /// user-defined conversion sequence that performs such a conversion
3535 /// and this routine will return true. Otherwise, this routine returns
3536 /// false and User is unspecified.
3537 ///
3538 /// \param AllowExplicit  true if the conversion should consider C++0x
3539 /// "explicit" conversion functions as well as non-explicit conversion
3540 /// functions (C++0x [class.conv.fct]p2).
3541 ///
3542 /// \param AllowObjCConversionOnExplicit true if the conversion should
3543 /// allow an extra Objective-C pointer conversion on uses of explicit
3544 /// constructors. Requires \c AllowExplicit to also be set.
3545 static OverloadingResult
3546 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3547                         UserDefinedConversionSequence &User,
3548                         OverloadCandidateSet &CandidateSet,
3549                         AllowedExplicit AllowExplicit,
3550                         bool AllowObjCConversionOnExplicit) {
3551   assert(AllowExplicit != AllowedExplicit::None ||
3552          !AllowObjCConversionOnExplicit);
3553   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3554 
3555   // Whether we will only visit constructors.
3556   bool ConstructorsOnly = false;
3557 
3558   // If the type we are conversion to is a class type, enumerate its
3559   // constructors.
3560   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3561     // C++ [over.match.ctor]p1:
3562     //   When objects of class type are direct-initialized (8.5), or
3563     //   copy-initialized from an expression of the same or a
3564     //   derived class type (8.5), overload resolution selects the
3565     //   constructor. [...] For copy-initialization, the candidate
3566     //   functions are all the converting constructors (12.3.1) of
3567     //   that class. The argument list is the expression-list within
3568     //   the parentheses of the initializer.
3569     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3570         (From->getType()->getAs<RecordType>() &&
3571          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3572       ConstructorsOnly = true;
3573 
3574     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3575       // We're not going to find any constructors.
3576     } else if (CXXRecordDecl *ToRecordDecl
3577                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3578 
3579       Expr **Args = &From;
3580       unsigned NumArgs = 1;
3581       bool ListInitializing = false;
3582       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3583         // But first, see if there is an init-list-constructor that will work.
3584         OverloadingResult Result = IsInitializerListConstructorConversion(
3585             S, From, ToType, ToRecordDecl, User, CandidateSet,
3586             AllowExplicit == AllowedExplicit::All);
3587         if (Result != OR_No_Viable_Function)
3588           return Result;
3589         // Never mind.
3590         CandidateSet.clear(
3591             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3592 
3593         // If we're list-initializing, we pass the individual elements as
3594         // arguments, not the entire list.
3595         Args = InitList->getInits();
3596         NumArgs = InitList->getNumInits();
3597         ListInitializing = true;
3598       }
3599 
3600       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3601         auto Info = getConstructorInfo(D);
3602         if (!Info)
3603           continue;
3604 
3605         bool Usable = !Info.Constructor->isInvalidDecl();
3606         if (!ListInitializing)
3607           Usable = Usable && Info.Constructor->isConvertingConstructor(
3608                                  /*AllowExplicit*/ true);
3609         if (Usable) {
3610           bool SuppressUserConversions = !ConstructorsOnly;
3611           // C++20 [over.best.ics.general]/4.5:
3612           //   if the target is the first parameter of a constructor [of class
3613           //   X] and the constructor [...] is a candidate by [...] the second
3614           //   phase of [over.match.list] when the initializer list has exactly
3615           //   one element that is itself an initializer list, [...] and the
3616           //   conversion is to X or reference to cv X, user-defined conversion
3617           //   sequences are not cnosidered.
3618           if (SuppressUserConversions && ListInitializing) {
3619             SuppressUserConversions =
3620                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3621                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3622                                                   ToType);
3623           }
3624           if (Info.ConstructorTmpl)
3625             S.AddTemplateOverloadCandidate(
3626                 Info.ConstructorTmpl, Info.FoundDecl,
3627                 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3628                 CandidateSet, SuppressUserConversions,
3629                 /*PartialOverloading*/ false,
3630                 AllowExplicit == AllowedExplicit::All);
3631           else
3632             // Allow one user-defined conversion when user specifies a
3633             // From->ToType conversion via an static cast (c-style, etc).
3634             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3635                                    llvm::ArrayRef(Args, NumArgs), CandidateSet,
3636                                    SuppressUserConversions,
3637                                    /*PartialOverloading*/ false,
3638                                    AllowExplicit == AllowedExplicit::All);
3639         }
3640       }
3641     }
3642   }
3643 
3644   // Enumerate conversion functions, if we're allowed to.
3645   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3646   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3647     // No conversion functions from incomplete types.
3648   } else if (const RecordType *FromRecordType =
3649                  From->getType()->getAs<RecordType>()) {
3650     if (CXXRecordDecl *FromRecordDecl
3651          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3652       // Add all of the conversion functions as candidates.
3653       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3654       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3655         DeclAccessPair FoundDecl = I.getPair();
3656         NamedDecl *D = FoundDecl.getDecl();
3657         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3658         if (isa<UsingShadowDecl>(D))
3659           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3660 
3661         CXXConversionDecl *Conv;
3662         FunctionTemplateDecl *ConvTemplate;
3663         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3664           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3665         else
3666           Conv = cast<CXXConversionDecl>(D);
3667 
3668         if (ConvTemplate)
3669           S.AddTemplateConversionCandidate(
3670               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3671               CandidateSet, AllowObjCConversionOnExplicit,
3672               AllowExplicit != AllowedExplicit::None);
3673         else
3674           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3675                                    CandidateSet, AllowObjCConversionOnExplicit,
3676                                    AllowExplicit != AllowedExplicit::None);
3677       }
3678     }
3679   }
3680 
3681   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3682 
3683   OverloadCandidateSet::iterator Best;
3684   switch (auto Result =
3685               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3686   case OR_Success:
3687   case OR_Deleted:
3688     // Record the standard conversion we used and the conversion function.
3689     if (CXXConstructorDecl *Constructor
3690           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3691       // C++ [over.ics.user]p1:
3692       //   If the user-defined conversion is specified by a
3693       //   constructor (12.3.1), the initial standard conversion
3694       //   sequence converts the source type to the type required by
3695       //   the argument of the constructor.
3696       //
3697       QualType ThisType = Constructor->getThisType();
3698       if (isa<InitListExpr>(From)) {
3699         // Initializer lists don't have conversions as such.
3700         User.Before.setAsIdentityConversion();
3701       } else {
3702         if (Best->Conversions[0].isEllipsis())
3703           User.EllipsisConversion = true;
3704         else {
3705           User.Before = Best->Conversions[0].Standard;
3706           User.EllipsisConversion = false;
3707         }
3708       }
3709       User.HadMultipleCandidates = HadMultipleCandidates;
3710       User.ConversionFunction = Constructor;
3711       User.FoundConversionFunction = Best->FoundDecl;
3712       User.After.setAsIdentityConversion();
3713       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3714       User.After.setAllToTypes(ToType);
3715       return Result;
3716     }
3717     if (CXXConversionDecl *Conversion
3718                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3719       // C++ [over.ics.user]p1:
3720       //
3721       //   [...] If the user-defined conversion is specified by a
3722       //   conversion function (12.3.2), the initial standard
3723       //   conversion sequence converts the source type to the
3724       //   implicit object parameter of the conversion function.
3725       User.Before = Best->Conversions[0].Standard;
3726       User.HadMultipleCandidates = HadMultipleCandidates;
3727       User.ConversionFunction = Conversion;
3728       User.FoundConversionFunction = Best->FoundDecl;
3729       User.EllipsisConversion = false;
3730 
3731       // C++ [over.ics.user]p2:
3732       //   The second standard conversion sequence converts the
3733       //   result of the user-defined conversion to the target type
3734       //   for the sequence. Since an implicit conversion sequence
3735       //   is an initialization, the special rules for
3736       //   initialization by user-defined conversion apply when
3737       //   selecting the best user-defined conversion for a
3738       //   user-defined conversion sequence (see 13.3.3 and
3739       //   13.3.3.1).
3740       User.After = Best->FinalConversion;
3741       return Result;
3742     }
3743     llvm_unreachable("Not a constructor or conversion function?");
3744 
3745   case OR_No_Viable_Function:
3746     return OR_No_Viable_Function;
3747 
3748   case OR_Ambiguous:
3749     return OR_Ambiguous;
3750   }
3751 
3752   llvm_unreachable("Invalid OverloadResult!");
3753 }
3754 
3755 bool
3756 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3757   ImplicitConversionSequence ICS;
3758   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3759                                     OverloadCandidateSet::CSK_Normal);
3760   OverloadingResult OvResult =
3761     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3762                             CandidateSet, AllowedExplicit::None, false);
3763 
3764   if (!(OvResult == OR_Ambiguous ||
3765         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3766     return false;
3767 
3768   auto Cands = CandidateSet.CompleteCandidates(
3769       *this,
3770       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3771       From);
3772   if (OvResult == OR_Ambiguous)
3773     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3774         << From->getType() << ToType << From->getSourceRange();
3775   else { // OR_No_Viable_Function && !CandidateSet.empty()
3776     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3777                              diag::err_typecheck_nonviable_condition_incomplete,
3778                              From->getType(), From->getSourceRange()))
3779       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3780           << false << From->getType() << From->getSourceRange() << ToType;
3781   }
3782 
3783   CandidateSet.NoteCandidates(
3784                               *this, From, Cands);
3785   return true;
3786 }
3787 
3788 // Helper for compareConversionFunctions that gets the FunctionType that the
3789 // conversion-operator return  value 'points' to, or nullptr.
3790 static const FunctionType *
3791 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3792   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3793   const PointerType *RetPtrTy =
3794       ConvFuncTy->getReturnType()->getAs<PointerType>();
3795 
3796   if (!RetPtrTy)
3797     return nullptr;
3798 
3799   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3800 }
3801 
3802 /// Compare the user-defined conversion functions or constructors
3803 /// of two user-defined conversion sequences to determine whether any ordering
3804 /// is possible.
3805 static ImplicitConversionSequence::CompareKind
3806 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3807                            FunctionDecl *Function2) {
3808   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3809   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3810   if (!Conv1 || !Conv2)
3811     return ImplicitConversionSequence::Indistinguishable;
3812 
3813   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3814     return ImplicitConversionSequence::Indistinguishable;
3815 
3816   // Objective-C++:
3817   //   If both conversion functions are implicitly-declared conversions from
3818   //   a lambda closure type to a function pointer and a block pointer,
3819   //   respectively, always prefer the conversion to a function pointer,
3820   //   because the function pointer is more lightweight and is more likely
3821   //   to keep code working.
3822   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3823     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3824     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3825     if (Block1 != Block2)
3826       return Block1 ? ImplicitConversionSequence::Worse
3827                     : ImplicitConversionSequence::Better;
3828   }
3829 
3830   // In order to support multiple calling conventions for the lambda conversion
3831   // operator (such as when the free and member function calling convention is
3832   // different), prefer the 'free' mechanism, followed by the calling-convention
3833   // of operator(). The latter is in place to support the MSVC-like solution of
3834   // defining ALL of the possible conversions in regards to calling-convention.
3835   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3836   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3837 
3838   if (Conv1FuncRet && Conv2FuncRet &&
3839       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3840     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3841     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3842 
3843     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3844     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3845 
3846     CallingConv CallOpCC =
3847         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3848     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3849         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3850     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3851         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3852 
3853     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3854     for (CallingConv CC : PrefOrder) {
3855       if (Conv1CC == CC)
3856         return ImplicitConversionSequence::Better;
3857       if (Conv2CC == CC)
3858         return ImplicitConversionSequence::Worse;
3859     }
3860   }
3861 
3862   return ImplicitConversionSequence::Indistinguishable;
3863 }
3864 
3865 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3866     const ImplicitConversionSequence &ICS) {
3867   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3868          (ICS.isUserDefined() &&
3869           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3870 }
3871 
3872 /// CompareImplicitConversionSequences - Compare two implicit
3873 /// conversion sequences to determine whether one is better than the
3874 /// other or if they are indistinguishable (C++ 13.3.3.2).
3875 static ImplicitConversionSequence::CompareKind
3876 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3877                                    const ImplicitConversionSequence& ICS1,
3878                                    const ImplicitConversionSequence& ICS2)
3879 {
3880   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3881   // conversion sequences (as defined in 13.3.3.1)
3882   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3883   //      conversion sequence than a user-defined conversion sequence or
3884   //      an ellipsis conversion sequence, and
3885   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3886   //      conversion sequence than an ellipsis conversion sequence
3887   //      (13.3.3.1.3).
3888   //
3889   // C++0x [over.best.ics]p10:
3890   //   For the purpose of ranking implicit conversion sequences as
3891   //   described in 13.3.3.2, the ambiguous conversion sequence is
3892   //   treated as a user-defined sequence that is indistinguishable
3893   //   from any other user-defined conversion sequence.
3894 
3895   // String literal to 'char *' conversion has been deprecated in C++03. It has
3896   // been removed from C++11. We still accept this conversion, if it happens at
3897   // the best viable function. Otherwise, this conversion is considered worse
3898   // than ellipsis conversion. Consider this as an extension; this is not in the
3899   // standard. For example:
3900   //
3901   // int &f(...);    // #1
3902   // void f(char*);  // #2
3903   // void g() { int &r = f("foo"); }
3904   //
3905   // In C++03, we pick #2 as the best viable function.
3906   // In C++11, we pick #1 as the best viable function, because ellipsis
3907   // conversion is better than string-literal to char* conversion (since there
3908   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3909   // convert arguments, #2 would be the best viable function in C++11.
3910   // If the best viable function has this conversion, a warning will be issued
3911   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3912 
3913   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3914       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3915           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3916       // Ill-formedness must not differ
3917       ICS1.isBad() == ICS2.isBad())
3918     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3919                ? ImplicitConversionSequence::Worse
3920                : ImplicitConversionSequence::Better;
3921 
3922   if (ICS1.getKindRank() < ICS2.getKindRank())
3923     return ImplicitConversionSequence::Better;
3924   if (ICS2.getKindRank() < ICS1.getKindRank())
3925     return ImplicitConversionSequence::Worse;
3926 
3927   // The following checks require both conversion sequences to be of
3928   // the same kind.
3929   if (ICS1.getKind() != ICS2.getKind())
3930     return ImplicitConversionSequence::Indistinguishable;
3931 
3932   ImplicitConversionSequence::CompareKind Result =
3933       ImplicitConversionSequence::Indistinguishable;
3934 
3935   // Two implicit conversion sequences of the same form are
3936   // indistinguishable conversion sequences unless one of the
3937   // following rules apply: (C++ 13.3.3.2p3):
3938 
3939   // List-initialization sequence L1 is a better conversion sequence than
3940   // list-initialization sequence L2 if:
3941   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3942   //   if not that,
3943   // — L1 and L2 convert to arrays of the same element type, and either the
3944   //   number of elements n_1 initialized by L1 is less than the number of
3945   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3946   //   an array of unknown bound and L1 does not,
3947   // even if one of the other rules in this paragraph would otherwise apply.
3948   if (!ICS1.isBad()) {
3949     bool StdInit1 = false, StdInit2 = false;
3950     if (ICS1.hasInitializerListContainerType())
3951       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3952                                         nullptr);
3953     if (ICS2.hasInitializerListContainerType())
3954       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3955                                         nullptr);
3956     if (StdInit1 != StdInit2)
3957       return StdInit1 ? ImplicitConversionSequence::Better
3958                       : ImplicitConversionSequence::Worse;
3959 
3960     if (ICS1.hasInitializerListContainerType() &&
3961         ICS2.hasInitializerListContainerType())
3962       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3963               ICS1.getInitializerListContainerType()))
3964         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3965                 ICS2.getInitializerListContainerType())) {
3966           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3967                                                CAT2->getElementType())) {
3968             // Both to arrays of the same element type
3969             if (CAT1->getSize() != CAT2->getSize())
3970               // Different sized, the smaller wins
3971               return CAT1->getSize().ult(CAT2->getSize())
3972                          ? ImplicitConversionSequence::Better
3973                          : ImplicitConversionSequence::Worse;
3974             if (ICS1.isInitializerListOfIncompleteArray() !=
3975                 ICS2.isInitializerListOfIncompleteArray())
3976               // One is incomplete, it loses
3977               return ICS2.isInitializerListOfIncompleteArray()
3978                          ? ImplicitConversionSequence::Better
3979                          : ImplicitConversionSequence::Worse;
3980           }
3981         }
3982   }
3983 
3984   if (ICS1.isStandard())
3985     // Standard conversion sequence S1 is a better conversion sequence than
3986     // standard conversion sequence S2 if [...]
3987     Result = CompareStandardConversionSequences(S, Loc,
3988                                                 ICS1.Standard, ICS2.Standard);
3989   else if (ICS1.isUserDefined()) {
3990     // User-defined conversion sequence U1 is a better conversion
3991     // sequence than another user-defined conversion sequence U2 if
3992     // they contain the same user-defined conversion function or
3993     // constructor and if the second standard conversion sequence of
3994     // U1 is better than the second standard conversion sequence of
3995     // U2 (C++ 13.3.3.2p3).
3996     if (ICS1.UserDefined.ConversionFunction ==
3997           ICS2.UserDefined.ConversionFunction)
3998       Result = CompareStandardConversionSequences(S, Loc,
3999                                                   ICS1.UserDefined.After,
4000                                                   ICS2.UserDefined.After);
4001     else
4002       Result = compareConversionFunctions(S,
4003                                           ICS1.UserDefined.ConversionFunction,
4004                                           ICS2.UserDefined.ConversionFunction);
4005   }
4006 
4007   return Result;
4008 }
4009 
4010 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4011 // determine if one is a proper subset of the other.
4012 static ImplicitConversionSequence::CompareKind
4013 compareStandardConversionSubsets(ASTContext &Context,
4014                                  const StandardConversionSequence& SCS1,
4015                                  const StandardConversionSequence& SCS2) {
4016   ImplicitConversionSequence::CompareKind Result
4017     = ImplicitConversionSequence::Indistinguishable;
4018 
4019   // the identity conversion sequence is considered to be a subsequence of
4020   // any non-identity conversion sequence
4021   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4022     return ImplicitConversionSequence::Better;
4023   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4024     return ImplicitConversionSequence::Worse;
4025 
4026   if (SCS1.Second != SCS2.Second) {
4027     if (SCS1.Second == ICK_Identity)
4028       Result = ImplicitConversionSequence::Better;
4029     else if (SCS2.Second == ICK_Identity)
4030       Result = ImplicitConversionSequence::Worse;
4031     else
4032       return ImplicitConversionSequence::Indistinguishable;
4033   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4034     return ImplicitConversionSequence::Indistinguishable;
4035 
4036   if (SCS1.Third == SCS2.Third) {
4037     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4038                              : ImplicitConversionSequence::Indistinguishable;
4039   }
4040 
4041   if (SCS1.Third == ICK_Identity)
4042     return Result == ImplicitConversionSequence::Worse
4043              ? ImplicitConversionSequence::Indistinguishable
4044              : ImplicitConversionSequence::Better;
4045 
4046   if (SCS2.Third == ICK_Identity)
4047     return Result == ImplicitConversionSequence::Better
4048              ? ImplicitConversionSequence::Indistinguishable
4049              : ImplicitConversionSequence::Worse;
4050 
4051   return ImplicitConversionSequence::Indistinguishable;
4052 }
4053 
4054 /// Determine whether one of the given reference bindings is better
4055 /// than the other based on what kind of bindings they are.
4056 static bool
4057 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4058                              const StandardConversionSequence &SCS2) {
4059   // C++0x [over.ics.rank]p3b4:
4060   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4061   //      implicit object parameter of a non-static member function declared
4062   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
4063   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
4064   //      lvalue reference to a function lvalue and S2 binds an rvalue
4065   //      reference*.
4066   //
4067   // FIXME: Rvalue references. We're going rogue with the above edits,
4068   // because the semantics in the current C++0x working paper (N3225 at the
4069   // time of this writing) break the standard definition of std::forward
4070   // and std::reference_wrapper when dealing with references to functions.
4071   // Proposed wording changes submitted to CWG for consideration.
4072   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4073       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4074     return false;
4075 
4076   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4077           SCS2.IsLvalueReference) ||
4078          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4079           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4080 }
4081 
4082 enum class FixedEnumPromotion {
4083   None,
4084   ToUnderlyingType,
4085   ToPromotedUnderlyingType
4086 };
4087 
4088 /// Returns kind of fixed enum promotion the \a SCS uses.
4089 static FixedEnumPromotion
4090 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4091 
4092   if (SCS.Second != ICK_Integral_Promotion)
4093     return FixedEnumPromotion::None;
4094 
4095   QualType FromType = SCS.getFromType();
4096   if (!FromType->isEnumeralType())
4097     return FixedEnumPromotion::None;
4098 
4099   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4100   if (!Enum->isFixed())
4101     return FixedEnumPromotion::None;
4102 
4103   QualType UnderlyingType = Enum->getIntegerType();
4104   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4105     return FixedEnumPromotion::ToUnderlyingType;
4106 
4107   return FixedEnumPromotion::ToPromotedUnderlyingType;
4108 }
4109 
4110 /// CompareStandardConversionSequences - Compare two standard
4111 /// conversion sequences to determine whether one is better than the
4112 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4113 static ImplicitConversionSequence::CompareKind
4114 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4115                                    const StandardConversionSequence& SCS1,
4116                                    const StandardConversionSequence& SCS2)
4117 {
4118   // Standard conversion sequence S1 is a better conversion sequence
4119   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4120 
4121   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4122   //     sequences in the canonical form defined by 13.3.3.1.1,
4123   //     excluding any Lvalue Transformation; the identity conversion
4124   //     sequence is considered to be a subsequence of any
4125   //     non-identity conversion sequence) or, if not that,
4126   if (ImplicitConversionSequence::CompareKind CK
4127         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4128     return CK;
4129 
4130   //  -- the rank of S1 is better than the rank of S2 (by the rules
4131   //     defined below), or, if not that,
4132   ImplicitConversionRank Rank1 = SCS1.getRank();
4133   ImplicitConversionRank Rank2 = SCS2.getRank();
4134   if (Rank1 < Rank2)
4135     return ImplicitConversionSequence::Better;
4136   else if (Rank2 < Rank1)
4137     return ImplicitConversionSequence::Worse;
4138 
4139   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4140   // are indistinguishable unless one of the following rules
4141   // applies:
4142 
4143   //   A conversion that is not a conversion of a pointer, or
4144   //   pointer to member, to bool is better than another conversion
4145   //   that is such a conversion.
4146   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4147     return SCS2.isPointerConversionToBool()
4148              ? ImplicitConversionSequence::Better
4149              : ImplicitConversionSequence::Worse;
4150 
4151   // C++14 [over.ics.rank]p4b2:
4152   // This is retroactively applied to C++11 by CWG 1601.
4153   //
4154   //   A conversion that promotes an enumeration whose underlying type is fixed
4155   //   to its underlying type is better than one that promotes to the promoted
4156   //   underlying type, if the two are different.
4157   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4158   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4159   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4160       FEP1 != FEP2)
4161     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4162                ? ImplicitConversionSequence::Better
4163                : ImplicitConversionSequence::Worse;
4164 
4165   // C++ [over.ics.rank]p4b2:
4166   //
4167   //   If class B is derived directly or indirectly from class A,
4168   //   conversion of B* to A* is better than conversion of B* to
4169   //   void*, and conversion of A* to void* is better than conversion
4170   //   of B* to void*.
4171   bool SCS1ConvertsToVoid
4172     = SCS1.isPointerConversionToVoidPointer(S.Context);
4173   bool SCS2ConvertsToVoid
4174     = SCS2.isPointerConversionToVoidPointer(S.Context);
4175   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4176     // Exactly one of the conversion sequences is a conversion to
4177     // a void pointer; it's the worse conversion.
4178     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4179                               : ImplicitConversionSequence::Worse;
4180   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4181     // Neither conversion sequence converts to a void pointer; compare
4182     // their derived-to-base conversions.
4183     if (ImplicitConversionSequence::CompareKind DerivedCK
4184           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4185       return DerivedCK;
4186   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4187              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4188     // Both conversion sequences are conversions to void
4189     // pointers. Compare the source types to determine if there's an
4190     // inheritance relationship in their sources.
4191     QualType FromType1 = SCS1.getFromType();
4192     QualType FromType2 = SCS2.getFromType();
4193 
4194     // Adjust the types we're converting from via the array-to-pointer
4195     // conversion, if we need to.
4196     if (SCS1.First == ICK_Array_To_Pointer)
4197       FromType1 = S.Context.getArrayDecayedType(FromType1);
4198     if (SCS2.First == ICK_Array_To_Pointer)
4199       FromType2 = S.Context.getArrayDecayedType(FromType2);
4200 
4201     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4202     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4203 
4204     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4205       return ImplicitConversionSequence::Better;
4206     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4207       return ImplicitConversionSequence::Worse;
4208 
4209     // Objective-C++: If one interface is more specific than the
4210     // other, it is the better one.
4211     const ObjCObjectPointerType* FromObjCPtr1
4212       = FromType1->getAs<ObjCObjectPointerType>();
4213     const ObjCObjectPointerType* FromObjCPtr2
4214       = FromType2->getAs<ObjCObjectPointerType>();
4215     if (FromObjCPtr1 && FromObjCPtr2) {
4216       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4217                                                           FromObjCPtr2);
4218       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4219                                                            FromObjCPtr1);
4220       if (AssignLeft != AssignRight) {
4221         return AssignLeft? ImplicitConversionSequence::Better
4222                          : ImplicitConversionSequence::Worse;
4223       }
4224     }
4225   }
4226 
4227   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4228     // Check for a better reference binding based on the kind of bindings.
4229     if (isBetterReferenceBindingKind(SCS1, SCS2))
4230       return ImplicitConversionSequence::Better;
4231     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4232       return ImplicitConversionSequence::Worse;
4233   }
4234 
4235   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4236   // bullet 3).
4237   if (ImplicitConversionSequence::CompareKind QualCK
4238         = CompareQualificationConversions(S, SCS1, SCS2))
4239     return QualCK;
4240 
4241   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4242     // C++ [over.ics.rank]p3b4:
4243     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4244     //      which the references refer are the same type except for
4245     //      top-level cv-qualifiers, and the type to which the reference
4246     //      initialized by S2 refers is more cv-qualified than the type
4247     //      to which the reference initialized by S1 refers.
4248     QualType T1 = SCS1.getToType(2);
4249     QualType T2 = SCS2.getToType(2);
4250     T1 = S.Context.getCanonicalType(T1);
4251     T2 = S.Context.getCanonicalType(T2);
4252     Qualifiers T1Quals, T2Quals;
4253     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4254     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4255     if (UnqualT1 == UnqualT2) {
4256       // Objective-C++ ARC: If the references refer to objects with different
4257       // lifetimes, prefer bindings that don't change lifetime.
4258       if (SCS1.ObjCLifetimeConversionBinding !=
4259                                           SCS2.ObjCLifetimeConversionBinding) {
4260         return SCS1.ObjCLifetimeConversionBinding
4261                                            ? ImplicitConversionSequence::Worse
4262                                            : ImplicitConversionSequence::Better;
4263       }
4264 
4265       // If the type is an array type, promote the element qualifiers to the
4266       // type for comparison.
4267       if (isa<ArrayType>(T1) && T1Quals)
4268         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4269       if (isa<ArrayType>(T2) && T2Quals)
4270         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4271       if (T2.isMoreQualifiedThan(T1))
4272         return ImplicitConversionSequence::Better;
4273       if (T1.isMoreQualifiedThan(T2))
4274         return ImplicitConversionSequence::Worse;
4275     }
4276   }
4277 
4278   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4279   // floating-to-integral conversion if the integral conversion
4280   // is between types of the same size.
4281   // For example:
4282   // void f(float);
4283   // void f(int);
4284   // int main {
4285   //    long a;
4286   //    f(a);
4287   // }
4288   // Here, MSVC will call f(int) instead of generating a compile error
4289   // as clang will do in standard mode.
4290   if (S.getLangOpts().MSVCCompat &&
4291       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4292       SCS1.Second == ICK_Integral_Conversion &&
4293       SCS2.Second == ICK_Floating_Integral &&
4294       S.Context.getTypeSize(SCS1.getFromType()) ==
4295           S.Context.getTypeSize(SCS1.getToType(2)))
4296     return ImplicitConversionSequence::Better;
4297 
4298   // Prefer a compatible vector conversion over a lax vector conversion
4299   // For example:
4300   //
4301   // typedef float __v4sf __attribute__((__vector_size__(16)));
4302   // void f(vector float);
4303   // void f(vector signed int);
4304   // int main() {
4305   //   __v4sf a;
4306   //   f(a);
4307   // }
4308   // Here, we'd like to choose f(vector float) and not
4309   // report an ambiguous call error
4310   if (SCS1.Second == ICK_Vector_Conversion &&
4311       SCS2.Second == ICK_Vector_Conversion) {
4312     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4313         SCS1.getFromType(), SCS1.getToType(2));
4314     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4315         SCS2.getFromType(), SCS2.getToType(2));
4316 
4317     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4318       return SCS1IsCompatibleVectorConversion
4319                  ? ImplicitConversionSequence::Better
4320                  : ImplicitConversionSequence::Worse;
4321   }
4322 
4323   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4324       SCS2.Second == ICK_SVE_Vector_Conversion) {
4325     bool SCS1IsCompatibleSVEVectorConversion =
4326         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4327     bool SCS2IsCompatibleSVEVectorConversion =
4328         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4329 
4330     if (SCS1IsCompatibleSVEVectorConversion !=
4331         SCS2IsCompatibleSVEVectorConversion)
4332       return SCS1IsCompatibleSVEVectorConversion
4333                  ? ImplicitConversionSequence::Better
4334                  : ImplicitConversionSequence::Worse;
4335   }
4336 
4337   if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4338       SCS2.Second == ICK_RVV_Vector_Conversion) {
4339     bool SCS1IsCompatibleRVVVectorConversion =
4340         S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4341     bool SCS2IsCompatibleRVVVectorConversion =
4342         S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4343 
4344     if (SCS1IsCompatibleRVVVectorConversion !=
4345         SCS2IsCompatibleRVVVectorConversion)
4346       return SCS1IsCompatibleRVVVectorConversion
4347                  ? ImplicitConversionSequence::Better
4348                  : ImplicitConversionSequence::Worse;
4349   }
4350 
4351   return ImplicitConversionSequence::Indistinguishable;
4352 }
4353 
4354 /// CompareQualificationConversions - Compares two standard conversion
4355 /// sequences to determine whether they can be ranked based on their
4356 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4357 static ImplicitConversionSequence::CompareKind
4358 CompareQualificationConversions(Sema &S,
4359                                 const StandardConversionSequence& SCS1,
4360                                 const StandardConversionSequence& SCS2) {
4361   // C++ [over.ics.rank]p3:
4362   //  -- S1 and S2 differ only in their qualification conversion and
4363   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4364   // [C++98]
4365   //     [...] and the cv-qualification signature of type T1 is a proper subset
4366   //     of the cv-qualification signature of type T2, and S1 is not the
4367   //     deprecated string literal array-to-pointer conversion (4.2).
4368   // [C++2a]
4369   //     [...] where T1 can be converted to T2 by a qualification conversion.
4370   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4371       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4372     return ImplicitConversionSequence::Indistinguishable;
4373 
4374   // FIXME: the example in the standard doesn't use a qualification
4375   // conversion (!)
4376   QualType T1 = SCS1.getToType(2);
4377   QualType T2 = SCS2.getToType(2);
4378   T1 = S.Context.getCanonicalType(T1);
4379   T2 = S.Context.getCanonicalType(T2);
4380   assert(!T1->isReferenceType() && !T2->isReferenceType());
4381   Qualifiers T1Quals, T2Quals;
4382   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4383   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4384 
4385   // If the types are the same, we won't learn anything by unwrapping
4386   // them.
4387   if (UnqualT1 == UnqualT2)
4388     return ImplicitConversionSequence::Indistinguishable;
4389 
4390   // Don't ever prefer a standard conversion sequence that uses the deprecated
4391   // string literal array to pointer conversion.
4392   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4393   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4394 
4395   // Objective-C++ ARC:
4396   //   Prefer qualification conversions not involving a change in lifetime
4397   //   to qualification conversions that do change lifetime.
4398   if (SCS1.QualificationIncludesObjCLifetime &&
4399       !SCS2.QualificationIncludesObjCLifetime)
4400     CanPick1 = false;
4401   if (SCS2.QualificationIncludesObjCLifetime &&
4402       !SCS1.QualificationIncludesObjCLifetime)
4403     CanPick2 = false;
4404 
4405   bool ObjCLifetimeConversion;
4406   if (CanPick1 &&
4407       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4408     CanPick1 = false;
4409   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4410   // directions, so we can't short-cut this second check in general.
4411   if (CanPick2 &&
4412       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4413     CanPick2 = false;
4414 
4415   if (CanPick1 != CanPick2)
4416     return CanPick1 ? ImplicitConversionSequence::Better
4417                     : ImplicitConversionSequence::Worse;
4418   return ImplicitConversionSequence::Indistinguishable;
4419 }
4420 
4421 /// CompareDerivedToBaseConversions - Compares two standard conversion
4422 /// sequences to determine whether they can be ranked based on their
4423 /// various kinds of derived-to-base conversions (C++
4424 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4425 /// conversions between Objective-C interface types.
4426 static ImplicitConversionSequence::CompareKind
4427 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4428                                 const StandardConversionSequence& SCS1,
4429                                 const StandardConversionSequence& SCS2) {
4430   QualType FromType1 = SCS1.getFromType();
4431   QualType ToType1 = SCS1.getToType(1);
4432   QualType FromType2 = SCS2.getFromType();
4433   QualType ToType2 = SCS2.getToType(1);
4434 
4435   // Adjust the types we're converting from via the array-to-pointer
4436   // conversion, if we need to.
4437   if (SCS1.First == ICK_Array_To_Pointer)
4438     FromType1 = S.Context.getArrayDecayedType(FromType1);
4439   if (SCS2.First == ICK_Array_To_Pointer)
4440     FromType2 = S.Context.getArrayDecayedType(FromType2);
4441 
4442   // Canonicalize all of the types.
4443   FromType1 = S.Context.getCanonicalType(FromType1);
4444   ToType1 = S.Context.getCanonicalType(ToType1);
4445   FromType2 = S.Context.getCanonicalType(FromType2);
4446   ToType2 = S.Context.getCanonicalType(ToType2);
4447 
4448   // C++ [over.ics.rank]p4b3:
4449   //
4450   //   If class B is derived directly or indirectly from class A and
4451   //   class C is derived directly or indirectly from B,
4452   //
4453   // Compare based on pointer conversions.
4454   if (SCS1.Second == ICK_Pointer_Conversion &&
4455       SCS2.Second == ICK_Pointer_Conversion &&
4456       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4457       FromType1->isPointerType() && FromType2->isPointerType() &&
4458       ToType1->isPointerType() && ToType2->isPointerType()) {
4459     QualType FromPointee1 =
4460         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4461     QualType ToPointee1 =
4462         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4463     QualType FromPointee2 =
4464         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4465     QualType ToPointee2 =
4466         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4467 
4468     //   -- conversion of C* to B* is better than conversion of C* to A*,
4469     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4470       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4471         return ImplicitConversionSequence::Better;
4472       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4473         return ImplicitConversionSequence::Worse;
4474     }
4475 
4476     //   -- conversion of B* to A* is better than conversion of C* to A*,
4477     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4478       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4479         return ImplicitConversionSequence::Better;
4480       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4481         return ImplicitConversionSequence::Worse;
4482     }
4483   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4484              SCS2.Second == ICK_Pointer_Conversion) {
4485     const ObjCObjectPointerType *FromPtr1
4486       = FromType1->getAs<ObjCObjectPointerType>();
4487     const ObjCObjectPointerType *FromPtr2
4488       = FromType2->getAs<ObjCObjectPointerType>();
4489     const ObjCObjectPointerType *ToPtr1
4490       = ToType1->getAs<ObjCObjectPointerType>();
4491     const ObjCObjectPointerType *ToPtr2
4492       = ToType2->getAs<ObjCObjectPointerType>();
4493 
4494     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4495       // Apply the same conversion ranking rules for Objective-C pointer types
4496       // that we do for C++ pointers to class types. However, we employ the
4497       // Objective-C pseudo-subtyping relationship used for assignment of
4498       // Objective-C pointer types.
4499       bool FromAssignLeft
4500         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4501       bool FromAssignRight
4502         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4503       bool ToAssignLeft
4504         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4505       bool ToAssignRight
4506         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4507 
4508       // A conversion to an a non-id object pointer type or qualified 'id'
4509       // type is better than a conversion to 'id'.
4510       if (ToPtr1->isObjCIdType() &&
4511           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4512         return ImplicitConversionSequence::Worse;
4513       if (ToPtr2->isObjCIdType() &&
4514           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4515         return ImplicitConversionSequence::Better;
4516 
4517       // A conversion to a non-id object pointer type is better than a
4518       // conversion to a qualified 'id' type
4519       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4520         return ImplicitConversionSequence::Worse;
4521       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4522         return ImplicitConversionSequence::Better;
4523 
4524       // A conversion to an a non-Class object pointer type or qualified 'Class'
4525       // type is better than a conversion to 'Class'.
4526       if (ToPtr1->isObjCClassType() &&
4527           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4528         return ImplicitConversionSequence::Worse;
4529       if (ToPtr2->isObjCClassType() &&
4530           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4531         return ImplicitConversionSequence::Better;
4532 
4533       // A conversion to a non-Class object pointer type is better than a
4534       // conversion to a qualified 'Class' type.
4535       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4536         return ImplicitConversionSequence::Worse;
4537       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4538         return ImplicitConversionSequence::Better;
4539 
4540       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4541       if (S.Context.hasSameType(FromType1, FromType2) &&
4542           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4543           (ToAssignLeft != ToAssignRight)) {
4544         if (FromPtr1->isSpecialized()) {
4545           // "conversion of B<A> * to B * is better than conversion of B * to
4546           // C *.
4547           bool IsFirstSame =
4548               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4549           bool IsSecondSame =
4550               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4551           if (IsFirstSame) {
4552             if (!IsSecondSame)
4553               return ImplicitConversionSequence::Better;
4554           } else if (IsSecondSame)
4555             return ImplicitConversionSequence::Worse;
4556         }
4557         return ToAssignLeft? ImplicitConversionSequence::Worse
4558                            : ImplicitConversionSequence::Better;
4559       }
4560 
4561       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4562       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4563           (FromAssignLeft != FromAssignRight))
4564         return FromAssignLeft? ImplicitConversionSequence::Better
4565         : ImplicitConversionSequence::Worse;
4566     }
4567   }
4568 
4569   // Ranking of member-pointer types.
4570   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4571       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4572       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4573     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4574     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4575     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4576     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4577     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4578     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4579     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4580     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4581     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4582     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4583     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4584     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4585     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4586     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4587       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4588         return ImplicitConversionSequence::Worse;
4589       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4590         return ImplicitConversionSequence::Better;
4591     }
4592     // conversion of B::* to C::* is better than conversion of A::* to C::*
4593     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4594       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4595         return ImplicitConversionSequence::Better;
4596       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4597         return ImplicitConversionSequence::Worse;
4598     }
4599   }
4600 
4601   if (SCS1.Second == ICK_Derived_To_Base) {
4602     //   -- conversion of C to B is better than conversion of C to A,
4603     //   -- binding of an expression of type C to a reference of type
4604     //      B& is better than binding an expression of type C to a
4605     //      reference of type A&,
4606     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4607         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4608       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4609         return ImplicitConversionSequence::Better;
4610       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4611         return ImplicitConversionSequence::Worse;
4612     }
4613 
4614     //   -- conversion of B to A is better than conversion of C to A.
4615     //   -- binding of an expression of type B to a reference of type
4616     //      A& is better than binding an expression of type C to a
4617     //      reference of type A&,
4618     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4619         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4620       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4621         return ImplicitConversionSequence::Better;
4622       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4623         return ImplicitConversionSequence::Worse;
4624     }
4625   }
4626 
4627   return ImplicitConversionSequence::Indistinguishable;
4628 }
4629 
4630 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4631   if (!T.getQualifiers().hasUnaligned())
4632     return T;
4633 
4634   Qualifiers Q;
4635   T = Ctx.getUnqualifiedArrayType(T, Q);
4636   Q.removeUnaligned();
4637   return Ctx.getQualifiedType(T, Q);
4638 }
4639 
4640 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4641 /// determine whether they are reference-compatible,
4642 /// reference-related, or incompatible, for use in C++ initialization by
4643 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4644 /// type, and the first type (T1) is the pointee type of the reference
4645 /// type being initialized.
4646 Sema::ReferenceCompareResult
4647 Sema::CompareReferenceRelationship(SourceLocation Loc,
4648                                    QualType OrigT1, QualType OrigT2,
4649                                    ReferenceConversions *ConvOut) {
4650   assert(!OrigT1->isReferenceType() &&
4651     "T1 must be the pointee type of the reference type");
4652   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4653 
4654   QualType T1 = Context.getCanonicalType(OrigT1);
4655   QualType T2 = Context.getCanonicalType(OrigT2);
4656   Qualifiers T1Quals, T2Quals;
4657   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4658   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4659 
4660   ReferenceConversions ConvTmp;
4661   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4662   Conv = ReferenceConversions();
4663 
4664   // C++2a [dcl.init.ref]p4:
4665   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4666   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4667   //   T1 is a base class of T2.
4668   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4669   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4670   //   "pointer to cv1 T1" via a standard conversion sequence.
4671 
4672   // Check for standard conversions we can apply to pointers: derived-to-base
4673   // conversions, ObjC pointer conversions, and function pointer conversions.
4674   // (Qualification conversions are checked last.)
4675   QualType ConvertedT2;
4676   if (UnqualT1 == UnqualT2) {
4677     // Nothing to do.
4678   } else if (isCompleteType(Loc, OrigT2) &&
4679              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4680     Conv |= ReferenceConversions::DerivedToBase;
4681   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4682            UnqualT2->isObjCObjectOrInterfaceType() &&
4683            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4684     Conv |= ReferenceConversions::ObjC;
4685   else if (UnqualT2->isFunctionType() &&
4686            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4687     Conv |= ReferenceConversions::Function;
4688     // No need to check qualifiers; function types don't have them.
4689     return Ref_Compatible;
4690   }
4691   bool ConvertedReferent = Conv != 0;
4692 
4693   // We can have a qualification conversion. Compute whether the types are
4694   // similar at the same time.
4695   bool PreviousToQualsIncludeConst = true;
4696   bool TopLevel = true;
4697   do {
4698     if (T1 == T2)
4699       break;
4700 
4701     // We will need a qualification conversion.
4702     Conv |= ReferenceConversions::Qualification;
4703 
4704     // Track whether we performed a qualification conversion anywhere other
4705     // than the top level. This matters for ranking reference bindings in
4706     // overload resolution.
4707     if (!TopLevel)
4708       Conv |= ReferenceConversions::NestedQualification;
4709 
4710     // MS compiler ignores __unaligned qualifier for references; do the same.
4711     T1 = withoutUnaligned(Context, T1);
4712     T2 = withoutUnaligned(Context, T2);
4713 
4714     // If we find a qualifier mismatch, the types are not reference-compatible,
4715     // but are still be reference-related if they're similar.
4716     bool ObjCLifetimeConversion = false;
4717     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4718                                        PreviousToQualsIncludeConst,
4719                                        ObjCLifetimeConversion))
4720       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4721                  ? Ref_Related
4722                  : Ref_Incompatible;
4723 
4724     // FIXME: Should we track this for any level other than the first?
4725     if (ObjCLifetimeConversion)
4726       Conv |= ReferenceConversions::ObjCLifetime;
4727 
4728     TopLevel = false;
4729   } while (Context.UnwrapSimilarTypes(T1, T2));
4730 
4731   // At this point, if the types are reference-related, we must either have the
4732   // same inner type (ignoring qualifiers), or must have already worked out how
4733   // to convert the referent.
4734   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4735              ? Ref_Compatible
4736              : Ref_Incompatible;
4737 }
4738 
4739 /// Look for a user-defined conversion to a value reference-compatible
4740 ///        with DeclType. Return true if something definite is found.
4741 static bool
4742 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4743                          QualType DeclType, SourceLocation DeclLoc,
4744                          Expr *Init, QualType T2, bool AllowRvalues,
4745                          bool AllowExplicit) {
4746   assert(T2->isRecordType() && "Can only find conversions of record types.");
4747   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4748 
4749   OverloadCandidateSet CandidateSet(
4750       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4751   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4752   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4753     NamedDecl *D = *I;
4754     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4755     if (isa<UsingShadowDecl>(D))
4756       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4757 
4758     FunctionTemplateDecl *ConvTemplate
4759       = dyn_cast<FunctionTemplateDecl>(D);
4760     CXXConversionDecl *Conv;
4761     if (ConvTemplate)
4762       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4763     else
4764       Conv = cast<CXXConversionDecl>(D);
4765 
4766     if (AllowRvalues) {
4767       // If we are initializing an rvalue reference, don't permit conversion
4768       // functions that return lvalues.
4769       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4770         const ReferenceType *RefType
4771           = Conv->getConversionType()->getAs<LValueReferenceType>();
4772         if (RefType && !RefType->getPointeeType()->isFunctionType())
4773           continue;
4774       }
4775 
4776       if (!ConvTemplate &&
4777           S.CompareReferenceRelationship(
4778               DeclLoc,
4779               Conv->getConversionType()
4780                   .getNonReferenceType()
4781                   .getUnqualifiedType(),
4782               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4783               Sema::Ref_Incompatible)
4784         continue;
4785     } else {
4786       // If the conversion function doesn't return a reference type,
4787       // it can't be considered for this conversion. An rvalue reference
4788       // is only acceptable if its referencee is a function type.
4789 
4790       const ReferenceType *RefType =
4791         Conv->getConversionType()->getAs<ReferenceType>();
4792       if (!RefType ||
4793           (!RefType->isLValueReferenceType() &&
4794            !RefType->getPointeeType()->isFunctionType()))
4795         continue;
4796     }
4797 
4798     if (ConvTemplate)
4799       S.AddTemplateConversionCandidate(
4800           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4801           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4802     else
4803       S.AddConversionCandidate(
4804           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4805           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4806   }
4807 
4808   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4809 
4810   OverloadCandidateSet::iterator Best;
4811   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4812   case OR_Success:
4813     // C++ [over.ics.ref]p1:
4814     //
4815     //   [...] If the parameter binds directly to the result of
4816     //   applying a conversion function to the argument
4817     //   expression, the implicit conversion sequence is a
4818     //   user-defined conversion sequence (13.3.3.1.2), with the
4819     //   second standard conversion sequence either an identity
4820     //   conversion or, if the conversion function returns an
4821     //   entity of a type that is a derived class of the parameter
4822     //   type, a derived-to-base Conversion.
4823     if (!Best->FinalConversion.DirectBinding)
4824       return false;
4825 
4826     ICS.setUserDefined();
4827     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4828     ICS.UserDefined.After = Best->FinalConversion;
4829     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4830     ICS.UserDefined.ConversionFunction = Best->Function;
4831     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4832     ICS.UserDefined.EllipsisConversion = false;
4833     assert(ICS.UserDefined.After.ReferenceBinding &&
4834            ICS.UserDefined.After.DirectBinding &&
4835            "Expected a direct reference binding!");
4836     return true;
4837 
4838   case OR_Ambiguous:
4839     ICS.setAmbiguous();
4840     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4841          Cand != CandidateSet.end(); ++Cand)
4842       if (Cand->Best)
4843         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4844     return true;
4845 
4846   case OR_No_Viable_Function:
4847   case OR_Deleted:
4848     // There was no suitable conversion, or we found a deleted
4849     // conversion; continue with other checks.
4850     return false;
4851   }
4852 
4853   llvm_unreachable("Invalid OverloadResult!");
4854 }
4855 
4856 /// Compute an implicit conversion sequence for reference
4857 /// initialization.
4858 static ImplicitConversionSequence
4859 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4860                  SourceLocation DeclLoc,
4861                  bool SuppressUserConversions,
4862                  bool AllowExplicit) {
4863   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4864 
4865   // Most paths end in a failed conversion.
4866   ImplicitConversionSequence ICS;
4867   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4868 
4869   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4870   QualType T2 = Init->getType();
4871 
4872   // If the initializer is the address of an overloaded function, try
4873   // to resolve the overloaded function. If all goes well, T2 is the
4874   // type of the resulting function.
4875   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4876     DeclAccessPair Found;
4877     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4878                                                                 false, Found))
4879       T2 = Fn->getType();
4880   }
4881 
4882   // Compute some basic properties of the types and the initializer.
4883   bool isRValRef = DeclType->isRValueReferenceType();
4884   Expr::Classification InitCategory = Init->Classify(S.Context);
4885 
4886   Sema::ReferenceConversions RefConv;
4887   Sema::ReferenceCompareResult RefRelationship =
4888       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4889 
4890   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4891     ICS.setStandard();
4892     ICS.Standard.First = ICK_Identity;
4893     // FIXME: A reference binding can be a function conversion too. We should
4894     // consider that when ordering reference-to-function bindings.
4895     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4896                               ? ICK_Derived_To_Base
4897                               : (RefConv & Sema::ReferenceConversions::ObjC)
4898                                     ? ICK_Compatible_Conversion
4899                                     : ICK_Identity;
4900     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4901     // a reference binding that performs a non-top-level qualification
4902     // conversion as a qualification conversion, not as an identity conversion.
4903     ICS.Standard.Third = (RefConv &
4904                               Sema::ReferenceConversions::NestedQualification)
4905                              ? ICK_Qualification
4906                              : ICK_Identity;
4907     ICS.Standard.setFromType(T2);
4908     ICS.Standard.setToType(0, T2);
4909     ICS.Standard.setToType(1, T1);
4910     ICS.Standard.setToType(2, T1);
4911     ICS.Standard.ReferenceBinding = true;
4912     ICS.Standard.DirectBinding = BindsDirectly;
4913     ICS.Standard.IsLvalueReference = !isRValRef;
4914     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4915     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4916     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4917     ICS.Standard.ObjCLifetimeConversionBinding =
4918         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4919     ICS.Standard.CopyConstructor = nullptr;
4920     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4921   };
4922 
4923   // C++0x [dcl.init.ref]p5:
4924   //   A reference to type "cv1 T1" is initialized by an expression
4925   //   of type "cv2 T2" as follows:
4926 
4927   //     -- If reference is an lvalue reference and the initializer expression
4928   if (!isRValRef) {
4929     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4930     //        reference-compatible with "cv2 T2," or
4931     //
4932     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4933     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4934       // C++ [over.ics.ref]p1:
4935       //   When a parameter of reference type binds directly (8.5.3)
4936       //   to an argument expression, the implicit conversion sequence
4937       //   is the identity conversion, unless the argument expression
4938       //   has a type that is a derived class of the parameter type,
4939       //   in which case the implicit conversion sequence is a
4940       //   derived-to-base Conversion (13.3.3.1).
4941       SetAsReferenceBinding(/*BindsDirectly=*/true);
4942 
4943       // Nothing more to do: the inaccessibility/ambiguity check for
4944       // derived-to-base conversions is suppressed when we're
4945       // computing the implicit conversion sequence (C++
4946       // [over.best.ics]p2).
4947       return ICS;
4948     }
4949 
4950     //       -- has a class type (i.e., T2 is a class type), where T1 is
4951     //          not reference-related to T2, and can be implicitly
4952     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4953     //          is reference-compatible with "cv3 T3" 92) (this
4954     //          conversion is selected by enumerating the applicable
4955     //          conversion functions (13.3.1.6) and choosing the best
4956     //          one through overload resolution (13.3)),
4957     if (!SuppressUserConversions && T2->isRecordType() &&
4958         S.isCompleteType(DeclLoc, T2) &&
4959         RefRelationship == Sema::Ref_Incompatible) {
4960       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4961                                    Init, T2, /*AllowRvalues=*/false,
4962                                    AllowExplicit))
4963         return ICS;
4964     }
4965   }
4966 
4967   //     -- Otherwise, the reference shall be an lvalue reference to a
4968   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4969   //        shall be an rvalue reference.
4970   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4971     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4972       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4973     return ICS;
4974   }
4975 
4976   //       -- If the initializer expression
4977   //
4978   //            -- is an xvalue, class prvalue, array prvalue or function
4979   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4980   if (RefRelationship == Sema::Ref_Compatible &&
4981       (InitCategory.isXValue() ||
4982        (InitCategory.isPRValue() &&
4983           (T2->isRecordType() || T2->isArrayType())) ||
4984        (InitCategory.isLValue() && T2->isFunctionType()))) {
4985     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4986     // binding unless we're binding to a class prvalue.
4987     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4988     // allow the use of rvalue references in C++98/03 for the benefit of
4989     // standard library implementors; therefore, we need the xvalue check here.
4990     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4991                           !(InitCategory.isPRValue() || T2->isRecordType()));
4992     return ICS;
4993   }
4994 
4995   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4996   //               reference-related to T2, and can be implicitly converted to
4997   //               an xvalue, class prvalue, or function lvalue of type
4998   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4999   //               "cv3 T3",
5000   //
5001   //          then the reference is bound to the value of the initializer
5002   //          expression in the first case and to the result of the conversion
5003   //          in the second case (or, in either case, to an appropriate base
5004   //          class subobject).
5005   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5006       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5007       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5008                                Init, T2, /*AllowRvalues=*/true,
5009                                AllowExplicit)) {
5010     // In the second case, if the reference is an rvalue reference
5011     // and the second standard conversion sequence of the
5012     // user-defined conversion sequence includes an lvalue-to-rvalue
5013     // conversion, the program is ill-formed.
5014     if (ICS.isUserDefined() && isRValRef &&
5015         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5016       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5017 
5018     return ICS;
5019   }
5020 
5021   // A temporary of function type cannot be created; don't even try.
5022   if (T1->isFunctionType())
5023     return ICS;
5024 
5025   //       -- Otherwise, a temporary of type "cv1 T1" is created and
5026   //          initialized from the initializer expression using the
5027   //          rules for a non-reference copy initialization (8.5). The
5028   //          reference is then bound to the temporary. If T1 is
5029   //          reference-related to T2, cv1 must be the same
5030   //          cv-qualification as, or greater cv-qualification than,
5031   //          cv2; otherwise, the program is ill-formed.
5032   if (RefRelationship == Sema::Ref_Related) {
5033     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5034     // we would be reference-compatible or reference-compatible with
5035     // added qualification. But that wasn't the case, so the reference
5036     // initialization fails.
5037     //
5038     // Note that we only want to check address spaces and cvr-qualifiers here.
5039     // ObjC GC, lifetime and unaligned qualifiers aren't important.
5040     Qualifiers T1Quals = T1.getQualifiers();
5041     Qualifiers T2Quals = T2.getQualifiers();
5042     T1Quals.removeObjCGCAttr();
5043     T1Quals.removeObjCLifetime();
5044     T2Quals.removeObjCGCAttr();
5045     T2Quals.removeObjCLifetime();
5046     // MS compiler ignores __unaligned qualifier for references; do the same.
5047     T1Quals.removeUnaligned();
5048     T2Quals.removeUnaligned();
5049     if (!T1Quals.compatiblyIncludes(T2Quals))
5050       return ICS;
5051   }
5052 
5053   // If at least one of the types is a class type, the types are not
5054   // related, and we aren't allowed any user conversions, the
5055   // reference binding fails. This case is important for breaking
5056   // recursion, since TryImplicitConversion below will attempt to
5057   // create a temporary through the use of a copy constructor.
5058   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5059       (T1->isRecordType() || T2->isRecordType()))
5060     return ICS;
5061 
5062   // If T1 is reference-related to T2 and the reference is an rvalue
5063   // reference, the initializer expression shall not be an lvalue.
5064   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5065       Init->Classify(S.Context).isLValue()) {
5066     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5067     return ICS;
5068   }
5069 
5070   // C++ [over.ics.ref]p2:
5071   //   When a parameter of reference type is not bound directly to
5072   //   an argument expression, the conversion sequence is the one
5073   //   required to convert the argument expression to the
5074   //   underlying type of the reference according to
5075   //   13.3.3.1. Conceptually, this conversion sequence corresponds
5076   //   to copy-initializing a temporary of the underlying type with
5077   //   the argument expression. Any difference in top-level
5078   //   cv-qualification is subsumed by the initialization itself
5079   //   and does not constitute a conversion.
5080   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5081                               AllowedExplicit::None,
5082                               /*InOverloadResolution=*/false,
5083                               /*CStyle=*/false,
5084                               /*AllowObjCWritebackConversion=*/false,
5085                               /*AllowObjCConversionOnExplicit=*/false);
5086 
5087   // Of course, that's still a reference binding.
5088   if (ICS.isStandard()) {
5089     ICS.Standard.ReferenceBinding = true;
5090     ICS.Standard.IsLvalueReference = !isRValRef;
5091     ICS.Standard.BindsToFunctionLvalue = false;
5092     ICS.Standard.BindsToRvalue = true;
5093     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5094     ICS.Standard.ObjCLifetimeConversionBinding = false;
5095   } else if (ICS.isUserDefined()) {
5096     const ReferenceType *LValRefType =
5097         ICS.UserDefined.ConversionFunction->getReturnType()
5098             ->getAs<LValueReferenceType>();
5099 
5100     // C++ [over.ics.ref]p3:
5101     //   Except for an implicit object parameter, for which see 13.3.1, a
5102     //   standard conversion sequence cannot be formed if it requires [...]
5103     //   binding an rvalue reference to an lvalue other than a function
5104     //   lvalue.
5105     // Note that the function case is not possible here.
5106     if (isRValRef && LValRefType) {
5107       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5108       return ICS;
5109     }
5110 
5111     ICS.UserDefined.After.ReferenceBinding = true;
5112     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5113     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5114     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5115     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5116     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5117   }
5118 
5119   return ICS;
5120 }
5121 
5122 static ImplicitConversionSequence
5123 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5124                       bool SuppressUserConversions,
5125                       bool InOverloadResolution,
5126                       bool AllowObjCWritebackConversion,
5127                       bool AllowExplicit = false);
5128 
5129 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5130 /// initializer list From.
5131 static ImplicitConversionSequence
5132 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5133                   bool SuppressUserConversions,
5134                   bool InOverloadResolution,
5135                   bool AllowObjCWritebackConversion) {
5136   // C++11 [over.ics.list]p1:
5137   //   When an argument is an initializer list, it is not an expression and
5138   //   special rules apply for converting it to a parameter type.
5139 
5140   ImplicitConversionSequence Result;
5141   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5142 
5143   // We need a complete type for what follows.  With one C++20 exception,
5144   // incomplete types can never be initialized from init lists.
5145   QualType InitTy = ToType;
5146   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5147   if (AT && S.getLangOpts().CPlusPlus20)
5148     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5149       // C++20 allows list initialization of an incomplete array type.
5150       InitTy = IAT->getElementType();
5151   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5152     return Result;
5153 
5154   // C++20 [over.ics.list]/2:
5155   //   If the initializer list is a designated-initializer-list, a conversion
5156   //   is only possible if the parameter has an aggregate type
5157   //
5158   // FIXME: The exception for reference initialization here is not part of the
5159   // language rules, but follow other compilers in adding it as a tentative DR
5160   // resolution.
5161   bool IsDesignatedInit = From->hasDesignatedInit();
5162   if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5163       IsDesignatedInit)
5164     return Result;
5165 
5166   // Per DR1467:
5167   //   If the parameter type is a class X and the initializer list has a single
5168   //   element of type cv U, where U is X or a class derived from X, the
5169   //   implicit conversion sequence is the one required to convert the element
5170   //   to the parameter type.
5171   //
5172   //   Otherwise, if the parameter type is a character array [... ]
5173   //   and the initializer list has a single element that is an
5174   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5175   //   implicit conversion sequence is the identity conversion.
5176   if (From->getNumInits() == 1 && !IsDesignatedInit) {
5177     if (ToType->isRecordType()) {
5178       QualType InitType = From->getInit(0)->getType();
5179       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5180           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5181         return TryCopyInitialization(S, From->getInit(0), ToType,
5182                                      SuppressUserConversions,
5183                                      InOverloadResolution,
5184                                      AllowObjCWritebackConversion);
5185     }
5186 
5187     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5188       InitializedEntity Entity =
5189           InitializedEntity::InitializeParameter(S.Context, ToType,
5190                                                  /*Consumed=*/false);
5191       if (S.CanPerformCopyInitialization(Entity, From)) {
5192         Result.setStandard();
5193         Result.Standard.setAsIdentityConversion();
5194         Result.Standard.setFromType(ToType);
5195         Result.Standard.setAllToTypes(ToType);
5196         return Result;
5197       }
5198     }
5199   }
5200 
5201   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5202   // C++11 [over.ics.list]p2:
5203   //   If the parameter type is std::initializer_list<X> or "array of X" and
5204   //   all the elements can be implicitly converted to X, the implicit
5205   //   conversion sequence is the worst conversion necessary to convert an
5206   //   element of the list to X.
5207   //
5208   // C++14 [over.ics.list]p3:
5209   //   Otherwise, if the parameter type is "array of N X", if the initializer
5210   //   list has exactly N elements or if it has fewer than N elements and X is
5211   //   default-constructible, and if all the elements of the initializer list
5212   //   can be implicitly converted to X, the implicit conversion sequence is
5213   //   the worst conversion necessary to convert an element of the list to X.
5214   if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5215     unsigned e = From->getNumInits();
5216     ImplicitConversionSequence DfltElt;
5217     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5218                    QualType());
5219     QualType ContTy = ToType;
5220     bool IsUnbounded = false;
5221     if (AT) {
5222       InitTy = AT->getElementType();
5223       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5224         if (CT->getSize().ult(e)) {
5225           // Too many inits, fatally bad
5226           Result.setBad(BadConversionSequence::too_many_initializers, From,
5227                         ToType);
5228           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5229           return Result;
5230         }
5231         if (CT->getSize().ugt(e)) {
5232           // Need an init from empty {}, is there one?
5233           InitListExpr EmptyList(S.Context, From->getEndLoc(), std::nullopt,
5234                                  From->getEndLoc());
5235           EmptyList.setType(S.Context.VoidTy);
5236           DfltElt = TryListConversion(
5237               S, &EmptyList, InitTy, SuppressUserConversions,
5238               InOverloadResolution, AllowObjCWritebackConversion);
5239           if (DfltElt.isBad()) {
5240             // No {} init, fatally bad
5241             Result.setBad(BadConversionSequence::too_few_initializers, From,
5242                           ToType);
5243             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5244             return Result;
5245           }
5246         }
5247       } else {
5248         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5249         IsUnbounded = true;
5250         if (!e) {
5251           // Cannot convert to zero-sized.
5252           Result.setBad(BadConversionSequence::too_few_initializers, From,
5253                         ToType);
5254           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5255           return Result;
5256         }
5257         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5258         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5259                                                 ArrayType::Normal, 0);
5260       }
5261     }
5262 
5263     Result.setStandard();
5264     Result.Standard.setAsIdentityConversion();
5265     Result.Standard.setFromType(InitTy);
5266     Result.Standard.setAllToTypes(InitTy);
5267     for (unsigned i = 0; i < e; ++i) {
5268       Expr *Init = From->getInit(i);
5269       ImplicitConversionSequence ICS = TryCopyInitialization(
5270           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5271           AllowObjCWritebackConversion);
5272 
5273       // Keep the worse conversion seen so far.
5274       // FIXME: Sequences are not totally ordered, so 'worse' can be
5275       // ambiguous. CWG has been informed.
5276       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5277                                              Result) ==
5278           ImplicitConversionSequence::Worse) {
5279         Result = ICS;
5280         // Bail as soon as we find something unconvertible.
5281         if (Result.isBad()) {
5282           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5283           return Result;
5284         }
5285       }
5286     }
5287 
5288     // If we needed any implicit {} initialization, compare that now.
5289     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5290     // has been informed that this might not be the best thing.
5291     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5292                                 S, From->getEndLoc(), DfltElt, Result) ==
5293                                 ImplicitConversionSequence::Worse)
5294       Result = DfltElt;
5295     // Record the type being initialized so that we may compare sequences
5296     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5297     return Result;
5298   }
5299 
5300   // C++14 [over.ics.list]p4:
5301   // C++11 [over.ics.list]p3:
5302   //   Otherwise, if the parameter is a non-aggregate class X and overload
5303   //   resolution chooses a single best constructor [...] the implicit
5304   //   conversion sequence is a user-defined conversion sequence. If multiple
5305   //   constructors are viable but none is better than the others, the
5306   //   implicit conversion sequence is a user-defined conversion sequence.
5307   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5308     // This function can deal with initializer lists.
5309     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5310                                     AllowedExplicit::None,
5311                                     InOverloadResolution, /*CStyle=*/false,
5312                                     AllowObjCWritebackConversion,
5313                                     /*AllowObjCConversionOnExplicit=*/false);
5314   }
5315 
5316   // C++14 [over.ics.list]p5:
5317   // C++11 [over.ics.list]p4:
5318   //   Otherwise, if the parameter has an aggregate type which can be
5319   //   initialized from the initializer list [...] the implicit conversion
5320   //   sequence is a user-defined conversion sequence.
5321   if (ToType->isAggregateType()) {
5322     // Type is an aggregate, argument is an init list. At this point it comes
5323     // down to checking whether the initialization works.
5324     // FIXME: Find out whether this parameter is consumed or not.
5325     InitializedEntity Entity =
5326         InitializedEntity::InitializeParameter(S.Context, ToType,
5327                                                /*Consumed=*/false);
5328     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5329                                                                  From)) {
5330       Result.setUserDefined();
5331       Result.UserDefined.Before.setAsIdentityConversion();
5332       // Initializer lists don't have a type.
5333       Result.UserDefined.Before.setFromType(QualType());
5334       Result.UserDefined.Before.setAllToTypes(QualType());
5335 
5336       Result.UserDefined.After.setAsIdentityConversion();
5337       Result.UserDefined.After.setFromType(ToType);
5338       Result.UserDefined.After.setAllToTypes(ToType);
5339       Result.UserDefined.ConversionFunction = nullptr;
5340     }
5341     return Result;
5342   }
5343 
5344   // C++14 [over.ics.list]p6:
5345   // C++11 [over.ics.list]p5:
5346   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5347   if (ToType->isReferenceType()) {
5348     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5349     // mention initializer lists in any way. So we go by what list-
5350     // initialization would do and try to extrapolate from that.
5351 
5352     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5353 
5354     // If the initializer list has a single element that is reference-related
5355     // to the parameter type, we initialize the reference from that.
5356     if (From->getNumInits() == 1 && !IsDesignatedInit) {
5357       Expr *Init = From->getInit(0);
5358 
5359       QualType T2 = Init->getType();
5360 
5361       // If the initializer is the address of an overloaded function, try
5362       // to resolve the overloaded function. If all goes well, T2 is the
5363       // type of the resulting function.
5364       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5365         DeclAccessPair Found;
5366         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5367                                    Init, ToType, false, Found))
5368           T2 = Fn->getType();
5369       }
5370 
5371       // Compute some basic properties of the types and the initializer.
5372       Sema::ReferenceCompareResult RefRelationship =
5373           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5374 
5375       if (RefRelationship >= Sema::Ref_Related) {
5376         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5377                                 SuppressUserConversions,
5378                                 /*AllowExplicit=*/false);
5379       }
5380     }
5381 
5382     // Otherwise, we bind the reference to a temporary created from the
5383     // initializer list.
5384     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5385                                InOverloadResolution,
5386                                AllowObjCWritebackConversion);
5387     if (Result.isFailure())
5388       return Result;
5389     assert(!Result.isEllipsis() &&
5390            "Sub-initialization cannot result in ellipsis conversion.");
5391 
5392     // Can we even bind to a temporary?
5393     if (ToType->isRValueReferenceType() ||
5394         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5395       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5396                                             Result.UserDefined.After;
5397       SCS.ReferenceBinding = true;
5398       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5399       SCS.BindsToRvalue = true;
5400       SCS.BindsToFunctionLvalue = false;
5401       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5402       SCS.ObjCLifetimeConversionBinding = false;
5403     } else
5404       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5405                     From, ToType);
5406     return Result;
5407   }
5408 
5409   // C++14 [over.ics.list]p7:
5410   // C++11 [over.ics.list]p6:
5411   //   Otherwise, if the parameter type is not a class:
5412   if (!ToType->isRecordType()) {
5413     //    - if the initializer list has one element that is not itself an
5414     //      initializer list, the implicit conversion sequence is the one
5415     //      required to convert the element to the parameter type.
5416     unsigned NumInits = From->getNumInits();
5417     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5418       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5419                                      SuppressUserConversions,
5420                                      InOverloadResolution,
5421                                      AllowObjCWritebackConversion);
5422     //    - if the initializer list has no elements, the implicit conversion
5423     //      sequence is the identity conversion.
5424     else if (NumInits == 0) {
5425       Result.setStandard();
5426       Result.Standard.setAsIdentityConversion();
5427       Result.Standard.setFromType(ToType);
5428       Result.Standard.setAllToTypes(ToType);
5429     }
5430     return Result;
5431   }
5432 
5433   // C++14 [over.ics.list]p8:
5434   // C++11 [over.ics.list]p7:
5435   //   In all cases other than those enumerated above, no conversion is possible
5436   return Result;
5437 }
5438 
5439 /// TryCopyInitialization - Try to copy-initialize a value of type
5440 /// ToType from the expression From. Return the implicit conversion
5441 /// sequence required to pass this argument, which may be a bad
5442 /// conversion sequence (meaning that the argument cannot be passed to
5443 /// a parameter of this type). If @p SuppressUserConversions, then we
5444 /// do not permit any user-defined conversion sequences.
5445 static ImplicitConversionSequence
5446 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5447                       bool SuppressUserConversions,
5448                       bool InOverloadResolution,
5449                       bool AllowObjCWritebackConversion,
5450                       bool AllowExplicit) {
5451   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5452     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5453                              InOverloadResolution,AllowObjCWritebackConversion);
5454 
5455   if (ToType->isReferenceType())
5456     return TryReferenceInit(S, From, ToType,
5457                             /*FIXME:*/ From->getBeginLoc(),
5458                             SuppressUserConversions, AllowExplicit);
5459 
5460   return TryImplicitConversion(S, From, ToType,
5461                                SuppressUserConversions,
5462                                AllowedExplicit::None,
5463                                InOverloadResolution,
5464                                /*CStyle=*/false,
5465                                AllowObjCWritebackConversion,
5466                                /*AllowObjCConversionOnExplicit=*/false);
5467 }
5468 
5469 static bool TryCopyInitialization(const CanQualType FromQTy,
5470                                   const CanQualType ToQTy,
5471                                   Sema &S,
5472                                   SourceLocation Loc,
5473                                   ExprValueKind FromVK) {
5474   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5475   ImplicitConversionSequence ICS =
5476     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5477 
5478   return !ICS.isBad();
5479 }
5480 
5481 /// TryObjectArgumentInitialization - Try to initialize the object
5482 /// parameter of the given member function (@c Method) from the
5483 /// expression @p From.
5484 static ImplicitConversionSequence
5485 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5486                                 Expr::Classification FromClassification,
5487                                 CXXMethodDecl *Method,
5488                                 CXXRecordDecl *ActingContext) {
5489   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5490   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5491   //                 const volatile object.
5492   Qualifiers Quals = Method->getMethodQualifiers();
5493   if (isa<CXXDestructorDecl>(Method)) {
5494     Quals.addConst();
5495     Quals.addVolatile();
5496   }
5497 
5498   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5499 
5500   // Set up the conversion sequence as a "bad" conversion, to allow us
5501   // to exit early.
5502   ImplicitConversionSequence ICS;
5503 
5504   // We need to have an object of class type.
5505   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5506     FromType = PT->getPointeeType();
5507 
5508     // When we had a pointer, it's implicitly dereferenced, so we
5509     // better have an lvalue.
5510     assert(FromClassification.isLValue());
5511   }
5512 
5513   assert(FromType->isRecordType());
5514 
5515   // C++0x [over.match.funcs]p4:
5516   //   For non-static member functions, the type of the implicit object
5517   //   parameter is
5518   //
5519   //     - "lvalue reference to cv X" for functions declared without a
5520   //        ref-qualifier or with the & ref-qualifier
5521   //     - "rvalue reference to cv X" for functions declared with the &&
5522   //        ref-qualifier
5523   //
5524   // where X is the class of which the function is a member and cv is the
5525   // cv-qualification on the member function declaration.
5526   //
5527   // However, when finding an implicit conversion sequence for the argument, we
5528   // are not allowed to perform user-defined conversions
5529   // (C++ [over.match.funcs]p5). We perform a simplified version of
5530   // reference binding here, that allows class rvalues to bind to
5531   // non-constant references.
5532 
5533   // First check the qualifiers.
5534   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5535   if (ImplicitParamType.getCVRQualifiers()
5536                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5537       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5538     ICS.setBad(BadConversionSequence::bad_qualifiers,
5539                FromType, ImplicitParamType);
5540     return ICS;
5541   }
5542 
5543   if (FromTypeCanon.hasAddressSpace()) {
5544     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5545     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5546     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5547       ICS.setBad(BadConversionSequence::bad_qualifiers,
5548                  FromType, ImplicitParamType);
5549       return ICS;
5550     }
5551   }
5552 
5553   // Check that we have either the same type or a derived type. It
5554   // affects the conversion rank.
5555   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5556   ImplicitConversionKind SecondKind;
5557   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5558     SecondKind = ICK_Identity;
5559   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5560     SecondKind = ICK_Derived_To_Base;
5561   else {
5562     ICS.setBad(BadConversionSequence::unrelated_class,
5563                FromType, ImplicitParamType);
5564     return ICS;
5565   }
5566 
5567   // Check the ref-qualifier.
5568   switch (Method->getRefQualifier()) {
5569   case RQ_None:
5570     // Do nothing; we don't care about lvalueness or rvalueness.
5571     break;
5572 
5573   case RQ_LValue:
5574     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5575       // non-const lvalue reference cannot bind to an rvalue
5576       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5577                  ImplicitParamType);
5578       return ICS;
5579     }
5580     break;
5581 
5582   case RQ_RValue:
5583     if (!FromClassification.isRValue()) {
5584       // rvalue reference cannot bind to an lvalue
5585       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5586                  ImplicitParamType);
5587       return ICS;
5588     }
5589     break;
5590   }
5591 
5592   // Success. Mark this as a reference binding.
5593   ICS.setStandard();
5594   ICS.Standard.setAsIdentityConversion();
5595   ICS.Standard.Second = SecondKind;
5596   ICS.Standard.setFromType(FromType);
5597   ICS.Standard.setAllToTypes(ImplicitParamType);
5598   ICS.Standard.ReferenceBinding = true;
5599   ICS.Standard.DirectBinding = true;
5600   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5601   ICS.Standard.BindsToFunctionLvalue = false;
5602   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5603   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5604     = (Method->getRefQualifier() == RQ_None);
5605   return ICS;
5606 }
5607 
5608 /// PerformObjectArgumentInitialization - Perform initialization of
5609 /// the implicit object parameter for the given Method with the given
5610 /// expression.
5611 ExprResult
5612 Sema::PerformObjectArgumentInitialization(Expr *From,
5613                                           NestedNameSpecifier *Qualifier,
5614                                           NamedDecl *FoundDecl,
5615                                           CXXMethodDecl *Method) {
5616   QualType FromRecordType, DestType;
5617   QualType ImplicitParamRecordType  =
5618     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5619 
5620   Expr::Classification FromClassification;
5621   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5622     FromRecordType = PT->getPointeeType();
5623     DestType = Method->getThisType();
5624     FromClassification = Expr::Classification::makeSimpleLValue();
5625   } else {
5626     FromRecordType = From->getType();
5627     DestType = ImplicitParamRecordType;
5628     FromClassification = From->Classify(Context);
5629 
5630     // When performing member access on a prvalue, materialize a temporary.
5631     if (From->isPRValue()) {
5632       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5633                                             Method->getRefQualifier() !=
5634                                                 RefQualifierKind::RQ_RValue);
5635     }
5636   }
5637 
5638   // Note that we always use the true parent context when performing
5639   // the actual argument initialization.
5640   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5641       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5642       Method->getParent());
5643   if (ICS.isBad()) {
5644     switch (ICS.Bad.Kind) {
5645     case BadConversionSequence::bad_qualifiers: {
5646       Qualifiers FromQs = FromRecordType.getQualifiers();
5647       Qualifiers ToQs = DestType.getQualifiers();
5648       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5649       if (CVR) {
5650         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5651             << Method->getDeclName() << FromRecordType << (CVR - 1)
5652             << From->getSourceRange();
5653         Diag(Method->getLocation(), diag::note_previous_decl)
5654           << Method->getDeclName();
5655         return ExprError();
5656       }
5657       break;
5658     }
5659 
5660     case BadConversionSequence::lvalue_ref_to_rvalue:
5661     case BadConversionSequence::rvalue_ref_to_lvalue: {
5662       bool IsRValueQualified =
5663         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5664       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5665           << Method->getDeclName() << FromClassification.isRValue()
5666           << IsRValueQualified;
5667       Diag(Method->getLocation(), diag::note_previous_decl)
5668         << Method->getDeclName();
5669       return ExprError();
5670     }
5671 
5672     case BadConversionSequence::no_conversion:
5673     case BadConversionSequence::unrelated_class:
5674       break;
5675 
5676     case BadConversionSequence::too_few_initializers:
5677     case BadConversionSequence::too_many_initializers:
5678       llvm_unreachable("Lists are not objects");
5679     }
5680 
5681     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5682            << ImplicitParamRecordType << FromRecordType
5683            << From->getSourceRange();
5684   }
5685 
5686   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5687     ExprResult FromRes =
5688       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5689     if (FromRes.isInvalid())
5690       return ExprError();
5691     From = FromRes.get();
5692   }
5693 
5694   if (!Context.hasSameType(From->getType(), DestType)) {
5695     CastKind CK;
5696     QualType PteeTy = DestType->getPointeeType();
5697     LangAS DestAS =
5698         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5699     if (FromRecordType.getAddressSpace() != DestAS)
5700       CK = CK_AddressSpaceConversion;
5701     else
5702       CK = CK_NoOp;
5703     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5704   }
5705   return From;
5706 }
5707 
5708 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5709 /// expression From to bool (C++0x [conv]p3).
5710 static ImplicitConversionSequence
5711 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5712   // C++ [dcl.init]/17.8:
5713   //   - Otherwise, if the initialization is direct-initialization, the source
5714   //     type is std::nullptr_t, and the destination type is bool, the initial
5715   //     value of the object being initialized is false.
5716   if (From->getType()->isNullPtrType())
5717     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5718                                                         S.Context.BoolTy,
5719                                                         From->isGLValue());
5720 
5721   // All other direct-initialization of bool is equivalent to an implicit
5722   // conversion to bool in which explicit conversions are permitted.
5723   return TryImplicitConversion(S, From, S.Context.BoolTy,
5724                                /*SuppressUserConversions=*/false,
5725                                AllowedExplicit::Conversions,
5726                                /*InOverloadResolution=*/false,
5727                                /*CStyle=*/false,
5728                                /*AllowObjCWritebackConversion=*/false,
5729                                /*AllowObjCConversionOnExplicit=*/false);
5730 }
5731 
5732 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5733 /// of the expression From to bool (C++0x [conv]p3).
5734 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5735   if (checkPlaceholderForOverload(*this, From))
5736     return ExprError();
5737 
5738   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5739   if (!ICS.isBad())
5740     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5741 
5742   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5743     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5744            << From->getType() << From->getSourceRange();
5745   return ExprError();
5746 }
5747 
5748 /// Check that the specified conversion is permitted in a converted constant
5749 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5750 /// is acceptable.
5751 static bool CheckConvertedConstantConversions(Sema &S,
5752                                               StandardConversionSequence &SCS) {
5753   // Since we know that the target type is an integral or unscoped enumeration
5754   // type, most conversion kinds are impossible. All possible First and Third
5755   // conversions are fine.
5756   switch (SCS.Second) {
5757   case ICK_Identity:
5758   case ICK_Integral_Promotion:
5759   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5760   case ICK_Zero_Queue_Conversion:
5761     return true;
5762 
5763   case ICK_Boolean_Conversion:
5764     // Conversion from an integral or unscoped enumeration type to bool is
5765     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5766     // conversion, so we allow it in a converted constant expression.
5767     //
5768     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5769     // a lot of popular code. We should at least add a warning for this
5770     // (non-conforming) extension.
5771     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5772            SCS.getToType(2)->isBooleanType();
5773 
5774   case ICK_Pointer_Conversion:
5775   case ICK_Pointer_Member:
5776     // C++1z: null pointer conversions and null member pointer conversions are
5777     // only permitted if the source type is std::nullptr_t.
5778     return SCS.getFromType()->isNullPtrType();
5779 
5780   case ICK_Floating_Promotion:
5781   case ICK_Complex_Promotion:
5782   case ICK_Floating_Conversion:
5783   case ICK_Complex_Conversion:
5784   case ICK_Floating_Integral:
5785   case ICK_Compatible_Conversion:
5786   case ICK_Derived_To_Base:
5787   case ICK_Vector_Conversion:
5788   case ICK_SVE_Vector_Conversion:
5789   case ICK_RVV_Vector_Conversion:
5790   case ICK_Vector_Splat:
5791   case ICK_Complex_Real:
5792   case ICK_Block_Pointer_Conversion:
5793   case ICK_TransparentUnionConversion:
5794   case ICK_Writeback_Conversion:
5795   case ICK_Zero_Event_Conversion:
5796   case ICK_C_Only_Conversion:
5797   case ICK_Incompatible_Pointer_Conversion:
5798     return false;
5799 
5800   case ICK_Lvalue_To_Rvalue:
5801   case ICK_Array_To_Pointer:
5802   case ICK_Function_To_Pointer:
5803     llvm_unreachable("found a first conversion kind in Second");
5804 
5805   case ICK_Function_Conversion:
5806   case ICK_Qualification:
5807     llvm_unreachable("found a third conversion kind in Second");
5808 
5809   case ICK_Num_Conversion_Kinds:
5810     break;
5811   }
5812 
5813   llvm_unreachable("unknown conversion kind");
5814 }
5815 
5816 /// BuildConvertedConstantExpression - Check that the expression From is a
5817 /// converted constant expression of type T, perform the conversion but
5818 /// does not evaluate the expression
5819 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
5820                                                    QualType T,
5821                                                    Sema::CCEKind CCE,
5822                                                    NamedDecl *Dest,
5823                                                    APValue &PreNarrowingValue) {
5824   assert(S.getLangOpts().CPlusPlus11 &&
5825          "converted constant expression outside C++11");
5826 
5827   if (checkPlaceholderForOverload(S, From))
5828     return ExprError();
5829 
5830   // C++1z [expr.const]p3:
5831   //  A converted constant expression of type T is an expression,
5832   //  implicitly converted to type T, where the converted
5833   //  expression is a constant expression and the implicit conversion
5834   //  sequence contains only [... list of conversions ...].
5835   ImplicitConversionSequence ICS =
5836       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5837           ? TryContextuallyConvertToBool(S, From)
5838           : TryCopyInitialization(S, From, T,
5839                                   /*SuppressUserConversions=*/false,
5840                                   /*InOverloadResolution=*/false,
5841                                   /*AllowObjCWritebackConversion=*/false,
5842                                   /*AllowExplicit=*/false);
5843   StandardConversionSequence *SCS = nullptr;
5844   switch (ICS.getKind()) {
5845   case ImplicitConversionSequence::StandardConversion:
5846     SCS = &ICS.Standard;
5847     break;
5848   case ImplicitConversionSequence::UserDefinedConversion:
5849     if (T->isRecordType())
5850       SCS = &ICS.UserDefined.Before;
5851     else
5852       SCS = &ICS.UserDefined.After;
5853     break;
5854   case ImplicitConversionSequence::AmbiguousConversion:
5855   case ImplicitConversionSequence::BadConversion:
5856     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5857       return S.Diag(From->getBeginLoc(),
5858                     diag::err_typecheck_converted_constant_expression)
5859              << From->getType() << From->getSourceRange() << T;
5860     return ExprError();
5861 
5862   case ImplicitConversionSequence::EllipsisConversion:
5863   case ImplicitConversionSequence::StaticObjectArgumentConversion:
5864     llvm_unreachable("bad conversion in converted constant expression");
5865   }
5866 
5867   // Check that we would only use permitted conversions.
5868   if (!CheckConvertedConstantConversions(S, *SCS)) {
5869     return S.Diag(From->getBeginLoc(),
5870                   diag::err_typecheck_converted_constant_expression_disallowed)
5871            << From->getType() << From->getSourceRange() << T;
5872   }
5873   // [...] and where the reference binding (if any) binds directly.
5874   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5875     return S.Diag(From->getBeginLoc(),
5876                   diag::err_typecheck_converted_constant_expression_indirect)
5877            << From->getType() << From->getSourceRange() << T;
5878   }
5879 
5880   // Usually we can simply apply the ImplicitConversionSequence we formed
5881   // earlier, but that's not guaranteed to work when initializing an object of
5882   // class type.
5883   ExprResult Result;
5884   if (T->isRecordType()) {
5885     assert(CCE == Sema::CCEK_TemplateArg &&
5886            "unexpected class type converted constant expr");
5887     Result = S.PerformCopyInitialization(
5888         InitializedEntity::InitializeTemplateParameter(
5889             T, cast<NonTypeTemplateParmDecl>(Dest)),
5890         SourceLocation(), From);
5891   } else {
5892     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5893   }
5894   if (Result.isInvalid())
5895     return Result;
5896 
5897   // C++2a [intro.execution]p5:
5898   //   A full-expression is [...] a constant-expression [...]
5899   Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5900                                  /*DiscardedValue=*/false, /*IsConstexpr=*/true,
5901                                  CCE == Sema::CCEKind::CCEK_TemplateArg);
5902   if (Result.isInvalid())
5903     return Result;
5904 
5905   // Check for a narrowing implicit conversion.
5906   bool ReturnPreNarrowingValue = false;
5907   QualType PreNarrowingType;
5908   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5909                                 PreNarrowingType)) {
5910   case NK_Dependent_Narrowing:
5911     // Implicit conversion to a narrower type, but the expression is
5912     // value-dependent so we can't tell whether it's actually narrowing.
5913   case NK_Variable_Narrowing:
5914     // Implicit conversion to a narrower type, and the value is not a constant
5915     // expression. We'll diagnose this in a moment.
5916   case NK_Not_Narrowing:
5917     break;
5918 
5919   case NK_Constant_Narrowing:
5920     if (CCE == Sema::CCEK_ArrayBound &&
5921         PreNarrowingType->isIntegralOrEnumerationType() &&
5922         PreNarrowingValue.isInt()) {
5923       // Don't diagnose array bound narrowing here; we produce more precise
5924       // errors by allowing the un-narrowed value through.
5925       ReturnPreNarrowingValue = true;
5926       break;
5927     }
5928     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5929         << CCE << /*Constant*/ 1
5930         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5931     break;
5932 
5933   case NK_Type_Narrowing:
5934     // FIXME: It would be better to diagnose that the expression is not a
5935     // constant expression.
5936     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5937         << CCE << /*Constant*/ 0 << From->getType() << T;
5938     break;
5939   }
5940   if (!ReturnPreNarrowingValue)
5941     PreNarrowingValue = {};
5942 
5943   return Result;
5944 }
5945 
5946 /// EvaluateConvertedConstantExpression - Evaluate an Expression
5947 /// That is a converted constant expression
5948 /// (which was built with BuildConvertedConstantExpression)
5949 static ExprResult EvaluateConvertedConstantExpression(
5950     Sema &S, Expr *E, QualType T, APValue &Value, Sema::CCEKind CCE,
5951     bool RequireInt, const APValue &PreNarrowingValue) {
5952   ExprResult Result = E;
5953   // Check the expression is a constant expression.
5954   SmallVector<PartialDiagnosticAt, 8> Notes;
5955   Expr::EvalResult Eval;
5956   Eval.Diag = &Notes;
5957 
5958   ConstantExprKind Kind;
5959   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5960     Kind = ConstantExprKind::ClassTemplateArgument;
5961   else if (CCE == Sema::CCEK_TemplateArg)
5962     Kind = ConstantExprKind::NonClassTemplateArgument;
5963   else
5964     Kind = ConstantExprKind::Normal;
5965 
5966   if (!E->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5967       (RequireInt && !Eval.Val.isInt())) {
5968     // The expression can't be folded, so we can't keep it at this position in
5969     // the AST.
5970     Result = ExprError();
5971   } else {
5972     Value = Eval.Val;
5973 
5974     if (Notes.empty()) {
5975       // It's a constant expression.
5976       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5977       if (!PreNarrowingValue.isAbsent())
5978         Value = std::move(PreNarrowingValue);
5979       return E;
5980     }
5981   }
5982 
5983   // It's not a constant expression. Produce an appropriate diagnostic.
5984   if (Notes.size() == 1 &&
5985       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5986     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5987   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5988                                    diag::note_constexpr_invalid_template_arg) {
5989     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5990     for (unsigned I = 0; I < Notes.size(); ++I)
5991       S.Diag(Notes[I].first, Notes[I].second);
5992   } else {
5993     S.Diag(E->getBeginLoc(), diag::err_expr_not_cce)
5994         << CCE << E->getSourceRange();
5995     for (unsigned I = 0; I < Notes.size(); ++I)
5996       S.Diag(Notes[I].first, Notes[I].second);
5997   }
5998   return ExprError();
5999 }
6000 
6001 /// CheckConvertedConstantExpression - Check that the expression From is a
6002 /// converted constant expression of type T, perform the conversion and produce
6003 /// the converted expression, per C++11 [expr.const]p3.
6004 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6005                                                    QualType T, APValue &Value,
6006                                                    Sema::CCEKind CCE,
6007                                                    bool RequireInt,
6008                                                    NamedDecl *Dest) {
6009 
6010   APValue PreNarrowingValue;
6011   ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6012                                                        PreNarrowingValue);
6013   if (Result.isInvalid() || Result.get()->isValueDependent()) {
6014     Value = APValue();
6015     return Result;
6016   }
6017   return EvaluateConvertedConstantExpression(S, Result.get(), T, Value, CCE,
6018                                              RequireInt, PreNarrowingValue);
6019 }
6020 
6021 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6022                                                   CCEKind CCE,
6023                                                   NamedDecl *Dest) {
6024   APValue PreNarrowingValue;
6025   return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6026                                             PreNarrowingValue);
6027 }
6028 
6029 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6030                                                   APValue &Value, CCEKind CCE,
6031                                                   NamedDecl *Dest) {
6032   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6033                                             Dest);
6034 }
6035 
6036 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6037                                                   llvm::APSInt &Value,
6038                                                   CCEKind CCE) {
6039   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6040 
6041   APValue V;
6042   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6043                                               /*Dest=*/nullptr);
6044   if (!R.isInvalid() && !R.get()->isValueDependent())
6045     Value = V.getInt();
6046   return R;
6047 }
6048 
6049 
6050 /// dropPointerConversions - If the given standard conversion sequence
6051 /// involves any pointer conversions, remove them.  This may change
6052 /// the result type of the conversion sequence.
6053 static void dropPointerConversion(StandardConversionSequence &SCS) {
6054   if (SCS.Second == ICK_Pointer_Conversion) {
6055     SCS.Second = ICK_Identity;
6056     SCS.Third = ICK_Identity;
6057     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6058   }
6059 }
6060 
6061 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6062 /// convert the expression From to an Objective-C pointer type.
6063 static ImplicitConversionSequence
6064 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6065   // Do an implicit conversion to 'id'.
6066   QualType Ty = S.Context.getObjCIdType();
6067   ImplicitConversionSequence ICS
6068     = TryImplicitConversion(S, From, Ty,
6069                             // FIXME: Are these flags correct?
6070                             /*SuppressUserConversions=*/false,
6071                             AllowedExplicit::Conversions,
6072                             /*InOverloadResolution=*/false,
6073                             /*CStyle=*/false,
6074                             /*AllowObjCWritebackConversion=*/false,
6075                             /*AllowObjCConversionOnExplicit=*/true);
6076 
6077   // Strip off any final conversions to 'id'.
6078   switch (ICS.getKind()) {
6079   case ImplicitConversionSequence::BadConversion:
6080   case ImplicitConversionSequence::AmbiguousConversion:
6081   case ImplicitConversionSequence::EllipsisConversion:
6082   case ImplicitConversionSequence::StaticObjectArgumentConversion:
6083     break;
6084 
6085   case ImplicitConversionSequence::UserDefinedConversion:
6086     dropPointerConversion(ICS.UserDefined.After);
6087     break;
6088 
6089   case ImplicitConversionSequence::StandardConversion:
6090     dropPointerConversion(ICS.Standard);
6091     break;
6092   }
6093 
6094   return ICS;
6095 }
6096 
6097 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6098 /// conversion of the expression From to an Objective-C pointer type.
6099 /// Returns a valid but null ExprResult if no conversion sequence exists.
6100 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6101   if (checkPlaceholderForOverload(*this, From))
6102     return ExprError();
6103 
6104   QualType Ty = Context.getObjCIdType();
6105   ImplicitConversionSequence ICS =
6106     TryContextuallyConvertToObjCPointer(*this, From);
6107   if (!ICS.isBad())
6108     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
6109   return ExprResult();
6110 }
6111 
6112 /// Determine whether the provided type is an integral type, or an enumeration
6113 /// type of a permitted flavor.
6114 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6115   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6116                                  : T->isIntegralOrUnscopedEnumerationType();
6117 }
6118 
6119 static ExprResult
6120 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6121                             Sema::ContextualImplicitConverter &Converter,
6122                             QualType T, UnresolvedSetImpl &ViableConversions) {
6123 
6124   if (Converter.Suppress)
6125     return ExprError();
6126 
6127   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6128   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6129     CXXConversionDecl *Conv =
6130         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6131     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6132     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6133   }
6134   return From;
6135 }
6136 
6137 static bool
6138 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6139                            Sema::ContextualImplicitConverter &Converter,
6140                            QualType T, bool HadMultipleCandidates,
6141                            UnresolvedSetImpl &ExplicitConversions) {
6142   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6143     DeclAccessPair Found = ExplicitConversions[0];
6144     CXXConversionDecl *Conversion =
6145         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6146 
6147     // The user probably meant to invoke the given explicit
6148     // conversion; use it.
6149     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6150     std::string TypeStr;
6151     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6152 
6153     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6154         << FixItHint::CreateInsertion(From->getBeginLoc(),
6155                                       "static_cast<" + TypeStr + ">(")
6156         << FixItHint::CreateInsertion(
6157                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6158     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6159 
6160     // If we aren't in a SFINAE context, build a call to the
6161     // explicit conversion function.
6162     if (SemaRef.isSFINAEContext())
6163       return true;
6164 
6165     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6166     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6167                                                        HadMultipleCandidates);
6168     if (Result.isInvalid())
6169       return true;
6170     // Record usage of conversion in an implicit cast.
6171     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6172                                     CK_UserDefinedConversion, Result.get(),
6173                                     nullptr, Result.get()->getValueKind(),
6174                                     SemaRef.CurFPFeatureOverrides());
6175   }
6176   return false;
6177 }
6178 
6179 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6180                              Sema::ContextualImplicitConverter &Converter,
6181                              QualType T, bool HadMultipleCandidates,
6182                              DeclAccessPair &Found) {
6183   CXXConversionDecl *Conversion =
6184       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6185   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6186 
6187   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6188   if (!Converter.SuppressConversion) {
6189     if (SemaRef.isSFINAEContext())
6190       return true;
6191 
6192     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6193         << From->getSourceRange();
6194   }
6195 
6196   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6197                                                      HadMultipleCandidates);
6198   if (Result.isInvalid())
6199     return true;
6200   // Record usage of conversion in an implicit cast.
6201   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6202                                   CK_UserDefinedConversion, Result.get(),
6203                                   nullptr, Result.get()->getValueKind(),
6204                                   SemaRef.CurFPFeatureOverrides());
6205   return false;
6206 }
6207 
6208 static ExprResult finishContextualImplicitConversion(
6209     Sema &SemaRef, SourceLocation Loc, Expr *From,
6210     Sema::ContextualImplicitConverter &Converter) {
6211   if (!Converter.match(From->getType()) && !Converter.Suppress)
6212     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6213         << From->getSourceRange();
6214 
6215   return SemaRef.DefaultLvalueConversion(From);
6216 }
6217 
6218 static void
6219 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6220                                   UnresolvedSetImpl &ViableConversions,
6221                                   OverloadCandidateSet &CandidateSet) {
6222   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6223     DeclAccessPair FoundDecl = ViableConversions[I];
6224     NamedDecl *D = FoundDecl.getDecl();
6225     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6226     if (isa<UsingShadowDecl>(D))
6227       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6228 
6229     CXXConversionDecl *Conv;
6230     FunctionTemplateDecl *ConvTemplate;
6231     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6232       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6233     else
6234       Conv = cast<CXXConversionDecl>(D);
6235 
6236     if (ConvTemplate)
6237       SemaRef.AddTemplateConversionCandidate(
6238           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6239           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6240     else
6241       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6242                                      ToType, CandidateSet,
6243                                      /*AllowObjCConversionOnExplicit=*/false,
6244                                      /*AllowExplicit*/ true);
6245   }
6246 }
6247 
6248 /// Attempt to convert the given expression to a type which is accepted
6249 /// by the given converter.
6250 ///
6251 /// This routine will attempt to convert an expression of class type to a
6252 /// type accepted by the specified converter. In C++11 and before, the class
6253 /// must have a single non-explicit conversion function converting to a matching
6254 /// type. In C++1y, there can be multiple such conversion functions, but only
6255 /// one target type.
6256 ///
6257 /// \param Loc The source location of the construct that requires the
6258 /// conversion.
6259 ///
6260 /// \param From The expression we're converting from.
6261 ///
6262 /// \param Converter Used to control and diagnose the conversion process.
6263 ///
6264 /// \returns The expression, converted to an integral or enumeration type if
6265 /// successful.
6266 ExprResult Sema::PerformContextualImplicitConversion(
6267     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6268   // We can't perform any more checking for type-dependent expressions.
6269   if (From->isTypeDependent())
6270     return From;
6271 
6272   // Process placeholders immediately.
6273   if (From->hasPlaceholderType()) {
6274     ExprResult result = CheckPlaceholderExpr(From);
6275     if (result.isInvalid())
6276       return result;
6277     From = result.get();
6278   }
6279 
6280   // If the expression already has a matching type, we're golden.
6281   QualType T = From->getType();
6282   if (Converter.match(T))
6283     return DefaultLvalueConversion(From);
6284 
6285   // FIXME: Check for missing '()' if T is a function type?
6286 
6287   // We can only perform contextual implicit conversions on objects of class
6288   // type.
6289   const RecordType *RecordTy = T->getAs<RecordType>();
6290   if (!RecordTy || !getLangOpts().CPlusPlus) {
6291     if (!Converter.Suppress)
6292       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6293     return From;
6294   }
6295 
6296   // We must have a complete class type.
6297   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6298     ContextualImplicitConverter &Converter;
6299     Expr *From;
6300 
6301     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6302         : Converter(Converter), From(From) {}
6303 
6304     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6305       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6306     }
6307   } IncompleteDiagnoser(Converter, From);
6308 
6309   if (Converter.Suppress ? !isCompleteType(Loc, T)
6310                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6311     return From;
6312 
6313   // Look for a conversion to an integral or enumeration type.
6314   UnresolvedSet<4>
6315       ViableConversions; // These are *potentially* viable in C++1y.
6316   UnresolvedSet<4> ExplicitConversions;
6317   const auto &Conversions =
6318       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6319 
6320   bool HadMultipleCandidates =
6321       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6322 
6323   // To check that there is only one target type, in C++1y:
6324   QualType ToType;
6325   bool HasUniqueTargetType = true;
6326 
6327   // Collect explicit or viable (potentially in C++1y) conversions.
6328   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6329     NamedDecl *D = (*I)->getUnderlyingDecl();
6330     CXXConversionDecl *Conversion;
6331     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6332     if (ConvTemplate) {
6333       if (getLangOpts().CPlusPlus14)
6334         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6335       else
6336         continue; // C++11 does not consider conversion operator templates(?).
6337     } else
6338       Conversion = cast<CXXConversionDecl>(D);
6339 
6340     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6341            "Conversion operator templates are considered potentially "
6342            "viable in C++1y");
6343 
6344     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6345     if (Converter.match(CurToType) || ConvTemplate) {
6346 
6347       if (Conversion->isExplicit()) {
6348         // FIXME: For C++1y, do we need this restriction?
6349         // cf. diagnoseNoViableConversion()
6350         if (!ConvTemplate)
6351           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6352       } else {
6353         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6354           if (ToType.isNull())
6355             ToType = CurToType.getUnqualifiedType();
6356           else if (HasUniqueTargetType &&
6357                    (CurToType.getUnqualifiedType() != ToType))
6358             HasUniqueTargetType = false;
6359         }
6360         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6361       }
6362     }
6363   }
6364 
6365   if (getLangOpts().CPlusPlus14) {
6366     // C++1y [conv]p6:
6367     // ... An expression e of class type E appearing in such a context
6368     // is said to be contextually implicitly converted to a specified
6369     // type T and is well-formed if and only if e can be implicitly
6370     // converted to a type T that is determined as follows: E is searched
6371     // for conversion functions whose return type is cv T or reference to
6372     // cv T such that T is allowed by the context. There shall be
6373     // exactly one such T.
6374 
6375     // If no unique T is found:
6376     if (ToType.isNull()) {
6377       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6378                                      HadMultipleCandidates,
6379                                      ExplicitConversions))
6380         return ExprError();
6381       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6382     }
6383 
6384     // If more than one unique Ts are found:
6385     if (!HasUniqueTargetType)
6386       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6387                                          ViableConversions);
6388 
6389     // If one unique T is found:
6390     // First, build a candidate set from the previously recorded
6391     // potentially viable conversions.
6392     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6393     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6394                                       CandidateSet);
6395 
6396     // Then, perform overload resolution over the candidate set.
6397     OverloadCandidateSet::iterator Best;
6398     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6399     case OR_Success: {
6400       // Apply this conversion.
6401       DeclAccessPair Found =
6402           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6403       if (recordConversion(*this, Loc, From, Converter, T,
6404                            HadMultipleCandidates, Found))
6405         return ExprError();
6406       break;
6407     }
6408     case OR_Ambiguous:
6409       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6410                                          ViableConversions);
6411     case OR_No_Viable_Function:
6412       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6413                                      HadMultipleCandidates,
6414                                      ExplicitConversions))
6415         return ExprError();
6416       [[fallthrough]];
6417     case OR_Deleted:
6418       // We'll complain below about a non-integral condition type.
6419       break;
6420     }
6421   } else {
6422     switch (ViableConversions.size()) {
6423     case 0: {
6424       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6425                                      HadMultipleCandidates,
6426                                      ExplicitConversions))
6427         return ExprError();
6428 
6429       // We'll complain below about a non-integral condition type.
6430       break;
6431     }
6432     case 1: {
6433       // Apply this conversion.
6434       DeclAccessPair Found = ViableConversions[0];
6435       if (recordConversion(*this, Loc, From, Converter, T,
6436                            HadMultipleCandidates, Found))
6437         return ExprError();
6438       break;
6439     }
6440     default:
6441       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6442                                          ViableConversions);
6443     }
6444   }
6445 
6446   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6447 }
6448 
6449 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6450 /// an acceptable non-member overloaded operator for a call whose
6451 /// arguments have types T1 (and, if non-empty, T2). This routine
6452 /// implements the check in C++ [over.match.oper]p3b2 concerning
6453 /// enumeration types.
6454 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6455                                                    FunctionDecl *Fn,
6456                                                    ArrayRef<Expr *> Args) {
6457   QualType T1 = Args[0]->getType();
6458   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6459 
6460   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6461     return true;
6462 
6463   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6464     return true;
6465 
6466   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6467   if (Proto->getNumParams() < 1)
6468     return false;
6469 
6470   if (T1->isEnumeralType()) {
6471     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6472     if (Context.hasSameUnqualifiedType(T1, ArgType))
6473       return true;
6474   }
6475 
6476   if (Proto->getNumParams() < 2)
6477     return false;
6478 
6479   if (!T2.isNull() && T2->isEnumeralType()) {
6480     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6481     if (Context.hasSameUnqualifiedType(T2, ArgType))
6482       return true;
6483   }
6484 
6485   return false;
6486 }
6487 
6488 /// AddOverloadCandidate - Adds the given function to the set of
6489 /// candidate functions, using the given function call arguments.  If
6490 /// @p SuppressUserConversions, then don't allow user-defined
6491 /// conversions via constructors or conversion operators.
6492 ///
6493 /// \param PartialOverloading true if we are performing "partial" overloading
6494 /// based on an incomplete set of function arguments. This feature is used by
6495 /// code completion.
6496 void Sema::AddOverloadCandidate(
6497     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6498     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6499     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6500     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6501     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6502   const FunctionProtoType *Proto
6503     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6504   assert(Proto && "Functions without a prototype cannot be overloaded");
6505   assert(!Function->getDescribedFunctionTemplate() &&
6506          "Use AddTemplateOverloadCandidate for function templates");
6507 
6508   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6509     if (!isa<CXXConstructorDecl>(Method)) {
6510       // If we get here, it's because we're calling a member function
6511       // that is named without a member access expression (e.g.,
6512       // "this->f") that was either written explicitly or created
6513       // implicitly. This can happen with a qualified call to a member
6514       // function, e.g., X::f(). We use an empty type for the implied
6515       // object argument (C++ [over.call.func]p3), and the acting context
6516       // is irrelevant.
6517       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6518                          Expr::Classification::makeSimpleLValue(), Args,
6519                          CandidateSet, SuppressUserConversions,
6520                          PartialOverloading, EarlyConversions, PO);
6521       return;
6522     }
6523     // We treat a constructor like a non-member function, since its object
6524     // argument doesn't participate in overload resolution.
6525   }
6526 
6527   if (!CandidateSet.isNewCandidate(Function, PO))
6528     return;
6529 
6530   // C++11 [class.copy]p11: [DR1402]
6531   //   A defaulted move constructor that is defined as deleted is ignored by
6532   //   overload resolution.
6533   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6534   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6535       Constructor->isMoveConstructor())
6536     return;
6537 
6538   // Overload resolution is always an unevaluated context.
6539   EnterExpressionEvaluationContext Unevaluated(
6540       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6541 
6542   // C++ [over.match.oper]p3:
6543   //   if no operand has a class type, only those non-member functions in the
6544   //   lookup set that have a first parameter of type T1 or "reference to
6545   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6546   //   is a right operand) a second parameter of type T2 or "reference to
6547   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6548   //   candidate functions.
6549   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6550       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6551     return;
6552 
6553   // Add this candidate
6554   OverloadCandidate &Candidate =
6555       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6556   Candidate.FoundDecl = FoundDecl;
6557   Candidate.Function = Function;
6558   Candidate.Viable = true;
6559   Candidate.RewriteKind =
6560       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6561   Candidate.IsSurrogate = false;
6562   Candidate.IsADLCandidate = IsADLCandidate;
6563   Candidate.IgnoreObjectArgument = false;
6564   Candidate.ExplicitCallArguments = Args.size();
6565 
6566   // Explicit functions are not actually candidates at all if we're not
6567   // allowing them in this context, but keep them around so we can point
6568   // to them in diagnostics.
6569   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6570     Candidate.Viable = false;
6571     Candidate.FailureKind = ovl_fail_explicit;
6572     return;
6573   }
6574 
6575   // Functions with internal linkage are only viable in the same module unit.
6576   if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6577     /// FIXME: Currently, the semantics of linkage in clang is slightly
6578     /// different from the semantics in C++ spec. In C++ spec, only names
6579     /// have linkage. So that all entities of the same should share one
6580     /// linkage. But in clang, different entities of the same could have
6581     /// different linkage.
6582     NamedDecl *ND = Function;
6583     if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6584       ND = SpecInfo->getTemplate();
6585 
6586     if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6587       Candidate.Viable = false;
6588       Candidate.FailureKind = ovl_fail_module_mismatched;
6589       return;
6590     }
6591   }
6592 
6593   if (Function->isMultiVersion() &&
6594       ((Function->hasAttr<TargetAttr>() &&
6595         !Function->getAttr<TargetAttr>()->isDefaultVersion()) ||
6596        (Function->hasAttr<TargetVersionAttr>() &&
6597         !Function->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
6598     Candidate.Viable = false;
6599     Candidate.FailureKind = ovl_non_default_multiversion_function;
6600     return;
6601   }
6602 
6603   if (Constructor) {
6604     // C++ [class.copy]p3:
6605     //   A member function template is never instantiated to perform the copy
6606     //   of a class object to an object of its class type.
6607     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6608     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6609         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6610          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6611                        ClassType))) {
6612       Candidate.Viable = false;
6613       Candidate.FailureKind = ovl_fail_illegal_constructor;
6614       return;
6615     }
6616 
6617     // C++ [over.match.funcs]p8: (proposed DR resolution)
6618     //   A constructor inherited from class type C that has a first parameter
6619     //   of type "reference to P" (including such a constructor instantiated
6620     //   from a template) is excluded from the set of candidate functions when
6621     //   constructing an object of type cv D if the argument list has exactly
6622     //   one argument and D is reference-related to P and P is reference-related
6623     //   to C.
6624     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6625     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6626         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6627       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6628       QualType C = Context.getRecordType(Constructor->getParent());
6629       QualType D = Context.getRecordType(Shadow->getParent());
6630       SourceLocation Loc = Args.front()->getExprLoc();
6631       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6632           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6633         Candidate.Viable = false;
6634         Candidate.FailureKind = ovl_fail_inhctor_slice;
6635         return;
6636       }
6637     }
6638 
6639     // Check that the constructor is capable of constructing an object in the
6640     // destination address space.
6641     if (!Qualifiers::isAddressSpaceSupersetOf(
6642             Constructor->getMethodQualifiers().getAddressSpace(),
6643             CandidateSet.getDestAS())) {
6644       Candidate.Viable = false;
6645       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6646     }
6647   }
6648 
6649   unsigned NumParams = Proto->getNumParams();
6650 
6651   // (C++ 13.3.2p2): A candidate function having fewer than m
6652   // parameters is viable only if it has an ellipsis in its parameter
6653   // list (8.3.5).
6654   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6655       !Proto->isVariadic() &&
6656       shouldEnforceArgLimit(PartialOverloading, Function)) {
6657     Candidate.Viable = false;
6658     Candidate.FailureKind = ovl_fail_too_many_arguments;
6659     return;
6660   }
6661 
6662   // (C++ 13.3.2p2): A candidate function having more than m parameters
6663   // is viable only if the (m+1)st parameter has a default argument
6664   // (8.3.6). For the purposes of overload resolution, the
6665   // parameter list is truncated on the right, so that there are
6666   // exactly m parameters.
6667   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6668   if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
6669       !PartialOverloading) {
6670     // Not enough arguments.
6671     Candidate.Viable = false;
6672     Candidate.FailureKind = ovl_fail_too_few_arguments;
6673     return;
6674   }
6675 
6676   // (CUDA B.1): Check for invalid calls between targets.
6677   if (getLangOpts().CUDA)
6678     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6679       // Skip the check for callers that are implicit members, because in this
6680       // case we may not yet know what the member's target is; the target is
6681       // inferred for the member automatically, based on the bases and fields of
6682       // the class.
6683       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6684         Candidate.Viable = false;
6685         Candidate.FailureKind = ovl_fail_bad_target;
6686         return;
6687       }
6688 
6689   if (Function->getTrailingRequiresClause()) {
6690     ConstraintSatisfaction Satisfaction;
6691     if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
6692                                  /*ForOverloadResolution*/ true) ||
6693         !Satisfaction.IsSatisfied) {
6694       Candidate.Viable = false;
6695       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6696       return;
6697     }
6698   }
6699 
6700   // Determine the implicit conversion sequences for each of the
6701   // arguments.
6702   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6703     unsigned ConvIdx =
6704         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6705     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6706       // We already formed a conversion sequence for this parameter during
6707       // template argument deduction.
6708     } else if (ArgIdx < NumParams) {
6709       // (C++ 13.3.2p3): for F to be a viable function, there shall
6710       // exist for each argument an implicit conversion sequence
6711       // (13.3.3.1) that converts that argument to the corresponding
6712       // parameter of F.
6713       QualType ParamType = Proto->getParamType(ArgIdx);
6714       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6715           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6716           /*InOverloadResolution=*/true,
6717           /*AllowObjCWritebackConversion=*/
6718           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6719       if (Candidate.Conversions[ConvIdx].isBad()) {
6720         Candidate.Viable = false;
6721         Candidate.FailureKind = ovl_fail_bad_conversion;
6722         return;
6723       }
6724     } else {
6725       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6726       // argument for which there is no corresponding parameter is
6727       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6728       Candidate.Conversions[ConvIdx].setEllipsis();
6729     }
6730   }
6731 
6732   if (EnableIfAttr *FailedAttr =
6733           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6734     Candidate.Viable = false;
6735     Candidate.FailureKind = ovl_fail_enable_if;
6736     Candidate.DeductionFailure.Data = FailedAttr;
6737     return;
6738   }
6739 }
6740 
6741 ObjCMethodDecl *
6742 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6743                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6744   if (Methods.size() <= 1)
6745     return nullptr;
6746 
6747   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6748     bool Match = true;
6749     ObjCMethodDecl *Method = Methods[b];
6750     unsigned NumNamedArgs = Sel.getNumArgs();
6751     // Method might have more arguments than selector indicates. This is due
6752     // to addition of c-style arguments in method.
6753     if (Method->param_size() > NumNamedArgs)
6754       NumNamedArgs = Method->param_size();
6755     if (Args.size() < NumNamedArgs)
6756       continue;
6757 
6758     for (unsigned i = 0; i < NumNamedArgs; i++) {
6759       // We can't do any type-checking on a type-dependent argument.
6760       if (Args[i]->isTypeDependent()) {
6761         Match = false;
6762         break;
6763       }
6764 
6765       ParmVarDecl *param = Method->parameters()[i];
6766       Expr *argExpr = Args[i];
6767       assert(argExpr && "SelectBestMethod(): missing expression");
6768 
6769       // Strip the unbridged-cast placeholder expression off unless it's
6770       // a consumed argument.
6771       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6772           !param->hasAttr<CFConsumedAttr>())
6773         argExpr = stripARCUnbridgedCast(argExpr);
6774 
6775       // If the parameter is __unknown_anytype, move on to the next method.
6776       if (param->getType() == Context.UnknownAnyTy) {
6777         Match = false;
6778         break;
6779       }
6780 
6781       ImplicitConversionSequence ConversionState
6782         = TryCopyInitialization(*this, argExpr, param->getType(),
6783                                 /*SuppressUserConversions*/false,
6784                                 /*InOverloadResolution=*/true,
6785                                 /*AllowObjCWritebackConversion=*/
6786                                 getLangOpts().ObjCAutoRefCount,
6787                                 /*AllowExplicit*/false);
6788       // This function looks for a reasonably-exact match, so we consider
6789       // incompatible pointer conversions to be a failure here.
6790       if (ConversionState.isBad() ||
6791           (ConversionState.isStandard() &&
6792            ConversionState.Standard.Second ==
6793                ICK_Incompatible_Pointer_Conversion)) {
6794         Match = false;
6795         break;
6796       }
6797     }
6798     // Promote additional arguments to variadic methods.
6799     if (Match && Method->isVariadic()) {
6800       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6801         if (Args[i]->isTypeDependent()) {
6802           Match = false;
6803           break;
6804         }
6805         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6806                                                           nullptr);
6807         if (Arg.isInvalid()) {
6808           Match = false;
6809           break;
6810         }
6811       }
6812     } else {
6813       // Check for extra arguments to non-variadic methods.
6814       if (Args.size() != NumNamedArgs)
6815         Match = false;
6816       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6817         // Special case when selectors have no argument. In this case, select
6818         // one with the most general result type of 'id'.
6819         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6820           QualType ReturnT = Methods[b]->getReturnType();
6821           if (ReturnT->isObjCIdType())
6822             return Methods[b];
6823         }
6824       }
6825     }
6826 
6827     if (Match)
6828       return Method;
6829   }
6830   return nullptr;
6831 }
6832 
6833 static bool convertArgsForAvailabilityChecks(
6834     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6835     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6836     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6837   if (ThisArg) {
6838     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6839     assert(!isa<CXXConstructorDecl>(Method) &&
6840            "Shouldn't have `this` for ctors!");
6841     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6842     ExprResult R = S.PerformObjectArgumentInitialization(
6843         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6844     if (R.isInvalid())
6845       return false;
6846     ConvertedThis = R.get();
6847   } else {
6848     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6849       (void)MD;
6850       assert((MissingImplicitThis || MD->isStatic() ||
6851               isa<CXXConstructorDecl>(MD)) &&
6852              "Expected `this` for non-ctor instance methods");
6853     }
6854     ConvertedThis = nullptr;
6855   }
6856 
6857   // Ignore any variadic arguments. Converting them is pointless, since the
6858   // user can't refer to them in the function condition.
6859   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6860 
6861   // Convert the arguments.
6862   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6863     ExprResult R;
6864     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6865                                         S.Context, Function->getParamDecl(I)),
6866                                     SourceLocation(), Args[I]);
6867 
6868     if (R.isInvalid())
6869       return false;
6870 
6871     ConvertedArgs.push_back(R.get());
6872   }
6873 
6874   if (Trap.hasErrorOccurred())
6875     return false;
6876 
6877   // Push default arguments if needed.
6878   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6879     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6880       ParmVarDecl *P = Function->getParamDecl(i);
6881       if (!P->hasDefaultArg())
6882         return false;
6883       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6884       if (R.isInvalid())
6885         return false;
6886       ConvertedArgs.push_back(R.get());
6887     }
6888 
6889     if (Trap.hasErrorOccurred())
6890       return false;
6891   }
6892   return true;
6893 }
6894 
6895 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6896                                   SourceLocation CallLoc,
6897                                   ArrayRef<Expr *> Args,
6898                                   bool MissingImplicitThis) {
6899   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6900   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6901     return nullptr;
6902 
6903   SFINAETrap Trap(*this);
6904   SmallVector<Expr *, 16> ConvertedArgs;
6905   // FIXME: We should look into making enable_if late-parsed.
6906   Expr *DiscardedThis;
6907   if (!convertArgsForAvailabilityChecks(
6908           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6909           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6910     return *EnableIfAttrs.begin();
6911 
6912   for (auto *EIA : EnableIfAttrs) {
6913     APValue Result;
6914     // FIXME: This doesn't consider value-dependent cases, because doing so is
6915     // very difficult. Ideally, we should handle them more gracefully.
6916     if (EIA->getCond()->isValueDependent() ||
6917         !EIA->getCond()->EvaluateWithSubstitution(
6918             Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
6919       return EIA;
6920 
6921     if (!Result.isInt() || !Result.getInt().getBoolValue())
6922       return EIA;
6923   }
6924   return nullptr;
6925 }
6926 
6927 template <typename CheckFn>
6928 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6929                                         bool ArgDependent, SourceLocation Loc,
6930                                         CheckFn &&IsSuccessful) {
6931   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6932   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6933     if (ArgDependent == DIA->getArgDependent())
6934       Attrs.push_back(DIA);
6935   }
6936 
6937   // Common case: No diagnose_if attributes, so we can quit early.
6938   if (Attrs.empty())
6939     return false;
6940 
6941   auto WarningBegin = std::stable_partition(
6942       Attrs.begin(), Attrs.end(),
6943       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6944 
6945   // Note that diagnose_if attributes are late-parsed, so they appear in the
6946   // correct order (unlike enable_if attributes).
6947   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6948                                IsSuccessful);
6949   if (ErrAttr != WarningBegin) {
6950     const DiagnoseIfAttr *DIA = *ErrAttr;
6951     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6952     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6953         << DIA->getParent() << DIA->getCond()->getSourceRange();
6954     return true;
6955   }
6956 
6957   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6958     if (IsSuccessful(DIA)) {
6959       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6960       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6961           << DIA->getParent() << DIA->getCond()->getSourceRange();
6962     }
6963 
6964   return false;
6965 }
6966 
6967 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6968                                                const Expr *ThisArg,
6969                                                ArrayRef<const Expr *> Args,
6970                                                SourceLocation Loc) {
6971   return diagnoseDiagnoseIfAttrsWith(
6972       *this, Function, /*ArgDependent=*/true, Loc,
6973       [&](const DiagnoseIfAttr *DIA) {
6974         APValue Result;
6975         // It's sane to use the same Args for any redecl of this function, since
6976         // EvaluateWithSubstitution only cares about the position of each
6977         // argument in the arg list, not the ParmVarDecl* it maps to.
6978         if (!DIA->getCond()->EvaluateWithSubstitution(
6979                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6980           return false;
6981         return Result.isInt() && Result.getInt().getBoolValue();
6982       });
6983 }
6984 
6985 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6986                                                  SourceLocation Loc) {
6987   return diagnoseDiagnoseIfAttrsWith(
6988       *this, ND, /*ArgDependent=*/false, Loc,
6989       [&](const DiagnoseIfAttr *DIA) {
6990         bool Result;
6991         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6992                Result;
6993       });
6994 }
6995 
6996 /// Add all of the function declarations in the given function set to
6997 /// the overload candidate set.
6998 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6999                                  ArrayRef<Expr *> Args,
7000                                  OverloadCandidateSet &CandidateSet,
7001                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
7002                                  bool SuppressUserConversions,
7003                                  bool PartialOverloading,
7004                                  bool FirstArgumentIsBase) {
7005   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7006     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7007     ArrayRef<Expr *> FunctionArgs = Args;
7008 
7009     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7010     FunctionDecl *FD =
7011         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7012 
7013     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7014       QualType ObjectType;
7015       Expr::Classification ObjectClassification;
7016       if (Args.size() > 0) {
7017         if (Expr *E = Args[0]) {
7018           // Use the explicit base to restrict the lookup:
7019           ObjectType = E->getType();
7020           // Pointers in the object arguments are implicitly dereferenced, so we
7021           // always classify them as l-values.
7022           if (!ObjectType.isNull() && ObjectType->isPointerType())
7023             ObjectClassification = Expr::Classification::makeSimpleLValue();
7024           else
7025             ObjectClassification = E->Classify(Context);
7026         } // .. else there is an implicit base.
7027         FunctionArgs = Args.slice(1);
7028       }
7029       if (FunTmpl) {
7030         AddMethodTemplateCandidate(
7031             FunTmpl, F.getPair(),
7032             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7033             ExplicitTemplateArgs, ObjectType, ObjectClassification,
7034             FunctionArgs, CandidateSet, SuppressUserConversions,
7035             PartialOverloading);
7036       } else {
7037         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7038                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7039                            ObjectClassification, FunctionArgs, CandidateSet,
7040                            SuppressUserConversions, PartialOverloading);
7041       }
7042     } else {
7043       // This branch handles both standalone functions and static methods.
7044 
7045       // Slice the first argument (which is the base) when we access
7046       // static method as non-static.
7047       if (Args.size() > 0 &&
7048           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7049                         !isa<CXXConstructorDecl>(FD)))) {
7050         assert(cast<CXXMethodDecl>(FD)->isStatic());
7051         FunctionArgs = Args.slice(1);
7052       }
7053       if (FunTmpl) {
7054         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7055                                      ExplicitTemplateArgs, FunctionArgs,
7056                                      CandidateSet, SuppressUserConversions,
7057                                      PartialOverloading);
7058       } else {
7059         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7060                              SuppressUserConversions, PartialOverloading);
7061       }
7062     }
7063   }
7064 }
7065 
7066 /// AddMethodCandidate - Adds a named decl (which is some kind of
7067 /// method) as a method candidate to the given overload set.
7068 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7069                               Expr::Classification ObjectClassification,
7070                               ArrayRef<Expr *> Args,
7071                               OverloadCandidateSet &CandidateSet,
7072                               bool SuppressUserConversions,
7073                               OverloadCandidateParamOrder PO) {
7074   NamedDecl *Decl = FoundDecl.getDecl();
7075   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7076 
7077   if (isa<UsingShadowDecl>(Decl))
7078     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7079 
7080   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7081     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7082            "Expected a member function template");
7083     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7084                                /*ExplicitArgs*/ nullptr, ObjectType,
7085                                ObjectClassification, Args, CandidateSet,
7086                                SuppressUserConversions, false, PO);
7087   } else {
7088     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7089                        ObjectType, ObjectClassification, Args, CandidateSet,
7090                        SuppressUserConversions, false, std::nullopt, PO);
7091   }
7092 }
7093 
7094 /// AddMethodCandidate - Adds the given C++ member function to the set
7095 /// of candidate functions, using the given function call arguments
7096 /// and the object argument (@c Object). For example, in a call
7097 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7098 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7099 /// allow user-defined conversions via constructors or conversion
7100 /// operators.
7101 void
7102 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7103                          CXXRecordDecl *ActingContext, QualType ObjectType,
7104                          Expr::Classification ObjectClassification,
7105                          ArrayRef<Expr *> Args,
7106                          OverloadCandidateSet &CandidateSet,
7107                          bool SuppressUserConversions,
7108                          bool PartialOverloading,
7109                          ConversionSequenceList EarlyConversions,
7110                          OverloadCandidateParamOrder PO) {
7111   const FunctionProtoType *Proto
7112     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7113   assert(Proto && "Methods without a prototype cannot be overloaded");
7114   assert(!isa<CXXConstructorDecl>(Method) &&
7115          "Use AddOverloadCandidate for constructors");
7116 
7117   if (!CandidateSet.isNewCandidate(Method, PO))
7118     return;
7119 
7120   // C++11 [class.copy]p23: [DR1402]
7121   //   A defaulted move assignment operator that is defined as deleted is
7122   //   ignored by overload resolution.
7123   if (Method->isDefaulted() && Method->isDeleted() &&
7124       Method->isMoveAssignmentOperator())
7125     return;
7126 
7127   // Overload resolution is always an unevaluated context.
7128   EnterExpressionEvaluationContext Unevaluated(
7129       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7130 
7131   // Add this candidate
7132   OverloadCandidate &Candidate =
7133       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7134   Candidate.FoundDecl = FoundDecl;
7135   Candidate.Function = Method;
7136   Candidate.RewriteKind =
7137       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7138   Candidate.IsSurrogate = false;
7139   Candidate.IgnoreObjectArgument = false;
7140   Candidate.ExplicitCallArguments = Args.size();
7141 
7142   unsigned NumParams = Proto->getNumParams();
7143 
7144   // (C++ 13.3.2p2): A candidate function having fewer than m
7145   // parameters is viable only if it has an ellipsis in its parameter
7146   // list (8.3.5).
7147   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7148       !Proto->isVariadic() &&
7149       shouldEnforceArgLimit(PartialOverloading, Method)) {
7150     Candidate.Viable = false;
7151     Candidate.FailureKind = ovl_fail_too_many_arguments;
7152     return;
7153   }
7154 
7155   // (C++ 13.3.2p2): A candidate function having more than m parameters
7156   // is viable only if the (m+1)st parameter has a default argument
7157   // (8.3.6). For the purposes of overload resolution, the
7158   // parameter list is truncated on the right, so that there are
7159   // exactly m parameters.
7160   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
7161   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7162     // Not enough arguments.
7163     Candidate.Viable = false;
7164     Candidate.FailureKind = ovl_fail_too_few_arguments;
7165     return;
7166   }
7167 
7168   Candidate.Viable = true;
7169 
7170   unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7171   if (ObjectType.isNull())
7172     Candidate.IgnoreObjectArgument = true;
7173   else if (Method->isStatic()) {
7174     // [over.best.ics.general]p8
7175     // When the parameter is the implicit object parameter of a static member
7176     // function, the implicit conversion sequence is a standard conversion
7177     // sequence that is neither better nor worse than any other standard
7178     // conversion sequence.
7179     //
7180     // This is a rule that was introduced in C++23 to support static lambdas. We
7181     // apply it retroactively because we want to support static lambdas as an
7182     // extension and it doesn't hurt previous code.
7183     Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7184   } else {
7185     // Determine the implicit conversion sequence for the object
7186     // parameter.
7187     Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7188         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7189         Method, ActingContext);
7190     if (Candidate.Conversions[FirstConvIdx].isBad()) {
7191       Candidate.Viable = false;
7192       Candidate.FailureKind = ovl_fail_bad_conversion;
7193       return;
7194     }
7195   }
7196 
7197   // (CUDA B.1): Check for invalid calls between targets.
7198   if (getLangOpts().CUDA)
7199     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7200       if (!IsAllowedCUDACall(Caller, Method)) {
7201         Candidate.Viable = false;
7202         Candidate.FailureKind = ovl_fail_bad_target;
7203         return;
7204       }
7205 
7206   if (Method->getTrailingRequiresClause()) {
7207     ConstraintSatisfaction Satisfaction;
7208     if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7209                                  /*ForOverloadResolution*/ true) ||
7210         !Satisfaction.IsSatisfied) {
7211       Candidate.Viable = false;
7212       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7213       return;
7214     }
7215   }
7216 
7217   // Determine the implicit conversion sequences for each of the
7218   // arguments.
7219   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7220     unsigned ConvIdx =
7221         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7222     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7223       // We already formed a conversion sequence for this parameter during
7224       // template argument deduction.
7225     } else if (ArgIdx < NumParams) {
7226       // (C++ 13.3.2p3): for F to be a viable function, there shall
7227       // exist for each argument an implicit conversion sequence
7228       // (13.3.3.1) that converts that argument to the corresponding
7229       // parameter of F.
7230       QualType ParamType = Proto->getParamType(ArgIdx);
7231       Candidate.Conversions[ConvIdx]
7232         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7233                                 SuppressUserConversions,
7234                                 /*InOverloadResolution=*/true,
7235                                 /*AllowObjCWritebackConversion=*/
7236                                   getLangOpts().ObjCAutoRefCount);
7237       if (Candidate.Conversions[ConvIdx].isBad()) {
7238         Candidate.Viable = false;
7239         Candidate.FailureKind = ovl_fail_bad_conversion;
7240         return;
7241       }
7242     } else {
7243       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7244       // argument for which there is no corresponding parameter is
7245       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7246       Candidate.Conversions[ConvIdx].setEllipsis();
7247     }
7248   }
7249 
7250   if (EnableIfAttr *FailedAttr =
7251           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7252     Candidate.Viable = false;
7253     Candidate.FailureKind = ovl_fail_enable_if;
7254     Candidate.DeductionFailure.Data = FailedAttr;
7255     return;
7256   }
7257 
7258   if (Method->isMultiVersion() &&
7259       ((Method->hasAttr<TargetAttr>() &&
7260         !Method->getAttr<TargetAttr>()->isDefaultVersion()) ||
7261        (Method->hasAttr<TargetVersionAttr>() &&
7262         !Method->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7263     Candidate.Viable = false;
7264     Candidate.FailureKind = ovl_non_default_multiversion_function;
7265   }
7266 }
7267 
7268 /// Add a C++ member function template as a candidate to the candidate
7269 /// set, using template argument deduction to produce an appropriate member
7270 /// function template specialization.
7271 void Sema::AddMethodTemplateCandidate(
7272     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7273     CXXRecordDecl *ActingContext,
7274     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7275     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7276     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7277     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7278   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7279     return;
7280 
7281   // C++ [over.match.funcs]p7:
7282   //   In each case where a candidate is a function template, candidate
7283   //   function template specializations are generated using template argument
7284   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7285   //   candidate functions in the usual way.113) A given name can refer to one
7286   //   or more function templates and also to a set of overloaded non-template
7287   //   functions. In such a case, the candidate functions generated from each
7288   //   function template are combined with the set of non-template candidate
7289   //   functions.
7290   TemplateDeductionInfo Info(CandidateSet.getLocation());
7291   FunctionDecl *Specialization = nullptr;
7292   ConversionSequenceList Conversions;
7293   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7294           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7295           PartialOverloading, /*AggregateDeductionCandidate=*/false,
7296           [&](ArrayRef<QualType> ParamTypes) {
7297             return CheckNonDependentConversions(
7298                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7299                 SuppressUserConversions, ActingContext, ObjectType,
7300                 ObjectClassification, PO);
7301           })) {
7302     OverloadCandidate &Candidate =
7303         CandidateSet.addCandidate(Conversions.size(), Conversions);
7304     Candidate.FoundDecl = FoundDecl;
7305     Candidate.Function = MethodTmpl->getTemplatedDecl();
7306     Candidate.Viable = false;
7307     Candidate.RewriteKind =
7308       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7309     Candidate.IsSurrogate = false;
7310     Candidate.IgnoreObjectArgument =
7311         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7312         ObjectType.isNull();
7313     Candidate.ExplicitCallArguments = Args.size();
7314     if (Result == TDK_NonDependentConversionFailure)
7315       Candidate.FailureKind = ovl_fail_bad_conversion;
7316     else {
7317       Candidate.FailureKind = ovl_fail_bad_deduction;
7318       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7319                                                             Info);
7320     }
7321     return;
7322   }
7323 
7324   // Add the function template specialization produced by template argument
7325   // deduction as a candidate.
7326   assert(Specialization && "Missing member function template specialization?");
7327   assert(isa<CXXMethodDecl>(Specialization) &&
7328          "Specialization is not a member function?");
7329   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7330                      ActingContext, ObjectType, ObjectClassification, Args,
7331                      CandidateSet, SuppressUserConversions, PartialOverloading,
7332                      Conversions, PO);
7333 }
7334 
7335 /// Determine whether a given function template has a simple explicit specifier
7336 /// or a non-value-dependent explicit-specification that evaluates to true.
7337 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7338   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7339 }
7340 
7341 /// Add a C++ function template specialization as a candidate
7342 /// in the candidate set, using template argument deduction to produce
7343 /// an appropriate function template specialization.
7344 void Sema::AddTemplateOverloadCandidate(
7345     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7346     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7347     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7348     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7349     OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7350   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7351     return;
7352 
7353   // If the function template has a non-dependent explicit specification,
7354   // exclude it now if appropriate; we are not permitted to perform deduction
7355   // and substitution in this case.
7356   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7357     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7358     Candidate.FoundDecl = FoundDecl;
7359     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7360     Candidate.Viable = false;
7361     Candidate.FailureKind = ovl_fail_explicit;
7362     return;
7363   }
7364 
7365   // C++ [over.match.funcs]p7:
7366   //   In each case where a candidate is a function template, candidate
7367   //   function template specializations are generated using template argument
7368   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7369   //   candidate functions in the usual way.113) A given name can refer to one
7370   //   or more function templates and also to a set of overloaded non-template
7371   //   functions. In such a case, the candidate functions generated from each
7372   //   function template are combined with the set of non-template candidate
7373   //   functions.
7374   TemplateDeductionInfo Info(CandidateSet.getLocation());
7375   FunctionDecl *Specialization = nullptr;
7376   ConversionSequenceList Conversions;
7377   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7378           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7379           PartialOverloading, AggregateCandidateDeduction,
7380           [&](ArrayRef<QualType> ParamTypes) {
7381             return CheckNonDependentConversions(
7382                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7383                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7384           })) {
7385     OverloadCandidate &Candidate =
7386         CandidateSet.addCandidate(Conversions.size(), Conversions);
7387     Candidate.FoundDecl = FoundDecl;
7388     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7389     Candidate.Viable = false;
7390     Candidate.RewriteKind =
7391       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7392     Candidate.IsSurrogate = false;
7393     Candidate.IsADLCandidate = IsADLCandidate;
7394     // Ignore the object argument if there is one, since we don't have an object
7395     // type.
7396     Candidate.IgnoreObjectArgument =
7397         isa<CXXMethodDecl>(Candidate.Function) &&
7398         !isa<CXXConstructorDecl>(Candidate.Function);
7399     Candidate.ExplicitCallArguments = Args.size();
7400     if (Result == TDK_NonDependentConversionFailure)
7401       Candidate.FailureKind = ovl_fail_bad_conversion;
7402     else {
7403       Candidate.FailureKind = ovl_fail_bad_deduction;
7404       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7405                                                             Info);
7406     }
7407     return;
7408   }
7409 
7410   // Add the function template specialization produced by template argument
7411   // deduction as a candidate.
7412   assert(Specialization && "Missing function template specialization?");
7413   AddOverloadCandidate(
7414       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7415       PartialOverloading, AllowExplicit,
7416       /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7417       Info.AggregateDeductionCandidateHasMismatchedArity);
7418 }
7419 
7420 /// Check that implicit conversion sequences can be formed for each argument
7421 /// whose corresponding parameter has a non-dependent type, per DR1391's
7422 /// [temp.deduct.call]p10.
7423 bool Sema::CheckNonDependentConversions(
7424     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7425     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7426     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7427     CXXRecordDecl *ActingContext, QualType ObjectType,
7428     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7429   // FIXME: The cases in which we allow explicit conversions for constructor
7430   // arguments never consider calling a constructor template. It's not clear
7431   // that is correct.
7432   const bool AllowExplicit = false;
7433 
7434   auto *FD = FunctionTemplate->getTemplatedDecl();
7435   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7436   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7437   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7438 
7439   Conversions =
7440       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7441 
7442   // Overload resolution is always an unevaluated context.
7443   EnterExpressionEvaluationContext Unevaluated(
7444       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7445 
7446   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7447   // require that, but this check should never result in a hard error, and
7448   // overload resolution is permitted to sidestep instantiations.
7449   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7450       !ObjectType.isNull()) {
7451     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7452     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7453         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7454         Method, ActingContext);
7455     if (Conversions[ConvIdx].isBad())
7456       return true;
7457   }
7458 
7459   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7460        ++I) {
7461     QualType ParamType = ParamTypes[I];
7462     if (!ParamType->isDependentType()) {
7463       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7464                              ? 0
7465                              : (ThisConversions + I);
7466       Conversions[ConvIdx]
7467         = TryCopyInitialization(*this, Args[I], ParamType,
7468                                 SuppressUserConversions,
7469                                 /*InOverloadResolution=*/true,
7470                                 /*AllowObjCWritebackConversion=*/
7471                                   getLangOpts().ObjCAutoRefCount,
7472                                 AllowExplicit);
7473       if (Conversions[ConvIdx].isBad())
7474         return true;
7475     }
7476   }
7477 
7478   return false;
7479 }
7480 
7481 /// Determine whether this is an allowable conversion from the result
7482 /// of an explicit conversion operator to the expected type, per C++
7483 /// [over.match.conv]p1 and [over.match.ref]p1.
7484 ///
7485 /// \param ConvType The return type of the conversion function.
7486 ///
7487 /// \param ToType The type we are converting to.
7488 ///
7489 /// \param AllowObjCPointerConversion Allow a conversion from one
7490 /// Objective-C pointer to another.
7491 ///
7492 /// \returns true if the conversion is allowable, false otherwise.
7493 static bool isAllowableExplicitConversion(Sema &S,
7494                                           QualType ConvType, QualType ToType,
7495                                           bool AllowObjCPointerConversion) {
7496   QualType ToNonRefType = ToType.getNonReferenceType();
7497 
7498   // Easy case: the types are the same.
7499   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7500     return true;
7501 
7502   // Allow qualification conversions.
7503   bool ObjCLifetimeConversion;
7504   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7505                                   ObjCLifetimeConversion))
7506     return true;
7507 
7508   // If we're not allowed to consider Objective-C pointer conversions,
7509   // we're done.
7510   if (!AllowObjCPointerConversion)
7511     return false;
7512 
7513   // Is this an Objective-C pointer conversion?
7514   bool IncompatibleObjC = false;
7515   QualType ConvertedType;
7516   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7517                                    IncompatibleObjC);
7518 }
7519 
7520 /// AddConversionCandidate - Add a C++ conversion function as a
7521 /// candidate in the candidate set (C++ [over.match.conv],
7522 /// C++ [over.match.copy]). From is the expression we're converting from,
7523 /// and ToType is the type that we're eventually trying to convert to
7524 /// (which may or may not be the same type as the type that the
7525 /// conversion function produces).
7526 void Sema::AddConversionCandidate(
7527     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7528     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7529     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7530     bool AllowExplicit, bool AllowResultConversion) {
7531   assert(!Conversion->getDescribedFunctionTemplate() &&
7532          "Conversion function templates use AddTemplateConversionCandidate");
7533   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7534   if (!CandidateSet.isNewCandidate(Conversion))
7535     return;
7536 
7537   // If the conversion function has an undeduced return type, trigger its
7538   // deduction now.
7539   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7540     if (DeduceReturnType(Conversion, From->getExprLoc()))
7541       return;
7542     ConvType = Conversion->getConversionType().getNonReferenceType();
7543   }
7544 
7545   // If we don't allow any conversion of the result type, ignore conversion
7546   // functions that don't convert to exactly (possibly cv-qualified) T.
7547   if (!AllowResultConversion &&
7548       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7549     return;
7550 
7551   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7552   // operator is only a candidate if its return type is the target type or
7553   // can be converted to the target type with a qualification conversion.
7554   //
7555   // FIXME: Include such functions in the candidate list and explain why we
7556   // can't select them.
7557   if (Conversion->isExplicit() &&
7558       !isAllowableExplicitConversion(*this, ConvType, ToType,
7559                                      AllowObjCConversionOnExplicit))
7560     return;
7561 
7562   // Overload resolution is always an unevaluated context.
7563   EnterExpressionEvaluationContext Unevaluated(
7564       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7565 
7566   // Add this candidate
7567   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7568   Candidate.FoundDecl = FoundDecl;
7569   Candidate.Function = Conversion;
7570   Candidate.IsSurrogate = false;
7571   Candidate.IgnoreObjectArgument = false;
7572   Candidate.FinalConversion.setAsIdentityConversion();
7573   Candidate.FinalConversion.setFromType(ConvType);
7574   Candidate.FinalConversion.setAllToTypes(ToType);
7575   Candidate.Viable = true;
7576   Candidate.ExplicitCallArguments = 1;
7577 
7578   // Explicit functions are not actually candidates at all if we're not
7579   // allowing them in this context, but keep them around so we can point
7580   // to them in diagnostics.
7581   if (!AllowExplicit && Conversion->isExplicit()) {
7582     Candidate.Viable = false;
7583     Candidate.FailureKind = ovl_fail_explicit;
7584     return;
7585   }
7586 
7587   // C++ [over.match.funcs]p4:
7588   //   For conversion functions, the function is considered to be a member of
7589   //   the class of the implicit implied object argument for the purpose of
7590   //   defining the type of the implicit object parameter.
7591   //
7592   // Determine the implicit conversion sequence for the implicit
7593   // object parameter.
7594   QualType ImplicitParamType = From->getType();
7595   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7596     ImplicitParamType = FromPtrType->getPointeeType();
7597   CXXRecordDecl *ConversionContext
7598     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7599 
7600   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7601       *this, CandidateSet.getLocation(), From->getType(),
7602       From->Classify(Context), Conversion, ConversionContext);
7603 
7604   if (Candidate.Conversions[0].isBad()) {
7605     Candidate.Viable = false;
7606     Candidate.FailureKind = ovl_fail_bad_conversion;
7607     return;
7608   }
7609 
7610   if (Conversion->getTrailingRequiresClause()) {
7611     ConstraintSatisfaction Satisfaction;
7612     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7613         !Satisfaction.IsSatisfied) {
7614       Candidate.Viable = false;
7615       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7616       return;
7617     }
7618   }
7619 
7620   // We won't go through a user-defined type conversion function to convert a
7621   // derived to base as such conversions are given Conversion Rank. They only
7622   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7623   QualType FromCanon
7624     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7625   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7626   if (FromCanon == ToCanon ||
7627       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7628     Candidate.Viable = false;
7629     Candidate.FailureKind = ovl_fail_trivial_conversion;
7630     return;
7631   }
7632 
7633   // To determine what the conversion from the result of calling the
7634   // conversion function to the type we're eventually trying to
7635   // convert to (ToType), we need to synthesize a call to the
7636   // conversion function and attempt copy initialization from it. This
7637   // makes sure that we get the right semantics with respect to
7638   // lvalues/rvalues and the type. Fortunately, we can allocate this
7639   // call on the stack and we don't need its arguments to be
7640   // well-formed.
7641   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7642                             VK_LValue, From->getBeginLoc());
7643   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7644                                 Context.getPointerType(Conversion->getType()),
7645                                 CK_FunctionToPointerDecay, &ConversionRef,
7646                                 VK_PRValue, FPOptionsOverride());
7647 
7648   QualType ConversionType = Conversion->getConversionType();
7649   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7650     Candidate.Viable = false;
7651     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7652     return;
7653   }
7654 
7655   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7656 
7657   // Note that it is safe to allocate CallExpr on the stack here because
7658   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7659   // allocator).
7660   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7661 
7662   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7663   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7664       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7665 
7666   ImplicitConversionSequence ICS =
7667       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7668                             /*SuppressUserConversions=*/true,
7669                             /*InOverloadResolution=*/false,
7670                             /*AllowObjCWritebackConversion=*/false);
7671 
7672   switch (ICS.getKind()) {
7673   case ImplicitConversionSequence::StandardConversion:
7674     Candidate.FinalConversion = ICS.Standard;
7675 
7676     // C++ [over.ics.user]p3:
7677     //   If the user-defined conversion is specified by a specialization of a
7678     //   conversion function template, the second standard conversion sequence
7679     //   shall have exact match rank.
7680     if (Conversion->getPrimaryTemplate() &&
7681         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7682       Candidate.Viable = false;
7683       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7684       return;
7685     }
7686 
7687     // C++0x [dcl.init.ref]p5:
7688     //    In the second case, if the reference is an rvalue reference and
7689     //    the second standard conversion sequence of the user-defined
7690     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7691     //    program is ill-formed.
7692     if (ToType->isRValueReferenceType() &&
7693         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7694       Candidate.Viable = false;
7695       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7696       return;
7697     }
7698     break;
7699 
7700   case ImplicitConversionSequence::BadConversion:
7701     Candidate.Viable = false;
7702     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7703     return;
7704 
7705   default:
7706     llvm_unreachable(
7707            "Can only end up with a standard conversion sequence or failure");
7708   }
7709 
7710   if (EnableIfAttr *FailedAttr =
7711           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7712     Candidate.Viable = false;
7713     Candidate.FailureKind = ovl_fail_enable_if;
7714     Candidate.DeductionFailure.Data = FailedAttr;
7715     return;
7716   }
7717 
7718   if (Conversion->isMultiVersion() &&
7719       ((Conversion->hasAttr<TargetAttr>() &&
7720         !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) ||
7721        (Conversion->hasAttr<TargetVersionAttr>() &&
7722         !Conversion->getAttr<TargetVersionAttr>()->isDefaultVersion()))) {
7723     Candidate.Viable = false;
7724     Candidate.FailureKind = ovl_non_default_multiversion_function;
7725   }
7726 }
7727 
7728 /// Adds a conversion function template specialization
7729 /// candidate to the overload set, using template argument deduction
7730 /// to deduce the template arguments of the conversion function
7731 /// template from the type that we are converting to (C++
7732 /// [temp.deduct.conv]).
7733 void Sema::AddTemplateConversionCandidate(
7734     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7735     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7736     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7737     bool AllowExplicit, bool AllowResultConversion) {
7738   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7739          "Only conversion function templates permitted here");
7740 
7741   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7742     return;
7743 
7744   // If the function template has a non-dependent explicit specification,
7745   // exclude it now if appropriate; we are not permitted to perform deduction
7746   // and substitution in this case.
7747   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7748     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7749     Candidate.FoundDecl = FoundDecl;
7750     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7751     Candidate.Viable = false;
7752     Candidate.FailureKind = ovl_fail_explicit;
7753     return;
7754   }
7755 
7756   TemplateDeductionInfo Info(CandidateSet.getLocation());
7757   CXXConversionDecl *Specialization = nullptr;
7758   if (TemplateDeductionResult Result
7759         = DeduceTemplateArguments(FunctionTemplate, ToType,
7760                                   Specialization, Info)) {
7761     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7762     Candidate.FoundDecl = FoundDecl;
7763     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7764     Candidate.Viable = false;
7765     Candidate.FailureKind = ovl_fail_bad_deduction;
7766     Candidate.IsSurrogate = false;
7767     Candidate.IgnoreObjectArgument = false;
7768     Candidate.ExplicitCallArguments = 1;
7769     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7770                                                           Info);
7771     return;
7772   }
7773 
7774   // Add the conversion function template specialization produced by
7775   // template argument deduction as a candidate.
7776   assert(Specialization && "Missing function template specialization?");
7777   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7778                          CandidateSet, AllowObjCConversionOnExplicit,
7779                          AllowExplicit, AllowResultConversion);
7780 }
7781 
7782 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7783 /// converts the given @c Object to a function pointer via the
7784 /// conversion function @c Conversion, and then attempts to call it
7785 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7786 /// the type of function that we'll eventually be calling.
7787 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7788                                  DeclAccessPair FoundDecl,
7789                                  CXXRecordDecl *ActingContext,
7790                                  const FunctionProtoType *Proto,
7791                                  Expr *Object,
7792                                  ArrayRef<Expr *> Args,
7793                                  OverloadCandidateSet& CandidateSet) {
7794   if (!CandidateSet.isNewCandidate(Conversion))
7795     return;
7796 
7797   // Overload resolution is always an unevaluated context.
7798   EnterExpressionEvaluationContext Unevaluated(
7799       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7800 
7801   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7802   Candidate.FoundDecl = FoundDecl;
7803   Candidate.Function = nullptr;
7804   Candidate.Surrogate = Conversion;
7805   Candidate.Viable = true;
7806   Candidate.IsSurrogate = true;
7807   Candidate.IgnoreObjectArgument = false;
7808   Candidate.ExplicitCallArguments = Args.size();
7809 
7810   // Determine the implicit conversion sequence for the implicit
7811   // object parameter.
7812   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7813       *this, CandidateSet.getLocation(), Object->getType(),
7814       Object->Classify(Context), Conversion, ActingContext);
7815   if (ObjectInit.isBad()) {
7816     Candidate.Viable = false;
7817     Candidate.FailureKind = ovl_fail_bad_conversion;
7818     Candidate.Conversions[0] = ObjectInit;
7819     return;
7820   }
7821 
7822   // The first conversion is actually a user-defined conversion whose
7823   // first conversion is ObjectInit's standard conversion (which is
7824   // effectively a reference binding). Record it as such.
7825   Candidate.Conversions[0].setUserDefined();
7826   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7827   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7828   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7829   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7830   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7831   Candidate.Conversions[0].UserDefined.After
7832     = Candidate.Conversions[0].UserDefined.Before;
7833   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7834 
7835   // Find the
7836   unsigned NumParams = Proto->getNumParams();
7837 
7838   // (C++ 13.3.2p2): A candidate function having fewer than m
7839   // parameters is viable only if it has an ellipsis in its parameter
7840   // list (8.3.5).
7841   if (Args.size() > NumParams && !Proto->isVariadic()) {
7842     Candidate.Viable = false;
7843     Candidate.FailureKind = ovl_fail_too_many_arguments;
7844     return;
7845   }
7846 
7847   // Function types don't have any default arguments, so just check if
7848   // we have enough arguments.
7849   if (Args.size() < NumParams) {
7850     // Not enough arguments.
7851     Candidate.Viable = false;
7852     Candidate.FailureKind = ovl_fail_too_few_arguments;
7853     return;
7854   }
7855 
7856   // Determine the implicit conversion sequences for each of the
7857   // arguments.
7858   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7859     if (ArgIdx < NumParams) {
7860       // (C++ 13.3.2p3): for F to be a viable function, there shall
7861       // exist for each argument an implicit conversion sequence
7862       // (13.3.3.1) that converts that argument to the corresponding
7863       // parameter of F.
7864       QualType ParamType = Proto->getParamType(ArgIdx);
7865       Candidate.Conversions[ArgIdx + 1]
7866         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7867                                 /*SuppressUserConversions=*/false,
7868                                 /*InOverloadResolution=*/false,
7869                                 /*AllowObjCWritebackConversion=*/
7870                                   getLangOpts().ObjCAutoRefCount);
7871       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7872         Candidate.Viable = false;
7873         Candidate.FailureKind = ovl_fail_bad_conversion;
7874         return;
7875       }
7876     } else {
7877       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7878       // argument for which there is no corresponding parameter is
7879       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7880       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7881     }
7882   }
7883 
7884   if (Conversion->getTrailingRequiresClause()) {
7885     ConstraintSatisfaction Satisfaction;
7886     if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
7887                                  /*ForOverloadResolution*/ true) ||
7888         !Satisfaction.IsSatisfied) {
7889       Candidate.Viable = false;
7890       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7891       return;
7892     }
7893   }
7894 
7895   if (EnableIfAttr *FailedAttr =
7896           CheckEnableIf(Conversion, CandidateSet.getLocation(), std::nullopt)) {
7897     Candidate.Viable = false;
7898     Candidate.FailureKind = ovl_fail_enable_if;
7899     Candidate.DeductionFailure.Data = FailedAttr;
7900     return;
7901   }
7902 }
7903 
7904 /// Add all of the non-member operator function declarations in the given
7905 /// function set to the overload candidate set.
7906 void Sema::AddNonMemberOperatorCandidates(
7907     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7908     OverloadCandidateSet &CandidateSet,
7909     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7910   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7911     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7912     ArrayRef<Expr *> FunctionArgs = Args;
7913 
7914     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7915     FunctionDecl *FD =
7916         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7917 
7918     // Don't consider rewritten functions if we're not rewriting.
7919     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7920       continue;
7921 
7922     assert(!isa<CXXMethodDecl>(FD) &&
7923            "unqualified operator lookup found a member function");
7924 
7925     if (FunTmpl) {
7926       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7927                                    FunctionArgs, CandidateSet);
7928       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7929         AddTemplateOverloadCandidate(
7930             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7931             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7932             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7933     } else {
7934       if (ExplicitTemplateArgs)
7935         continue;
7936       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7937       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
7938         AddOverloadCandidate(
7939             FD, F.getPair(), {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7940             false, false, true, false, ADLCallKind::NotADL, std::nullopt,
7941             OverloadCandidateParamOrder::Reversed);
7942     }
7943   }
7944 }
7945 
7946 /// Add overload candidates for overloaded operators that are
7947 /// member functions.
7948 ///
7949 /// Add the overloaded operator candidates that are member functions
7950 /// for the operator Op that was used in an operator expression such
7951 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7952 /// CandidateSet will store the added overload candidates. (C++
7953 /// [over.match.oper]).
7954 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7955                                        SourceLocation OpLoc,
7956                                        ArrayRef<Expr *> Args,
7957                                        OverloadCandidateSet &CandidateSet,
7958                                        OverloadCandidateParamOrder PO) {
7959   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7960 
7961   // C++ [over.match.oper]p3:
7962   //   For a unary operator @ with an operand of a type whose
7963   //   cv-unqualified version is T1, and for a binary operator @ with
7964   //   a left operand of a type whose cv-unqualified version is T1 and
7965   //   a right operand of a type whose cv-unqualified version is T2,
7966   //   three sets of candidate functions, designated member
7967   //   candidates, non-member candidates and built-in candidates, are
7968   //   constructed as follows:
7969   QualType T1 = Args[0]->getType();
7970 
7971   //     -- If T1 is a complete class type or a class currently being
7972   //        defined, the set of member candidates is the result of the
7973   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7974   //        the set of member candidates is empty.
7975   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7976     // Complete the type if it can be completed.
7977     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7978       return;
7979     // If the type is neither complete nor being defined, bail out now.
7980     if (!T1Rec->getDecl()->getDefinition())
7981       return;
7982 
7983     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7984     LookupQualifiedName(Operators, T1Rec->getDecl());
7985     Operators.suppressDiagnostics();
7986 
7987     for (LookupResult::iterator Oper = Operators.begin(),
7988                                 OperEnd = Operators.end();
7989          Oper != OperEnd; ++Oper) {
7990       if (Oper->getAsFunction() &&
7991           PO == OverloadCandidateParamOrder::Reversed &&
7992           !CandidateSet.getRewriteInfo().shouldAddReversed(
7993               *this, {Args[1], Args[0]}, Oper->getAsFunction()))
7994         continue;
7995       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7996                          Args[0]->Classify(Context), Args.slice(1),
7997                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7998     }
7999   }
8000 }
8001 
8002 /// AddBuiltinCandidate - Add a candidate for a built-in
8003 /// operator. ResultTy and ParamTys are the result and parameter types
8004 /// of the built-in candidate, respectively. Args and NumArgs are the
8005 /// arguments being passed to the candidate. IsAssignmentOperator
8006 /// should be true when this built-in candidate is an assignment
8007 /// operator. NumContextualBoolArguments is the number of arguments
8008 /// (at the beginning of the argument list) that will be contextually
8009 /// converted to bool.
8010 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8011                                OverloadCandidateSet& CandidateSet,
8012                                bool IsAssignmentOperator,
8013                                unsigned NumContextualBoolArguments) {
8014   // Overload resolution is always an unevaluated context.
8015   EnterExpressionEvaluationContext Unevaluated(
8016       *this, Sema::ExpressionEvaluationContext::Unevaluated);
8017 
8018   // Add this candidate
8019   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8020   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8021   Candidate.Function = nullptr;
8022   Candidate.IsSurrogate = false;
8023   Candidate.IgnoreObjectArgument = false;
8024   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8025 
8026   // Determine the implicit conversion sequences for each of the
8027   // arguments.
8028   Candidate.Viable = true;
8029   Candidate.ExplicitCallArguments = Args.size();
8030   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8031     // C++ [over.match.oper]p4:
8032     //   For the built-in assignment operators, conversions of the
8033     //   left operand are restricted as follows:
8034     //     -- no temporaries are introduced to hold the left operand, and
8035     //     -- no user-defined conversions are applied to the left
8036     //        operand to achieve a type match with the left-most
8037     //        parameter of a built-in candidate.
8038     //
8039     // We block these conversions by turning off user-defined
8040     // conversions, since that is the only way that initialization of
8041     // a reference to a non-class type can occur from something that
8042     // is not of the same type.
8043     if (ArgIdx < NumContextualBoolArguments) {
8044       assert(ParamTys[ArgIdx] == Context.BoolTy &&
8045              "Contextual conversion to bool requires bool type");
8046       Candidate.Conversions[ArgIdx]
8047         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8048     } else {
8049       Candidate.Conversions[ArgIdx]
8050         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8051                                 ArgIdx == 0 && IsAssignmentOperator,
8052                                 /*InOverloadResolution=*/false,
8053                                 /*AllowObjCWritebackConversion=*/
8054                                   getLangOpts().ObjCAutoRefCount);
8055     }
8056     if (Candidate.Conversions[ArgIdx].isBad()) {
8057       Candidate.Viable = false;
8058       Candidate.FailureKind = ovl_fail_bad_conversion;
8059       break;
8060     }
8061   }
8062 }
8063 
8064 namespace {
8065 
8066 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8067 /// candidate operator functions for built-in operators (C++
8068 /// [over.built]). The types are separated into pointer types and
8069 /// enumeration types.
8070 class BuiltinCandidateTypeSet  {
8071   /// TypeSet - A set of types.
8072   typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8073 
8074   /// PointerTypes - The set of pointer types that will be used in the
8075   /// built-in candidates.
8076   TypeSet PointerTypes;
8077 
8078   /// MemberPointerTypes - The set of member pointer types that will be
8079   /// used in the built-in candidates.
8080   TypeSet MemberPointerTypes;
8081 
8082   /// EnumerationTypes - The set of enumeration types that will be
8083   /// used in the built-in candidates.
8084   TypeSet EnumerationTypes;
8085 
8086   /// The set of vector types that will be used in the built-in
8087   /// candidates.
8088   TypeSet VectorTypes;
8089 
8090   /// The set of matrix types that will be used in the built-in
8091   /// candidates.
8092   TypeSet MatrixTypes;
8093 
8094   /// A flag indicating non-record types are viable candidates
8095   bool HasNonRecordTypes;
8096 
8097   /// A flag indicating whether either arithmetic or enumeration types
8098   /// were present in the candidate set.
8099   bool HasArithmeticOrEnumeralTypes;
8100 
8101   /// A flag indicating whether the nullptr type was present in the
8102   /// candidate set.
8103   bool HasNullPtrType;
8104 
8105   /// Sema - The semantic analysis instance where we are building the
8106   /// candidate type set.
8107   Sema &SemaRef;
8108 
8109   /// Context - The AST context in which we will build the type sets.
8110   ASTContext &Context;
8111 
8112   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8113                                                const Qualifiers &VisibleQuals);
8114   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8115 
8116 public:
8117   /// iterator - Iterates through the types that are part of the set.
8118   typedef TypeSet::iterator iterator;
8119 
8120   BuiltinCandidateTypeSet(Sema &SemaRef)
8121     : HasNonRecordTypes(false),
8122       HasArithmeticOrEnumeralTypes(false),
8123       HasNullPtrType(false),
8124       SemaRef(SemaRef),
8125       Context(SemaRef.Context) { }
8126 
8127   void AddTypesConvertedFrom(QualType Ty,
8128                              SourceLocation Loc,
8129                              bool AllowUserConversions,
8130                              bool AllowExplicitConversions,
8131                              const Qualifiers &VisibleTypeConversionsQuals);
8132 
8133   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8134   llvm::iterator_range<iterator> member_pointer_types() {
8135     return MemberPointerTypes;
8136   }
8137   llvm::iterator_range<iterator> enumeration_types() {
8138     return EnumerationTypes;
8139   }
8140   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8141   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8142 
8143   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8144   bool hasNonRecordTypes() { return HasNonRecordTypes; }
8145   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8146   bool hasNullPtrType() const { return HasNullPtrType; }
8147 };
8148 
8149 } // end anonymous namespace
8150 
8151 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8152 /// the set of pointer types along with any more-qualified variants of
8153 /// that type. For example, if @p Ty is "int const *", this routine
8154 /// will add "int const *", "int const volatile *", "int const
8155 /// restrict *", and "int const volatile restrict *" to the set of
8156 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8157 /// false otherwise.
8158 ///
8159 /// FIXME: what to do about extended qualifiers?
8160 bool
8161 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8162                                              const Qualifiers &VisibleQuals) {
8163 
8164   // Insert this type.
8165   if (!PointerTypes.insert(Ty))
8166     return false;
8167 
8168   QualType PointeeTy;
8169   const PointerType *PointerTy = Ty->getAs<PointerType>();
8170   bool buildObjCPtr = false;
8171   if (!PointerTy) {
8172     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8173     PointeeTy = PTy->getPointeeType();
8174     buildObjCPtr = true;
8175   } else {
8176     PointeeTy = PointerTy->getPointeeType();
8177   }
8178 
8179   // Don't add qualified variants of arrays. For one, they're not allowed
8180   // (the qualifier would sink to the element type), and for another, the
8181   // only overload situation where it matters is subscript or pointer +- int,
8182   // and those shouldn't have qualifier variants anyway.
8183   if (PointeeTy->isArrayType())
8184     return true;
8185 
8186   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8187   bool hasVolatile = VisibleQuals.hasVolatile();
8188   bool hasRestrict = VisibleQuals.hasRestrict();
8189 
8190   // Iterate through all strict supersets of BaseCVR.
8191   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8192     if ((CVR | BaseCVR) != CVR) continue;
8193     // Skip over volatile if no volatile found anywhere in the types.
8194     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8195 
8196     // Skip over restrict if no restrict found anywhere in the types, or if
8197     // the type cannot be restrict-qualified.
8198     if ((CVR & Qualifiers::Restrict) &&
8199         (!hasRestrict ||
8200          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8201       continue;
8202 
8203     // Build qualified pointee type.
8204     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8205 
8206     // Build qualified pointer type.
8207     QualType QPointerTy;
8208     if (!buildObjCPtr)
8209       QPointerTy = Context.getPointerType(QPointeeTy);
8210     else
8211       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8212 
8213     // Insert qualified pointer type.
8214     PointerTypes.insert(QPointerTy);
8215   }
8216 
8217   return true;
8218 }
8219 
8220 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8221 /// to the set of pointer types along with any more-qualified variants of
8222 /// that type. For example, if @p Ty is "int const *", this routine
8223 /// will add "int const *", "int const volatile *", "int const
8224 /// restrict *", and "int const volatile restrict *" to the set of
8225 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8226 /// false otherwise.
8227 ///
8228 /// FIXME: what to do about extended qualifiers?
8229 bool
8230 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8231     QualType Ty) {
8232   // Insert this type.
8233   if (!MemberPointerTypes.insert(Ty))
8234     return false;
8235 
8236   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8237   assert(PointerTy && "type was not a member pointer type!");
8238 
8239   QualType PointeeTy = PointerTy->getPointeeType();
8240   // Don't add qualified variants of arrays. For one, they're not allowed
8241   // (the qualifier would sink to the element type), and for another, the
8242   // only overload situation where it matters is subscript or pointer +- int,
8243   // and those shouldn't have qualifier variants anyway.
8244   if (PointeeTy->isArrayType())
8245     return true;
8246   const Type *ClassTy = PointerTy->getClass();
8247 
8248   // Iterate through all strict supersets of the pointee type's CVR
8249   // qualifiers.
8250   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8251   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8252     if ((CVR | BaseCVR) != CVR) continue;
8253 
8254     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8255     MemberPointerTypes.insert(
8256       Context.getMemberPointerType(QPointeeTy, ClassTy));
8257   }
8258 
8259   return true;
8260 }
8261 
8262 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8263 /// Ty can be implicit converted to the given set of @p Types. We're
8264 /// primarily interested in pointer types and enumeration types. We also
8265 /// take member pointer types, for the conditional operator.
8266 /// AllowUserConversions is true if we should look at the conversion
8267 /// functions of a class type, and AllowExplicitConversions if we
8268 /// should also include the explicit conversion functions of a class
8269 /// type.
8270 void
8271 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8272                                                SourceLocation Loc,
8273                                                bool AllowUserConversions,
8274                                                bool AllowExplicitConversions,
8275                                                const Qualifiers &VisibleQuals) {
8276   // Only deal with canonical types.
8277   Ty = Context.getCanonicalType(Ty);
8278 
8279   // Look through reference types; they aren't part of the type of an
8280   // expression for the purposes of conversions.
8281   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8282     Ty = RefTy->getPointeeType();
8283 
8284   // If we're dealing with an array type, decay to the pointer.
8285   if (Ty->isArrayType())
8286     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8287 
8288   // Otherwise, we don't care about qualifiers on the type.
8289   Ty = Ty.getLocalUnqualifiedType();
8290 
8291   // Flag if we ever add a non-record type.
8292   const RecordType *TyRec = Ty->getAs<RecordType>();
8293   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8294 
8295   // Flag if we encounter an arithmetic type.
8296   HasArithmeticOrEnumeralTypes =
8297     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8298 
8299   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8300     PointerTypes.insert(Ty);
8301   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8302     // Insert our type, and its more-qualified variants, into the set
8303     // of types.
8304     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8305       return;
8306   } else if (Ty->isMemberPointerType()) {
8307     // Member pointers are far easier, since the pointee can't be converted.
8308     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8309       return;
8310   } else if (Ty->isEnumeralType()) {
8311     HasArithmeticOrEnumeralTypes = true;
8312     EnumerationTypes.insert(Ty);
8313   } else if (Ty->isVectorType()) {
8314     // We treat vector types as arithmetic types in many contexts as an
8315     // extension.
8316     HasArithmeticOrEnumeralTypes = true;
8317     VectorTypes.insert(Ty);
8318   } else if (Ty->isMatrixType()) {
8319     // Similar to vector types, we treat vector types as arithmetic types in
8320     // many contexts as an extension.
8321     HasArithmeticOrEnumeralTypes = true;
8322     MatrixTypes.insert(Ty);
8323   } else if (Ty->isNullPtrType()) {
8324     HasNullPtrType = true;
8325   } else if (AllowUserConversions && TyRec) {
8326     // No conversion functions in incomplete types.
8327     if (!SemaRef.isCompleteType(Loc, Ty))
8328       return;
8329 
8330     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8331     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8332       if (isa<UsingShadowDecl>(D))
8333         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8334 
8335       // Skip conversion function templates; they don't tell us anything
8336       // about which builtin types we can convert to.
8337       if (isa<FunctionTemplateDecl>(D))
8338         continue;
8339 
8340       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8341       if (AllowExplicitConversions || !Conv->isExplicit()) {
8342         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8343                               VisibleQuals);
8344       }
8345     }
8346   }
8347 }
8348 /// Helper function for adjusting address spaces for the pointer or reference
8349 /// operands of builtin operators depending on the argument.
8350 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8351                                                         Expr *Arg) {
8352   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8353 }
8354 
8355 /// Helper function for AddBuiltinOperatorCandidates() that adds
8356 /// the volatile- and non-volatile-qualified assignment operators for the
8357 /// given type to the candidate set.
8358 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8359                                                    QualType T,
8360                                                    ArrayRef<Expr *> Args,
8361                                     OverloadCandidateSet &CandidateSet) {
8362   QualType ParamTypes[2];
8363 
8364   // T& operator=(T&, T)
8365   ParamTypes[0] = S.Context.getLValueReferenceType(
8366       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8367   ParamTypes[1] = T;
8368   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8369                         /*IsAssignmentOperator=*/true);
8370 
8371   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8372     // volatile T& operator=(volatile T&, T)
8373     ParamTypes[0] = S.Context.getLValueReferenceType(
8374         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8375                                                 Args[0]));
8376     ParamTypes[1] = T;
8377     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8378                           /*IsAssignmentOperator=*/true);
8379   }
8380 }
8381 
8382 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8383 /// if any, found in visible type conversion functions found in ArgExpr's type.
8384 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8385     Qualifiers VRQuals;
8386     const RecordType *TyRec;
8387     if (const MemberPointerType *RHSMPType =
8388         ArgExpr->getType()->getAs<MemberPointerType>())
8389       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8390     else
8391       TyRec = ArgExpr->getType()->getAs<RecordType>();
8392     if (!TyRec) {
8393       // Just to be safe, assume the worst case.
8394       VRQuals.addVolatile();
8395       VRQuals.addRestrict();
8396       return VRQuals;
8397     }
8398 
8399     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8400     if (!ClassDecl->hasDefinition())
8401       return VRQuals;
8402 
8403     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8404       if (isa<UsingShadowDecl>(D))
8405         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8406       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8407         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8408         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8409           CanTy = ResTypeRef->getPointeeType();
8410         // Need to go down the pointer/mempointer chain and add qualifiers
8411         // as see them.
8412         bool done = false;
8413         while (!done) {
8414           if (CanTy.isRestrictQualified())
8415             VRQuals.addRestrict();
8416           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8417             CanTy = ResTypePtr->getPointeeType();
8418           else if (const MemberPointerType *ResTypeMPtr =
8419                 CanTy->getAs<MemberPointerType>())
8420             CanTy = ResTypeMPtr->getPointeeType();
8421           else
8422             done = true;
8423           if (CanTy.isVolatileQualified())
8424             VRQuals.addVolatile();
8425           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8426             return VRQuals;
8427         }
8428       }
8429     }
8430     return VRQuals;
8431 }
8432 
8433 // Note: We're currently only handling qualifiers that are meaningful for the
8434 // LHS of compound assignment overloading.
8435 static void forAllQualifierCombinationsImpl(
8436     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8437     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8438   // _Atomic
8439   if (Available.hasAtomic()) {
8440     Available.removeAtomic();
8441     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8442     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8443     return;
8444   }
8445 
8446   // volatile
8447   if (Available.hasVolatile()) {
8448     Available.removeVolatile();
8449     assert(!Applied.hasVolatile());
8450     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8451                                     Callback);
8452     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8453     return;
8454   }
8455 
8456   Callback(Applied);
8457 }
8458 
8459 static void forAllQualifierCombinations(
8460     QualifiersAndAtomic Quals,
8461     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8462   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8463                                          Callback);
8464 }
8465 
8466 static QualType makeQualifiedLValueReferenceType(QualType Base,
8467                                                  QualifiersAndAtomic Quals,
8468                                                  Sema &S) {
8469   if (Quals.hasAtomic())
8470     Base = S.Context.getAtomicType(Base);
8471   if (Quals.hasVolatile())
8472     Base = S.Context.getVolatileType(Base);
8473   return S.Context.getLValueReferenceType(Base);
8474 }
8475 
8476 namespace {
8477 
8478 /// Helper class to manage the addition of builtin operator overload
8479 /// candidates. It provides shared state and utility methods used throughout
8480 /// the process, as well as a helper method to add each group of builtin
8481 /// operator overloads from the standard to a candidate set.
8482 class BuiltinOperatorOverloadBuilder {
8483   // Common instance state available to all overload candidate addition methods.
8484   Sema &S;
8485   ArrayRef<Expr *> Args;
8486   QualifiersAndAtomic VisibleTypeConversionsQuals;
8487   bool HasArithmeticOrEnumeralCandidateType;
8488   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8489   OverloadCandidateSet &CandidateSet;
8490 
8491   static constexpr int ArithmeticTypesCap = 24;
8492   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8493 
8494   // Define some indices used to iterate over the arithmetic types in
8495   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8496   // types are that preserved by promotion (C++ [over.built]p2).
8497   unsigned FirstIntegralType,
8498            LastIntegralType;
8499   unsigned FirstPromotedIntegralType,
8500            LastPromotedIntegralType;
8501   unsigned FirstPromotedArithmeticType,
8502            LastPromotedArithmeticType;
8503   unsigned NumArithmeticTypes;
8504 
8505   void InitArithmeticTypes() {
8506     // Start of promoted types.
8507     FirstPromotedArithmeticType = 0;
8508     ArithmeticTypes.push_back(S.Context.FloatTy);
8509     ArithmeticTypes.push_back(S.Context.DoubleTy);
8510     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8511     if (S.Context.getTargetInfo().hasFloat128Type())
8512       ArithmeticTypes.push_back(S.Context.Float128Ty);
8513     if (S.Context.getTargetInfo().hasIbm128Type())
8514       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8515 
8516     // Start of integral types.
8517     FirstIntegralType = ArithmeticTypes.size();
8518     FirstPromotedIntegralType = ArithmeticTypes.size();
8519     ArithmeticTypes.push_back(S.Context.IntTy);
8520     ArithmeticTypes.push_back(S.Context.LongTy);
8521     ArithmeticTypes.push_back(S.Context.LongLongTy);
8522     if (S.Context.getTargetInfo().hasInt128Type() ||
8523         (S.Context.getAuxTargetInfo() &&
8524          S.Context.getAuxTargetInfo()->hasInt128Type()))
8525       ArithmeticTypes.push_back(S.Context.Int128Ty);
8526     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8527     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8528     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8529     if (S.Context.getTargetInfo().hasInt128Type() ||
8530         (S.Context.getAuxTargetInfo() &&
8531          S.Context.getAuxTargetInfo()->hasInt128Type()))
8532       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8533     LastPromotedIntegralType = ArithmeticTypes.size();
8534     LastPromotedArithmeticType = ArithmeticTypes.size();
8535     // End of promoted types.
8536 
8537     ArithmeticTypes.push_back(S.Context.BoolTy);
8538     ArithmeticTypes.push_back(S.Context.CharTy);
8539     ArithmeticTypes.push_back(S.Context.WCharTy);
8540     if (S.Context.getLangOpts().Char8)
8541       ArithmeticTypes.push_back(S.Context.Char8Ty);
8542     ArithmeticTypes.push_back(S.Context.Char16Ty);
8543     ArithmeticTypes.push_back(S.Context.Char32Ty);
8544     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8545     ArithmeticTypes.push_back(S.Context.ShortTy);
8546     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8547     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8548     LastIntegralType = ArithmeticTypes.size();
8549     NumArithmeticTypes = ArithmeticTypes.size();
8550     // End of integral types.
8551     // FIXME: What about complex? What about half?
8552 
8553     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8554            "Enough inline storage for all arithmetic types.");
8555   }
8556 
8557   /// Helper method to factor out the common pattern of adding overloads
8558   /// for '++' and '--' builtin operators.
8559   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8560                                            bool HasVolatile,
8561                                            bool HasRestrict) {
8562     QualType ParamTypes[2] = {
8563       S.Context.getLValueReferenceType(CandidateTy),
8564       S.Context.IntTy
8565     };
8566 
8567     // Non-volatile version.
8568     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8569 
8570     // Use a heuristic to reduce number of builtin candidates in the set:
8571     // add volatile version only if there are conversions to a volatile type.
8572     if (HasVolatile) {
8573       ParamTypes[0] =
8574         S.Context.getLValueReferenceType(
8575           S.Context.getVolatileType(CandidateTy));
8576       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8577     }
8578 
8579     // Add restrict version only if there are conversions to a restrict type
8580     // and our candidate type is a non-restrict-qualified pointer.
8581     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8582         !CandidateTy.isRestrictQualified()) {
8583       ParamTypes[0]
8584         = S.Context.getLValueReferenceType(
8585             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8586       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8587 
8588       if (HasVolatile) {
8589         ParamTypes[0]
8590           = S.Context.getLValueReferenceType(
8591               S.Context.getCVRQualifiedType(CandidateTy,
8592                                             (Qualifiers::Volatile |
8593                                              Qualifiers::Restrict)));
8594         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8595       }
8596     }
8597 
8598   }
8599 
8600   /// Helper to add an overload candidate for a binary builtin with types \p L
8601   /// and \p R.
8602   void AddCandidate(QualType L, QualType R) {
8603     QualType LandR[2] = {L, R};
8604     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8605   }
8606 
8607 public:
8608   BuiltinOperatorOverloadBuilder(
8609     Sema &S, ArrayRef<Expr *> Args,
8610     QualifiersAndAtomic VisibleTypeConversionsQuals,
8611     bool HasArithmeticOrEnumeralCandidateType,
8612     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8613     OverloadCandidateSet &CandidateSet)
8614     : S(S), Args(Args),
8615       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8616       HasArithmeticOrEnumeralCandidateType(
8617         HasArithmeticOrEnumeralCandidateType),
8618       CandidateTypes(CandidateTypes),
8619       CandidateSet(CandidateSet) {
8620 
8621     InitArithmeticTypes();
8622   }
8623 
8624   // Increment is deprecated for bool since C++17.
8625   //
8626   // C++ [over.built]p3:
8627   //
8628   //   For every pair (T, VQ), where T is an arithmetic type other
8629   //   than bool, and VQ is either volatile or empty, there exist
8630   //   candidate operator functions of the form
8631   //
8632   //       VQ T&      operator++(VQ T&);
8633   //       T          operator++(VQ T&, int);
8634   //
8635   // C++ [over.built]p4:
8636   //
8637   //   For every pair (T, VQ), where T is an arithmetic type other
8638   //   than bool, and VQ is either volatile or empty, there exist
8639   //   candidate operator functions of the form
8640   //
8641   //       VQ T&      operator--(VQ T&);
8642   //       T          operator--(VQ T&, int);
8643   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8644     if (!HasArithmeticOrEnumeralCandidateType)
8645       return;
8646 
8647     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8648       const auto TypeOfT = ArithmeticTypes[Arith];
8649       if (TypeOfT == S.Context.BoolTy) {
8650         if (Op == OO_MinusMinus)
8651           continue;
8652         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8653           continue;
8654       }
8655       addPlusPlusMinusMinusStyleOverloads(
8656         TypeOfT,
8657         VisibleTypeConversionsQuals.hasVolatile(),
8658         VisibleTypeConversionsQuals.hasRestrict());
8659     }
8660   }
8661 
8662   // C++ [over.built]p5:
8663   //
8664   //   For every pair (T, VQ), where T is a cv-qualified or
8665   //   cv-unqualified object type, and VQ is either volatile or
8666   //   empty, there exist candidate operator functions of the form
8667   //
8668   //       T*VQ&      operator++(T*VQ&);
8669   //       T*VQ&      operator--(T*VQ&);
8670   //       T*         operator++(T*VQ&, int);
8671   //       T*         operator--(T*VQ&, int);
8672   void addPlusPlusMinusMinusPointerOverloads() {
8673     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8674       // Skip pointer types that aren't pointers to object types.
8675       if (!PtrTy->getPointeeType()->isObjectType())
8676         continue;
8677 
8678       addPlusPlusMinusMinusStyleOverloads(
8679           PtrTy,
8680           (!PtrTy.isVolatileQualified() &&
8681            VisibleTypeConversionsQuals.hasVolatile()),
8682           (!PtrTy.isRestrictQualified() &&
8683            VisibleTypeConversionsQuals.hasRestrict()));
8684     }
8685   }
8686 
8687   // C++ [over.built]p6:
8688   //   For every cv-qualified or cv-unqualified object type T, there
8689   //   exist candidate operator functions of the form
8690   //
8691   //       T&         operator*(T*);
8692   //
8693   // C++ [over.built]p7:
8694   //   For every function type T that does not have cv-qualifiers or a
8695   //   ref-qualifier, there exist candidate operator functions of the form
8696   //       T&         operator*(T*);
8697   void addUnaryStarPointerOverloads() {
8698     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8699       QualType PointeeTy = ParamTy->getPointeeType();
8700       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8701         continue;
8702 
8703       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8704         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8705           continue;
8706 
8707       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8708     }
8709   }
8710 
8711   // C++ [over.built]p9:
8712   //  For every promoted arithmetic type T, there exist candidate
8713   //  operator functions of the form
8714   //
8715   //       T         operator+(T);
8716   //       T         operator-(T);
8717   void addUnaryPlusOrMinusArithmeticOverloads() {
8718     if (!HasArithmeticOrEnumeralCandidateType)
8719       return;
8720 
8721     for (unsigned Arith = FirstPromotedArithmeticType;
8722          Arith < LastPromotedArithmeticType; ++Arith) {
8723       QualType ArithTy = ArithmeticTypes[Arith];
8724       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8725     }
8726 
8727     // Extension: We also add these operators for vector types.
8728     for (QualType VecTy : CandidateTypes[0].vector_types())
8729       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8730   }
8731 
8732   // C++ [over.built]p8:
8733   //   For every type T, there exist candidate operator functions of
8734   //   the form
8735   //
8736   //       T*         operator+(T*);
8737   void addUnaryPlusPointerOverloads() {
8738     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8739       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8740   }
8741 
8742   // C++ [over.built]p10:
8743   //   For every promoted integral type T, there exist candidate
8744   //   operator functions of the form
8745   //
8746   //        T         operator~(T);
8747   void addUnaryTildePromotedIntegralOverloads() {
8748     if (!HasArithmeticOrEnumeralCandidateType)
8749       return;
8750 
8751     for (unsigned Int = FirstPromotedIntegralType;
8752          Int < LastPromotedIntegralType; ++Int) {
8753       QualType IntTy = ArithmeticTypes[Int];
8754       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8755     }
8756 
8757     // Extension: We also add this operator for vector types.
8758     for (QualType VecTy : CandidateTypes[0].vector_types())
8759       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8760   }
8761 
8762   // C++ [over.match.oper]p16:
8763   //   For every pointer to member type T or type std::nullptr_t, there
8764   //   exist candidate operator functions of the form
8765   //
8766   //        bool operator==(T,T);
8767   //        bool operator!=(T,T);
8768   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8769     /// Set of (canonical) types that we've already handled.
8770     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8771 
8772     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8773       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8774         // Don't add the same builtin candidate twice.
8775         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8776           continue;
8777 
8778         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8779         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8780       }
8781 
8782       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8783         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8784         if (AddedTypes.insert(NullPtrTy).second) {
8785           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8786           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8787         }
8788       }
8789     }
8790   }
8791 
8792   // C++ [over.built]p15:
8793   //
8794   //   For every T, where T is an enumeration type or a pointer type,
8795   //   there exist candidate operator functions of the form
8796   //
8797   //        bool       operator<(T, T);
8798   //        bool       operator>(T, T);
8799   //        bool       operator<=(T, T);
8800   //        bool       operator>=(T, T);
8801   //        bool       operator==(T, T);
8802   //        bool       operator!=(T, T);
8803   //           R       operator<=>(T, T)
8804   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8805     // C++ [over.match.oper]p3:
8806     //   [...]the built-in candidates include all of the candidate operator
8807     //   functions defined in 13.6 that, compared to the given operator, [...]
8808     //   do not have the same parameter-type-list as any non-template non-member
8809     //   candidate.
8810     //
8811     // Note that in practice, this only affects enumeration types because there
8812     // aren't any built-in candidates of record type, and a user-defined operator
8813     // must have an operand of record or enumeration type. Also, the only other
8814     // overloaded operator with enumeration arguments, operator=,
8815     // cannot be overloaded for enumeration types, so this is the only place
8816     // where we must suppress candidates like this.
8817     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8818       UserDefinedBinaryOperators;
8819 
8820     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8821       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8822         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8823                                          CEnd = CandidateSet.end();
8824              C != CEnd; ++C) {
8825           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8826             continue;
8827 
8828           if (C->Function->isFunctionTemplateSpecialization())
8829             continue;
8830 
8831           // We interpret "same parameter-type-list" as applying to the
8832           // "synthesized candidate, with the order of the two parameters
8833           // reversed", not to the original function.
8834           bool Reversed = C->isReversed();
8835           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8836                                         ->getType()
8837                                         .getUnqualifiedType();
8838           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8839                                          ->getType()
8840                                          .getUnqualifiedType();
8841 
8842           // Skip if either parameter isn't of enumeral type.
8843           if (!FirstParamType->isEnumeralType() ||
8844               !SecondParamType->isEnumeralType())
8845             continue;
8846 
8847           // Add this operator to the set of known user-defined operators.
8848           UserDefinedBinaryOperators.insert(
8849             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8850                            S.Context.getCanonicalType(SecondParamType)));
8851         }
8852       }
8853     }
8854 
8855     /// Set of (canonical) types that we've already handled.
8856     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8857 
8858     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8859       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8860         // Don't add the same builtin candidate twice.
8861         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8862           continue;
8863         if (IsSpaceship && PtrTy->isFunctionPointerType())
8864           continue;
8865 
8866         QualType ParamTypes[2] = {PtrTy, PtrTy};
8867         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8868       }
8869       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8870         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8871 
8872         // Don't add the same builtin candidate twice, or if a user defined
8873         // candidate exists.
8874         if (!AddedTypes.insert(CanonType).second ||
8875             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8876                                                             CanonType)))
8877           continue;
8878         QualType ParamTypes[2] = {EnumTy, EnumTy};
8879         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8880       }
8881     }
8882   }
8883 
8884   // C++ [over.built]p13:
8885   //
8886   //   For every cv-qualified or cv-unqualified object type T
8887   //   there exist candidate operator functions of the form
8888   //
8889   //      T*         operator+(T*, ptrdiff_t);
8890   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8891   //      T*         operator-(T*, ptrdiff_t);
8892   //      T*         operator+(ptrdiff_t, T*);
8893   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8894   //
8895   // C++ [over.built]p14:
8896   //
8897   //   For every T, where T is a pointer to object type, there
8898   //   exist candidate operator functions of the form
8899   //
8900   //      ptrdiff_t  operator-(T, T);
8901   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8902     /// Set of (canonical) types that we've already handled.
8903     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8904 
8905     for (int Arg = 0; Arg < 2; ++Arg) {
8906       QualType AsymmetricParamTypes[2] = {
8907         S.Context.getPointerDiffType(),
8908         S.Context.getPointerDiffType(),
8909       };
8910       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8911         QualType PointeeTy = PtrTy->getPointeeType();
8912         if (!PointeeTy->isObjectType())
8913           continue;
8914 
8915         AsymmetricParamTypes[Arg] = PtrTy;
8916         if (Arg == 0 || Op == OO_Plus) {
8917           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8918           // T* operator+(ptrdiff_t, T*);
8919           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8920         }
8921         if (Op == OO_Minus) {
8922           // ptrdiff_t operator-(T, T);
8923           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8924             continue;
8925 
8926           QualType ParamTypes[2] = {PtrTy, PtrTy};
8927           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8928         }
8929       }
8930     }
8931   }
8932 
8933   // C++ [over.built]p12:
8934   //
8935   //   For every pair of promoted arithmetic types L and R, there
8936   //   exist candidate operator functions of the form
8937   //
8938   //        LR         operator*(L, R);
8939   //        LR         operator/(L, R);
8940   //        LR         operator+(L, R);
8941   //        LR         operator-(L, R);
8942   //        bool       operator<(L, R);
8943   //        bool       operator>(L, R);
8944   //        bool       operator<=(L, R);
8945   //        bool       operator>=(L, R);
8946   //        bool       operator==(L, R);
8947   //        bool       operator!=(L, R);
8948   //
8949   //   where LR is the result of the usual arithmetic conversions
8950   //   between types L and R.
8951   //
8952   // C++ [over.built]p24:
8953   //
8954   //   For every pair of promoted arithmetic types L and R, there exist
8955   //   candidate operator functions of the form
8956   //
8957   //        LR       operator?(bool, L, R);
8958   //
8959   //   where LR is the result of the usual arithmetic conversions
8960   //   between types L and R.
8961   // Our candidates ignore the first parameter.
8962   void addGenericBinaryArithmeticOverloads() {
8963     if (!HasArithmeticOrEnumeralCandidateType)
8964       return;
8965 
8966     for (unsigned Left = FirstPromotedArithmeticType;
8967          Left < LastPromotedArithmeticType; ++Left) {
8968       for (unsigned Right = FirstPromotedArithmeticType;
8969            Right < LastPromotedArithmeticType; ++Right) {
8970         QualType LandR[2] = { ArithmeticTypes[Left],
8971                               ArithmeticTypes[Right] };
8972         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8973       }
8974     }
8975 
8976     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8977     // conditional operator for vector types.
8978     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8979       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8980         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8981         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8982       }
8983   }
8984 
8985   /// Add binary operator overloads for each candidate matrix type M1, M2:
8986   ///  * (M1, M1) -> M1
8987   ///  * (M1, M1.getElementType()) -> M1
8988   ///  * (M2.getElementType(), M2) -> M2
8989   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8990   void addMatrixBinaryArithmeticOverloads() {
8991     if (!HasArithmeticOrEnumeralCandidateType)
8992       return;
8993 
8994     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8995       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8996       AddCandidate(M1, M1);
8997     }
8998 
8999     for (QualType M2 : CandidateTypes[1].matrix_types()) {
9000       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9001       if (!CandidateTypes[0].containsMatrixType(M2))
9002         AddCandidate(M2, M2);
9003     }
9004   }
9005 
9006   // C++2a [over.built]p14:
9007   //
9008   //   For every integral type T there exists a candidate operator function
9009   //   of the form
9010   //
9011   //        std::strong_ordering operator<=>(T, T)
9012   //
9013   // C++2a [over.built]p15:
9014   //
9015   //   For every pair of floating-point types L and R, there exists a candidate
9016   //   operator function of the form
9017   //
9018   //       std::partial_ordering operator<=>(L, R);
9019   //
9020   // FIXME: The current specification for integral types doesn't play nice with
9021   // the direction of p0946r0, which allows mixed integral and unscoped-enum
9022   // comparisons. Under the current spec this can lead to ambiguity during
9023   // overload resolution. For example:
9024   //
9025   //   enum A : int {a};
9026   //   auto x = (a <=> (long)42);
9027   //
9028   //   error: call is ambiguous for arguments 'A' and 'long'.
9029   //   note: candidate operator<=>(int, int)
9030   //   note: candidate operator<=>(long, long)
9031   //
9032   // To avoid this error, this function deviates from the specification and adds
9033   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9034   // arithmetic types (the same as the generic relational overloads).
9035   //
9036   // For now this function acts as a placeholder.
9037   void addThreeWayArithmeticOverloads() {
9038     addGenericBinaryArithmeticOverloads();
9039   }
9040 
9041   // C++ [over.built]p17:
9042   //
9043   //   For every pair of promoted integral types L and R, there
9044   //   exist candidate operator functions of the form
9045   //
9046   //      LR         operator%(L, R);
9047   //      LR         operator&(L, R);
9048   //      LR         operator^(L, R);
9049   //      LR         operator|(L, R);
9050   //      L          operator<<(L, R);
9051   //      L          operator>>(L, R);
9052   //
9053   //   where LR is the result of the usual arithmetic conversions
9054   //   between types L and R.
9055   void addBinaryBitwiseArithmeticOverloads() {
9056     if (!HasArithmeticOrEnumeralCandidateType)
9057       return;
9058 
9059     for (unsigned Left = FirstPromotedIntegralType;
9060          Left < LastPromotedIntegralType; ++Left) {
9061       for (unsigned Right = FirstPromotedIntegralType;
9062            Right < LastPromotedIntegralType; ++Right) {
9063         QualType LandR[2] = { ArithmeticTypes[Left],
9064                               ArithmeticTypes[Right] };
9065         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9066       }
9067     }
9068   }
9069 
9070   // C++ [over.built]p20:
9071   //
9072   //   For every pair (T, VQ), where T is an enumeration or
9073   //   pointer to member type and VQ is either volatile or
9074   //   empty, there exist candidate operator functions of the form
9075   //
9076   //        VQ T&      operator=(VQ T&, T);
9077   void addAssignmentMemberPointerOrEnumeralOverloads() {
9078     /// Set of (canonical) types that we've already handled.
9079     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9080 
9081     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9082       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9083         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9084           continue;
9085 
9086         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9087       }
9088 
9089       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9090         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9091           continue;
9092 
9093         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9094       }
9095     }
9096   }
9097 
9098   // C++ [over.built]p19:
9099   //
9100   //   For every pair (T, VQ), where T is any type and VQ is either
9101   //   volatile or empty, there exist candidate operator functions
9102   //   of the form
9103   //
9104   //        T*VQ&      operator=(T*VQ&, T*);
9105   //
9106   // C++ [over.built]p21:
9107   //
9108   //   For every pair (T, VQ), where T is a cv-qualified or
9109   //   cv-unqualified object type and VQ is either volatile or
9110   //   empty, there exist candidate operator functions of the form
9111   //
9112   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
9113   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
9114   void addAssignmentPointerOverloads(bool isEqualOp) {
9115     /// Set of (canonical) types that we've already handled.
9116     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9117 
9118     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9119       // If this is operator=, keep track of the builtin candidates we added.
9120       if (isEqualOp)
9121         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9122       else if (!PtrTy->getPointeeType()->isObjectType())
9123         continue;
9124 
9125       // non-volatile version
9126       QualType ParamTypes[2] = {
9127           S.Context.getLValueReferenceType(PtrTy),
9128           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9129       };
9130       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9131                             /*IsAssignmentOperator=*/ isEqualOp);
9132 
9133       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9134                           VisibleTypeConversionsQuals.hasVolatile();
9135       if (NeedVolatile) {
9136         // volatile version
9137         ParamTypes[0] =
9138             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9139         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9140                               /*IsAssignmentOperator=*/isEqualOp);
9141       }
9142 
9143       if (!PtrTy.isRestrictQualified() &&
9144           VisibleTypeConversionsQuals.hasRestrict()) {
9145         // restrict version
9146         ParamTypes[0] =
9147             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9148         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9149                               /*IsAssignmentOperator=*/isEqualOp);
9150 
9151         if (NeedVolatile) {
9152           // volatile restrict version
9153           ParamTypes[0] =
9154               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9155                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9156           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9157                                 /*IsAssignmentOperator=*/isEqualOp);
9158         }
9159       }
9160     }
9161 
9162     if (isEqualOp) {
9163       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9164         // Make sure we don't add the same candidate twice.
9165         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9166           continue;
9167 
9168         QualType ParamTypes[2] = {
9169             S.Context.getLValueReferenceType(PtrTy),
9170             PtrTy,
9171         };
9172 
9173         // non-volatile version
9174         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9175                               /*IsAssignmentOperator=*/true);
9176 
9177         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9178                             VisibleTypeConversionsQuals.hasVolatile();
9179         if (NeedVolatile) {
9180           // volatile version
9181           ParamTypes[0] = S.Context.getLValueReferenceType(
9182               S.Context.getVolatileType(PtrTy));
9183           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9184                                 /*IsAssignmentOperator=*/true);
9185         }
9186 
9187         if (!PtrTy.isRestrictQualified() &&
9188             VisibleTypeConversionsQuals.hasRestrict()) {
9189           // restrict version
9190           ParamTypes[0] = S.Context.getLValueReferenceType(
9191               S.Context.getRestrictType(PtrTy));
9192           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9193                                 /*IsAssignmentOperator=*/true);
9194 
9195           if (NeedVolatile) {
9196             // volatile restrict version
9197             ParamTypes[0] =
9198                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9199                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9200             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9201                                   /*IsAssignmentOperator=*/true);
9202           }
9203         }
9204       }
9205     }
9206   }
9207 
9208   // C++ [over.built]p18:
9209   //
9210   //   For every triple (L, VQ, R), where L is an arithmetic type,
9211   //   VQ is either volatile or empty, and R is a promoted
9212   //   arithmetic type, there exist candidate operator functions of
9213   //   the form
9214   //
9215   //        VQ L&      operator=(VQ L&, R);
9216   //        VQ L&      operator*=(VQ L&, R);
9217   //        VQ L&      operator/=(VQ L&, R);
9218   //        VQ L&      operator+=(VQ L&, R);
9219   //        VQ L&      operator-=(VQ L&, R);
9220   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9221     if (!HasArithmeticOrEnumeralCandidateType)
9222       return;
9223 
9224     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9225       for (unsigned Right = FirstPromotedArithmeticType;
9226            Right < LastPromotedArithmeticType; ++Right) {
9227         QualType ParamTypes[2];
9228         ParamTypes[1] = ArithmeticTypes[Right];
9229         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9230             S, ArithmeticTypes[Left], Args[0]);
9231 
9232         forAllQualifierCombinations(
9233             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9234               ParamTypes[0] =
9235                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9236               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9237                                     /*IsAssignmentOperator=*/isEqualOp);
9238             });
9239       }
9240     }
9241 
9242     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9243     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9244       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9245         QualType ParamTypes[2];
9246         ParamTypes[1] = Vec2Ty;
9247         // Add this built-in operator as a candidate (VQ is empty).
9248         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9249         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9250                               /*IsAssignmentOperator=*/isEqualOp);
9251 
9252         // Add this built-in operator as a candidate (VQ is 'volatile').
9253         if (VisibleTypeConversionsQuals.hasVolatile()) {
9254           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9255           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9256           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9257                                 /*IsAssignmentOperator=*/isEqualOp);
9258         }
9259       }
9260   }
9261 
9262   // C++ [over.built]p22:
9263   //
9264   //   For every triple (L, VQ, R), where L is an integral type, VQ
9265   //   is either volatile or empty, and R is a promoted integral
9266   //   type, there exist candidate operator functions of the form
9267   //
9268   //        VQ L&       operator%=(VQ L&, R);
9269   //        VQ L&       operator<<=(VQ L&, R);
9270   //        VQ L&       operator>>=(VQ L&, R);
9271   //        VQ L&       operator&=(VQ L&, R);
9272   //        VQ L&       operator^=(VQ L&, R);
9273   //        VQ L&       operator|=(VQ L&, R);
9274   void addAssignmentIntegralOverloads() {
9275     if (!HasArithmeticOrEnumeralCandidateType)
9276       return;
9277 
9278     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9279       for (unsigned Right = FirstPromotedIntegralType;
9280            Right < LastPromotedIntegralType; ++Right) {
9281         QualType ParamTypes[2];
9282         ParamTypes[1] = ArithmeticTypes[Right];
9283         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9284             S, ArithmeticTypes[Left], Args[0]);
9285 
9286         forAllQualifierCombinations(
9287             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9288               ParamTypes[0] =
9289                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9290               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9291             });
9292       }
9293     }
9294   }
9295 
9296   // C++ [over.operator]p23:
9297   //
9298   //   There also exist candidate operator functions of the form
9299   //
9300   //        bool        operator!(bool);
9301   //        bool        operator&&(bool, bool);
9302   //        bool        operator||(bool, bool);
9303   void addExclaimOverload() {
9304     QualType ParamTy = S.Context.BoolTy;
9305     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9306                           /*IsAssignmentOperator=*/false,
9307                           /*NumContextualBoolArguments=*/1);
9308   }
9309   void addAmpAmpOrPipePipeOverload() {
9310     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9311     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9312                           /*IsAssignmentOperator=*/false,
9313                           /*NumContextualBoolArguments=*/2);
9314   }
9315 
9316   // C++ [over.built]p13:
9317   //
9318   //   For every cv-qualified or cv-unqualified object type T there
9319   //   exist candidate operator functions of the form
9320   //
9321   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9322   //        T&         operator[](T*, ptrdiff_t);
9323   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9324   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9325   //        T&         operator[](ptrdiff_t, T*);
9326   void addSubscriptOverloads() {
9327     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9328       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9329       QualType PointeeType = PtrTy->getPointeeType();
9330       if (!PointeeType->isObjectType())
9331         continue;
9332 
9333       // T& operator[](T*, ptrdiff_t)
9334       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9335     }
9336 
9337     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9338       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9339       QualType PointeeType = PtrTy->getPointeeType();
9340       if (!PointeeType->isObjectType())
9341         continue;
9342 
9343       // T& operator[](ptrdiff_t, T*)
9344       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9345     }
9346   }
9347 
9348   // C++ [over.built]p11:
9349   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9350   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9351   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9352   //    there exist candidate operator functions of the form
9353   //
9354   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9355   //
9356   //    where CV12 is the union of CV1 and CV2.
9357   void addArrowStarOverloads() {
9358     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9359       QualType C1Ty = PtrTy;
9360       QualType C1;
9361       QualifierCollector Q1;
9362       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9363       if (!isa<RecordType>(C1))
9364         continue;
9365       // heuristic to reduce number of builtin candidates in the set.
9366       // Add volatile/restrict version only if there are conversions to a
9367       // volatile/restrict type.
9368       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9369         continue;
9370       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9371         continue;
9372       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9373         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9374         QualType C2 = QualType(mptr->getClass(), 0);
9375         C2 = C2.getUnqualifiedType();
9376         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9377           break;
9378         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9379         // build CV12 T&
9380         QualType T = mptr->getPointeeType();
9381         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9382             T.isVolatileQualified())
9383           continue;
9384         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9385             T.isRestrictQualified())
9386           continue;
9387         T = Q1.apply(S.Context, T);
9388         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9389       }
9390     }
9391   }
9392 
9393   // Note that we don't consider the first argument, since it has been
9394   // contextually converted to bool long ago. The candidates below are
9395   // therefore added as binary.
9396   //
9397   // C++ [over.built]p25:
9398   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9399   //   enumeration type, there exist candidate operator functions of the form
9400   //
9401   //        T        operator?(bool, T, T);
9402   //
9403   void addConditionalOperatorOverloads() {
9404     /// Set of (canonical) types that we've already handled.
9405     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9406 
9407     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9408       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9409         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9410           continue;
9411 
9412         QualType ParamTypes[2] = {PtrTy, PtrTy};
9413         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9414       }
9415 
9416       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9417         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9418           continue;
9419 
9420         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9421         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9422       }
9423 
9424       if (S.getLangOpts().CPlusPlus11) {
9425         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9426           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9427             continue;
9428 
9429           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9430             continue;
9431 
9432           QualType ParamTypes[2] = {EnumTy, EnumTy};
9433           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9434         }
9435       }
9436     }
9437   }
9438 };
9439 
9440 } // end anonymous namespace
9441 
9442 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9443 /// operator overloads to the candidate set (C++ [over.built]), based
9444 /// on the operator @p Op and the arguments given. For example, if the
9445 /// operator is a binary '+', this routine might add "int
9446 /// operator+(int, int)" to cover integer addition.
9447 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9448                                         SourceLocation OpLoc,
9449                                         ArrayRef<Expr *> Args,
9450                                         OverloadCandidateSet &CandidateSet) {
9451   // Find all of the types that the arguments can convert to, but only
9452   // if the operator we're looking at has built-in operator candidates
9453   // that make use of these types. Also record whether we encounter non-record
9454   // candidate types or either arithmetic or enumeral candidate types.
9455   QualifiersAndAtomic VisibleTypeConversionsQuals;
9456   VisibleTypeConversionsQuals.addConst();
9457   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9458     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9459     if (Args[ArgIdx]->getType()->isAtomicType())
9460       VisibleTypeConversionsQuals.addAtomic();
9461   }
9462 
9463   bool HasNonRecordCandidateType = false;
9464   bool HasArithmeticOrEnumeralCandidateType = false;
9465   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9466   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9467     CandidateTypes.emplace_back(*this);
9468     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9469                                                  OpLoc,
9470                                                  true,
9471                                                  (Op == OO_Exclaim ||
9472                                                   Op == OO_AmpAmp ||
9473                                                   Op == OO_PipePipe),
9474                                                  VisibleTypeConversionsQuals);
9475     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9476         CandidateTypes[ArgIdx].hasNonRecordTypes();
9477     HasArithmeticOrEnumeralCandidateType =
9478         HasArithmeticOrEnumeralCandidateType ||
9479         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9480   }
9481 
9482   // Exit early when no non-record types have been added to the candidate set
9483   // for any of the arguments to the operator.
9484   //
9485   // We can't exit early for !, ||, or &&, since there we have always have
9486   // 'bool' overloads.
9487   if (!HasNonRecordCandidateType &&
9488       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9489     return;
9490 
9491   // Setup an object to manage the common state for building overloads.
9492   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9493                                            VisibleTypeConversionsQuals,
9494                                            HasArithmeticOrEnumeralCandidateType,
9495                                            CandidateTypes, CandidateSet);
9496 
9497   // Dispatch over the operation to add in only those overloads which apply.
9498   switch (Op) {
9499   case OO_None:
9500   case NUM_OVERLOADED_OPERATORS:
9501     llvm_unreachable("Expected an overloaded operator");
9502 
9503   case OO_New:
9504   case OO_Delete:
9505   case OO_Array_New:
9506   case OO_Array_Delete:
9507   case OO_Call:
9508     llvm_unreachable(
9509                     "Special operators don't use AddBuiltinOperatorCandidates");
9510 
9511   case OO_Comma:
9512   case OO_Arrow:
9513   case OO_Coawait:
9514     // C++ [over.match.oper]p3:
9515     //   -- For the operator ',', the unary operator '&', the
9516     //      operator '->', or the operator 'co_await', the
9517     //      built-in candidates set is empty.
9518     break;
9519 
9520   case OO_Plus: // '+' is either unary or binary
9521     if (Args.size() == 1)
9522       OpBuilder.addUnaryPlusPointerOverloads();
9523     [[fallthrough]];
9524 
9525   case OO_Minus: // '-' is either unary or binary
9526     if (Args.size() == 1) {
9527       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9528     } else {
9529       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9530       OpBuilder.addGenericBinaryArithmeticOverloads();
9531       OpBuilder.addMatrixBinaryArithmeticOverloads();
9532     }
9533     break;
9534 
9535   case OO_Star: // '*' is either unary or binary
9536     if (Args.size() == 1)
9537       OpBuilder.addUnaryStarPointerOverloads();
9538     else {
9539       OpBuilder.addGenericBinaryArithmeticOverloads();
9540       OpBuilder.addMatrixBinaryArithmeticOverloads();
9541     }
9542     break;
9543 
9544   case OO_Slash:
9545     OpBuilder.addGenericBinaryArithmeticOverloads();
9546     break;
9547 
9548   case OO_PlusPlus:
9549   case OO_MinusMinus:
9550     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9551     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9552     break;
9553 
9554   case OO_EqualEqual:
9555   case OO_ExclaimEqual:
9556     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9557     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9558     OpBuilder.addGenericBinaryArithmeticOverloads();
9559     break;
9560 
9561   case OO_Less:
9562   case OO_Greater:
9563   case OO_LessEqual:
9564   case OO_GreaterEqual:
9565     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9566     OpBuilder.addGenericBinaryArithmeticOverloads();
9567     break;
9568 
9569   case OO_Spaceship:
9570     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9571     OpBuilder.addThreeWayArithmeticOverloads();
9572     break;
9573 
9574   case OO_Percent:
9575   case OO_Caret:
9576   case OO_Pipe:
9577   case OO_LessLess:
9578   case OO_GreaterGreater:
9579     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9580     break;
9581 
9582   case OO_Amp: // '&' is either unary or binary
9583     if (Args.size() == 1)
9584       // C++ [over.match.oper]p3:
9585       //   -- For the operator ',', the unary operator '&', or the
9586       //      operator '->', the built-in candidates set is empty.
9587       break;
9588 
9589     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9590     break;
9591 
9592   case OO_Tilde:
9593     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9594     break;
9595 
9596   case OO_Equal:
9597     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9598     [[fallthrough]];
9599 
9600   case OO_PlusEqual:
9601   case OO_MinusEqual:
9602     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9603     [[fallthrough]];
9604 
9605   case OO_StarEqual:
9606   case OO_SlashEqual:
9607     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9608     break;
9609 
9610   case OO_PercentEqual:
9611   case OO_LessLessEqual:
9612   case OO_GreaterGreaterEqual:
9613   case OO_AmpEqual:
9614   case OO_CaretEqual:
9615   case OO_PipeEqual:
9616     OpBuilder.addAssignmentIntegralOverloads();
9617     break;
9618 
9619   case OO_Exclaim:
9620     OpBuilder.addExclaimOverload();
9621     break;
9622 
9623   case OO_AmpAmp:
9624   case OO_PipePipe:
9625     OpBuilder.addAmpAmpOrPipePipeOverload();
9626     break;
9627 
9628   case OO_Subscript:
9629     if (Args.size() == 2)
9630       OpBuilder.addSubscriptOverloads();
9631     break;
9632 
9633   case OO_ArrowStar:
9634     OpBuilder.addArrowStarOverloads();
9635     break;
9636 
9637   case OO_Conditional:
9638     OpBuilder.addConditionalOperatorOverloads();
9639     OpBuilder.addGenericBinaryArithmeticOverloads();
9640     break;
9641   }
9642 }
9643 
9644 /// Add function candidates found via argument-dependent lookup
9645 /// to the set of overloading candidates.
9646 ///
9647 /// This routine performs argument-dependent name lookup based on the
9648 /// given function name (which may also be an operator name) and adds
9649 /// all of the overload candidates found by ADL to the overload
9650 /// candidate set (C++ [basic.lookup.argdep]).
9651 void
9652 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9653                                            SourceLocation Loc,
9654                                            ArrayRef<Expr *> Args,
9655                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9656                                            OverloadCandidateSet& CandidateSet,
9657                                            bool PartialOverloading) {
9658   ADLResult Fns;
9659 
9660   // FIXME: This approach for uniquing ADL results (and removing
9661   // redundant candidates from the set) relies on pointer-equality,
9662   // which means we need to key off the canonical decl.  However,
9663   // always going back to the canonical decl might not get us the
9664   // right set of default arguments.  What default arguments are
9665   // we supposed to consider on ADL candidates, anyway?
9666 
9667   // FIXME: Pass in the explicit template arguments?
9668   ArgumentDependentLookup(Name, Loc, Args, Fns);
9669 
9670   // Erase all of the candidates we already knew about.
9671   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9672                                    CandEnd = CandidateSet.end();
9673        Cand != CandEnd; ++Cand)
9674     if (Cand->Function) {
9675       Fns.erase(Cand->Function);
9676       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9677         Fns.erase(FunTmpl);
9678     }
9679 
9680   // For each of the ADL candidates we found, add it to the overload
9681   // set.
9682   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9683     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9684 
9685     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9686       if (ExplicitTemplateArgs)
9687         continue;
9688 
9689       AddOverloadCandidate(
9690           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9691           PartialOverloading, /*AllowExplicit=*/true,
9692           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9693       if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
9694         AddOverloadCandidate(
9695             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9696             /*SuppressUserConversions=*/false, PartialOverloading,
9697             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9698             ADLCallKind::UsesADL, std::nullopt,
9699             OverloadCandidateParamOrder::Reversed);
9700       }
9701     } else {
9702       auto *FTD = cast<FunctionTemplateDecl>(*I);
9703       AddTemplateOverloadCandidate(
9704           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9705           /*SuppressUserConversions=*/false, PartialOverloading,
9706           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9707       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9708               *this, Args, FTD->getTemplatedDecl())) {
9709         AddTemplateOverloadCandidate(
9710             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9711             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9712             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9713             OverloadCandidateParamOrder::Reversed);
9714       }
9715     }
9716   }
9717 }
9718 
9719 namespace {
9720 enum class Comparison { Equal, Better, Worse };
9721 }
9722 
9723 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9724 /// overload resolution.
9725 ///
9726 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9727 /// Cand1's first N enable_if attributes have precisely the same conditions as
9728 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9729 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9730 ///
9731 /// Note that you can have a pair of candidates such that Cand1's enable_if
9732 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9733 /// worse than Cand1's.
9734 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9735                                        const FunctionDecl *Cand2) {
9736   // Common case: One (or both) decls don't have enable_if attrs.
9737   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9738   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9739   if (!Cand1Attr || !Cand2Attr) {
9740     if (Cand1Attr == Cand2Attr)
9741       return Comparison::Equal;
9742     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9743   }
9744 
9745   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9746   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9747 
9748   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9749   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9750     std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9751     std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9752 
9753     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9754     // has fewer enable_if attributes than Cand2, and vice versa.
9755     if (!Cand1A)
9756       return Comparison::Worse;
9757     if (!Cand2A)
9758       return Comparison::Better;
9759 
9760     Cand1ID.clear();
9761     Cand2ID.clear();
9762 
9763     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9764     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9765     if (Cand1ID != Cand2ID)
9766       return Comparison::Worse;
9767   }
9768 
9769   return Comparison::Equal;
9770 }
9771 
9772 static Comparison
9773 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9774                               const OverloadCandidate &Cand2) {
9775   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9776       !Cand2.Function->isMultiVersion())
9777     return Comparison::Equal;
9778 
9779   // If both are invalid, they are equal. If one of them is invalid, the other
9780   // is better.
9781   if (Cand1.Function->isInvalidDecl()) {
9782     if (Cand2.Function->isInvalidDecl())
9783       return Comparison::Equal;
9784     return Comparison::Worse;
9785   }
9786   if (Cand2.Function->isInvalidDecl())
9787     return Comparison::Better;
9788 
9789   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9790   // cpu_dispatch, else arbitrarily based on the identifiers.
9791   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9792   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9793   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9794   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9795 
9796   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9797     return Comparison::Equal;
9798 
9799   if (Cand1CPUDisp && !Cand2CPUDisp)
9800     return Comparison::Better;
9801   if (Cand2CPUDisp && !Cand1CPUDisp)
9802     return Comparison::Worse;
9803 
9804   if (Cand1CPUSpec && Cand2CPUSpec) {
9805     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9806       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9807                  ? Comparison::Better
9808                  : Comparison::Worse;
9809 
9810     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9811         FirstDiff = std::mismatch(
9812             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9813             Cand2CPUSpec->cpus_begin(),
9814             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9815               return LHS->getName() == RHS->getName();
9816             });
9817 
9818     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9819            "Two different cpu-specific versions should not have the same "
9820            "identifier list, otherwise they'd be the same decl!");
9821     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9822                ? Comparison::Better
9823                : Comparison::Worse;
9824   }
9825   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9826 }
9827 
9828 /// Compute the type of the implicit object parameter for the given function,
9829 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
9830 /// null QualType if there is a 'matches anything' implicit object parameter.
9831 static std::optional<QualType>
9832 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
9833   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9834     return std::nullopt;
9835 
9836   auto *M = cast<CXXMethodDecl>(F);
9837   // Static member functions' object parameters match all types.
9838   if (M->isStatic())
9839     return QualType();
9840 
9841   QualType T = M->getThisObjectType();
9842   if (M->getRefQualifier() == RQ_RValue)
9843     return Context.getRValueReferenceType(T);
9844   return Context.getLValueReferenceType(T);
9845 }
9846 
9847 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9848                                    const FunctionDecl *F2, unsigned NumParams) {
9849   if (declaresSameEntity(F1, F2))
9850     return true;
9851 
9852   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9853     if (First) {
9854       if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
9855         return *T;
9856     }
9857     assert(I < F->getNumParams());
9858     return F->getParamDecl(I++)->getType();
9859   };
9860 
9861   unsigned I1 = 0, I2 = 0;
9862   for (unsigned I = 0; I != NumParams; ++I) {
9863     QualType T1 = NextParam(F1, I1, I == 0);
9864     QualType T2 = NextParam(F2, I2, I == 0);
9865     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9866     if (!Context.hasSameUnqualifiedType(T1, T2))
9867       return false;
9868   }
9869   return true;
9870 }
9871 
9872 /// We're allowed to use constraints partial ordering only if the candidates
9873 /// have the same parameter types:
9874 /// [over.match.best]p2.6
9875 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9876 /// and F1 is more constrained than F2 [...]
9877 static bool sameFunctionParameterTypeLists(Sema &S,
9878                                           const OverloadCandidate &Cand1,
9879                                           const OverloadCandidate &Cand2) {
9880   if (Cand1.Function && Cand2.Function) {
9881     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9882     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9883     if (PT1->getNumParams() == PT2->getNumParams() &&
9884         PT1->isVariadic() == PT2->isVariadic() &&
9885         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9886                                      Cand1.isReversed() ^ Cand2.isReversed()))
9887       return true;
9888   }
9889   return false;
9890 }
9891 
9892 /// isBetterOverloadCandidate - Determines whether the first overload
9893 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9894 bool clang::isBetterOverloadCandidate(
9895     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9896     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9897   // Define viable functions to be better candidates than non-viable
9898   // functions.
9899   if (!Cand2.Viable)
9900     return Cand1.Viable;
9901   else if (!Cand1.Viable)
9902     return false;
9903 
9904   // [CUDA] A function with 'never' preference is marked not viable, therefore
9905   // is never shown up here. The worst preference shown up here is 'wrong side',
9906   // e.g. an H function called by a HD function in device compilation. This is
9907   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9908   // function which is called only by an H function. A deferred diagnostic will
9909   // be triggered if it is emitted. However a wrong-sided function is still
9910   // a viable candidate here.
9911   //
9912   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9913   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9914   // can be emitted, Cand1 is not better than Cand2. This rule should have
9915   // precedence over other rules.
9916   //
9917   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9918   // other rules should be used to determine which is better. This is because
9919   // host/device based overloading resolution is mostly for determining
9920   // viability of a function. If two functions are both viable, other factors
9921   // should take precedence in preference, e.g. the standard-defined preferences
9922   // like argument conversion ranks or enable_if partial-ordering. The
9923   // preference for pass-object-size parameters is probably most similar to a
9924   // type-based-overloading decision and so should take priority.
9925   //
9926   // If other rules cannot determine which is better, CUDA preference will be
9927   // used again to determine which is better.
9928   //
9929   // TODO: Currently IdentifyCUDAPreference does not return correct values
9930   // for functions called in global variable initializers due to missing
9931   // correct context about device/host. Therefore we can only enforce this
9932   // rule when there is a caller. We should enforce this rule for functions
9933   // in global variable initializers once proper context is added.
9934   //
9935   // TODO: We can only enable the hostness based overloading resolution when
9936   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9937   // overloading resolution diagnostics.
9938   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9939       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9940     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9941       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9942       bool IsCand1ImplicitHD =
9943           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9944       bool IsCand2ImplicitHD =
9945           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9946       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9947       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9948       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9949       // The implicit HD function may be a function in a system header which
9950       // is forced by pragma. In device compilation, if we prefer HD candidates
9951       // over wrong-sided candidates, overloading resolution may change, which
9952       // may result in non-deferrable diagnostics. As a workaround, we let
9953       // implicit HD candidates take equal preference as wrong-sided candidates.
9954       // This will preserve the overloading resolution.
9955       // TODO: We still need special handling of implicit HD functions since
9956       // they may incur other diagnostics to be deferred. We should make all
9957       // host/device related diagnostics deferrable and remove special handling
9958       // of implicit HD functions.
9959       auto EmitThreshold =
9960           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9961            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9962               ? Sema::CFP_Never
9963               : Sema::CFP_WrongSide;
9964       auto Cand1Emittable = P1 > EmitThreshold;
9965       auto Cand2Emittable = P2 > EmitThreshold;
9966       if (Cand1Emittable && !Cand2Emittable)
9967         return true;
9968       if (!Cand1Emittable && Cand2Emittable)
9969         return false;
9970     }
9971   }
9972 
9973   // C++ [over.match.best]p1: (Changed in C++23)
9974   //
9975   //   -- if F is a static member function, ICS1(F) is defined such
9976   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9977   //      any function G, and, symmetrically, ICS1(G) is neither
9978   //      better nor worse than ICS1(F).
9979   unsigned StartArg = 0;
9980   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9981     StartArg = 1;
9982 
9983   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9984     // We don't allow incompatible pointer conversions in C++.
9985     if (!S.getLangOpts().CPlusPlus)
9986       return ICS.isStandard() &&
9987              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9988 
9989     // The only ill-formed conversion we allow in C++ is the string literal to
9990     // char* conversion, which is only considered ill-formed after C++11.
9991     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9992            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9993   };
9994 
9995   // Define functions that don't require ill-formed conversions for a given
9996   // argument to be better candidates than functions that do.
9997   unsigned NumArgs = Cand1.Conversions.size();
9998   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9999   bool HasBetterConversion = false;
10000   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10001     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10002     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10003     if (Cand1Bad != Cand2Bad) {
10004       if (Cand1Bad)
10005         return false;
10006       HasBetterConversion = true;
10007     }
10008   }
10009 
10010   if (HasBetterConversion)
10011     return true;
10012 
10013   // C++ [over.match.best]p1:
10014   //   A viable function F1 is defined to be a better function than another
10015   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
10016   //   conversion sequence than ICSi(F2), and then...
10017   bool HasWorseConversion = false;
10018   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10019     switch (CompareImplicitConversionSequences(S, Loc,
10020                                                Cand1.Conversions[ArgIdx],
10021                                                Cand2.Conversions[ArgIdx])) {
10022     case ImplicitConversionSequence::Better:
10023       // Cand1 has a better conversion sequence.
10024       HasBetterConversion = true;
10025       break;
10026 
10027     case ImplicitConversionSequence::Worse:
10028       if (Cand1.Function && Cand2.Function &&
10029           Cand1.isReversed() != Cand2.isReversed() &&
10030           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
10031                                  NumArgs)) {
10032         // Work around large-scale breakage caused by considering reversed
10033         // forms of operator== in C++20:
10034         //
10035         // When comparing a function against a reversed function with the same
10036         // parameter types, if we have a better conversion for one argument and
10037         // a worse conversion for the other, the implicit conversion sequences
10038         // are treated as being equally good.
10039         //
10040         // This prevents a comparison function from being considered ambiguous
10041         // with a reversed form that is written in the same way.
10042         //
10043         // We diagnose this as an extension from CreateOverloadedBinOp.
10044         HasWorseConversion = true;
10045         break;
10046       }
10047 
10048       // Cand1 can't be better than Cand2.
10049       return false;
10050 
10051     case ImplicitConversionSequence::Indistinguishable:
10052       // Do nothing.
10053       break;
10054     }
10055   }
10056 
10057   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
10058   //       ICSj(F2), or, if not that,
10059   if (HasBetterConversion && !HasWorseConversion)
10060     return true;
10061 
10062   //   -- the context is an initialization by user-defined conversion
10063   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
10064   //      from the return type of F1 to the destination type (i.e.,
10065   //      the type of the entity being initialized) is a better
10066   //      conversion sequence than the standard conversion sequence
10067   //      from the return type of F2 to the destination type.
10068   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10069       Cand1.Function && Cand2.Function &&
10070       isa<CXXConversionDecl>(Cand1.Function) &&
10071       isa<CXXConversionDecl>(Cand2.Function)) {
10072     // First check whether we prefer one of the conversion functions over the
10073     // other. This only distinguishes the results in non-standard, extension
10074     // cases such as the conversion from a lambda closure type to a function
10075     // pointer or block.
10076     ImplicitConversionSequence::CompareKind Result =
10077         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10078     if (Result == ImplicitConversionSequence::Indistinguishable)
10079       Result = CompareStandardConversionSequences(S, Loc,
10080                                                   Cand1.FinalConversion,
10081                                                   Cand2.FinalConversion);
10082 
10083     if (Result != ImplicitConversionSequence::Indistinguishable)
10084       return Result == ImplicitConversionSequence::Better;
10085 
10086     // FIXME: Compare kind of reference binding if conversion functions
10087     // convert to a reference type used in direct reference binding, per
10088     // C++14 [over.match.best]p1 section 2 bullet 3.
10089   }
10090 
10091   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10092   // as combined with the resolution to CWG issue 243.
10093   //
10094   // When the context is initialization by constructor ([over.match.ctor] or
10095   // either phase of [over.match.list]), a constructor is preferred over
10096   // a conversion function.
10097   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10098       Cand1.Function && Cand2.Function &&
10099       isa<CXXConstructorDecl>(Cand1.Function) !=
10100           isa<CXXConstructorDecl>(Cand2.Function))
10101     return isa<CXXConstructorDecl>(Cand1.Function);
10102 
10103   //    -- F1 is a non-template function and F2 is a function template
10104   //       specialization, or, if not that,
10105   bool Cand1IsSpecialization = Cand1.Function &&
10106                                Cand1.Function->getPrimaryTemplate();
10107   bool Cand2IsSpecialization = Cand2.Function &&
10108                                Cand2.Function->getPrimaryTemplate();
10109   if (Cand1IsSpecialization != Cand2IsSpecialization)
10110     return Cand2IsSpecialization;
10111 
10112   //   -- F1 and F2 are function template specializations, and the function
10113   //      template for F1 is more specialized than the template for F2
10114   //      according to the partial ordering rules described in 14.5.5.2, or,
10115   //      if not that,
10116   if (Cand1IsSpecialization && Cand2IsSpecialization) {
10117     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10118             Cand1.Function->getPrimaryTemplate(),
10119             Cand2.Function->getPrimaryTemplate(), Loc,
10120             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10121                                                    : TPOC_Call,
10122             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
10123             Cand1.isReversed() ^ Cand2.isReversed()))
10124       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10125   }
10126 
10127   //   -— F1 and F2 are non-template functions with the same
10128   //      parameter-type-lists, and F1 is more constrained than F2 [...],
10129   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10130       sameFunctionParameterTypeLists(S, Cand1, Cand2)) {
10131     FunctionDecl *Function1 = Cand1.Function;
10132     FunctionDecl *Function2 = Cand2.Function;
10133     if (FunctionDecl *MF = Function1->getInstantiatedFromMemberFunction())
10134       Function1 = MF;
10135     if (FunctionDecl *MF = Function2->getInstantiatedFromMemberFunction())
10136       Function2 = MF;
10137 
10138     const Expr *RC1 = Function1->getTrailingRequiresClause();
10139     const Expr *RC2 = Function2->getTrailingRequiresClause();
10140     if (RC1 && RC2) {
10141       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
10142       if (S.IsAtLeastAsConstrained(Function1, RC1, Function2, RC2,
10143                                    AtLeastAsConstrained1) ||
10144           S.IsAtLeastAsConstrained(Function2, RC2, Function1, RC1,
10145                                    AtLeastAsConstrained2))
10146         return false;
10147       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
10148         return AtLeastAsConstrained1;
10149     } else if (RC1 || RC2) {
10150       return RC1 != nullptr;
10151     }
10152   }
10153 
10154   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
10155   //      class B of D, and for all arguments the corresponding parameters of
10156   //      F1 and F2 have the same type.
10157   // FIXME: Implement the "all parameters have the same type" check.
10158   bool Cand1IsInherited =
10159       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10160   bool Cand2IsInherited =
10161       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10162   if (Cand1IsInherited != Cand2IsInherited)
10163     return Cand2IsInherited;
10164   else if (Cand1IsInherited) {
10165     assert(Cand2IsInherited);
10166     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10167     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10168     if (Cand1Class->isDerivedFrom(Cand2Class))
10169       return true;
10170     if (Cand2Class->isDerivedFrom(Cand1Class))
10171       return false;
10172     // Inherited from sibling base classes: still ambiguous.
10173   }
10174 
10175   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10176   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10177   //      with reversed order of parameters and F1 is not
10178   //
10179   // We rank reversed + different operator as worse than just reversed, but
10180   // that comparison can never happen, because we only consider reversing for
10181   // the maximally-rewritten operator (== or <=>).
10182   if (Cand1.RewriteKind != Cand2.RewriteKind)
10183     return Cand1.RewriteKind < Cand2.RewriteKind;
10184 
10185   // Check C++17 tie-breakers for deduction guides.
10186   {
10187     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10188     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10189     if (Guide1 && Guide2) {
10190       //  -- F1 is generated from a deduction-guide and F2 is not
10191       if (Guide1->isImplicit() != Guide2->isImplicit())
10192         return Guide2->isImplicit();
10193 
10194       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10195       if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10196         return true;
10197     }
10198   }
10199 
10200   // Check for enable_if value-based overload resolution.
10201   if (Cand1.Function && Cand2.Function) {
10202     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10203     if (Cmp != Comparison::Equal)
10204       return Cmp == Comparison::Better;
10205   }
10206 
10207   bool HasPS1 = Cand1.Function != nullptr &&
10208                 functionHasPassObjectSizeParams(Cand1.Function);
10209   bool HasPS2 = Cand2.Function != nullptr &&
10210                 functionHasPassObjectSizeParams(Cand2.Function);
10211   if (HasPS1 != HasPS2 && HasPS1)
10212     return true;
10213 
10214   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10215   if (MV == Comparison::Better)
10216     return true;
10217   if (MV == Comparison::Worse)
10218     return false;
10219 
10220   // If other rules cannot determine which is better, CUDA preference is used
10221   // to determine which is better.
10222   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10223     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10224     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10225            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10226   }
10227 
10228   // General member function overloading is handled above, so this only handles
10229   // constructors with address spaces.
10230   // This only handles address spaces since C++ has no other
10231   // qualifier that can be used with constructors.
10232   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10233   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10234   if (CD1 && CD2) {
10235     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10236     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10237     if (AS1 != AS2) {
10238       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10239         return true;
10240       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10241         return false;
10242     }
10243   }
10244 
10245   return false;
10246 }
10247 
10248 /// Determine whether two declarations are "equivalent" for the purposes of
10249 /// name lookup and overload resolution. This applies when the same internal/no
10250 /// linkage entity is defined by two modules (probably by textually including
10251 /// the same header). In such a case, we don't consider the declarations to
10252 /// declare the same entity, but we also don't want lookups with both
10253 /// declarations visible to be ambiguous in some cases (this happens when using
10254 /// a modularized libstdc++).
10255 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10256                                                   const NamedDecl *B) {
10257   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10258   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10259   if (!VA || !VB)
10260     return false;
10261 
10262   // The declarations must be declaring the same name as an internal linkage
10263   // entity in different modules.
10264   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10265           VB->getDeclContext()->getRedeclContext()) ||
10266       getOwningModule(VA) == getOwningModule(VB) ||
10267       VA->isExternallyVisible() || VB->isExternallyVisible())
10268     return false;
10269 
10270   // Check that the declarations appear to be equivalent.
10271   //
10272   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10273   // For constants and functions, we should check the initializer or body is
10274   // the same. For non-constant variables, we shouldn't allow it at all.
10275   if (Context.hasSameType(VA->getType(), VB->getType()))
10276     return true;
10277 
10278   // Enum constants within unnamed enumerations will have different types, but
10279   // may still be similar enough to be interchangeable for our purposes.
10280   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10281     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10282       // Only handle anonymous enums. If the enumerations were named and
10283       // equivalent, they would have been merged to the same type.
10284       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10285       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10286       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10287           !Context.hasSameType(EnumA->getIntegerType(),
10288                                EnumB->getIntegerType()))
10289         return false;
10290       // Allow this only if the value is the same for both enumerators.
10291       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10292     }
10293   }
10294 
10295   // Nothing else is sufficiently similar.
10296   return false;
10297 }
10298 
10299 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10300     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10301   assert(D && "Unknown declaration");
10302   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10303 
10304   Module *M = getOwningModule(D);
10305   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10306       << !M << (M ? M->getFullModuleName() : "");
10307 
10308   for (auto *E : Equiv) {
10309     Module *M = getOwningModule(E);
10310     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10311         << !M << (M ? M->getFullModuleName() : "");
10312   }
10313 }
10314 
10315 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10316   return FailureKind == ovl_fail_bad_deduction &&
10317          DeductionFailure.Result == Sema::TDK_ConstraintsNotSatisfied &&
10318          static_cast<CNSInfo *>(DeductionFailure.Data)
10319              ->Satisfaction.ContainsErrors;
10320 }
10321 
10322 /// Computes the best viable function (C++ 13.3.3)
10323 /// within an overload candidate set.
10324 ///
10325 /// \param Loc The location of the function name (or operator symbol) for
10326 /// which overload resolution occurs.
10327 ///
10328 /// \param Best If overload resolution was successful or found a deleted
10329 /// function, \p Best points to the candidate function found.
10330 ///
10331 /// \returns The result of overload resolution.
10332 OverloadingResult
10333 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10334                                          iterator &Best) {
10335   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10336   std::transform(begin(), end(), std::back_inserter(Candidates),
10337                  [](OverloadCandidate &Cand) { return &Cand; });
10338 
10339   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10340   // are accepted by both clang and NVCC. However, during a particular
10341   // compilation mode only one call variant is viable. We need to
10342   // exclude non-viable overload candidates from consideration based
10343   // only on their host/device attributes. Specifically, if one
10344   // candidate call is WrongSide and the other is SameSide, we ignore
10345   // the WrongSide candidate.
10346   // We only need to remove wrong-sided candidates here if
10347   // -fgpu-exclude-wrong-side-overloads is off. When
10348   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10349   // uniformly in isBetterOverloadCandidate.
10350   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10351     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10352     bool ContainsSameSideCandidate =
10353         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10354           // Check viable function only.
10355           return Cand->Viable && Cand->Function &&
10356                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10357                      Sema::CFP_SameSide;
10358         });
10359     if (ContainsSameSideCandidate) {
10360       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10361         // Check viable function only to avoid unnecessary data copying/moving.
10362         return Cand->Viable && Cand->Function &&
10363                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10364                    Sema::CFP_WrongSide;
10365       };
10366       llvm::erase_if(Candidates, IsWrongSideCandidate);
10367     }
10368   }
10369 
10370   // Find the best viable function.
10371   Best = end();
10372   for (auto *Cand : Candidates) {
10373     Cand->Best = false;
10374     if (Cand->Viable) {
10375       if (Best == end() ||
10376           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10377         Best = Cand;
10378     } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10379       // This candidate has constraint that we were unable to evaluate because
10380       // it referenced an expression that contained an error. Rather than fall
10381       // back onto a potentially unintended candidate (made worse by
10382       // subsuming constraints), treat this as 'no viable candidate'.
10383       Best = end();
10384       return OR_No_Viable_Function;
10385     }
10386   }
10387 
10388   // If we didn't find any viable functions, abort.
10389   if (Best == end())
10390     return OR_No_Viable_Function;
10391 
10392   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10393 
10394   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10395   PendingBest.push_back(&*Best);
10396   Best->Best = true;
10397 
10398   // Make sure that this function is better than every other viable
10399   // function. If not, we have an ambiguity.
10400   while (!PendingBest.empty()) {
10401     auto *Curr = PendingBest.pop_back_val();
10402     for (auto *Cand : Candidates) {
10403       if (Cand->Viable && !Cand->Best &&
10404           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10405         PendingBest.push_back(Cand);
10406         Cand->Best = true;
10407 
10408         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10409                                                      Curr->Function))
10410           EquivalentCands.push_back(Cand->Function);
10411         else
10412           Best = end();
10413       }
10414     }
10415   }
10416 
10417   // If we found more than one best candidate, this is ambiguous.
10418   if (Best == end())
10419     return OR_Ambiguous;
10420 
10421   // Best is the best viable function.
10422   if (Best->Function && Best->Function->isDeleted())
10423     return OR_Deleted;
10424 
10425   if (!EquivalentCands.empty())
10426     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10427                                                     EquivalentCands);
10428 
10429   return OR_Success;
10430 }
10431 
10432 namespace {
10433 
10434 enum OverloadCandidateKind {
10435   oc_function,
10436   oc_method,
10437   oc_reversed_binary_operator,
10438   oc_constructor,
10439   oc_implicit_default_constructor,
10440   oc_implicit_copy_constructor,
10441   oc_implicit_move_constructor,
10442   oc_implicit_copy_assignment,
10443   oc_implicit_move_assignment,
10444   oc_implicit_equality_comparison,
10445   oc_inherited_constructor
10446 };
10447 
10448 enum OverloadCandidateSelect {
10449   ocs_non_template,
10450   ocs_template,
10451   ocs_described_template,
10452 };
10453 
10454 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10455 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10456                           const FunctionDecl *Fn,
10457                           OverloadCandidateRewriteKind CRK,
10458                           std::string &Description) {
10459 
10460   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10461   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10462     isTemplate = true;
10463     Description = S.getTemplateArgumentBindingsText(
10464         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10465   }
10466 
10467   OverloadCandidateSelect Select = [&]() {
10468     if (!Description.empty())
10469       return ocs_described_template;
10470     return isTemplate ? ocs_template : ocs_non_template;
10471   }();
10472 
10473   OverloadCandidateKind Kind = [&]() {
10474     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10475       return oc_implicit_equality_comparison;
10476 
10477     if (CRK & CRK_Reversed)
10478       return oc_reversed_binary_operator;
10479 
10480     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10481       if (!Ctor->isImplicit()) {
10482         if (isa<ConstructorUsingShadowDecl>(Found))
10483           return oc_inherited_constructor;
10484         else
10485           return oc_constructor;
10486       }
10487 
10488       if (Ctor->isDefaultConstructor())
10489         return oc_implicit_default_constructor;
10490 
10491       if (Ctor->isMoveConstructor())
10492         return oc_implicit_move_constructor;
10493 
10494       assert(Ctor->isCopyConstructor() &&
10495              "unexpected sort of implicit constructor");
10496       return oc_implicit_copy_constructor;
10497     }
10498 
10499     if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10500       // This actually gets spelled 'candidate function' for now, but
10501       // it doesn't hurt to split it out.
10502       if (!Meth->isImplicit())
10503         return oc_method;
10504 
10505       if (Meth->isMoveAssignmentOperator())
10506         return oc_implicit_move_assignment;
10507 
10508       if (Meth->isCopyAssignmentOperator())
10509         return oc_implicit_copy_assignment;
10510 
10511       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10512       return oc_method;
10513     }
10514 
10515     return oc_function;
10516   }();
10517 
10518   return std::make_pair(Kind, Select);
10519 }
10520 
10521 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10522   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10523   // set.
10524   if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10525     S.Diag(FoundDecl->getLocation(),
10526            diag::note_ovl_candidate_inherited_constructor)
10527       << Shadow->getNominatedBaseClass();
10528 }
10529 
10530 } // end anonymous namespace
10531 
10532 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10533                                     const FunctionDecl *FD) {
10534   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10535     bool AlwaysTrue;
10536     if (EnableIf->getCond()->isValueDependent() ||
10537         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10538       return false;
10539     if (!AlwaysTrue)
10540       return false;
10541   }
10542   return true;
10543 }
10544 
10545 /// Returns true if we can take the address of the function.
10546 ///
10547 /// \param Complain - If true, we'll emit a diagnostic
10548 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10549 ///   we in overload resolution?
10550 /// \param Loc - The location of the statement we're complaining about. Ignored
10551 ///   if we're not complaining, or if we're in overload resolution.
10552 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10553                                               bool Complain,
10554                                               bool InOverloadResolution,
10555                                               SourceLocation Loc) {
10556   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10557     if (Complain) {
10558       if (InOverloadResolution)
10559         S.Diag(FD->getBeginLoc(),
10560                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10561       else
10562         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10563     }
10564     return false;
10565   }
10566 
10567   if (FD->getTrailingRequiresClause()) {
10568     ConstraintSatisfaction Satisfaction;
10569     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10570       return false;
10571     if (!Satisfaction.IsSatisfied) {
10572       if (Complain) {
10573         if (InOverloadResolution) {
10574           SmallString<128> TemplateArgString;
10575           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10576             TemplateArgString += " ";
10577             TemplateArgString += S.getTemplateArgumentBindingsText(
10578                 FunTmpl->getTemplateParameters(),
10579                 *FD->getTemplateSpecializationArgs());
10580           }
10581 
10582           S.Diag(FD->getBeginLoc(),
10583                  diag::note_ovl_candidate_unsatisfied_constraints)
10584               << TemplateArgString;
10585         } else
10586           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10587               << FD;
10588         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10589       }
10590       return false;
10591     }
10592   }
10593 
10594   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10595     return P->hasAttr<PassObjectSizeAttr>();
10596   });
10597   if (I == FD->param_end())
10598     return true;
10599 
10600   if (Complain) {
10601     // Add one to ParamNo because it's user-facing
10602     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10603     if (InOverloadResolution)
10604       S.Diag(FD->getLocation(),
10605              diag::note_ovl_candidate_has_pass_object_size_params)
10606           << ParamNo;
10607     else
10608       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10609           << FD << ParamNo;
10610   }
10611   return false;
10612 }
10613 
10614 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10615                                                const FunctionDecl *FD) {
10616   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10617                                            /*InOverloadResolution=*/true,
10618                                            /*Loc=*/SourceLocation());
10619 }
10620 
10621 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10622                                              bool Complain,
10623                                              SourceLocation Loc) {
10624   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10625                                              /*InOverloadResolution=*/false,
10626                                              Loc);
10627 }
10628 
10629 // Don't print candidates other than the one that matches the calling
10630 // convention of the call operator, since that is guaranteed to exist.
10631 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
10632   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10633 
10634   if (!ConvD)
10635     return false;
10636   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10637   if (!RD->isLambda())
10638     return false;
10639 
10640   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10641   CallingConv CallOpCC =
10642       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10643   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10644   CallingConv ConvToCC =
10645       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10646 
10647   return ConvToCC != CallOpCC;
10648 }
10649 
10650 // Notes the location of an overload candidate.
10651 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
10652                                  OverloadCandidateRewriteKind RewriteKind,
10653                                  QualType DestType, bool TakingAddress) {
10654   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10655     return;
10656   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10657       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10658     return;
10659   if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
10660       !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
10661     return;
10662   if (shouldSkipNotingLambdaConversionDecl(Fn))
10663     return;
10664 
10665   std::string FnDesc;
10666   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10667       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10668   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10669                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10670                          << Fn << FnDesc;
10671 
10672   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10673   Diag(Fn->getLocation(), PD);
10674   MaybeEmitInheritedConstructorNote(*this, Found);
10675 }
10676 
10677 static void
10678 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10679   // Perhaps the ambiguity was caused by two atomic constraints that are
10680   // 'identical' but not equivalent:
10681   //
10682   // void foo() requires (sizeof(T) > 4) { } // #1
10683   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10684   //
10685   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10686   // #2 to subsume #1, but these constraint are not considered equivalent
10687   // according to the subsumption rules because they are not the same
10688   // source-level construct. This behavior is quite confusing and we should try
10689   // to help the user figure out what happened.
10690 
10691   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10692   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10693   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10694     if (!I->Function)
10695       continue;
10696     SmallVector<const Expr *, 3> AC;
10697     if (auto *Template = I->Function->getPrimaryTemplate())
10698       Template->getAssociatedConstraints(AC);
10699     else
10700       I->Function->getAssociatedConstraints(AC);
10701     if (AC.empty())
10702       continue;
10703     if (FirstCand == nullptr) {
10704       FirstCand = I->Function;
10705       FirstAC = AC;
10706     } else if (SecondCand == nullptr) {
10707       SecondCand = I->Function;
10708       SecondAC = AC;
10709     } else {
10710       // We have more than one pair of constrained functions - this check is
10711       // expensive and we'd rather not try to diagnose it.
10712       return;
10713     }
10714   }
10715   if (!SecondCand)
10716     return;
10717   // The diagnostic can only happen if there are associated constraints on
10718   // both sides (there needs to be some identical atomic constraint).
10719   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10720                                                       SecondCand, SecondAC))
10721     // Just show the user one diagnostic, they'll probably figure it out
10722     // from here.
10723     return;
10724 }
10725 
10726 // Notes the location of all overload candidates designated through
10727 // OverloadedExpr
10728 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10729                                      bool TakingAddress) {
10730   assert(OverloadedExpr->getType() == Context.OverloadTy);
10731 
10732   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10733   OverloadExpr *OvlExpr = Ovl.Expression;
10734 
10735   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10736                             IEnd = OvlExpr->decls_end();
10737        I != IEnd; ++I) {
10738     if (FunctionTemplateDecl *FunTmpl =
10739                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10740       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10741                             TakingAddress);
10742     } else if (FunctionDecl *Fun
10743                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10744       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10745     }
10746   }
10747 }
10748 
10749 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10750 /// "lead" diagnostic; it will be given two arguments, the source and
10751 /// target types of the conversion.
10752 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10753                                  Sema &S,
10754                                  SourceLocation CaretLoc,
10755                                  const PartialDiagnostic &PDiag) const {
10756   S.Diag(CaretLoc, PDiag)
10757     << Ambiguous.getFromType() << Ambiguous.getToType();
10758   unsigned CandsShown = 0;
10759   AmbiguousConversionSequence::const_iterator I, E;
10760   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10761     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10762       break;
10763     ++CandsShown;
10764     S.NoteOverloadCandidate(I->first, I->second);
10765   }
10766   S.Diags.overloadCandidatesShown(CandsShown);
10767   if (I != E)
10768     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10769 }
10770 
10771 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10772                                   unsigned I, bool TakingCandidateAddress) {
10773   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10774   assert(Conv.isBad());
10775   assert(Cand->Function && "for now, candidate must be a function");
10776   FunctionDecl *Fn = Cand->Function;
10777 
10778   // There's a conversion slot for the object argument if this is a
10779   // non-constructor method.  Note that 'I' corresponds the
10780   // conversion-slot index.
10781   bool isObjectArgument = false;
10782   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10783     if (I == 0)
10784       isObjectArgument = true;
10785     else
10786       I--;
10787   }
10788 
10789   std::string FnDesc;
10790   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10791       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10792                                 FnDesc);
10793 
10794   Expr *FromExpr = Conv.Bad.FromExpr;
10795   QualType FromTy = Conv.Bad.getFromType();
10796   QualType ToTy = Conv.Bad.getToType();
10797   SourceRange ToParamRange =
10798       !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : SourceRange();
10799 
10800   if (FromTy == S.Context.OverloadTy) {
10801     assert(FromExpr && "overload set argument came from implicit argument?");
10802     Expr *E = FromExpr->IgnoreParens();
10803     if (isa<UnaryOperator>(E))
10804       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10805     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10806 
10807     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10808         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10809         << ToParamRange << ToTy << Name << I + 1;
10810     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10811     return;
10812   }
10813 
10814   // Do some hand-waving analysis to see if the non-viability is due
10815   // to a qualifier mismatch.
10816   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10817   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10818   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10819     CToTy = RT->getPointeeType();
10820   else {
10821     // TODO: detect and diagnose the full richness of const mismatches.
10822     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10823       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10824         CFromTy = FromPT->getPointeeType();
10825         CToTy = ToPT->getPointeeType();
10826       }
10827   }
10828 
10829   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10830       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10831     Qualifiers FromQs = CFromTy.getQualifiers();
10832     Qualifiers ToQs = CToTy.getQualifiers();
10833 
10834     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10835       if (isObjectArgument)
10836         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10837             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10838             << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10839       else
10840         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10841             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10842             << FnDesc << ToParamRange << FromQs.getAddressSpace()
10843             << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
10844       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10845       return;
10846     }
10847 
10848     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10849       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10850           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10851           << ToParamRange << FromTy << FromQs.getObjCLifetime()
10852           << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
10853       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10854       return;
10855     }
10856 
10857     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10858       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10859           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10860           << ToParamRange << FromTy << FromQs.getObjCGCAttr()
10861           << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
10862       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10863       return;
10864     }
10865 
10866     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10867     assert(CVR && "expected qualifiers mismatch");
10868 
10869     if (isObjectArgument) {
10870       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10871           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10872           << FromTy << (CVR - 1);
10873     } else {
10874       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10875           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10876           << ToParamRange << FromTy << (CVR - 1) << I + 1;
10877     }
10878     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10879     return;
10880   }
10881 
10882   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10883       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10884     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10885         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10886         << (unsigned)isObjectArgument << I + 1
10887         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10888         << ToParamRange;
10889     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10890     return;
10891   }
10892 
10893   // Special diagnostic for failure to convert an initializer list, since
10894   // telling the user that it has type void is not useful.
10895   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10896     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10897         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10898         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10899         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10900             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10901                 ? 2
10902                 : 0);
10903     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10904     return;
10905   }
10906 
10907   // Diagnose references or pointers to incomplete types differently,
10908   // since it's far from impossible that the incompleteness triggered
10909   // the failure.
10910   QualType TempFromTy = FromTy.getNonReferenceType();
10911   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10912     TempFromTy = PTy->getPointeeType();
10913   if (TempFromTy->isIncompleteType()) {
10914     // Emit the generic diagnostic and, optionally, add the hints to it.
10915     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10916         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10917         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10918         << (unsigned)(Cand->Fix.Kind);
10919 
10920     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10921     return;
10922   }
10923 
10924   // Diagnose base -> derived pointer conversions.
10925   unsigned BaseToDerivedConversion = 0;
10926   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10927     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10928       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10929                                                FromPtrTy->getPointeeType()) &&
10930           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10931           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10932           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10933                           FromPtrTy->getPointeeType()))
10934         BaseToDerivedConversion = 1;
10935     }
10936   } else if (const ObjCObjectPointerType *FromPtrTy
10937                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10938     if (const ObjCObjectPointerType *ToPtrTy
10939                                         = ToTy->getAs<ObjCObjectPointerType>())
10940       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10941         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10942           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10943                                                 FromPtrTy->getPointeeType()) &&
10944               FromIface->isSuperClassOf(ToIface))
10945             BaseToDerivedConversion = 2;
10946   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10947     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10948         !FromTy->isIncompleteType() &&
10949         !ToRefTy->getPointeeType()->isIncompleteType() &&
10950         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10951       BaseToDerivedConversion = 3;
10952     }
10953   }
10954 
10955   if (BaseToDerivedConversion) {
10956     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10957         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10958         << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
10959         << I + 1;
10960     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10961     return;
10962   }
10963 
10964   if (isa<ObjCObjectPointerType>(CFromTy) &&
10965       isa<PointerType>(CToTy)) {
10966     Qualifiers FromQs = CFromTy.getQualifiers();
10967     Qualifiers ToQs = CToTy.getQualifiers();
10968     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10969       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10970           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10971           << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
10972           << I + 1;
10973       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10974       return;
10975     }
10976   }
10977 
10978   if (TakingCandidateAddress &&
10979       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10980     return;
10981 
10982   // Emit the generic diagnostic and, optionally, add the hints to it.
10983   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10984   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10985         << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
10986         << (unsigned)(Cand->Fix.Kind);
10987 
10988   // Check that location of Fn is not in system header.
10989   if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
10990     // If we can fix the conversion, suggest the FixIts.
10991     for (const FixItHint &HI : Cand->Fix.Hints)
10992         FDiag << HI;
10993   }
10994 
10995   S.Diag(Fn->getLocation(), FDiag);
10996 
10997   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10998 }
10999 
11000 /// Additional arity mismatch diagnosis specific to a function overload
11001 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11002 /// over a candidate in any candidate set.
11003 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11004                                unsigned NumArgs) {
11005   FunctionDecl *Fn = Cand->Function;
11006   unsigned MinParams = Fn->getMinRequiredArguments();
11007 
11008   // With invalid overloaded operators, it's possible that we think we
11009   // have an arity mismatch when in fact it looks like we have the
11010   // right number of arguments, because only overloaded operators have
11011   // the weird behavior of overloading member and non-member functions.
11012   // Just don't report anything.
11013   if (Fn->isInvalidDecl() &&
11014       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11015     return true;
11016 
11017   if (NumArgs < MinParams) {
11018     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11019            (Cand->FailureKind == ovl_fail_bad_deduction &&
11020             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
11021   } else {
11022     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11023            (Cand->FailureKind == ovl_fail_bad_deduction &&
11024             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
11025   }
11026 
11027   return false;
11028 }
11029 
11030 /// General arity mismatch diagnosis over a candidate in a candidate set.
11031 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11032                                   unsigned NumFormalArgs) {
11033   assert(isa<FunctionDecl>(D) &&
11034       "The templated declaration should at least be a function"
11035       " when diagnosing bad template argument deduction due to too many"
11036       " or too few arguments");
11037 
11038   FunctionDecl *Fn = cast<FunctionDecl>(D);
11039 
11040   // TODO: treat calls to a missing default constructor as a special case
11041   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11042   unsigned MinParams = Fn->getMinRequiredArguments();
11043 
11044   // at least / at most / exactly
11045   unsigned mode, modeCount;
11046   if (NumFormalArgs < MinParams) {
11047     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
11048         FnTy->isTemplateVariadic())
11049       mode = 0; // "at least"
11050     else
11051       mode = 2; // "exactly"
11052     modeCount = MinParams;
11053   } else {
11054     if (MinParams != FnTy->getNumParams())
11055       mode = 1; // "at most"
11056     else
11057       mode = 2; // "exactly"
11058     modeCount = FnTy->getNumParams();
11059   }
11060 
11061   std::string Description;
11062   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11063       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11064 
11065   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
11066     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11067         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11068         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs
11069         << Fn->getParametersSourceRange();
11070   else
11071     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11072         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11073         << Description << mode << modeCount << NumFormalArgs
11074         << Fn->getParametersSourceRange();
11075 
11076   MaybeEmitInheritedConstructorNote(S, Found);
11077 }
11078 
11079 /// Arity mismatch diagnosis specific to a function overload candidate.
11080 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11081                                   unsigned NumFormalArgs) {
11082   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
11083     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
11084 }
11085 
11086 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11087   if (TemplateDecl *TD = Templated->getDescribedTemplate())
11088     return TD;
11089   llvm_unreachable("Unsupported: Getting the described template declaration"
11090                    " for bad deduction diagnosis");
11091 }
11092 
11093 /// Diagnose a failed template-argument deduction.
11094 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11095                                  DeductionFailureInfo &DeductionFailure,
11096                                  unsigned NumArgs,
11097                                  bool TakingCandidateAddress) {
11098   TemplateParameter Param = DeductionFailure.getTemplateParameter();
11099   NamedDecl *ParamD;
11100   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11101   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11102   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11103   switch (DeductionFailure.Result) {
11104   case Sema::TDK_Success:
11105     llvm_unreachable("TDK_success while diagnosing bad deduction");
11106 
11107   case Sema::TDK_Incomplete: {
11108     assert(ParamD && "no parameter found for incomplete deduction result");
11109     S.Diag(Templated->getLocation(),
11110            diag::note_ovl_candidate_incomplete_deduction)
11111         << ParamD->getDeclName();
11112     MaybeEmitInheritedConstructorNote(S, Found);
11113     return;
11114   }
11115 
11116   case Sema::TDK_IncompletePack: {
11117     assert(ParamD && "no parameter found for incomplete deduction result");
11118     S.Diag(Templated->getLocation(),
11119            diag::note_ovl_candidate_incomplete_deduction_pack)
11120         << ParamD->getDeclName()
11121         << (DeductionFailure.getFirstArg()->pack_size() + 1)
11122         << *DeductionFailure.getFirstArg();
11123     MaybeEmitInheritedConstructorNote(S, Found);
11124     return;
11125   }
11126 
11127   case Sema::TDK_Underqualified: {
11128     assert(ParamD && "no parameter found for bad qualifiers deduction result");
11129     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11130 
11131     QualType Param = DeductionFailure.getFirstArg()->getAsType();
11132 
11133     // Param will have been canonicalized, but it should just be a
11134     // qualified version of ParamD, so move the qualifiers to that.
11135     QualifierCollector Qs;
11136     Qs.strip(Param);
11137     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11138     assert(S.Context.hasSameType(Param, NonCanonParam));
11139 
11140     // Arg has also been canonicalized, but there's nothing we can do
11141     // about that.  It also doesn't matter as much, because it won't
11142     // have any template parameters in it (because deduction isn't
11143     // done on dependent types).
11144     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11145 
11146     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11147         << ParamD->getDeclName() << Arg << NonCanonParam;
11148     MaybeEmitInheritedConstructorNote(S, Found);
11149     return;
11150   }
11151 
11152   case Sema::TDK_Inconsistent: {
11153     assert(ParamD && "no parameter found for inconsistent deduction result");
11154     int which = 0;
11155     if (isa<TemplateTypeParmDecl>(ParamD))
11156       which = 0;
11157     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11158       // Deduction might have failed because we deduced arguments of two
11159       // different types for a non-type template parameter.
11160       // FIXME: Use a different TDK value for this.
11161       QualType T1 =
11162           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11163       QualType T2 =
11164           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11165       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11166         S.Diag(Templated->getLocation(),
11167                diag::note_ovl_candidate_inconsistent_deduction_types)
11168           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11169           << *DeductionFailure.getSecondArg() << T2;
11170         MaybeEmitInheritedConstructorNote(S, Found);
11171         return;
11172       }
11173 
11174       which = 1;
11175     } else {
11176       which = 2;
11177     }
11178 
11179     // Tweak the diagnostic if the problem is that we deduced packs of
11180     // different arities. We'll print the actual packs anyway in case that
11181     // includes additional useful information.
11182     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11183         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11184         DeductionFailure.getFirstArg()->pack_size() !=
11185             DeductionFailure.getSecondArg()->pack_size()) {
11186       which = 3;
11187     }
11188 
11189     S.Diag(Templated->getLocation(),
11190            diag::note_ovl_candidate_inconsistent_deduction)
11191         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11192         << *DeductionFailure.getSecondArg();
11193     MaybeEmitInheritedConstructorNote(S, Found);
11194     return;
11195   }
11196 
11197   case Sema::TDK_InvalidExplicitArguments:
11198     assert(ParamD && "no parameter found for invalid explicit arguments");
11199     if (ParamD->getDeclName())
11200       S.Diag(Templated->getLocation(),
11201              diag::note_ovl_candidate_explicit_arg_mismatch_named)
11202           << ParamD->getDeclName();
11203     else {
11204       int index = 0;
11205       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11206         index = TTP->getIndex();
11207       else if (NonTypeTemplateParmDecl *NTTP
11208                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11209         index = NTTP->getIndex();
11210       else
11211         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11212       S.Diag(Templated->getLocation(),
11213              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11214           << (index + 1);
11215     }
11216     MaybeEmitInheritedConstructorNote(S, Found);
11217     return;
11218 
11219   case Sema::TDK_ConstraintsNotSatisfied: {
11220     // Format the template argument list into the argument string.
11221     SmallString<128> TemplateArgString;
11222     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11223     TemplateArgString = " ";
11224     TemplateArgString += S.getTemplateArgumentBindingsText(
11225         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11226     if (TemplateArgString.size() == 1)
11227       TemplateArgString.clear();
11228     S.Diag(Templated->getLocation(),
11229            diag::note_ovl_candidate_unsatisfied_constraints)
11230         << TemplateArgString;
11231 
11232     S.DiagnoseUnsatisfiedConstraint(
11233         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11234     return;
11235   }
11236   case Sema::TDK_TooManyArguments:
11237   case Sema::TDK_TooFewArguments:
11238     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11239     return;
11240 
11241   case Sema::TDK_InstantiationDepth:
11242     S.Diag(Templated->getLocation(),
11243            diag::note_ovl_candidate_instantiation_depth);
11244     MaybeEmitInheritedConstructorNote(S, Found);
11245     return;
11246 
11247   case Sema::TDK_SubstitutionFailure: {
11248     // Format the template argument list into the argument string.
11249     SmallString<128> TemplateArgString;
11250     if (TemplateArgumentList *Args =
11251             DeductionFailure.getTemplateArgumentList()) {
11252       TemplateArgString = " ";
11253       TemplateArgString += S.getTemplateArgumentBindingsText(
11254           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11255       if (TemplateArgString.size() == 1)
11256         TemplateArgString.clear();
11257     }
11258 
11259     // If this candidate was disabled by enable_if, say so.
11260     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11261     if (PDiag && PDiag->second.getDiagID() ==
11262           diag::err_typename_nested_not_found_enable_if) {
11263       // FIXME: Use the source range of the condition, and the fully-qualified
11264       //        name of the enable_if template. These are both present in PDiag.
11265       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11266         << "'enable_if'" << TemplateArgString;
11267       return;
11268     }
11269 
11270     // We found a specific requirement that disabled the enable_if.
11271     if (PDiag && PDiag->second.getDiagID() ==
11272         diag::err_typename_nested_not_found_requirement) {
11273       S.Diag(Templated->getLocation(),
11274              diag::note_ovl_candidate_disabled_by_requirement)
11275         << PDiag->second.getStringArg(0) << TemplateArgString;
11276       return;
11277     }
11278 
11279     // Format the SFINAE diagnostic into the argument string.
11280     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11281     //        formatted message in another diagnostic.
11282     SmallString<128> SFINAEArgString;
11283     SourceRange R;
11284     if (PDiag) {
11285       SFINAEArgString = ": ";
11286       R = SourceRange(PDiag->first, PDiag->first);
11287       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11288     }
11289 
11290     S.Diag(Templated->getLocation(),
11291            diag::note_ovl_candidate_substitution_failure)
11292         << TemplateArgString << SFINAEArgString << R;
11293     MaybeEmitInheritedConstructorNote(S, Found);
11294     return;
11295   }
11296 
11297   case Sema::TDK_DeducedMismatch:
11298   case Sema::TDK_DeducedMismatchNested: {
11299     // Format the template argument list into the argument string.
11300     SmallString<128> TemplateArgString;
11301     if (TemplateArgumentList *Args =
11302             DeductionFailure.getTemplateArgumentList()) {
11303       TemplateArgString = " ";
11304       TemplateArgString += S.getTemplateArgumentBindingsText(
11305           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11306       if (TemplateArgString.size() == 1)
11307         TemplateArgString.clear();
11308     }
11309 
11310     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11311         << (*DeductionFailure.getCallArgIndex() + 1)
11312         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11313         << TemplateArgString
11314         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11315     break;
11316   }
11317 
11318   case Sema::TDK_NonDeducedMismatch: {
11319     // FIXME: Provide a source location to indicate what we couldn't match.
11320     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11321     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11322     if (FirstTA.getKind() == TemplateArgument::Template &&
11323         SecondTA.getKind() == TemplateArgument::Template) {
11324       TemplateName FirstTN = FirstTA.getAsTemplate();
11325       TemplateName SecondTN = SecondTA.getAsTemplate();
11326       if (FirstTN.getKind() == TemplateName::Template &&
11327           SecondTN.getKind() == TemplateName::Template) {
11328         if (FirstTN.getAsTemplateDecl()->getName() ==
11329             SecondTN.getAsTemplateDecl()->getName()) {
11330           // FIXME: This fixes a bad diagnostic where both templates are named
11331           // the same.  This particular case is a bit difficult since:
11332           // 1) It is passed as a string to the diagnostic printer.
11333           // 2) The diagnostic printer only attempts to find a better
11334           //    name for types, not decls.
11335           // Ideally, this should folded into the diagnostic printer.
11336           S.Diag(Templated->getLocation(),
11337                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11338               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11339           return;
11340         }
11341       }
11342     }
11343 
11344     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11345         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11346       return;
11347 
11348     // FIXME: For generic lambda parameters, check if the function is a lambda
11349     // call operator, and if so, emit a prettier and more informative
11350     // diagnostic that mentions 'auto' and lambda in addition to
11351     // (or instead of?) the canonical template type parameters.
11352     S.Diag(Templated->getLocation(),
11353            diag::note_ovl_candidate_non_deduced_mismatch)
11354         << FirstTA << SecondTA;
11355     return;
11356   }
11357   // TODO: diagnose these individually, then kill off
11358   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11359   case Sema::TDK_MiscellaneousDeductionFailure:
11360     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11361     MaybeEmitInheritedConstructorNote(S, Found);
11362     return;
11363   case Sema::TDK_CUDATargetMismatch:
11364     S.Diag(Templated->getLocation(),
11365            diag::note_cuda_ovl_candidate_target_mismatch);
11366     return;
11367   }
11368 }
11369 
11370 /// Diagnose a failed template-argument deduction, for function calls.
11371 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11372                                  unsigned NumArgs,
11373                                  bool TakingCandidateAddress) {
11374   unsigned TDK = Cand->DeductionFailure.Result;
11375   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11376     if (CheckArityMismatch(S, Cand, NumArgs))
11377       return;
11378   }
11379   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11380                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11381 }
11382 
11383 /// CUDA: diagnose an invalid call across targets.
11384 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11385   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11386   FunctionDecl *Callee = Cand->Function;
11387 
11388   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11389                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11390 
11391   std::string FnDesc;
11392   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11393       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11394                                 Cand->getRewriteKind(), FnDesc);
11395 
11396   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11397       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11398       << FnDesc /* Ignored */
11399       << CalleeTarget << CallerTarget;
11400 
11401   // This could be an implicit constructor for which we could not infer the
11402   // target due to a collsion. Diagnose that case.
11403   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11404   if (Meth != nullptr && Meth->isImplicit()) {
11405     CXXRecordDecl *ParentClass = Meth->getParent();
11406     Sema::CXXSpecialMember CSM;
11407 
11408     switch (FnKindPair.first) {
11409     default:
11410       return;
11411     case oc_implicit_default_constructor:
11412       CSM = Sema::CXXDefaultConstructor;
11413       break;
11414     case oc_implicit_copy_constructor:
11415       CSM = Sema::CXXCopyConstructor;
11416       break;
11417     case oc_implicit_move_constructor:
11418       CSM = Sema::CXXMoveConstructor;
11419       break;
11420     case oc_implicit_copy_assignment:
11421       CSM = Sema::CXXCopyAssignment;
11422       break;
11423     case oc_implicit_move_assignment:
11424       CSM = Sema::CXXMoveAssignment;
11425       break;
11426     };
11427 
11428     bool ConstRHS = false;
11429     if (Meth->getNumParams()) {
11430       if (const ReferenceType *RT =
11431               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11432         ConstRHS = RT->getPointeeType().isConstQualified();
11433       }
11434     }
11435 
11436     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11437                                               /* ConstRHS */ ConstRHS,
11438                                               /* Diagnose */ true);
11439   }
11440 }
11441 
11442 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11443   FunctionDecl *Callee = Cand->Function;
11444   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11445 
11446   S.Diag(Callee->getLocation(),
11447          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11448       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11449 }
11450 
11451 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11452   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11453   assert(ES.isExplicit() && "not an explicit candidate");
11454 
11455   unsigned Kind;
11456   switch (Cand->Function->getDeclKind()) {
11457   case Decl::Kind::CXXConstructor:
11458     Kind = 0;
11459     break;
11460   case Decl::Kind::CXXConversion:
11461     Kind = 1;
11462     break;
11463   case Decl::Kind::CXXDeductionGuide:
11464     Kind = Cand->Function->isImplicit() ? 0 : 2;
11465     break;
11466   default:
11467     llvm_unreachable("invalid Decl");
11468   }
11469 
11470   // Note the location of the first (in-class) declaration; a redeclaration
11471   // (particularly an out-of-class definition) will typically lack the
11472   // 'explicit' specifier.
11473   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11474   FunctionDecl *First = Cand->Function->getFirstDecl();
11475   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11476     First = Pattern->getFirstDecl();
11477 
11478   S.Diag(First->getLocation(),
11479          diag::note_ovl_candidate_explicit)
11480       << Kind << (ES.getExpr() ? 1 : 0)
11481       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11482 }
11483 
11484 /// Generates a 'note' diagnostic for an overload candidate.  We've
11485 /// already generated a primary error at the call site.
11486 ///
11487 /// It really does need to be a single diagnostic with its caret
11488 /// pointed at the candidate declaration.  Yes, this creates some
11489 /// major challenges of technical writing.  Yes, this makes pointing
11490 /// out problems with specific arguments quite awkward.  It's still
11491 /// better than generating twenty screens of text for every failed
11492 /// overload.
11493 ///
11494 /// It would be great to be able to express per-candidate problems
11495 /// more richly for those diagnostic clients that cared, but we'd
11496 /// still have to be just as careful with the default diagnostics.
11497 /// \param CtorDestAS Addr space of object being constructed (for ctor
11498 /// candidates only).
11499 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11500                                   unsigned NumArgs,
11501                                   bool TakingCandidateAddress,
11502                                   LangAS CtorDestAS = LangAS::Default) {
11503   FunctionDecl *Fn = Cand->Function;
11504   if (shouldSkipNotingLambdaConversionDecl(Fn))
11505     return;
11506 
11507   // There is no physical candidate declaration to point to for OpenCL builtins.
11508   // Except for failed conversions, the notes are identical for each candidate,
11509   // so do not generate such notes.
11510   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11511       Cand->FailureKind != ovl_fail_bad_conversion)
11512     return;
11513 
11514   // Note deleted candidates, but only if they're viable.
11515   if (Cand->Viable) {
11516     if (Fn->isDeleted()) {
11517       std::string FnDesc;
11518       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11519           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11520                                     Cand->getRewriteKind(), FnDesc);
11521 
11522       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11523           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11524           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11525       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11526       return;
11527     }
11528 
11529     // We don't really have anything else to say about viable candidates.
11530     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11531     return;
11532   }
11533 
11534   switch (Cand->FailureKind) {
11535   case ovl_fail_too_many_arguments:
11536   case ovl_fail_too_few_arguments:
11537     return DiagnoseArityMismatch(S, Cand, NumArgs);
11538 
11539   case ovl_fail_bad_deduction:
11540     return DiagnoseBadDeduction(S, Cand, NumArgs,
11541                                 TakingCandidateAddress);
11542 
11543   case ovl_fail_illegal_constructor: {
11544     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11545       << (Fn->getPrimaryTemplate() ? 1 : 0);
11546     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11547     return;
11548   }
11549 
11550   case ovl_fail_object_addrspace_mismatch: {
11551     Qualifiers QualsForPrinting;
11552     QualsForPrinting.setAddressSpace(CtorDestAS);
11553     S.Diag(Fn->getLocation(),
11554            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11555         << QualsForPrinting;
11556     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11557     return;
11558   }
11559 
11560   case ovl_fail_trivial_conversion:
11561   case ovl_fail_bad_final_conversion:
11562   case ovl_fail_final_conversion_not_exact:
11563     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11564 
11565   case ovl_fail_bad_conversion: {
11566     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11567     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11568       if (Cand->Conversions[I].isBad())
11569         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11570 
11571     // FIXME: this currently happens when we're called from SemaInit
11572     // when user-conversion overload fails.  Figure out how to handle
11573     // those conditions and diagnose them well.
11574     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11575   }
11576 
11577   case ovl_fail_bad_target:
11578     return DiagnoseBadTarget(S, Cand);
11579 
11580   case ovl_fail_enable_if:
11581     return DiagnoseFailedEnableIfAttr(S, Cand);
11582 
11583   case ovl_fail_explicit:
11584     return DiagnoseFailedExplicitSpec(S, Cand);
11585 
11586   case ovl_fail_inhctor_slice:
11587     // It's generally not interesting to note copy/move constructors here.
11588     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11589       return;
11590     S.Diag(Fn->getLocation(),
11591            diag::note_ovl_candidate_inherited_constructor_slice)
11592       << (Fn->getPrimaryTemplate() ? 1 : 0)
11593       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11594     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11595     return;
11596 
11597   case ovl_fail_addr_not_available: {
11598     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11599     (void)Available;
11600     assert(!Available);
11601     break;
11602   }
11603   case ovl_non_default_multiversion_function:
11604     // Do nothing, these should simply be ignored.
11605     break;
11606 
11607   case ovl_fail_constraints_not_satisfied: {
11608     std::string FnDesc;
11609     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11610         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11611                                   Cand->getRewriteKind(), FnDesc);
11612 
11613     S.Diag(Fn->getLocation(),
11614            diag::note_ovl_candidate_constraints_not_satisfied)
11615         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11616         << FnDesc /* Ignored */;
11617     ConstraintSatisfaction Satisfaction;
11618     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11619       break;
11620     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11621   }
11622   }
11623 }
11624 
11625 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11626   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11627     return;
11628 
11629   // Desugar the type of the surrogate down to a function type,
11630   // retaining as many typedefs as possible while still showing
11631   // the function type (and, therefore, its parameter types).
11632   QualType FnType = Cand->Surrogate->getConversionType();
11633   bool isLValueReference = false;
11634   bool isRValueReference = false;
11635   bool isPointer = false;
11636   if (const LValueReferenceType *FnTypeRef =
11637         FnType->getAs<LValueReferenceType>()) {
11638     FnType = FnTypeRef->getPointeeType();
11639     isLValueReference = true;
11640   } else if (const RValueReferenceType *FnTypeRef =
11641                FnType->getAs<RValueReferenceType>()) {
11642     FnType = FnTypeRef->getPointeeType();
11643     isRValueReference = true;
11644   }
11645   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11646     FnType = FnTypePtr->getPointeeType();
11647     isPointer = true;
11648   }
11649   // Desugar down to a function type.
11650   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11651   // Reconstruct the pointer/reference as appropriate.
11652   if (isPointer) FnType = S.Context.getPointerType(FnType);
11653   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11654   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11655 
11656   if (!Cand->Viable &&
11657       Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
11658     S.Diag(Cand->Surrogate->getLocation(),
11659            diag::note_ovl_surrogate_constraints_not_satisfied)
11660         << Cand->Surrogate;
11661     ConstraintSatisfaction Satisfaction;
11662     if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
11663       S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11664   } else {
11665     S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11666         << FnType;
11667   }
11668 }
11669 
11670 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11671                                          SourceLocation OpLoc,
11672                                          OverloadCandidate *Cand) {
11673   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11674   std::string TypeStr("operator");
11675   TypeStr += Opc;
11676   TypeStr += "(";
11677   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11678   if (Cand->Conversions.size() == 1) {
11679     TypeStr += ")";
11680     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11681   } else {
11682     TypeStr += ", ";
11683     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11684     TypeStr += ")";
11685     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11686   }
11687 }
11688 
11689 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11690                                          OverloadCandidate *Cand) {
11691   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11692     if (ICS.isBad()) break; // all meaningless after first invalid
11693     if (!ICS.isAmbiguous()) continue;
11694 
11695     ICS.DiagnoseAmbiguousConversion(
11696         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11697   }
11698 }
11699 
11700 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11701   if (Cand->Function)
11702     return Cand->Function->getLocation();
11703   if (Cand->IsSurrogate)
11704     return Cand->Surrogate->getLocation();
11705   return SourceLocation();
11706 }
11707 
11708 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11709   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11710   case Sema::TDK_Success:
11711   case Sema::TDK_NonDependentConversionFailure:
11712   case Sema::TDK_AlreadyDiagnosed:
11713     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11714 
11715   case Sema::TDK_Invalid:
11716   case Sema::TDK_Incomplete:
11717   case Sema::TDK_IncompletePack:
11718     return 1;
11719 
11720   case Sema::TDK_Underqualified:
11721   case Sema::TDK_Inconsistent:
11722     return 2;
11723 
11724   case Sema::TDK_SubstitutionFailure:
11725   case Sema::TDK_DeducedMismatch:
11726   case Sema::TDK_ConstraintsNotSatisfied:
11727   case Sema::TDK_DeducedMismatchNested:
11728   case Sema::TDK_NonDeducedMismatch:
11729   case Sema::TDK_MiscellaneousDeductionFailure:
11730   case Sema::TDK_CUDATargetMismatch:
11731     return 3;
11732 
11733   case Sema::TDK_InstantiationDepth:
11734     return 4;
11735 
11736   case Sema::TDK_InvalidExplicitArguments:
11737     return 5;
11738 
11739   case Sema::TDK_TooManyArguments:
11740   case Sema::TDK_TooFewArguments:
11741     return 6;
11742   }
11743   llvm_unreachable("Unhandled deduction result");
11744 }
11745 
11746 namespace {
11747 struct CompareOverloadCandidatesForDisplay {
11748   Sema &S;
11749   SourceLocation Loc;
11750   size_t NumArgs;
11751   OverloadCandidateSet::CandidateSetKind CSK;
11752 
11753   CompareOverloadCandidatesForDisplay(
11754       Sema &S, SourceLocation Loc, size_t NArgs,
11755       OverloadCandidateSet::CandidateSetKind CSK)
11756       : S(S), NumArgs(NArgs), CSK(CSK) {}
11757 
11758   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11759     // If there are too many or too few arguments, that's the high-order bit we
11760     // want to sort by, even if the immediate failure kind was something else.
11761     if (C->FailureKind == ovl_fail_too_many_arguments ||
11762         C->FailureKind == ovl_fail_too_few_arguments)
11763       return static_cast<OverloadFailureKind>(C->FailureKind);
11764 
11765     if (C->Function) {
11766       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11767         return ovl_fail_too_many_arguments;
11768       if (NumArgs < C->Function->getMinRequiredArguments())
11769         return ovl_fail_too_few_arguments;
11770     }
11771 
11772     return static_cast<OverloadFailureKind>(C->FailureKind);
11773   }
11774 
11775   bool operator()(const OverloadCandidate *L,
11776                   const OverloadCandidate *R) {
11777     // Fast-path this check.
11778     if (L == R) return false;
11779 
11780     // Order first by viability.
11781     if (L->Viable) {
11782       if (!R->Viable) return true;
11783 
11784       // TODO: introduce a tri-valued comparison for overload
11785       // candidates.  Would be more worthwhile if we had a sort
11786       // that could exploit it.
11787       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11788         return true;
11789       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11790         return false;
11791     } else if (R->Viable)
11792       return false;
11793 
11794     assert(L->Viable == R->Viable);
11795 
11796     // Criteria by which we can sort non-viable candidates:
11797     if (!L->Viable) {
11798       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11799       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11800 
11801       // 1. Arity mismatches come after other candidates.
11802       if (LFailureKind == ovl_fail_too_many_arguments ||
11803           LFailureKind == ovl_fail_too_few_arguments) {
11804         if (RFailureKind == ovl_fail_too_many_arguments ||
11805             RFailureKind == ovl_fail_too_few_arguments) {
11806           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11807           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11808           if (LDist == RDist) {
11809             if (LFailureKind == RFailureKind)
11810               // Sort non-surrogates before surrogates.
11811               return !L->IsSurrogate && R->IsSurrogate;
11812             // Sort candidates requiring fewer parameters than there were
11813             // arguments given after candidates requiring more parameters
11814             // than there were arguments given.
11815             return LFailureKind == ovl_fail_too_many_arguments;
11816           }
11817           return LDist < RDist;
11818         }
11819         return false;
11820       }
11821       if (RFailureKind == ovl_fail_too_many_arguments ||
11822           RFailureKind == ovl_fail_too_few_arguments)
11823         return true;
11824 
11825       // 2. Bad conversions come first and are ordered by the number
11826       // of bad conversions and quality of good conversions.
11827       if (LFailureKind == ovl_fail_bad_conversion) {
11828         if (RFailureKind != ovl_fail_bad_conversion)
11829           return true;
11830 
11831         // The conversion that can be fixed with a smaller number of changes,
11832         // comes first.
11833         unsigned numLFixes = L->Fix.NumConversionsFixed;
11834         unsigned numRFixes = R->Fix.NumConversionsFixed;
11835         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11836         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11837         if (numLFixes != numRFixes) {
11838           return numLFixes < numRFixes;
11839         }
11840 
11841         // If there's any ordering between the defined conversions...
11842         // FIXME: this might not be transitive.
11843         assert(L->Conversions.size() == R->Conversions.size());
11844 
11845         int leftBetter = 0;
11846         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11847         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11848           switch (CompareImplicitConversionSequences(S, Loc,
11849                                                      L->Conversions[I],
11850                                                      R->Conversions[I])) {
11851           case ImplicitConversionSequence::Better:
11852             leftBetter++;
11853             break;
11854 
11855           case ImplicitConversionSequence::Worse:
11856             leftBetter--;
11857             break;
11858 
11859           case ImplicitConversionSequence::Indistinguishable:
11860             break;
11861           }
11862         }
11863         if (leftBetter > 0) return true;
11864         if (leftBetter < 0) return false;
11865 
11866       } else if (RFailureKind == ovl_fail_bad_conversion)
11867         return false;
11868 
11869       if (LFailureKind == ovl_fail_bad_deduction) {
11870         if (RFailureKind != ovl_fail_bad_deduction)
11871           return true;
11872 
11873         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11874           return RankDeductionFailure(L->DeductionFailure)
11875                < RankDeductionFailure(R->DeductionFailure);
11876       } else if (RFailureKind == ovl_fail_bad_deduction)
11877         return false;
11878 
11879       // TODO: others?
11880     }
11881 
11882     // Sort everything else by location.
11883     SourceLocation LLoc = GetLocationForCandidate(L);
11884     SourceLocation RLoc = GetLocationForCandidate(R);
11885 
11886     // Put candidates without locations (e.g. builtins) at the end.
11887     if (LLoc.isInvalid()) return false;
11888     if (RLoc.isInvalid()) return true;
11889 
11890     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11891   }
11892 };
11893 }
11894 
11895 /// CompleteNonViableCandidate - Normally, overload resolution only
11896 /// computes up to the first bad conversion. Produces the FixIt set if
11897 /// possible.
11898 static void
11899 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11900                            ArrayRef<Expr *> Args,
11901                            OverloadCandidateSet::CandidateSetKind CSK) {
11902   assert(!Cand->Viable);
11903 
11904   // Don't do anything on failures other than bad conversion.
11905   if (Cand->FailureKind != ovl_fail_bad_conversion)
11906     return;
11907 
11908   // We only want the FixIts if all the arguments can be corrected.
11909   bool Unfixable = false;
11910   // Use a implicit copy initialization to check conversion fixes.
11911   Cand->Fix.setConversionChecker(TryCopyInitialization);
11912 
11913   // Attempt to fix the bad conversion.
11914   unsigned ConvCount = Cand->Conversions.size();
11915   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11916        ++ConvIdx) {
11917     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11918     if (Cand->Conversions[ConvIdx].isInitialized() &&
11919         Cand->Conversions[ConvIdx].isBad()) {
11920       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11921       break;
11922     }
11923   }
11924 
11925   // FIXME: this should probably be preserved from the overload
11926   // operation somehow.
11927   bool SuppressUserConversions = false;
11928 
11929   unsigned ConvIdx = 0;
11930   unsigned ArgIdx = 0;
11931   ArrayRef<QualType> ParamTypes;
11932   bool Reversed = Cand->isReversed();
11933 
11934   if (Cand->IsSurrogate) {
11935     QualType ConvType
11936       = Cand->Surrogate->getConversionType().getNonReferenceType();
11937     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11938       ConvType = ConvPtrType->getPointeeType();
11939     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11940     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11941     ConvIdx = 1;
11942   } else if (Cand->Function) {
11943     ParamTypes =
11944         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11945     if (isa<CXXMethodDecl>(Cand->Function) &&
11946         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11947       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11948       ConvIdx = 1;
11949       if (CSK == OverloadCandidateSet::CSK_Operator &&
11950           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11951           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11952               OO_Subscript)
11953         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11954         ArgIdx = 1;
11955     }
11956   } else {
11957     // Builtin operator.
11958     assert(ConvCount <= 3);
11959     ParamTypes = Cand->BuiltinParamTypes;
11960   }
11961 
11962   // Fill in the rest of the conversions.
11963   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11964        ConvIdx != ConvCount;
11965        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11966     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11967     if (Cand->Conversions[ConvIdx].isInitialized()) {
11968       // We've already checked this conversion.
11969     } else if (ParamIdx < ParamTypes.size()) {
11970       if (ParamTypes[ParamIdx]->isDependentType())
11971         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11972             Args[ArgIdx]->getType());
11973       else {
11974         Cand->Conversions[ConvIdx] =
11975             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11976                                   SuppressUserConversions,
11977                                   /*InOverloadResolution=*/true,
11978                                   /*AllowObjCWritebackConversion=*/
11979                                   S.getLangOpts().ObjCAutoRefCount);
11980         // Store the FixIt in the candidate if it exists.
11981         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11982           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11983       }
11984     } else
11985       Cand->Conversions[ConvIdx].setEllipsis();
11986   }
11987 }
11988 
11989 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11990     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11991     SourceLocation OpLoc,
11992     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11993   // Sort the candidates by viability and position.  Sorting directly would
11994   // be prohibitive, so we make a set of pointers and sort those.
11995   SmallVector<OverloadCandidate*, 32> Cands;
11996   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11997   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11998     if (!Filter(*Cand))
11999       continue;
12000     switch (OCD) {
12001     case OCD_AllCandidates:
12002       if (!Cand->Viable) {
12003         if (!Cand->Function && !Cand->IsSurrogate) {
12004           // This a non-viable builtin candidate.  We do not, in general,
12005           // want to list every possible builtin candidate.
12006           continue;
12007         }
12008         CompleteNonViableCandidate(S, Cand, Args, Kind);
12009       }
12010       break;
12011 
12012     case OCD_ViableCandidates:
12013       if (!Cand->Viable)
12014         continue;
12015       break;
12016 
12017     case OCD_AmbiguousCandidates:
12018       if (!Cand->Best)
12019         continue;
12020       break;
12021     }
12022 
12023     Cands.push_back(Cand);
12024   }
12025 
12026   llvm::stable_sort(
12027       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12028 
12029   return Cands;
12030 }
12031 
12032 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12033                                             SourceLocation OpLoc) {
12034   bool DeferHint = false;
12035   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12036     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12037     // host device candidates.
12038     auto WrongSidedCands =
12039         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12040           return (Cand.Viable == false &&
12041                   Cand.FailureKind == ovl_fail_bad_target) ||
12042                  (Cand.Function &&
12043                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
12044                   Cand.Function->template hasAttr<CUDADeviceAttr>());
12045         });
12046     DeferHint = !WrongSidedCands.empty();
12047   }
12048   return DeferHint;
12049 }
12050 
12051 /// When overload resolution fails, prints diagnostic messages containing the
12052 /// candidates in the candidate set.
12053 void OverloadCandidateSet::NoteCandidates(
12054     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12055     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12056     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12057 
12058   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12059 
12060   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12061 
12062   // In WebAssembly we don't want to emit further diagnostics if a table is
12063   // passed as an argument to a function.
12064   bool NoteCands = true;
12065   for (const Expr *Arg : Args) {
12066     if (Arg->getType()->isWebAssemblyTableType())
12067       NoteCands = false;
12068   }
12069 
12070   if (NoteCands)
12071     NoteCandidates(S, Args, Cands, Opc, OpLoc);
12072 
12073   if (OCD == OCD_AmbiguousCandidates)
12074     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12075 }
12076 
12077 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12078                                           ArrayRef<OverloadCandidate *> Cands,
12079                                           StringRef Opc, SourceLocation OpLoc) {
12080   bool ReportedAmbiguousConversions = false;
12081 
12082   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12083   unsigned CandsShown = 0;
12084   auto I = Cands.begin(), E = Cands.end();
12085   for (; I != E; ++I) {
12086     OverloadCandidate *Cand = *I;
12087 
12088     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12089         ShowOverloads == Ovl_Best) {
12090       break;
12091     }
12092     ++CandsShown;
12093 
12094     if (Cand->Function)
12095       NoteFunctionCandidate(S, Cand, Args.size(),
12096                             /*TakingCandidateAddress=*/false, DestAS);
12097     else if (Cand->IsSurrogate)
12098       NoteSurrogateCandidate(S, Cand);
12099     else {
12100       assert(Cand->Viable &&
12101              "Non-viable built-in candidates are not added to Cands.");
12102       // Generally we only see ambiguities including viable builtin
12103       // operators if overload resolution got screwed up by an
12104       // ambiguous user-defined conversion.
12105       //
12106       // FIXME: It's quite possible for different conversions to see
12107       // different ambiguities, though.
12108       if (!ReportedAmbiguousConversions) {
12109         NoteAmbiguousUserConversions(S, OpLoc, Cand);
12110         ReportedAmbiguousConversions = true;
12111       }
12112 
12113       // If this is a viable builtin, print it.
12114       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12115     }
12116   }
12117 
12118   // Inform S.Diags that we've shown an overload set with N elements.  This may
12119   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12120   S.Diags.overloadCandidatesShown(CandsShown);
12121 
12122   if (I != E)
12123     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12124            shouldDeferDiags(S, Args, OpLoc))
12125         << int(E - I);
12126 }
12127 
12128 static SourceLocation
12129 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12130   return Cand->Specialization ? Cand->Specialization->getLocation()
12131                               : SourceLocation();
12132 }
12133 
12134 namespace {
12135 struct CompareTemplateSpecCandidatesForDisplay {
12136   Sema &S;
12137   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12138 
12139   bool operator()(const TemplateSpecCandidate *L,
12140                   const TemplateSpecCandidate *R) {
12141     // Fast-path this check.
12142     if (L == R)
12143       return false;
12144 
12145     // Assuming that both candidates are not matches...
12146 
12147     // Sort by the ranking of deduction failures.
12148     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12149       return RankDeductionFailure(L->DeductionFailure) <
12150              RankDeductionFailure(R->DeductionFailure);
12151 
12152     // Sort everything else by location.
12153     SourceLocation LLoc = GetLocationForCandidate(L);
12154     SourceLocation RLoc = GetLocationForCandidate(R);
12155 
12156     // Put candidates without locations (e.g. builtins) at the end.
12157     if (LLoc.isInvalid())
12158       return false;
12159     if (RLoc.isInvalid())
12160       return true;
12161 
12162     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12163   }
12164 };
12165 }
12166 
12167 /// Diagnose a template argument deduction failure.
12168 /// We are treating these failures as overload failures due to bad
12169 /// deductions.
12170 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12171                                                  bool ForTakingAddress) {
12172   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12173                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12174 }
12175 
12176 void TemplateSpecCandidateSet::destroyCandidates() {
12177   for (iterator i = begin(), e = end(); i != e; ++i) {
12178     i->DeductionFailure.Destroy();
12179   }
12180 }
12181 
12182 void TemplateSpecCandidateSet::clear() {
12183   destroyCandidates();
12184   Candidates.clear();
12185 }
12186 
12187 /// NoteCandidates - When no template specialization match is found, prints
12188 /// diagnostic messages containing the non-matching specializations that form
12189 /// the candidate set.
12190 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12191 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12192 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12193   // Sort the candidates by position (assuming no candidate is a match).
12194   // Sorting directly would be prohibitive, so we make a set of pointers
12195   // and sort those.
12196   SmallVector<TemplateSpecCandidate *, 32> Cands;
12197   Cands.reserve(size());
12198   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12199     if (Cand->Specialization)
12200       Cands.push_back(Cand);
12201     // Otherwise, this is a non-matching builtin candidate.  We do not,
12202     // in general, want to list every possible builtin candidate.
12203   }
12204 
12205   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12206 
12207   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12208   // for generalization purposes (?).
12209   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12210 
12211   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12212   unsigned CandsShown = 0;
12213   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12214     TemplateSpecCandidate *Cand = *I;
12215 
12216     // Set an arbitrary limit on the number of candidates we'll spam
12217     // the user with.  FIXME: This limit should depend on details of the
12218     // candidate list.
12219     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12220       break;
12221     ++CandsShown;
12222 
12223     assert(Cand->Specialization &&
12224            "Non-matching built-in candidates are not added to Cands.");
12225     Cand->NoteDeductionFailure(S, ForTakingAddress);
12226   }
12227 
12228   if (I != E)
12229     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12230 }
12231 
12232 // [PossiblyAFunctionType]  -->   [Return]
12233 // NonFunctionType --> NonFunctionType
12234 // R (A) --> R(A)
12235 // R (*)(A) --> R (A)
12236 // R (&)(A) --> R (A)
12237 // R (S::*)(A) --> R (A)
12238 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12239   QualType Ret = PossiblyAFunctionType;
12240   if (const PointerType *ToTypePtr =
12241     PossiblyAFunctionType->getAs<PointerType>())
12242     Ret = ToTypePtr->getPointeeType();
12243   else if (const ReferenceType *ToTypeRef =
12244     PossiblyAFunctionType->getAs<ReferenceType>())
12245     Ret = ToTypeRef->getPointeeType();
12246   else if (const MemberPointerType *MemTypePtr =
12247     PossiblyAFunctionType->getAs<MemberPointerType>())
12248     Ret = MemTypePtr->getPointeeType();
12249   Ret =
12250     Context.getCanonicalType(Ret).getUnqualifiedType();
12251   return Ret;
12252 }
12253 
12254 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12255                                  bool Complain = true) {
12256   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12257       S.DeduceReturnType(FD, Loc, Complain))
12258     return true;
12259 
12260   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12261   if (S.getLangOpts().CPlusPlus17 &&
12262       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12263       !S.ResolveExceptionSpec(Loc, FPT))
12264     return true;
12265 
12266   return false;
12267 }
12268 
12269 namespace {
12270 // A helper class to help with address of function resolution
12271 // - allows us to avoid passing around all those ugly parameters
12272 class AddressOfFunctionResolver {
12273   Sema& S;
12274   Expr* SourceExpr;
12275   const QualType& TargetType;
12276   QualType TargetFunctionType; // Extracted function type from target type
12277 
12278   bool Complain;
12279   //DeclAccessPair& ResultFunctionAccessPair;
12280   ASTContext& Context;
12281 
12282   bool TargetTypeIsNonStaticMemberFunction;
12283   bool FoundNonTemplateFunction;
12284   bool StaticMemberFunctionFromBoundPointer;
12285   bool HasComplained;
12286 
12287   OverloadExpr::FindResult OvlExprInfo;
12288   OverloadExpr *OvlExpr;
12289   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12290   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12291   TemplateSpecCandidateSet FailedCandidates;
12292 
12293 public:
12294   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12295                             const QualType &TargetType, bool Complain)
12296       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12297         Complain(Complain), Context(S.getASTContext()),
12298         TargetTypeIsNonStaticMemberFunction(
12299             !!TargetType->getAs<MemberPointerType>()),
12300         FoundNonTemplateFunction(false),
12301         StaticMemberFunctionFromBoundPointer(false),
12302         HasComplained(false),
12303         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12304         OvlExpr(OvlExprInfo.Expression),
12305         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12306     ExtractUnqualifiedFunctionTypeFromTargetType();
12307 
12308     if (TargetFunctionType->isFunctionType()) {
12309       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12310         if (!UME->isImplicitAccess() &&
12311             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12312           StaticMemberFunctionFromBoundPointer = true;
12313     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12314       DeclAccessPair dap;
12315       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12316               OvlExpr, false, &dap)) {
12317         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12318           if (!Method->isStatic()) {
12319             // If the target type is a non-function type and the function found
12320             // is a non-static member function, pretend as if that was the
12321             // target, it's the only possible type to end up with.
12322             TargetTypeIsNonStaticMemberFunction = true;
12323 
12324             // And skip adding the function if its not in the proper form.
12325             // We'll diagnose this due to an empty set of functions.
12326             if (!OvlExprInfo.HasFormOfMemberPointer)
12327               return;
12328           }
12329 
12330         Matches.push_back(std::make_pair(dap, Fn));
12331       }
12332       return;
12333     }
12334 
12335     if (OvlExpr->hasExplicitTemplateArgs())
12336       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12337 
12338     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12339       // C++ [over.over]p4:
12340       //   If more than one function is selected, [...]
12341       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12342         if (FoundNonTemplateFunction)
12343           EliminateAllTemplateMatches();
12344         else
12345           EliminateAllExceptMostSpecializedTemplate();
12346       }
12347     }
12348 
12349     if (S.getLangOpts().CUDA && Matches.size() > 1)
12350       EliminateSuboptimalCudaMatches();
12351   }
12352 
12353   bool hasComplained() const { return HasComplained; }
12354 
12355 private:
12356   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12357     QualType Discard;
12358     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12359            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12360   }
12361 
12362   /// \return true if A is considered a better overload candidate for the
12363   /// desired type than B.
12364   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12365     // If A doesn't have exactly the correct type, we don't want to classify it
12366     // as "better" than anything else. This way, the user is required to
12367     // disambiguate for us if there are multiple candidates and no exact match.
12368     return candidateHasExactlyCorrectType(A) &&
12369            (!candidateHasExactlyCorrectType(B) ||
12370             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12371   }
12372 
12373   /// \return true if we were able to eliminate all but one overload candidate,
12374   /// false otherwise.
12375   bool eliminiateSuboptimalOverloadCandidates() {
12376     // Same algorithm as overload resolution -- one pass to pick the "best",
12377     // another pass to be sure that nothing is better than the best.
12378     auto Best = Matches.begin();
12379     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12380       if (isBetterCandidate(I->second, Best->second))
12381         Best = I;
12382 
12383     const FunctionDecl *BestFn = Best->second;
12384     auto IsBestOrInferiorToBest = [this, BestFn](
12385         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12386       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12387     };
12388 
12389     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12390     // option, so we can potentially give the user a better error
12391     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12392       return false;
12393     Matches[0] = *Best;
12394     Matches.resize(1);
12395     return true;
12396   }
12397 
12398   bool isTargetTypeAFunction() const {
12399     return TargetFunctionType->isFunctionType();
12400   }
12401 
12402   // [ToType]     [Return]
12403 
12404   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12405   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12406   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12407   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12408     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12409   }
12410 
12411   // return true if any matching specializations were found
12412   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12413                                    const DeclAccessPair& CurAccessFunPair) {
12414     if (CXXMethodDecl *Method
12415               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12416       // Skip non-static function templates when converting to pointer, and
12417       // static when converting to member pointer.
12418       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12419         return false;
12420     }
12421     else if (TargetTypeIsNonStaticMemberFunction)
12422       return false;
12423 
12424     // C++ [over.over]p2:
12425     //   If the name is a function template, template argument deduction is
12426     //   done (14.8.2.2), and if the argument deduction succeeds, the
12427     //   resulting template argument list is used to generate a single
12428     //   function template specialization, which is added to the set of
12429     //   overloaded functions considered.
12430     FunctionDecl *Specialization = nullptr;
12431     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12432     if (Sema::TemplateDeductionResult Result
12433           = S.DeduceTemplateArguments(FunctionTemplate,
12434                                       &OvlExplicitTemplateArgs,
12435                                       TargetFunctionType, Specialization,
12436                                       Info, /*IsAddressOfFunction*/true)) {
12437       // Make a note of the failed deduction for diagnostics.
12438       FailedCandidates.addCandidate()
12439           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12440                MakeDeductionFailureInfo(Context, Result, Info));
12441       return false;
12442     }
12443 
12444     // Template argument deduction ensures that we have an exact match or
12445     // compatible pointer-to-function arguments that would be adjusted by ICS.
12446     // This function template specicalization works.
12447     assert(S.isSameOrCompatibleFunctionType(
12448               Context.getCanonicalType(Specialization->getType()),
12449               Context.getCanonicalType(TargetFunctionType)));
12450 
12451     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12452       return false;
12453 
12454     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12455     return true;
12456   }
12457 
12458   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12459                                       const DeclAccessPair& CurAccessFunPair) {
12460     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12461       // Skip non-static functions when converting to pointer, and static
12462       // when converting to member pointer.
12463       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12464         return false;
12465     }
12466     else if (TargetTypeIsNonStaticMemberFunction)
12467       return false;
12468 
12469     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12470       if (S.getLangOpts().CUDA)
12471         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12472           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12473             return false;
12474       if (FunDecl->isMultiVersion()) {
12475         const auto *TA = FunDecl->getAttr<TargetAttr>();
12476         if (TA && !TA->isDefaultVersion())
12477           return false;
12478         const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
12479         if (TVA && !TVA->isDefaultVersion())
12480           return false;
12481       }
12482 
12483       // If any candidate has a placeholder return type, trigger its deduction
12484       // now.
12485       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12486                                Complain)) {
12487         HasComplained |= Complain;
12488         return false;
12489       }
12490 
12491       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12492         return false;
12493 
12494       // If we're in C, we need to support types that aren't exactly identical.
12495       if (!S.getLangOpts().CPlusPlus ||
12496           candidateHasExactlyCorrectType(FunDecl)) {
12497         Matches.push_back(std::make_pair(
12498             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12499         FoundNonTemplateFunction = true;
12500         return true;
12501       }
12502     }
12503 
12504     return false;
12505   }
12506 
12507   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12508     bool Ret = false;
12509 
12510     // If the overload expression doesn't have the form of a pointer to
12511     // member, don't try to convert it to a pointer-to-member type.
12512     if (IsInvalidFormOfPointerToMemberFunction())
12513       return false;
12514 
12515     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12516                                E = OvlExpr->decls_end();
12517          I != E; ++I) {
12518       // Look through any using declarations to find the underlying function.
12519       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12520 
12521       // C++ [over.over]p3:
12522       //   Non-member functions and static member functions match
12523       //   targets of type "pointer-to-function" or "reference-to-function."
12524       //   Nonstatic member functions match targets of
12525       //   type "pointer-to-member-function."
12526       // Note that according to DR 247, the containing class does not matter.
12527       if (FunctionTemplateDecl *FunctionTemplate
12528                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12529         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12530           Ret = true;
12531       }
12532       // If we have explicit template arguments supplied, skip non-templates.
12533       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12534                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12535         Ret = true;
12536     }
12537     assert(Ret || Matches.empty());
12538     return Ret;
12539   }
12540 
12541   void EliminateAllExceptMostSpecializedTemplate() {
12542     //   [...] and any given function template specialization F1 is
12543     //   eliminated if the set contains a second function template
12544     //   specialization whose function template is more specialized
12545     //   than the function template of F1 according to the partial
12546     //   ordering rules of 14.5.5.2.
12547 
12548     // The algorithm specified above is quadratic. We instead use a
12549     // two-pass algorithm (similar to the one used to identify the
12550     // best viable function in an overload set) that identifies the
12551     // best function template (if it exists).
12552 
12553     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12554     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12555       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12556 
12557     // TODO: It looks like FailedCandidates does not serve much purpose
12558     // here, since the no_viable diagnostic has index 0.
12559     UnresolvedSetIterator Result = S.getMostSpecialized(
12560         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12561         SourceExpr->getBeginLoc(), S.PDiag(),
12562         S.PDiag(diag::err_addr_ovl_ambiguous)
12563             << Matches[0].second->getDeclName(),
12564         S.PDiag(diag::note_ovl_candidate)
12565             << (unsigned)oc_function << (unsigned)ocs_described_template,
12566         Complain, TargetFunctionType);
12567 
12568     if (Result != MatchesCopy.end()) {
12569       // Make it the first and only element
12570       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12571       Matches[0].second = cast<FunctionDecl>(*Result);
12572       Matches.resize(1);
12573     } else
12574       HasComplained |= Complain;
12575   }
12576 
12577   void EliminateAllTemplateMatches() {
12578     //   [...] any function template specializations in the set are
12579     //   eliminated if the set also contains a non-template function, [...]
12580     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12581       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12582         ++I;
12583       else {
12584         Matches[I] = Matches[--N];
12585         Matches.resize(N);
12586       }
12587     }
12588   }
12589 
12590   void EliminateSuboptimalCudaMatches() {
12591     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12592                                Matches);
12593   }
12594 
12595 public:
12596   void ComplainNoMatchesFound() const {
12597     assert(Matches.empty());
12598     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12599         << OvlExpr->getName() << TargetFunctionType
12600         << OvlExpr->getSourceRange();
12601     if (FailedCandidates.empty())
12602       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12603                                   /*TakingAddress=*/true);
12604     else {
12605       // We have some deduction failure messages. Use them to diagnose
12606       // the function templates, and diagnose the non-template candidates
12607       // normally.
12608       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12609                                  IEnd = OvlExpr->decls_end();
12610            I != IEnd; ++I)
12611         if (FunctionDecl *Fun =
12612                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12613           if (!functionHasPassObjectSizeParams(Fun))
12614             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12615                                     /*TakingAddress=*/true);
12616       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12617     }
12618   }
12619 
12620   bool IsInvalidFormOfPointerToMemberFunction() const {
12621     return TargetTypeIsNonStaticMemberFunction &&
12622       !OvlExprInfo.HasFormOfMemberPointer;
12623   }
12624 
12625   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12626       // TODO: Should we condition this on whether any functions might
12627       // have matched, or is it more appropriate to do that in callers?
12628       // TODO: a fixit wouldn't hurt.
12629       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12630         << TargetType << OvlExpr->getSourceRange();
12631   }
12632 
12633   bool IsStaticMemberFunctionFromBoundPointer() const {
12634     return StaticMemberFunctionFromBoundPointer;
12635   }
12636 
12637   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12638     S.Diag(OvlExpr->getBeginLoc(),
12639            diag::err_invalid_form_pointer_member_function)
12640         << OvlExpr->getSourceRange();
12641   }
12642 
12643   void ComplainOfInvalidConversion() const {
12644     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12645         << OvlExpr->getName() << TargetType;
12646   }
12647 
12648   void ComplainMultipleMatchesFound() const {
12649     assert(Matches.size() > 1);
12650     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12651         << OvlExpr->getName() << OvlExpr->getSourceRange();
12652     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12653                                 /*TakingAddress=*/true);
12654   }
12655 
12656   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12657 
12658   int getNumMatches() const { return Matches.size(); }
12659 
12660   FunctionDecl* getMatchingFunctionDecl() const {
12661     if (Matches.size() != 1) return nullptr;
12662     return Matches[0].second;
12663   }
12664 
12665   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12666     if (Matches.size() != 1) return nullptr;
12667     return &Matches[0].first;
12668   }
12669 };
12670 }
12671 
12672 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12673 /// an overloaded function (C++ [over.over]), where @p From is an
12674 /// expression with overloaded function type and @p ToType is the type
12675 /// we're trying to resolve to. For example:
12676 ///
12677 /// @code
12678 /// int f(double);
12679 /// int f(int);
12680 ///
12681 /// int (*pfd)(double) = f; // selects f(double)
12682 /// @endcode
12683 ///
12684 /// This routine returns the resulting FunctionDecl if it could be
12685 /// resolved, and NULL otherwise. When @p Complain is true, this
12686 /// routine will emit diagnostics if there is an error.
12687 FunctionDecl *
12688 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12689                                          QualType TargetType,
12690                                          bool Complain,
12691                                          DeclAccessPair &FoundResult,
12692                                          bool *pHadMultipleCandidates) {
12693   assert(AddressOfExpr->getType() == Context.OverloadTy);
12694 
12695   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12696                                      Complain);
12697   int NumMatches = Resolver.getNumMatches();
12698   FunctionDecl *Fn = nullptr;
12699   bool ShouldComplain = Complain && !Resolver.hasComplained();
12700   if (NumMatches == 0 && ShouldComplain) {
12701     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12702       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12703     else
12704       Resolver.ComplainNoMatchesFound();
12705   }
12706   else if (NumMatches > 1 && ShouldComplain)
12707     Resolver.ComplainMultipleMatchesFound();
12708   else if (NumMatches == 1) {
12709     Fn = Resolver.getMatchingFunctionDecl();
12710     assert(Fn);
12711     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12712       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12713     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12714     if (Complain) {
12715       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12716         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12717       else
12718         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12719     }
12720   }
12721 
12722   if (pHadMultipleCandidates)
12723     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12724   return Fn;
12725 }
12726 
12727 /// Given an expression that refers to an overloaded function, try to
12728 /// resolve that function to a single function that can have its address taken.
12729 /// This will modify `Pair` iff it returns non-null.
12730 ///
12731 /// This routine can only succeed if from all of the candidates in the overload
12732 /// set for SrcExpr that can have their addresses taken, there is one candidate
12733 /// that is more constrained than the rest.
12734 FunctionDecl *
12735 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12736   OverloadExpr::FindResult R = OverloadExpr::find(E);
12737   OverloadExpr *Ovl = R.Expression;
12738   bool IsResultAmbiguous = false;
12739   FunctionDecl *Result = nullptr;
12740   DeclAccessPair DAP;
12741   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12742 
12743   auto CheckMoreConstrained = [&](FunctionDecl *FD1,
12744                                   FunctionDecl *FD2) -> std::optional<bool> {
12745     if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
12746       FD1 = MF;
12747     if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
12748       FD2 = MF;
12749     SmallVector<const Expr *, 1> AC1, AC2;
12750     FD1->getAssociatedConstraints(AC1);
12751     FD2->getAssociatedConstraints(AC2);
12752     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12753     if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12754       return std::nullopt;
12755     if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12756       return std::nullopt;
12757     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12758       return std::nullopt;
12759     return AtLeastAsConstrained1;
12760   };
12761 
12762   // Don't use the AddressOfResolver because we're specifically looking for
12763   // cases where we have one overload candidate that lacks
12764   // enable_if/pass_object_size/...
12765   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12766     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12767     if (!FD)
12768       return nullptr;
12769 
12770     if (!checkAddressOfFunctionIsAvailable(FD))
12771       continue;
12772 
12773     // We have more than one result - see if it is more constrained than the
12774     // previous one.
12775     if (Result) {
12776       std::optional<bool> MoreConstrainedThanPrevious =
12777           CheckMoreConstrained(FD, Result);
12778       if (!MoreConstrainedThanPrevious) {
12779         IsResultAmbiguous = true;
12780         AmbiguousDecls.push_back(FD);
12781         continue;
12782       }
12783       if (!*MoreConstrainedThanPrevious)
12784         continue;
12785       // FD is more constrained - replace Result with it.
12786     }
12787     IsResultAmbiguous = false;
12788     DAP = I.getPair();
12789     Result = FD;
12790   }
12791 
12792   if (IsResultAmbiguous)
12793     return nullptr;
12794 
12795   if (Result) {
12796     SmallVector<const Expr *, 1> ResultAC;
12797     // We skipped over some ambiguous declarations which might be ambiguous with
12798     // the selected result.
12799     for (FunctionDecl *Skipped : AmbiguousDecls)
12800       if (!CheckMoreConstrained(Skipped, Result))
12801         return nullptr;
12802     Pair = DAP;
12803   }
12804   return Result;
12805 }
12806 
12807 /// Given an overloaded function, tries to turn it into a non-overloaded
12808 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12809 /// will perform access checks, diagnose the use of the resultant decl, and, if
12810 /// requested, potentially perform a function-to-pointer decay.
12811 ///
12812 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12813 /// Otherwise, returns true. This may emit diagnostics and return true.
12814 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12815     ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
12816   Expr *E = SrcExpr.get();
12817   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12818 
12819   DeclAccessPair DAP;
12820   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12821   if (!Found || Found->isCPUDispatchMultiVersion() ||
12822       Found->isCPUSpecificMultiVersion())
12823     return false;
12824 
12825   // Emitting multiple diagnostics for a function that is both inaccessible and
12826   // unavailable is consistent with our behavior elsewhere. So, always check
12827   // for both.
12828   DiagnoseUseOfDecl(Found, E->getExprLoc());
12829   CheckAddressOfMemberAccess(E, DAP);
12830   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12831   if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
12832     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12833   else
12834     SrcExpr = Fixed;
12835   return true;
12836 }
12837 
12838 /// Given an expression that refers to an overloaded function, try to
12839 /// resolve that overloaded function expression down to a single function.
12840 ///
12841 /// This routine can only resolve template-ids that refer to a single function
12842 /// template, where that template-id refers to a single template whose template
12843 /// arguments are either provided by the template-id or have defaults,
12844 /// as described in C++0x [temp.arg.explicit]p3.
12845 ///
12846 /// If no template-ids are found, no diagnostics are emitted and NULL is
12847 /// returned.
12848 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
12849     OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
12850     TemplateSpecCandidateSet *FailedTSC) {
12851   // C++ [over.over]p1:
12852   //   [...] [Note: any redundant set of parentheses surrounding the
12853   //   overloaded function name is ignored (5.1). ]
12854   // C++ [over.over]p1:
12855   //   [...] The overloaded function name can be preceded by the &
12856   //   operator.
12857 
12858   // If we didn't actually find any template-ids, we're done.
12859   if (!ovl->hasExplicitTemplateArgs())
12860     return nullptr;
12861 
12862   TemplateArgumentListInfo ExplicitTemplateArgs;
12863   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12864 
12865   // Look through all of the overloaded functions, searching for one
12866   // whose type matches exactly.
12867   FunctionDecl *Matched = nullptr;
12868   for (UnresolvedSetIterator I = ovl->decls_begin(),
12869          E = ovl->decls_end(); I != E; ++I) {
12870     // C++0x [temp.arg.explicit]p3:
12871     //   [...] In contexts where deduction is done and fails, or in contexts
12872     //   where deduction is not done, if a template argument list is
12873     //   specified and it, along with any default template arguments,
12874     //   identifies a single function template specialization, then the
12875     //   template-id is an lvalue for the function template specialization.
12876     FunctionTemplateDecl *FunctionTemplate
12877       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12878 
12879     // C++ [over.over]p2:
12880     //   If the name is a function template, template argument deduction is
12881     //   done (14.8.2.2), and if the argument deduction succeeds, the
12882     //   resulting template argument list is used to generate a single
12883     //   function template specialization, which is added to the set of
12884     //   overloaded functions considered.
12885     FunctionDecl *Specialization = nullptr;
12886     TemplateDeductionInfo Info(ovl->getNameLoc());
12887     if (TemplateDeductionResult Result
12888           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12889                                     Specialization, Info,
12890                                     /*IsAddressOfFunction*/true)) {
12891       // Make a note of the failed deduction for diagnostics.
12892       if (FailedTSC)
12893         FailedTSC->addCandidate().set(
12894             I.getPair(), FunctionTemplate->getTemplatedDecl(),
12895             MakeDeductionFailureInfo(Context, Result, Info));
12896       continue;
12897     }
12898 
12899     assert(Specialization && "no specialization and no error?");
12900 
12901     // Multiple matches; we can't resolve to a single declaration.
12902     if (Matched) {
12903       if (Complain) {
12904         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12905           << ovl->getName();
12906         NoteAllOverloadCandidates(ovl);
12907       }
12908       return nullptr;
12909     }
12910 
12911     Matched = Specialization;
12912     if (FoundResult) *FoundResult = I.getPair();
12913   }
12914 
12915   if (Matched &&
12916       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12917     return nullptr;
12918 
12919   return Matched;
12920 }
12921 
12922 // Resolve and fix an overloaded expression that can be resolved
12923 // because it identifies a single function template specialization.
12924 //
12925 // Last three arguments should only be supplied if Complain = true
12926 //
12927 // Return true if it was logically possible to so resolve the
12928 // expression, regardless of whether or not it succeeded.  Always
12929 // returns true if 'complain' is set.
12930 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12931     ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
12932     SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
12933     unsigned DiagIDForComplaining) {
12934   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12935 
12936   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12937 
12938   DeclAccessPair found;
12939   ExprResult SingleFunctionExpression;
12940   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12941                            ovl.Expression, /*complain*/ false, &found)) {
12942     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12943       SrcExpr = ExprError();
12944       return true;
12945     }
12946 
12947     // It is only correct to resolve to an instance method if we're
12948     // resolving a form that's permitted to be a pointer to member.
12949     // Otherwise we'll end up making a bound member expression, which
12950     // is illegal in all the contexts we resolve like this.
12951     if (!ovl.HasFormOfMemberPointer &&
12952         isa<CXXMethodDecl>(fn) &&
12953         cast<CXXMethodDecl>(fn)->isInstance()) {
12954       if (!complain) return false;
12955 
12956       Diag(ovl.Expression->getExprLoc(),
12957            diag::err_bound_member_function)
12958         << 0 << ovl.Expression->getSourceRange();
12959 
12960       // TODO: I believe we only end up here if there's a mix of
12961       // static and non-static candidates (otherwise the expression
12962       // would have 'bound member' type, not 'overload' type).
12963       // Ideally we would note which candidate was chosen and why
12964       // the static candidates were rejected.
12965       SrcExpr = ExprError();
12966       return true;
12967     }
12968 
12969     // Fix the expression to refer to 'fn'.
12970     SingleFunctionExpression =
12971         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12972 
12973     // If desired, do function-to-pointer decay.
12974     if (doFunctionPointerConversion) {
12975       SingleFunctionExpression =
12976         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12977       if (SingleFunctionExpression.isInvalid()) {
12978         SrcExpr = ExprError();
12979         return true;
12980       }
12981     }
12982   }
12983 
12984   if (!SingleFunctionExpression.isUsable()) {
12985     if (complain) {
12986       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12987         << ovl.Expression->getName()
12988         << DestTypeForComplaining
12989         << OpRangeForComplaining
12990         << ovl.Expression->getQualifierLoc().getSourceRange();
12991       NoteAllOverloadCandidates(SrcExpr.get());
12992 
12993       SrcExpr = ExprError();
12994       return true;
12995     }
12996 
12997     return false;
12998   }
12999 
13000   SrcExpr = SingleFunctionExpression;
13001   return true;
13002 }
13003 
13004 /// Add a single candidate to the overload set.
13005 static void AddOverloadedCallCandidate(Sema &S,
13006                                        DeclAccessPair FoundDecl,
13007                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
13008                                        ArrayRef<Expr *> Args,
13009                                        OverloadCandidateSet &CandidateSet,
13010                                        bool PartialOverloading,
13011                                        bool KnownValid) {
13012   NamedDecl *Callee = FoundDecl.getDecl();
13013   if (isa<UsingShadowDecl>(Callee))
13014     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13015 
13016   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13017     if (ExplicitTemplateArgs) {
13018       assert(!KnownValid && "Explicit template arguments?");
13019       return;
13020     }
13021     // Prevent ill-formed function decls to be added as overload candidates.
13022     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13023       return;
13024 
13025     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13026                            /*SuppressUserConversions=*/false,
13027                            PartialOverloading);
13028     return;
13029   }
13030 
13031   if (FunctionTemplateDecl *FuncTemplate
13032       = dyn_cast<FunctionTemplateDecl>(Callee)) {
13033     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13034                                    ExplicitTemplateArgs, Args, CandidateSet,
13035                                    /*SuppressUserConversions=*/false,
13036                                    PartialOverloading);
13037     return;
13038   }
13039 
13040   assert(!KnownValid && "unhandled case in overloaded call candidate");
13041 }
13042 
13043 /// Add the overload candidates named by callee and/or found by argument
13044 /// dependent lookup to the given overload set.
13045 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13046                                        ArrayRef<Expr *> Args,
13047                                        OverloadCandidateSet &CandidateSet,
13048                                        bool PartialOverloading) {
13049 
13050 #ifndef NDEBUG
13051   // Verify that ArgumentDependentLookup is consistent with the rules
13052   // in C++0x [basic.lookup.argdep]p3:
13053   //
13054   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
13055   //   and let Y be the lookup set produced by argument dependent
13056   //   lookup (defined as follows). If X contains
13057   //
13058   //     -- a declaration of a class member, or
13059   //
13060   //     -- a block-scope function declaration that is not a
13061   //        using-declaration, or
13062   //
13063   //     -- a declaration that is neither a function or a function
13064   //        template
13065   //
13066   //   then Y is empty.
13067 
13068   if (ULE->requiresADL()) {
13069     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13070            E = ULE->decls_end(); I != E; ++I) {
13071       assert(!(*I)->getDeclContext()->isRecord());
13072       assert(isa<UsingShadowDecl>(*I) ||
13073              !(*I)->getDeclContext()->isFunctionOrMethod());
13074       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13075     }
13076   }
13077 #endif
13078 
13079   // It would be nice to avoid this copy.
13080   TemplateArgumentListInfo TABuffer;
13081   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13082   if (ULE->hasExplicitTemplateArgs()) {
13083     ULE->copyTemplateArgumentsInto(TABuffer);
13084     ExplicitTemplateArgs = &TABuffer;
13085   }
13086 
13087   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13088          E = ULE->decls_end(); I != E; ++I)
13089     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13090                                CandidateSet, PartialOverloading,
13091                                /*KnownValid*/ true);
13092 
13093   if (ULE->requiresADL())
13094     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13095                                          Args, ExplicitTemplateArgs,
13096                                          CandidateSet, PartialOverloading);
13097 }
13098 
13099 /// Add the call candidates from the given set of lookup results to the given
13100 /// overload set. Non-function lookup results are ignored.
13101 void Sema::AddOverloadedCallCandidates(
13102     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13103     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13104   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13105     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13106                                CandidateSet, false, /*KnownValid*/ false);
13107 }
13108 
13109 /// Determine whether a declaration with the specified name could be moved into
13110 /// a different namespace.
13111 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13112   switch (Name.getCXXOverloadedOperator()) {
13113   case OO_New: case OO_Array_New:
13114   case OO_Delete: case OO_Array_Delete:
13115     return false;
13116 
13117   default:
13118     return true;
13119   }
13120 }
13121 
13122 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13123 /// template, where the non-dependent name was declared after the template
13124 /// was defined. This is common in code written for a compilers which do not
13125 /// correctly implement two-stage name lookup.
13126 ///
13127 /// Returns true if a viable candidate was found and a diagnostic was issued.
13128 static bool DiagnoseTwoPhaseLookup(
13129     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13130     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13131     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13132     CXXRecordDecl **FoundInClass = nullptr) {
13133   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13134     return false;
13135 
13136   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13137     if (DC->isTransparentContext())
13138       continue;
13139 
13140     SemaRef.LookupQualifiedName(R, DC);
13141 
13142     if (!R.empty()) {
13143       R.suppressDiagnostics();
13144 
13145       OverloadCandidateSet Candidates(FnLoc, CSK);
13146       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13147                                           Candidates);
13148 
13149       OverloadCandidateSet::iterator Best;
13150       OverloadingResult OR =
13151           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13152 
13153       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13154         // We either found non-function declarations or a best viable function
13155         // at class scope. A class-scope lookup result disables ADL. Don't
13156         // look past this, but let the caller know that we found something that
13157         // either is, or might be, usable in this class.
13158         if (FoundInClass) {
13159           *FoundInClass = RD;
13160           if (OR == OR_Success) {
13161             R.clear();
13162             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13163             R.resolveKind();
13164           }
13165         }
13166         return false;
13167       }
13168 
13169       if (OR != OR_Success) {
13170         // There wasn't a unique best function or function template.
13171         return false;
13172       }
13173 
13174       // Find the namespaces where ADL would have looked, and suggest
13175       // declaring the function there instead.
13176       Sema::AssociatedNamespaceSet AssociatedNamespaces;
13177       Sema::AssociatedClassSet AssociatedClasses;
13178       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13179                                                  AssociatedNamespaces,
13180                                                  AssociatedClasses);
13181       Sema::AssociatedNamespaceSet SuggestedNamespaces;
13182       if (canBeDeclaredInNamespace(R.getLookupName())) {
13183         DeclContext *Std = SemaRef.getStdNamespace();
13184         for (Sema::AssociatedNamespaceSet::iterator
13185                it = AssociatedNamespaces.begin(),
13186                end = AssociatedNamespaces.end(); it != end; ++it) {
13187           // Never suggest declaring a function within namespace 'std'.
13188           if (Std && Std->Encloses(*it))
13189             continue;
13190 
13191           // Never suggest declaring a function within a namespace with a
13192           // reserved name, like __gnu_cxx.
13193           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13194           if (NS &&
13195               NS->getQualifiedNameAsString().find("__") != std::string::npos)
13196             continue;
13197 
13198           SuggestedNamespaces.insert(*it);
13199         }
13200       }
13201 
13202       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13203         << R.getLookupName();
13204       if (SuggestedNamespaces.empty()) {
13205         SemaRef.Diag(Best->Function->getLocation(),
13206                      diag::note_not_found_by_two_phase_lookup)
13207           << R.getLookupName() << 0;
13208       } else if (SuggestedNamespaces.size() == 1) {
13209         SemaRef.Diag(Best->Function->getLocation(),
13210                      diag::note_not_found_by_two_phase_lookup)
13211           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13212       } else {
13213         // FIXME: It would be useful to list the associated namespaces here,
13214         // but the diagnostics infrastructure doesn't provide a way to produce
13215         // a localized representation of a list of items.
13216         SemaRef.Diag(Best->Function->getLocation(),
13217                      diag::note_not_found_by_two_phase_lookup)
13218           << R.getLookupName() << 2;
13219       }
13220 
13221       // Try to recover by calling this function.
13222       return true;
13223     }
13224 
13225     R.clear();
13226   }
13227 
13228   return false;
13229 }
13230 
13231 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13232 /// template, where the non-dependent operator was declared after the template
13233 /// was defined.
13234 ///
13235 /// Returns true if a viable candidate was found and a diagnostic was issued.
13236 static bool
13237 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13238                                SourceLocation OpLoc,
13239                                ArrayRef<Expr *> Args) {
13240   DeclarationName OpName =
13241     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13242   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13243   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13244                                 OverloadCandidateSet::CSK_Operator,
13245                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13246 }
13247 
13248 namespace {
13249 class BuildRecoveryCallExprRAII {
13250   Sema &SemaRef;
13251   Sema::SatisfactionStackResetRAII SatStack;
13252 
13253 public:
13254   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13255     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13256     SemaRef.IsBuildingRecoveryCallExpr = true;
13257   }
13258 
13259   ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13260 };
13261 }
13262 
13263 /// Attempts to recover from a call where no functions were found.
13264 ///
13265 /// This function will do one of three things:
13266 ///  * Diagnose, recover, and return a recovery expression.
13267 ///  * Diagnose, fail to recover, and return ExprError().
13268 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13269 ///    expected to diagnose as appropriate.
13270 static ExprResult
13271 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13272                       UnresolvedLookupExpr *ULE,
13273                       SourceLocation LParenLoc,
13274                       MutableArrayRef<Expr *> Args,
13275                       SourceLocation RParenLoc,
13276                       bool EmptyLookup, bool AllowTypoCorrection) {
13277   // Do not try to recover if it is already building a recovery call.
13278   // This stops infinite loops for template instantiations like
13279   //
13280   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13281   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13282   if (SemaRef.IsBuildingRecoveryCallExpr)
13283     return ExprResult();
13284   BuildRecoveryCallExprRAII RCE(SemaRef);
13285 
13286   CXXScopeSpec SS;
13287   SS.Adopt(ULE->getQualifierLoc());
13288   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13289 
13290   TemplateArgumentListInfo TABuffer;
13291   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13292   if (ULE->hasExplicitTemplateArgs()) {
13293     ULE->copyTemplateArgumentsInto(TABuffer);
13294     ExplicitTemplateArgs = &TABuffer;
13295   }
13296 
13297   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13298                  Sema::LookupOrdinaryName);
13299   CXXRecordDecl *FoundInClass = nullptr;
13300   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13301                              OverloadCandidateSet::CSK_Normal,
13302                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13303     // OK, diagnosed a two-phase lookup issue.
13304   } else if (EmptyLookup) {
13305     // Try to recover from an empty lookup with typo correction.
13306     R.clear();
13307     NoTypoCorrectionCCC NoTypoValidator{};
13308     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13309                                                 ExplicitTemplateArgs != nullptr,
13310                                                 dyn_cast<MemberExpr>(Fn));
13311     CorrectionCandidateCallback &Validator =
13312         AllowTypoCorrection
13313             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13314             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13315     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13316                                     Args))
13317       return ExprError();
13318   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13319     // We found a usable declaration of the name in a dependent base of some
13320     // enclosing class.
13321     // FIXME: We should also explain why the candidates found by name lookup
13322     // were not viable.
13323     if (SemaRef.DiagnoseDependentMemberLookup(R))
13324       return ExprError();
13325   } else {
13326     // We had viable candidates and couldn't recover; let the caller diagnose
13327     // this.
13328     return ExprResult();
13329   }
13330 
13331   // If we get here, we should have issued a diagnostic and formed a recovery
13332   // lookup result.
13333   assert(!R.empty() && "lookup results empty despite recovery");
13334 
13335   // If recovery created an ambiguity, just bail out.
13336   if (R.isAmbiguous()) {
13337     R.suppressDiagnostics();
13338     return ExprError();
13339   }
13340 
13341   // Build an implicit member call if appropriate.  Just drop the
13342   // casts and such from the call, we don't really care.
13343   ExprResult NewFn = ExprError();
13344   if ((*R.begin())->isCXXClassMember())
13345     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13346                                                     ExplicitTemplateArgs, S);
13347   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13348     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13349                                         ExplicitTemplateArgs);
13350   else
13351     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13352 
13353   if (NewFn.isInvalid())
13354     return ExprError();
13355 
13356   // This shouldn't cause an infinite loop because we're giving it
13357   // an expression with viable lookup results, which should never
13358   // end up here.
13359   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13360                                MultiExprArg(Args.data(), Args.size()),
13361                                RParenLoc);
13362 }
13363 
13364 /// Constructs and populates an OverloadedCandidateSet from
13365 /// the given function.
13366 /// \returns true when an the ExprResult output parameter has been set.
13367 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13368                                   UnresolvedLookupExpr *ULE,
13369                                   MultiExprArg Args,
13370                                   SourceLocation RParenLoc,
13371                                   OverloadCandidateSet *CandidateSet,
13372                                   ExprResult *Result) {
13373 #ifndef NDEBUG
13374   if (ULE->requiresADL()) {
13375     // To do ADL, we must have found an unqualified name.
13376     assert(!ULE->getQualifier() && "qualified name with ADL");
13377 
13378     // We don't perform ADL for implicit declarations of builtins.
13379     // Verify that this was correctly set up.
13380     FunctionDecl *F;
13381     if (ULE->decls_begin() != ULE->decls_end() &&
13382         ULE->decls_begin() + 1 == ULE->decls_end() &&
13383         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13384         F->getBuiltinID() && F->isImplicit())
13385       llvm_unreachable("performing ADL for builtin");
13386 
13387     // We don't perform ADL in C.
13388     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13389   }
13390 #endif
13391 
13392   UnbridgedCastsSet UnbridgedCasts;
13393   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13394     *Result = ExprError();
13395     return true;
13396   }
13397 
13398   // Add the functions denoted by the callee to the set of candidate
13399   // functions, including those from argument-dependent lookup.
13400   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13401 
13402   if (getLangOpts().MSVCCompat &&
13403       CurContext->isDependentContext() && !isSFINAEContext() &&
13404       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13405 
13406     OverloadCandidateSet::iterator Best;
13407     if (CandidateSet->empty() ||
13408         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13409             OR_No_Viable_Function) {
13410       // In Microsoft mode, if we are inside a template class member function
13411       // then create a type dependent CallExpr. The goal is to postpone name
13412       // lookup to instantiation time to be able to search into type dependent
13413       // base classes.
13414       CallExpr *CE =
13415           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13416                            RParenLoc, CurFPFeatureOverrides());
13417       CE->markDependentForPostponedNameLookup();
13418       *Result = CE;
13419       return true;
13420     }
13421   }
13422 
13423   if (CandidateSet->empty())
13424     return false;
13425 
13426   UnbridgedCasts.restore();
13427   return false;
13428 }
13429 
13430 // Guess at what the return type for an unresolvable overload should be.
13431 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13432                                    OverloadCandidateSet::iterator *Best) {
13433   std::optional<QualType> Result;
13434   // Adjust Type after seeing a candidate.
13435   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13436     if (!Candidate.Function)
13437       return;
13438     if (Candidate.Function->isInvalidDecl())
13439       return;
13440     QualType T = Candidate.Function->getReturnType();
13441     if (T.isNull())
13442       return;
13443     if (!Result)
13444       Result = T;
13445     else if (Result != T)
13446       Result = QualType();
13447   };
13448 
13449   // Look for an unambiguous type from a progressively larger subset.
13450   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13451   //
13452   // First, consider only the best candidate.
13453   if (Best && *Best != CS.end())
13454     ConsiderCandidate(**Best);
13455   // Next, consider only viable candidates.
13456   if (!Result)
13457     for (const auto &C : CS)
13458       if (C.Viable)
13459         ConsiderCandidate(C);
13460   // Finally, consider all candidates.
13461   if (!Result)
13462     for (const auto &C : CS)
13463       ConsiderCandidate(C);
13464 
13465   if (!Result)
13466     return QualType();
13467   auto Value = *Result;
13468   if (Value.isNull() || Value->isUndeducedType())
13469     return QualType();
13470   return Value;
13471 }
13472 
13473 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13474 /// the completed call expression. If overload resolution fails, emits
13475 /// diagnostics and returns ExprError()
13476 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13477                                            UnresolvedLookupExpr *ULE,
13478                                            SourceLocation LParenLoc,
13479                                            MultiExprArg Args,
13480                                            SourceLocation RParenLoc,
13481                                            Expr *ExecConfig,
13482                                            OverloadCandidateSet *CandidateSet,
13483                                            OverloadCandidateSet::iterator *Best,
13484                                            OverloadingResult OverloadResult,
13485                                            bool AllowTypoCorrection) {
13486   switch (OverloadResult) {
13487   case OR_Success: {
13488     FunctionDecl *FDecl = (*Best)->Function;
13489     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13490     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13491       return ExprError();
13492     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13493     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13494                                          ExecConfig, /*IsExecConfig=*/false,
13495                                          (*Best)->IsADLCandidate);
13496   }
13497 
13498   case OR_No_Viable_Function: {
13499     // Try to recover by looking for viable functions which the user might
13500     // have meant to call.
13501     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13502                                                 Args, RParenLoc,
13503                                                 CandidateSet->empty(),
13504                                                 AllowTypoCorrection);
13505     if (Recovery.isInvalid() || Recovery.isUsable())
13506       return Recovery;
13507 
13508     // If the user passes in a function that we can't take the address of, we
13509     // generally end up emitting really bad error messages. Here, we attempt to
13510     // emit better ones.
13511     for (const Expr *Arg : Args) {
13512       if (!Arg->getType()->isFunctionType())
13513         continue;
13514       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13515         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13516         if (FD &&
13517             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13518                                                        Arg->getExprLoc()))
13519           return ExprError();
13520       }
13521     }
13522 
13523     CandidateSet->NoteCandidates(
13524         PartialDiagnosticAt(
13525             Fn->getBeginLoc(),
13526             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13527                 << ULE->getName() << Fn->getSourceRange()),
13528         SemaRef, OCD_AllCandidates, Args);
13529     break;
13530   }
13531 
13532   case OR_Ambiguous:
13533     CandidateSet->NoteCandidates(
13534         PartialDiagnosticAt(Fn->getBeginLoc(),
13535                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13536                                 << ULE->getName() << Fn->getSourceRange()),
13537         SemaRef, OCD_AmbiguousCandidates, Args);
13538     break;
13539 
13540   case OR_Deleted: {
13541     CandidateSet->NoteCandidates(
13542         PartialDiagnosticAt(Fn->getBeginLoc(),
13543                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13544                                 << ULE->getName() << Fn->getSourceRange()),
13545         SemaRef, OCD_AllCandidates, Args);
13546 
13547     // We emitted an error for the unavailable/deleted function call but keep
13548     // the call in the AST.
13549     FunctionDecl *FDecl = (*Best)->Function;
13550     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13551     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13552                                          ExecConfig, /*IsExecConfig=*/false,
13553                                          (*Best)->IsADLCandidate);
13554   }
13555   }
13556 
13557   // Overload resolution failed, try to recover.
13558   SmallVector<Expr *, 8> SubExprs = {Fn};
13559   SubExprs.append(Args.begin(), Args.end());
13560   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13561                                     chooseRecoveryType(*CandidateSet, Best));
13562 }
13563 
13564 static void markUnaddressableCandidatesUnviable(Sema &S,
13565                                                 OverloadCandidateSet &CS) {
13566   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13567     if (I->Viable &&
13568         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13569       I->Viable = false;
13570       I->FailureKind = ovl_fail_addr_not_available;
13571     }
13572   }
13573 }
13574 
13575 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13576 /// (which eventually refers to the declaration Func) and the call
13577 /// arguments Args/NumArgs, attempt to resolve the function call down
13578 /// to a specific function. If overload resolution succeeds, returns
13579 /// the call expression produced by overload resolution.
13580 /// Otherwise, emits diagnostics and returns ExprError.
13581 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13582                                          UnresolvedLookupExpr *ULE,
13583                                          SourceLocation LParenLoc,
13584                                          MultiExprArg Args,
13585                                          SourceLocation RParenLoc,
13586                                          Expr *ExecConfig,
13587                                          bool AllowTypoCorrection,
13588                                          bool CalleesAddressIsTaken) {
13589   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13590                                     OverloadCandidateSet::CSK_Normal);
13591   ExprResult result;
13592 
13593   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13594                              &result))
13595     return result;
13596 
13597   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13598   // functions that aren't addressible are considered unviable.
13599   if (CalleesAddressIsTaken)
13600     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13601 
13602   OverloadCandidateSet::iterator Best;
13603   OverloadingResult OverloadResult =
13604       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13605 
13606   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13607                                   ExecConfig, &CandidateSet, &Best,
13608                                   OverloadResult, AllowTypoCorrection);
13609 }
13610 
13611 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13612   return Functions.size() > 1 ||
13613          (Functions.size() == 1 &&
13614           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13615 }
13616 
13617 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13618                                             NestedNameSpecifierLoc NNSLoc,
13619                                             DeclarationNameInfo DNI,
13620                                             const UnresolvedSetImpl &Fns,
13621                                             bool PerformADL) {
13622   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13623                                       PerformADL, IsOverloaded(Fns),
13624                                       Fns.begin(), Fns.end());
13625 }
13626 
13627 /// Create a unary operation that may resolve to an overloaded
13628 /// operator.
13629 ///
13630 /// \param OpLoc The location of the operator itself (e.g., '*').
13631 ///
13632 /// \param Opc The UnaryOperatorKind that describes this operator.
13633 ///
13634 /// \param Fns The set of non-member functions that will be
13635 /// considered by overload resolution. The caller needs to build this
13636 /// set based on the context using, e.g.,
13637 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13638 /// set should not contain any member functions; those will be added
13639 /// by CreateOverloadedUnaryOp().
13640 ///
13641 /// \param Input The input argument.
13642 ExprResult
13643 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13644                               const UnresolvedSetImpl &Fns,
13645                               Expr *Input, bool PerformADL) {
13646   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13647   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13648   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13649   // TODO: provide better source location info.
13650   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13651 
13652   if (checkPlaceholderForOverload(*this, Input))
13653     return ExprError();
13654 
13655   Expr *Args[2] = { Input, nullptr };
13656   unsigned NumArgs = 1;
13657 
13658   // For post-increment and post-decrement, add the implicit '0' as
13659   // the second argument, so that we know this is a post-increment or
13660   // post-decrement.
13661   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13662     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13663     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13664                                      SourceLocation());
13665     NumArgs = 2;
13666   }
13667 
13668   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13669 
13670   if (Input->isTypeDependent()) {
13671     if (Fns.empty())
13672       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13673                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13674                                    CurFPFeatureOverrides());
13675 
13676     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13677     ExprResult Fn = CreateUnresolvedLookupExpr(
13678         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13679     if (Fn.isInvalid())
13680       return ExprError();
13681     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13682                                        Context.DependentTy, VK_PRValue, OpLoc,
13683                                        CurFPFeatureOverrides());
13684   }
13685 
13686   // Build an empty overload set.
13687   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13688 
13689   // Add the candidates from the given function set.
13690   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13691 
13692   // Add operator candidates that are member functions.
13693   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13694 
13695   // Add candidates from ADL.
13696   if (PerformADL) {
13697     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13698                                          /*ExplicitTemplateArgs*/nullptr,
13699                                          CandidateSet);
13700   }
13701 
13702   // Add builtin operator candidates.
13703   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13704 
13705   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13706 
13707   // Perform overload resolution.
13708   OverloadCandidateSet::iterator Best;
13709   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13710   case OR_Success: {
13711     // We found a built-in operator or an overloaded operator.
13712     FunctionDecl *FnDecl = Best->Function;
13713 
13714     if (FnDecl) {
13715       Expr *Base = nullptr;
13716       // We matched an overloaded operator. Build a call to that
13717       // operator.
13718 
13719       // Convert the arguments.
13720       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13721         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13722 
13723         ExprResult InputRes =
13724           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13725                                               Best->FoundDecl, Method);
13726         if (InputRes.isInvalid())
13727           return ExprError();
13728         Base = Input = InputRes.get();
13729       } else {
13730         // Convert the arguments.
13731         ExprResult InputInit
13732           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13733                                                       Context,
13734                                                       FnDecl->getParamDecl(0)),
13735                                       SourceLocation(),
13736                                       Input);
13737         if (InputInit.isInvalid())
13738           return ExprError();
13739         Input = InputInit.get();
13740       }
13741 
13742       // Build the actual expression node.
13743       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13744                                                 Base, HadMultipleCandidates,
13745                                                 OpLoc);
13746       if (FnExpr.isInvalid())
13747         return ExprError();
13748 
13749       // Determine the result type.
13750       QualType ResultTy = FnDecl->getReturnType();
13751       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13752       ResultTy = ResultTy.getNonLValueExprType(Context);
13753 
13754       Args[0] = Input;
13755       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13756           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13757           CurFPFeatureOverrides(), Best->IsADLCandidate);
13758 
13759       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13760         return ExprError();
13761 
13762       if (CheckFunctionCall(FnDecl, TheCall,
13763                             FnDecl->getType()->castAs<FunctionProtoType>()))
13764         return ExprError();
13765       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13766     } else {
13767       // We matched a built-in operator. Convert the arguments, then
13768       // break out so that we will build the appropriate built-in
13769       // operator node.
13770       ExprResult InputRes = PerformImplicitConversion(
13771           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13772           CCK_ForBuiltinOverloadedOp);
13773       if (InputRes.isInvalid())
13774         return ExprError();
13775       Input = InputRes.get();
13776       break;
13777     }
13778   }
13779 
13780   case OR_No_Viable_Function:
13781     // This is an erroneous use of an operator which can be overloaded by
13782     // a non-member function. Check for non-member operators which were
13783     // defined too late to be candidates.
13784     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13785       // FIXME: Recover by calling the found function.
13786       return ExprError();
13787 
13788     // No viable function; fall through to handling this as a
13789     // built-in operator, which will produce an error message for us.
13790     break;
13791 
13792   case OR_Ambiguous:
13793     CandidateSet.NoteCandidates(
13794         PartialDiagnosticAt(OpLoc,
13795                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13796                                 << UnaryOperator::getOpcodeStr(Opc)
13797                                 << Input->getType() << Input->getSourceRange()),
13798         *this, OCD_AmbiguousCandidates, ArgsArray,
13799         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13800     return ExprError();
13801 
13802   case OR_Deleted:
13803     CandidateSet.NoteCandidates(
13804         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13805                                        << UnaryOperator::getOpcodeStr(Opc)
13806                                        << Input->getSourceRange()),
13807         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13808         OpLoc);
13809     return ExprError();
13810   }
13811 
13812   // Either we found no viable overloaded operator or we matched a
13813   // built-in operator. In either case, fall through to trying to
13814   // build a built-in operation.
13815   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13816 }
13817 
13818 /// Perform lookup for an overloaded binary operator.
13819 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13820                                  OverloadedOperatorKind Op,
13821                                  const UnresolvedSetImpl &Fns,
13822                                  ArrayRef<Expr *> Args, bool PerformADL) {
13823   SourceLocation OpLoc = CandidateSet.getLocation();
13824 
13825   OverloadedOperatorKind ExtraOp =
13826       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13827           ? getRewrittenOverloadedOperator(Op)
13828           : OO_None;
13829 
13830   // Add the candidates from the given function set. This also adds the
13831   // rewritten candidates using these functions if necessary.
13832   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13833 
13834   // Add operator candidates that are member functions.
13835   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13836   if (CandidateSet.getRewriteInfo().allowsReversed(Op))
13837     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13838                                 OverloadCandidateParamOrder::Reversed);
13839 
13840   // In C++20, also add any rewritten member candidates.
13841   if (ExtraOp) {
13842     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13843     if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
13844       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13845                                   CandidateSet,
13846                                   OverloadCandidateParamOrder::Reversed);
13847   }
13848 
13849   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13850   // performed for an assignment operator (nor for operator[] nor operator->,
13851   // which don't get here).
13852   if (Op != OO_Equal && PerformADL) {
13853     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13854     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13855                                          /*ExplicitTemplateArgs*/ nullptr,
13856                                          CandidateSet);
13857     if (ExtraOp) {
13858       DeclarationName ExtraOpName =
13859           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13860       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13861                                            /*ExplicitTemplateArgs*/ nullptr,
13862                                            CandidateSet);
13863     }
13864   }
13865 
13866   // Add builtin operator candidates.
13867   //
13868   // FIXME: We don't add any rewritten candidates here. This is strictly
13869   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13870   // resulting in our selecting a rewritten builtin candidate. For example:
13871   //
13872   //   enum class E { e };
13873   //   bool operator!=(E, E) requires false;
13874   //   bool k = E::e != E::e;
13875   //
13876   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13877   // it seems unreasonable to consider rewritten builtin candidates. A core
13878   // issue has been filed proposing to removed this requirement.
13879   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13880 }
13881 
13882 /// Create a binary operation that may resolve to an overloaded
13883 /// operator.
13884 ///
13885 /// \param OpLoc The location of the operator itself (e.g., '+').
13886 ///
13887 /// \param Opc The BinaryOperatorKind that describes this operator.
13888 ///
13889 /// \param Fns The set of non-member functions that will be
13890 /// considered by overload resolution. The caller needs to build this
13891 /// set based on the context using, e.g.,
13892 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13893 /// set should not contain any member functions; those will be added
13894 /// by CreateOverloadedBinOp().
13895 ///
13896 /// \param LHS Left-hand argument.
13897 /// \param RHS Right-hand argument.
13898 /// \param PerformADL Whether to consider operator candidates found by ADL.
13899 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13900 ///        C++20 operator rewrites.
13901 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13902 ///        the function in question. Such a function is never a candidate in
13903 ///        our overload resolution. This also enables synthesizing a three-way
13904 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13905 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13906                                        BinaryOperatorKind Opc,
13907                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13908                                        Expr *RHS, bool PerformADL,
13909                                        bool AllowRewrittenCandidates,
13910                                        FunctionDecl *DefaultedFn) {
13911   Expr *Args[2] = { LHS, RHS };
13912   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13913 
13914   if (!getLangOpts().CPlusPlus20)
13915     AllowRewrittenCandidates = false;
13916 
13917   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13918 
13919   // If either side is type-dependent, create an appropriate dependent
13920   // expression.
13921   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13922     if (Fns.empty()) {
13923       // If there are no functions to store, just build a dependent
13924       // BinaryOperator or CompoundAssignment.
13925       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13926         return CompoundAssignOperator::Create(
13927             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13928             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13929             Context.DependentTy);
13930       return BinaryOperator::Create(
13931           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13932           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13933     }
13934 
13935     // FIXME: save results of ADL from here?
13936     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13937     // TODO: provide better source location info in DNLoc component.
13938     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13939     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13940     ExprResult Fn = CreateUnresolvedLookupExpr(
13941         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13942     if (Fn.isInvalid())
13943       return ExprError();
13944     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13945                                        Context.DependentTy, VK_PRValue, OpLoc,
13946                                        CurFPFeatureOverrides());
13947   }
13948 
13949   // Always do placeholder-like conversions on the RHS.
13950   if (checkPlaceholderForOverload(*this, Args[1]))
13951     return ExprError();
13952 
13953   // Do placeholder-like conversion on the LHS; note that we should
13954   // not get here with a PseudoObject LHS.
13955   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13956   if (checkPlaceholderForOverload(*this, Args[0]))
13957     return ExprError();
13958 
13959   // If this is the assignment operator, we only perform overload resolution
13960   // if the left-hand side is a class or enumeration type. This is actually
13961   // a hack. The standard requires that we do overload resolution between the
13962   // various built-in candidates, but as DR507 points out, this can lead to
13963   // problems. So we do it this way, which pretty much follows what GCC does.
13964   // Note that we go the traditional code path for compound assignment forms.
13965   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13966     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13967 
13968   // If this is the .* operator, which is not overloadable, just
13969   // create a built-in binary operator.
13970   if (Opc == BO_PtrMemD)
13971     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13972 
13973   // Build the overload set.
13974   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
13975                                     OverloadCandidateSet::OperatorRewriteInfo(
13976                                         Op, OpLoc, AllowRewrittenCandidates));
13977   if (DefaultedFn)
13978     CandidateSet.exclude(DefaultedFn);
13979   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13980 
13981   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13982 
13983   // Perform overload resolution.
13984   OverloadCandidateSet::iterator Best;
13985   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13986     case OR_Success: {
13987       // We found a built-in operator or an overloaded operator.
13988       FunctionDecl *FnDecl = Best->Function;
13989 
13990       bool IsReversed = Best->isReversed();
13991       if (IsReversed)
13992         std::swap(Args[0], Args[1]);
13993 
13994       if (FnDecl) {
13995         Expr *Base = nullptr;
13996         // We matched an overloaded operator. Build a call to that
13997         // operator.
13998 
13999         OverloadedOperatorKind ChosenOp =
14000             FnDecl->getDeclName().getCXXOverloadedOperator();
14001 
14002         // C++2a [over.match.oper]p9:
14003         //   If a rewritten operator== candidate is selected by overload
14004         //   resolution for an operator@, its return type shall be cv bool
14005         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14006             !FnDecl->getReturnType()->isBooleanType()) {
14007           bool IsExtension =
14008               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14009           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14010                                   : diag::err_ovl_rewrite_equalequal_not_bool)
14011               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14012               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14013           Diag(FnDecl->getLocation(), diag::note_declared_at);
14014           if (!IsExtension)
14015             return ExprError();
14016         }
14017 
14018         if (AllowRewrittenCandidates && !IsReversed &&
14019             CandidateSet.getRewriteInfo().isReversible()) {
14020           // We could have reversed this operator, but didn't. Check if some
14021           // reversed form was a viable candidate, and if so, if it had a
14022           // better conversion for either parameter. If so, this call is
14023           // formally ambiguous, and allowing it is an extension.
14024           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14025           for (OverloadCandidate &Cand : CandidateSet) {
14026             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14027                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
14028               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14029                 if (CompareImplicitConversionSequences(
14030                         *this, OpLoc, Cand.Conversions[ArgIdx],
14031                         Best->Conversions[ArgIdx]) ==
14032                     ImplicitConversionSequence::Better) {
14033                   AmbiguousWith.push_back(Cand.Function);
14034                   break;
14035                 }
14036               }
14037             }
14038           }
14039 
14040           if (!AmbiguousWith.empty()) {
14041             bool AmbiguousWithSelf =
14042                 AmbiguousWith.size() == 1 &&
14043                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14044             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14045                 << BinaryOperator::getOpcodeStr(Opc)
14046                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14047                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14048             if (AmbiguousWithSelf) {
14049               Diag(FnDecl->getLocation(),
14050                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
14051               // Mark member== const or provide matching != to disallow reversed
14052               // args. Eg.
14053               // struct S { bool operator==(const S&); };
14054               // S()==S();
14055               if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14056                 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14057                     !MD->isConst() &&
14058                     Context.hasSameUnqualifiedType(
14059                         MD->getThisObjectType(),
14060                         MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14061                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
14062                                                    Args[0]->getType()) &&
14063                     Context.hasSameUnqualifiedType(MD->getThisObjectType(),
14064                                                    Args[1]->getType()))
14065                   Diag(FnDecl->getLocation(),
14066                        diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14067             } else {
14068               Diag(FnDecl->getLocation(),
14069                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14070               for (auto *F : AmbiguousWith)
14071                 Diag(F->getLocation(),
14072                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14073             }
14074           }
14075         }
14076 
14077         // Convert the arguments.
14078         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14079           // Best->Access is only meaningful for class members.
14080           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14081 
14082           ExprResult Arg1 =
14083             PerformCopyInitialization(
14084               InitializedEntity::InitializeParameter(Context,
14085                                                      FnDecl->getParamDecl(0)),
14086               SourceLocation(), Args[1]);
14087           if (Arg1.isInvalid())
14088             return ExprError();
14089 
14090           ExprResult Arg0 =
14091             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14092                                                 Best->FoundDecl, Method);
14093           if (Arg0.isInvalid())
14094             return ExprError();
14095           Base = Args[0] = Arg0.getAs<Expr>();
14096           Args[1] = RHS = Arg1.getAs<Expr>();
14097         } else {
14098           // Convert the arguments.
14099           ExprResult Arg0 = PerformCopyInitialization(
14100             InitializedEntity::InitializeParameter(Context,
14101                                                    FnDecl->getParamDecl(0)),
14102             SourceLocation(), Args[0]);
14103           if (Arg0.isInvalid())
14104             return ExprError();
14105 
14106           ExprResult Arg1 =
14107             PerformCopyInitialization(
14108               InitializedEntity::InitializeParameter(Context,
14109                                                      FnDecl->getParamDecl(1)),
14110               SourceLocation(), Args[1]);
14111           if (Arg1.isInvalid())
14112             return ExprError();
14113           Args[0] = LHS = Arg0.getAs<Expr>();
14114           Args[1] = RHS = Arg1.getAs<Expr>();
14115         }
14116 
14117         // Build the actual expression node.
14118         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14119                                                   Best->FoundDecl, Base,
14120                                                   HadMultipleCandidates, OpLoc);
14121         if (FnExpr.isInvalid())
14122           return ExprError();
14123 
14124         // Determine the result type.
14125         QualType ResultTy = FnDecl->getReturnType();
14126         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14127         ResultTy = ResultTy.getNonLValueExprType(Context);
14128 
14129         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14130             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14131             CurFPFeatureOverrides(), Best->IsADLCandidate);
14132 
14133         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14134                                 FnDecl))
14135           return ExprError();
14136 
14137         ArrayRef<const Expr *> ArgsArray(Args, 2);
14138         const Expr *ImplicitThis = nullptr;
14139         // Cut off the implicit 'this'.
14140         if (isa<CXXMethodDecl>(FnDecl)) {
14141           ImplicitThis = ArgsArray[0];
14142           ArgsArray = ArgsArray.slice(1);
14143         }
14144 
14145         // Check for a self move.
14146         if (Op == OO_Equal)
14147           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14148 
14149         if (ImplicitThis) {
14150           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14151           QualType ThisTypeFromDecl = Context.getPointerType(
14152               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
14153 
14154           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14155                             ThisTypeFromDecl);
14156         }
14157 
14158         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14159                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14160                   VariadicDoesNotApply);
14161 
14162         ExprResult R = MaybeBindToTemporary(TheCall);
14163         if (R.isInvalid())
14164           return ExprError();
14165 
14166         R = CheckForImmediateInvocation(R, FnDecl);
14167         if (R.isInvalid())
14168           return ExprError();
14169 
14170         // For a rewritten candidate, we've already reversed the arguments
14171         // if needed. Perform the rest of the rewrite now.
14172         if ((Best->RewriteKind & CRK_DifferentOperator) ||
14173             (Op == OO_Spaceship && IsReversed)) {
14174           if (Op == OO_ExclaimEqual) {
14175             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14176             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14177           } else {
14178             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14179             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14180             Expr *ZeroLiteral =
14181                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14182 
14183             Sema::CodeSynthesisContext Ctx;
14184             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14185             Ctx.Entity = FnDecl;
14186             pushCodeSynthesisContext(Ctx);
14187 
14188             R = CreateOverloadedBinOp(
14189                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14190                 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14191                 /*AllowRewrittenCandidates=*/false);
14192 
14193             popCodeSynthesisContext();
14194           }
14195           if (R.isInvalid())
14196             return ExprError();
14197         } else {
14198           assert(ChosenOp == Op && "unexpected operator name");
14199         }
14200 
14201         // Make a note in the AST if we did any rewriting.
14202         if (Best->RewriteKind != CRK_None)
14203           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14204 
14205         return R;
14206       } else {
14207         // We matched a built-in operator. Convert the arguments, then
14208         // break out so that we will build the appropriate built-in
14209         // operator node.
14210         ExprResult ArgsRes0 = PerformImplicitConversion(
14211             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14212             AA_Passing, CCK_ForBuiltinOverloadedOp);
14213         if (ArgsRes0.isInvalid())
14214           return ExprError();
14215         Args[0] = ArgsRes0.get();
14216 
14217         ExprResult ArgsRes1 = PerformImplicitConversion(
14218             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14219             AA_Passing, CCK_ForBuiltinOverloadedOp);
14220         if (ArgsRes1.isInvalid())
14221           return ExprError();
14222         Args[1] = ArgsRes1.get();
14223         break;
14224       }
14225     }
14226 
14227     case OR_No_Viable_Function: {
14228       // C++ [over.match.oper]p9:
14229       //   If the operator is the operator , [...] and there are no
14230       //   viable functions, then the operator is assumed to be the
14231       //   built-in operator and interpreted according to clause 5.
14232       if (Opc == BO_Comma)
14233         break;
14234 
14235       // When defaulting an 'operator<=>', we can try to synthesize a three-way
14236       // compare result using '==' and '<'.
14237       if (DefaultedFn && Opc == BO_Cmp) {
14238         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14239                                                           Args[1], DefaultedFn);
14240         if (E.isInvalid() || E.isUsable())
14241           return E;
14242       }
14243 
14244       // For class as left operand for assignment or compound assignment
14245       // operator do not fall through to handling in built-in, but report that
14246       // no overloaded assignment operator found
14247       ExprResult Result = ExprError();
14248       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14249       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14250                                                    Args, OpLoc);
14251       DeferDiagsRAII DDR(*this,
14252                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14253       if (Args[0]->getType()->isRecordType() &&
14254           Opc >= BO_Assign && Opc <= BO_OrAssign) {
14255         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14256              << BinaryOperator::getOpcodeStr(Opc)
14257              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14258         if (Args[0]->getType()->isIncompleteType()) {
14259           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14260             << Args[0]->getType()
14261             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14262         }
14263       } else {
14264         // This is an erroneous use of an operator which can be overloaded by
14265         // a non-member function. Check for non-member operators which were
14266         // defined too late to be candidates.
14267         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14268           // FIXME: Recover by calling the found function.
14269           return ExprError();
14270 
14271         // No viable function; try to create a built-in operation, which will
14272         // produce an error. Then, show the non-viable candidates.
14273         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14274       }
14275       assert(Result.isInvalid() &&
14276              "C++ binary operator overloading is missing candidates!");
14277       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14278       return Result;
14279     }
14280 
14281     case OR_Ambiguous:
14282       CandidateSet.NoteCandidates(
14283           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14284                                          << BinaryOperator::getOpcodeStr(Opc)
14285                                          << Args[0]->getType()
14286                                          << Args[1]->getType()
14287                                          << Args[0]->getSourceRange()
14288                                          << Args[1]->getSourceRange()),
14289           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14290           OpLoc);
14291       return ExprError();
14292 
14293     case OR_Deleted:
14294       if (isImplicitlyDeleted(Best->Function)) {
14295         FunctionDecl *DeletedFD = Best->Function;
14296         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14297         if (DFK.isSpecialMember()) {
14298           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14299             << Args[0]->getType() << DFK.asSpecialMember();
14300         } else {
14301           assert(DFK.isComparison());
14302           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14303             << Args[0]->getType() << DeletedFD;
14304         }
14305 
14306         // The user probably meant to call this special member. Just
14307         // explain why it's deleted.
14308         NoteDeletedFunction(DeletedFD);
14309         return ExprError();
14310       }
14311       CandidateSet.NoteCandidates(
14312           PartialDiagnosticAt(
14313               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14314                          << getOperatorSpelling(Best->Function->getDeclName()
14315                                                     .getCXXOverloadedOperator())
14316                          << Args[0]->getSourceRange()
14317                          << Args[1]->getSourceRange()),
14318           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14319           OpLoc);
14320       return ExprError();
14321   }
14322 
14323   // We matched a built-in operator; build it.
14324   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14325 }
14326 
14327 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14328     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14329     FunctionDecl *DefaultedFn) {
14330   const ComparisonCategoryInfo *Info =
14331       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14332   // If we're not producing a known comparison category type, we can't
14333   // synthesize a three-way comparison. Let the caller diagnose this.
14334   if (!Info)
14335     return ExprResult((Expr*)nullptr);
14336 
14337   // If we ever want to perform this synthesis more generally, we will need to
14338   // apply the temporary materialization conversion to the operands.
14339   assert(LHS->isGLValue() && RHS->isGLValue() &&
14340          "cannot use prvalue expressions more than once");
14341   Expr *OrigLHS = LHS;
14342   Expr *OrigRHS = RHS;
14343 
14344   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14345   // each of them multiple times below.
14346   LHS = new (Context)
14347       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14348                       LHS->getObjectKind(), LHS);
14349   RHS = new (Context)
14350       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14351                       RHS->getObjectKind(), RHS);
14352 
14353   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14354                                         DefaultedFn);
14355   if (Eq.isInvalid())
14356     return ExprError();
14357 
14358   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14359                                           true, DefaultedFn);
14360   if (Less.isInvalid())
14361     return ExprError();
14362 
14363   ExprResult Greater;
14364   if (Info->isPartial()) {
14365     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14366                                     DefaultedFn);
14367     if (Greater.isInvalid())
14368       return ExprError();
14369   }
14370 
14371   // Form the list of comparisons we're going to perform.
14372   struct Comparison {
14373     ExprResult Cmp;
14374     ComparisonCategoryResult Result;
14375   } Comparisons[4] =
14376   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14377                           : ComparisonCategoryResult::Equivalent},
14378     {Less, ComparisonCategoryResult::Less},
14379     {Greater, ComparisonCategoryResult::Greater},
14380     {ExprResult(), ComparisonCategoryResult::Unordered},
14381   };
14382 
14383   int I = Info->isPartial() ? 3 : 2;
14384 
14385   // Combine the comparisons with suitable conditional expressions.
14386   ExprResult Result;
14387   for (; I >= 0; --I) {
14388     // Build a reference to the comparison category constant.
14389     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14390     // FIXME: Missing a constant for a comparison category. Diagnose this?
14391     if (!VI)
14392       return ExprResult((Expr*)nullptr);
14393     ExprResult ThisResult =
14394         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14395     if (ThisResult.isInvalid())
14396       return ExprError();
14397 
14398     // Build a conditional unless this is the final case.
14399     if (Result.get()) {
14400       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14401                                   ThisResult.get(), Result.get());
14402       if (Result.isInvalid())
14403         return ExprError();
14404     } else {
14405       Result = ThisResult;
14406     }
14407   }
14408 
14409   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14410   // bind the OpaqueValueExprs before they're (repeatedly) used.
14411   Expr *SyntacticForm = BinaryOperator::Create(
14412       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14413       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14414       CurFPFeatureOverrides());
14415   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14416   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14417 }
14418 
14419 static bool PrepareArgumentsForCallToObjectOfClassType(
14420     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14421     MultiExprArg Args, SourceLocation LParenLoc) {
14422 
14423   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14424   unsigned NumParams = Proto->getNumParams();
14425   unsigned NumArgsSlots =
14426       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14427   // Build the full argument list for the method call (the implicit object
14428   // parameter is placed at the beginning of the list).
14429   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14430   bool IsError = false;
14431   // Initialize the implicit object parameter.
14432   // Check the argument types.
14433   for (unsigned i = 0; i != NumParams; i++) {
14434     Expr *Arg;
14435     if (i < Args.size()) {
14436       Arg = Args[i];
14437       ExprResult InputInit =
14438           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14439                                           S.Context, Method->getParamDecl(i)),
14440                                       SourceLocation(), Arg);
14441       IsError |= InputInit.isInvalid();
14442       Arg = InputInit.getAs<Expr>();
14443     } else {
14444       ExprResult DefArg =
14445           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14446       if (DefArg.isInvalid()) {
14447         IsError = true;
14448         break;
14449       }
14450       Arg = DefArg.getAs<Expr>();
14451     }
14452 
14453     MethodArgs.push_back(Arg);
14454   }
14455   return IsError;
14456 }
14457 
14458 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14459                                                     SourceLocation RLoc,
14460                                                     Expr *Base,
14461                                                     MultiExprArg ArgExpr) {
14462   SmallVector<Expr *, 2> Args;
14463   Args.push_back(Base);
14464   for (auto *e : ArgExpr) {
14465     Args.push_back(e);
14466   }
14467   DeclarationName OpName =
14468       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14469 
14470   SourceRange Range = ArgExpr.empty()
14471                           ? SourceRange{}
14472                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14473                                         ArgExpr.back()->getEndLoc());
14474 
14475   // If either side is type-dependent, create an appropriate dependent
14476   // expression.
14477   if (Expr::hasAnyTypeDependentArguments(Args)) {
14478 
14479     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14480     // CHECKME: no 'operator' keyword?
14481     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14482     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14483     ExprResult Fn = CreateUnresolvedLookupExpr(
14484         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14485     if (Fn.isInvalid())
14486       return ExprError();
14487     // Can't add any actual overloads yet
14488 
14489     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14490                                        Context.DependentTy, VK_PRValue, RLoc,
14491                                        CurFPFeatureOverrides());
14492   }
14493 
14494   // Handle placeholders
14495   UnbridgedCastsSet UnbridgedCasts;
14496   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14497     return ExprError();
14498   }
14499   // Build an empty overload set.
14500   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14501 
14502   // Subscript can only be overloaded as a member function.
14503 
14504   // Add operator candidates that are member functions.
14505   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14506 
14507   // Add builtin operator candidates.
14508   if (Args.size() == 2)
14509     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14510 
14511   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14512 
14513   // Perform overload resolution.
14514   OverloadCandidateSet::iterator Best;
14515   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14516     case OR_Success: {
14517       // We found a built-in operator or an overloaded operator.
14518       FunctionDecl *FnDecl = Best->Function;
14519 
14520       if (FnDecl) {
14521         // We matched an overloaded operator. Build a call to that
14522         // operator.
14523 
14524         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14525 
14526         // Convert the arguments.
14527         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14528         SmallVector<Expr *, 2> MethodArgs;
14529 
14530         // Handle 'this' parameter if the selected function is not static.
14531         if (Method->isInstance()) {
14532           ExprResult Arg0 = PerformObjectArgumentInitialization(
14533               Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14534           if (Arg0.isInvalid())
14535             return ExprError();
14536 
14537           MethodArgs.push_back(Arg0.get());
14538         }
14539 
14540         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14541             *this, MethodArgs, Method, ArgExpr, LLoc);
14542         if (IsError)
14543           return ExprError();
14544 
14545         // Build the actual expression node.
14546         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14547         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14548         ExprResult FnExpr = CreateFunctionRefExpr(
14549             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14550             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14551         if (FnExpr.isInvalid())
14552           return ExprError();
14553 
14554         // Determine the result type
14555         QualType ResultTy = FnDecl->getReturnType();
14556         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14557         ResultTy = ResultTy.getNonLValueExprType(Context);
14558 
14559         CallExpr *TheCall;
14560         if (Method->isInstance())
14561           TheCall = CXXOperatorCallExpr::Create(
14562               Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK,
14563               RLoc, CurFPFeatureOverrides());
14564         else
14565           TheCall =
14566               CallExpr::Create(Context, FnExpr.get(), MethodArgs, ResultTy, VK,
14567                                RLoc, CurFPFeatureOverrides());
14568 
14569         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14570           return ExprError();
14571 
14572         if (CheckFunctionCall(Method, TheCall,
14573                               Method->getType()->castAs<FunctionProtoType>()))
14574           return ExprError();
14575 
14576         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14577                                            FnDecl);
14578       } else {
14579         // We matched a built-in operator. Convert the arguments, then
14580         // break out so that we will build the appropriate built-in
14581         // operator node.
14582         ExprResult ArgsRes0 = PerformImplicitConversion(
14583             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14584             AA_Passing, CCK_ForBuiltinOverloadedOp);
14585         if (ArgsRes0.isInvalid())
14586           return ExprError();
14587         Args[0] = ArgsRes0.get();
14588 
14589         ExprResult ArgsRes1 = PerformImplicitConversion(
14590             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14591             AA_Passing, CCK_ForBuiltinOverloadedOp);
14592         if (ArgsRes1.isInvalid())
14593           return ExprError();
14594         Args[1] = ArgsRes1.get();
14595 
14596         break;
14597       }
14598     }
14599 
14600     case OR_No_Viable_Function: {
14601       PartialDiagnostic PD =
14602           CandidateSet.empty()
14603               ? (PDiag(diag::err_ovl_no_oper)
14604                  << Args[0]->getType() << /*subscript*/ 0
14605                  << Args[0]->getSourceRange() << Range)
14606               : (PDiag(diag::err_ovl_no_viable_subscript)
14607                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14608       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14609                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14610       return ExprError();
14611     }
14612 
14613     case OR_Ambiguous:
14614       if (Args.size() == 2) {
14615         CandidateSet.NoteCandidates(
14616             PartialDiagnosticAt(
14617                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14618                           << "[]" << Args[0]->getType() << Args[1]->getType()
14619                           << Args[0]->getSourceRange() << Range),
14620             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14621       } else {
14622         CandidateSet.NoteCandidates(
14623             PartialDiagnosticAt(LLoc,
14624                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14625                                     << Args[0]->getType()
14626                                     << Args[0]->getSourceRange() << Range),
14627             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14628       }
14629       return ExprError();
14630 
14631     case OR_Deleted:
14632       CandidateSet.NoteCandidates(
14633           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14634                                         << "[]" << Args[0]->getSourceRange()
14635                                         << Range),
14636           *this, OCD_AllCandidates, Args, "[]", LLoc);
14637       return ExprError();
14638     }
14639 
14640   // We matched a built-in operator; build it.
14641   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14642 }
14643 
14644 /// BuildCallToMemberFunction - Build a call to a member
14645 /// function. MemExpr is the expression that refers to the member
14646 /// function (and includes the object parameter), Args/NumArgs are the
14647 /// arguments to the function call (not including the object
14648 /// parameter). The caller needs to validate that the member
14649 /// expression refers to a non-static member function or an overloaded
14650 /// member function.
14651 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14652                                            SourceLocation LParenLoc,
14653                                            MultiExprArg Args,
14654                                            SourceLocation RParenLoc,
14655                                            Expr *ExecConfig, bool IsExecConfig,
14656                                            bool AllowRecovery) {
14657   assert(MemExprE->getType() == Context.BoundMemberTy ||
14658          MemExprE->getType() == Context.OverloadTy);
14659 
14660   // Dig out the member expression. This holds both the object
14661   // argument and the member function we're referring to.
14662   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14663 
14664   // Determine whether this is a call to a pointer-to-member function.
14665   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14666     assert(op->getType() == Context.BoundMemberTy);
14667     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14668 
14669     QualType fnType =
14670       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14671 
14672     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14673     QualType resultType = proto->getCallResultType(Context);
14674     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14675 
14676     // Check that the object type isn't more qualified than the
14677     // member function we're calling.
14678     Qualifiers funcQuals = proto->getMethodQuals();
14679 
14680     QualType objectType = op->getLHS()->getType();
14681     if (op->getOpcode() == BO_PtrMemI)
14682       objectType = objectType->castAs<PointerType>()->getPointeeType();
14683     Qualifiers objectQuals = objectType.getQualifiers();
14684 
14685     Qualifiers difference = objectQuals - funcQuals;
14686     difference.removeObjCGCAttr();
14687     difference.removeAddressSpace();
14688     if (difference) {
14689       std::string qualsString = difference.getAsString();
14690       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14691         << fnType.getUnqualifiedType()
14692         << qualsString
14693         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14694     }
14695 
14696     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14697         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14698         CurFPFeatureOverrides(), proto->getNumParams());
14699 
14700     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14701                             call, nullptr))
14702       return ExprError();
14703 
14704     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14705       return ExprError();
14706 
14707     if (CheckOtherCall(call, proto))
14708       return ExprError();
14709 
14710     return MaybeBindToTemporary(call);
14711   }
14712 
14713   // We only try to build a recovery expr at this level if we can preserve
14714   // the return type, otherwise we return ExprError() and let the caller
14715   // recover.
14716   auto BuildRecoveryExpr = [&](QualType Type) {
14717     if (!AllowRecovery)
14718       return ExprError();
14719     std::vector<Expr *> SubExprs = {MemExprE};
14720     llvm::append_range(SubExprs, Args);
14721     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14722                               Type);
14723   };
14724   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14725     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14726                             RParenLoc, CurFPFeatureOverrides());
14727 
14728   UnbridgedCastsSet UnbridgedCasts;
14729   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14730     return ExprError();
14731 
14732   MemberExpr *MemExpr;
14733   CXXMethodDecl *Method = nullptr;
14734   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14735   NestedNameSpecifier *Qualifier = nullptr;
14736   if (isa<MemberExpr>(NakedMemExpr)) {
14737     MemExpr = cast<MemberExpr>(NakedMemExpr);
14738     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14739     FoundDecl = MemExpr->getFoundDecl();
14740     Qualifier = MemExpr->getQualifier();
14741     UnbridgedCasts.restore();
14742   } else {
14743     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14744     Qualifier = UnresExpr->getQualifier();
14745 
14746     QualType ObjectType = UnresExpr->getBaseType();
14747     Expr::Classification ObjectClassification
14748       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14749                             : UnresExpr->getBase()->Classify(Context);
14750 
14751     // Add overload candidates
14752     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14753                                       OverloadCandidateSet::CSK_Normal);
14754 
14755     // FIXME: avoid copy.
14756     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14757     if (UnresExpr->hasExplicitTemplateArgs()) {
14758       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14759       TemplateArgs = &TemplateArgsBuffer;
14760     }
14761 
14762     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14763            E = UnresExpr->decls_end(); I != E; ++I) {
14764 
14765       NamedDecl *Func = *I;
14766       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14767       if (isa<UsingShadowDecl>(Func))
14768         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14769 
14770 
14771       // Microsoft supports direct constructor calls.
14772       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14773         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14774                              CandidateSet,
14775                              /*SuppressUserConversions*/ false);
14776       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14777         // If explicit template arguments were provided, we can't call a
14778         // non-template member function.
14779         if (TemplateArgs)
14780           continue;
14781 
14782         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14783                            ObjectClassification, Args, CandidateSet,
14784                            /*SuppressUserConversions=*/false);
14785       } else {
14786         AddMethodTemplateCandidate(
14787             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14788             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14789             /*SuppressUserConversions=*/false);
14790       }
14791     }
14792 
14793     DeclarationName DeclName = UnresExpr->getMemberName();
14794 
14795     UnbridgedCasts.restore();
14796 
14797     OverloadCandidateSet::iterator Best;
14798     bool Succeeded = false;
14799     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14800                                             Best)) {
14801     case OR_Success:
14802       Method = cast<CXXMethodDecl>(Best->Function);
14803       FoundDecl = Best->FoundDecl;
14804       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14805       if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14806         break;
14807       // If FoundDecl is different from Method (such as if one is a template
14808       // and the other a specialization), make sure DiagnoseUseOfDecl is
14809       // called on both.
14810       // FIXME: This would be more comprehensively addressed by modifying
14811       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14812       // being used.
14813       if (Method != FoundDecl.getDecl() &&
14814           DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
14815         break;
14816       Succeeded = true;
14817       break;
14818 
14819     case OR_No_Viable_Function:
14820       CandidateSet.NoteCandidates(
14821           PartialDiagnosticAt(
14822               UnresExpr->getMemberLoc(),
14823               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14824                   << DeclName << MemExprE->getSourceRange()),
14825           *this, OCD_AllCandidates, Args);
14826       break;
14827     case OR_Ambiguous:
14828       CandidateSet.NoteCandidates(
14829           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14830                               PDiag(diag::err_ovl_ambiguous_member_call)
14831                                   << DeclName << MemExprE->getSourceRange()),
14832           *this, OCD_AmbiguousCandidates, Args);
14833       break;
14834     case OR_Deleted:
14835       CandidateSet.NoteCandidates(
14836           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14837                               PDiag(diag::err_ovl_deleted_member_call)
14838                                   << DeclName << MemExprE->getSourceRange()),
14839           *this, OCD_AllCandidates, Args);
14840       break;
14841     }
14842     // Overload resolution fails, try to recover.
14843     if (!Succeeded)
14844       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14845 
14846     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14847 
14848     // If overload resolution picked a static member, build a
14849     // non-member call based on that function.
14850     if (Method->isStatic()) {
14851       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14852                                    ExecConfig, IsExecConfig);
14853     }
14854 
14855     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14856   }
14857 
14858   QualType ResultType = Method->getReturnType();
14859   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14860   ResultType = ResultType.getNonLValueExprType(Context);
14861 
14862   assert(Method && "Member call to something that isn't a method?");
14863   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14864   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14865       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14866       CurFPFeatureOverrides(), Proto->getNumParams());
14867 
14868   // Check for a valid return type.
14869   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14870                           TheCall, Method))
14871     return BuildRecoveryExpr(ResultType);
14872 
14873   // Convert the object argument (for a non-static member function call).
14874   // We only need to do this if there was actually an overload; otherwise
14875   // it was done at lookup.
14876   if (!Method->isStatic()) {
14877     ExprResult ObjectArg =
14878       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14879                                           FoundDecl, Method);
14880     if (ObjectArg.isInvalid())
14881       return ExprError();
14882     MemExpr->setBase(ObjectArg.get());
14883   }
14884 
14885   // Convert the rest of the arguments
14886   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14887                               RParenLoc))
14888     return BuildRecoveryExpr(ResultType);
14889 
14890   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14891 
14892   if (CheckFunctionCall(Method, TheCall, Proto))
14893     return ExprError();
14894 
14895   // In the case the method to call was not selected by the overloading
14896   // resolution process, we still need to handle the enable_if attribute. Do
14897   // that here, so it will not hide previous -- and more relevant -- errors.
14898   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14899     if (const EnableIfAttr *Attr =
14900             CheckEnableIf(Method, LParenLoc, Args, true)) {
14901       Diag(MemE->getMemberLoc(),
14902            diag::err_ovl_no_viable_member_function_in_call)
14903           << Method << Method->getSourceRange();
14904       Diag(Method->getLocation(),
14905            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14906           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14907       return ExprError();
14908     }
14909   }
14910 
14911   if ((isa<CXXConstructorDecl>(CurContext) ||
14912        isa<CXXDestructorDecl>(CurContext)) &&
14913       TheCall->getMethodDecl()->isPure()) {
14914     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14915 
14916     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14917         MemExpr->performsVirtualDispatch(getLangOpts())) {
14918       Diag(MemExpr->getBeginLoc(),
14919            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14920           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14921           << MD->getParent();
14922 
14923       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14924       if (getLangOpts().AppleKext)
14925         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14926             << MD->getParent() << MD->getDeclName();
14927     }
14928   }
14929 
14930   if (CXXDestructorDecl *DD =
14931           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14932     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14933     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14934     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14935                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14936                          MemExpr->getMemberLoc());
14937   }
14938 
14939   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14940                                      TheCall->getMethodDecl());
14941 }
14942 
14943 /// BuildCallToObjectOfClassType - Build a call to an object of class
14944 /// type (C++ [over.call.object]), which can end up invoking an
14945 /// overloaded function call operator (@c operator()) or performing a
14946 /// user-defined conversion on the object argument.
14947 ExprResult
14948 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14949                                    SourceLocation LParenLoc,
14950                                    MultiExprArg Args,
14951                                    SourceLocation RParenLoc) {
14952   if (checkPlaceholderForOverload(*this, Obj))
14953     return ExprError();
14954   ExprResult Object = Obj;
14955 
14956   UnbridgedCastsSet UnbridgedCasts;
14957   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14958     return ExprError();
14959 
14960   assert(Object.get()->getType()->isRecordType() &&
14961          "Requires object type argument");
14962 
14963   // C++ [over.call.object]p1:
14964   //  If the primary-expression E in the function call syntax
14965   //  evaluates to a class object of type "cv T", then the set of
14966   //  candidate functions includes at least the function call
14967   //  operators of T. The function call operators of T are obtained by
14968   //  ordinary lookup of the name operator() in the context of
14969   //  (E).operator().
14970   OverloadCandidateSet CandidateSet(LParenLoc,
14971                                     OverloadCandidateSet::CSK_Operator);
14972   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14973 
14974   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14975                           diag::err_incomplete_object_call, Object.get()))
14976     return true;
14977 
14978   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14979   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14980   LookupQualifiedName(R, Record->getDecl());
14981   R.suppressDiagnostics();
14982 
14983   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14984        Oper != OperEnd; ++Oper) {
14985     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14986                        Object.get()->Classify(Context), Args, CandidateSet,
14987                        /*SuppressUserConversion=*/false);
14988   }
14989 
14990   // When calling a lambda, both the call operator, and
14991   // the conversion operator to function pointer
14992   // are considered. But when constraint checking
14993   // on the call operator fails, it will also fail on the
14994   // conversion operator as the constraints are always the same.
14995   // As the user probably does not intend to perform a surrogate call,
14996   // we filter them out to produce better error diagnostics, ie to avoid
14997   // showing 2 failed overloads instead of one.
14998   bool IgnoreSurrogateFunctions = false;
14999   if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15000     const OverloadCandidate &Candidate = *CandidateSet.begin();
15001     if (!Candidate.Viable &&
15002         Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15003       IgnoreSurrogateFunctions = true;
15004   }
15005 
15006   // C++ [over.call.object]p2:
15007   //   In addition, for each (non-explicit in C++0x) conversion function
15008   //   declared in T of the form
15009   //
15010   //        operator conversion-type-id () cv-qualifier;
15011   //
15012   //   where cv-qualifier is the same cv-qualification as, or a
15013   //   greater cv-qualification than, cv, and where conversion-type-id
15014   //   denotes the type "pointer to function of (P1,...,Pn) returning
15015   //   R", or the type "reference to pointer to function of
15016   //   (P1,...,Pn) returning R", or the type "reference to function
15017   //   of (P1,...,Pn) returning R", a surrogate call function [...]
15018   //   is also considered as a candidate function. Similarly,
15019   //   surrogate call functions are added to the set of candidate
15020   //   functions for each conversion function declared in an
15021   //   accessible base class provided the function is not hidden
15022   //   within T by another intervening declaration.
15023   const auto &Conversions =
15024       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15025   for (auto I = Conversions.begin(), E = Conversions.end();
15026        !IgnoreSurrogateFunctions && I != E; ++I) {
15027     NamedDecl *D = *I;
15028     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15029     if (isa<UsingShadowDecl>(D))
15030       D = cast<UsingShadowDecl>(D)->getTargetDecl();
15031 
15032     // Skip over templated conversion functions; they aren't
15033     // surrogates.
15034     if (isa<FunctionTemplateDecl>(D))
15035       continue;
15036 
15037     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15038     if (!Conv->isExplicit()) {
15039       // Strip the reference type (if any) and then the pointer type (if
15040       // any) to get down to what might be a function type.
15041       QualType ConvType = Conv->getConversionType().getNonReferenceType();
15042       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15043         ConvType = ConvPtrType->getPointeeType();
15044 
15045       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15046       {
15047         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15048                               Object.get(), Args, CandidateSet);
15049       }
15050     }
15051   }
15052 
15053   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15054 
15055   // Perform overload resolution.
15056   OverloadCandidateSet::iterator Best;
15057   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15058                                           Best)) {
15059   case OR_Success:
15060     // Overload resolution succeeded; we'll build the appropriate call
15061     // below.
15062     break;
15063 
15064   case OR_No_Viable_Function: {
15065     PartialDiagnostic PD =
15066         CandidateSet.empty()
15067             ? (PDiag(diag::err_ovl_no_oper)
15068                << Object.get()->getType() << /*call*/ 1
15069                << Object.get()->getSourceRange())
15070             : (PDiag(diag::err_ovl_no_viable_object_call)
15071                << Object.get()->getType() << Object.get()->getSourceRange());
15072     CandidateSet.NoteCandidates(
15073         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15074         OCD_AllCandidates, Args);
15075     break;
15076   }
15077   case OR_Ambiguous:
15078     CandidateSet.NoteCandidates(
15079         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15080                             PDiag(diag::err_ovl_ambiguous_object_call)
15081                                 << Object.get()->getType()
15082                                 << Object.get()->getSourceRange()),
15083         *this, OCD_AmbiguousCandidates, Args);
15084     break;
15085 
15086   case OR_Deleted:
15087     CandidateSet.NoteCandidates(
15088         PartialDiagnosticAt(Object.get()->getBeginLoc(),
15089                             PDiag(diag::err_ovl_deleted_object_call)
15090                                 << Object.get()->getType()
15091                                 << Object.get()->getSourceRange()),
15092         *this, OCD_AllCandidates, Args);
15093     break;
15094   }
15095 
15096   if (Best == CandidateSet.end())
15097     return true;
15098 
15099   UnbridgedCasts.restore();
15100 
15101   if (Best->Function == nullptr) {
15102     // Since there is no function declaration, this is one of the
15103     // surrogate candidates. Dig out the conversion function.
15104     CXXConversionDecl *Conv
15105       = cast<CXXConversionDecl>(
15106                          Best->Conversions[0].UserDefined.ConversionFunction);
15107 
15108     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15109                               Best->FoundDecl);
15110     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15111       return ExprError();
15112     assert(Conv == Best->FoundDecl.getDecl() &&
15113              "Found Decl & conversion-to-functionptr should be same, right?!");
15114     // We selected one of the surrogate functions that converts the
15115     // object parameter to a function pointer. Perform the conversion
15116     // on the object argument, then let BuildCallExpr finish the job.
15117 
15118     // Create an implicit member expr to refer to the conversion operator.
15119     // and then call it.
15120     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15121                                              Conv, HadMultipleCandidates);
15122     if (Call.isInvalid())
15123       return ExprError();
15124     // Record usage of conversion in an implicit cast.
15125     Call = ImplicitCastExpr::Create(
15126         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15127         nullptr, VK_PRValue, CurFPFeatureOverrides());
15128 
15129     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15130   }
15131 
15132   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15133 
15134   // We found an overloaded operator(). Build a CXXOperatorCallExpr
15135   // that calls this method, using Object for the implicit object
15136   // parameter and passing along the remaining arguments.
15137   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15138 
15139   // An error diagnostic has already been printed when parsing the declaration.
15140   if (Method->isInvalidDecl())
15141     return ExprError();
15142 
15143   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15144   unsigned NumParams = Proto->getNumParams();
15145 
15146   DeclarationNameInfo OpLocInfo(
15147                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15148   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15149   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15150                                            Obj, HadMultipleCandidates,
15151                                            OpLocInfo.getLoc(),
15152                                            OpLocInfo.getInfo());
15153   if (NewFn.isInvalid())
15154     return true;
15155 
15156   SmallVector<Expr *, 8> MethodArgs;
15157   MethodArgs.reserve(NumParams + 1);
15158 
15159   bool IsError = false;
15160 
15161   // Initialize the implicit object parameter if needed.
15162   // Since C++23, this could also be a call to a static call operator
15163   // which we emit as a regular CallExpr.
15164   if (Method->isInstance()) {
15165     ExprResult ObjRes = PerformObjectArgumentInitialization(
15166         Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15167     if (ObjRes.isInvalid())
15168       IsError = true;
15169     else
15170       Object = ObjRes;
15171     MethodArgs.push_back(Object.get());
15172   }
15173 
15174   IsError |= PrepareArgumentsForCallToObjectOfClassType(
15175       *this, MethodArgs, Method, Args, LParenLoc);
15176 
15177   // If this is a variadic call, handle args passed through "...".
15178   if (Proto->isVariadic()) {
15179     // Promote the arguments (C99 6.5.2.2p7).
15180     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15181       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15182                                                         nullptr);
15183       IsError |= Arg.isInvalid();
15184       MethodArgs.push_back(Arg.get());
15185     }
15186   }
15187 
15188   if (IsError)
15189     return true;
15190 
15191   DiagnoseSentinelCalls(Method, LParenLoc, Args);
15192 
15193   // Once we've built TheCall, all of the expressions are properly owned.
15194   QualType ResultTy = Method->getReturnType();
15195   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15196   ResultTy = ResultTy.getNonLValueExprType(Context);
15197 
15198   CallExpr *TheCall;
15199   if (Method->isInstance())
15200     TheCall = CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(),
15201                                           MethodArgs, ResultTy, VK, RParenLoc,
15202                                           CurFPFeatureOverrides());
15203   else
15204     TheCall = CallExpr::Create(Context, NewFn.get(), MethodArgs, ResultTy, VK,
15205                                RParenLoc, CurFPFeatureOverrides());
15206 
15207   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15208     return true;
15209 
15210   if (CheckFunctionCall(Method, TheCall, Proto))
15211     return true;
15212 
15213   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15214 }
15215 
15216 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15217 ///  (if one exists), where @c Base is an expression of class type and
15218 /// @c Member is the name of the member we're trying to find.
15219 ExprResult
15220 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15221                                bool *NoArrowOperatorFound) {
15222   assert(Base->getType()->isRecordType() &&
15223          "left-hand side must have class type");
15224 
15225   if (checkPlaceholderForOverload(*this, Base))
15226     return ExprError();
15227 
15228   SourceLocation Loc = Base->getExprLoc();
15229 
15230   // C++ [over.ref]p1:
15231   //
15232   //   [...] An expression x->m is interpreted as (x.operator->())->m
15233   //   for a class object x of type T if T::operator->() exists and if
15234   //   the operator is selected as the best match function by the
15235   //   overload resolution mechanism (13.3).
15236   DeclarationName OpName =
15237     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15238   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15239 
15240   if (RequireCompleteType(Loc, Base->getType(),
15241                           diag::err_typecheck_incomplete_tag, Base))
15242     return ExprError();
15243 
15244   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15245   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15246   R.suppressDiagnostics();
15247 
15248   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15249        Oper != OperEnd; ++Oper) {
15250     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15251                        std::nullopt, CandidateSet,
15252                        /*SuppressUserConversion=*/false);
15253   }
15254 
15255   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15256 
15257   // Perform overload resolution.
15258   OverloadCandidateSet::iterator Best;
15259   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15260   case OR_Success:
15261     // Overload resolution succeeded; we'll build the call below.
15262     break;
15263 
15264   case OR_No_Viable_Function: {
15265     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15266     if (CandidateSet.empty()) {
15267       QualType BaseType = Base->getType();
15268       if (NoArrowOperatorFound) {
15269         // Report this specific error to the caller instead of emitting a
15270         // diagnostic, as requested.
15271         *NoArrowOperatorFound = true;
15272         return ExprError();
15273       }
15274       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15275         << BaseType << Base->getSourceRange();
15276       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15277         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15278           << FixItHint::CreateReplacement(OpLoc, ".");
15279       }
15280     } else
15281       Diag(OpLoc, diag::err_ovl_no_viable_oper)
15282         << "operator->" << Base->getSourceRange();
15283     CandidateSet.NoteCandidates(*this, Base, Cands);
15284     return ExprError();
15285   }
15286   case OR_Ambiguous:
15287     CandidateSet.NoteCandidates(
15288         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15289                                        << "->" << Base->getType()
15290                                        << Base->getSourceRange()),
15291         *this, OCD_AmbiguousCandidates, Base);
15292     return ExprError();
15293 
15294   case OR_Deleted:
15295     CandidateSet.NoteCandidates(
15296         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15297                                        << "->" << Base->getSourceRange()),
15298         *this, OCD_AllCandidates, Base);
15299     return ExprError();
15300   }
15301 
15302   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15303 
15304   // Convert the object parameter.
15305   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15306   ExprResult BaseResult =
15307     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15308                                         Best->FoundDecl, Method);
15309   if (BaseResult.isInvalid())
15310     return ExprError();
15311   Base = BaseResult.get();
15312 
15313   // Build the operator call.
15314   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15315                                             Base, HadMultipleCandidates, OpLoc);
15316   if (FnExpr.isInvalid())
15317     return ExprError();
15318 
15319   QualType ResultTy = Method->getReturnType();
15320   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15321   ResultTy = ResultTy.getNonLValueExprType(Context);
15322   CXXOperatorCallExpr *TheCall =
15323       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15324                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15325 
15326   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15327     return ExprError();
15328 
15329   if (CheckFunctionCall(Method, TheCall,
15330                         Method->getType()->castAs<FunctionProtoType>()))
15331     return ExprError();
15332 
15333   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15334 }
15335 
15336 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15337 /// a literal operator described by the provided lookup results.
15338 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15339                                           DeclarationNameInfo &SuffixInfo,
15340                                           ArrayRef<Expr*> Args,
15341                                           SourceLocation LitEndLoc,
15342                                        TemplateArgumentListInfo *TemplateArgs) {
15343   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15344 
15345   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15346                                     OverloadCandidateSet::CSK_Normal);
15347   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15348                                  TemplateArgs);
15349 
15350   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15351 
15352   // Perform overload resolution. This will usually be trivial, but might need
15353   // to perform substitutions for a literal operator template.
15354   OverloadCandidateSet::iterator Best;
15355   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15356   case OR_Success:
15357   case OR_Deleted:
15358     break;
15359 
15360   case OR_No_Viable_Function:
15361     CandidateSet.NoteCandidates(
15362         PartialDiagnosticAt(UDSuffixLoc,
15363                             PDiag(diag::err_ovl_no_viable_function_in_call)
15364                                 << R.getLookupName()),
15365         *this, OCD_AllCandidates, Args);
15366     return ExprError();
15367 
15368   case OR_Ambiguous:
15369     CandidateSet.NoteCandidates(
15370         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15371                                                 << R.getLookupName()),
15372         *this, OCD_AmbiguousCandidates, Args);
15373     return ExprError();
15374   }
15375 
15376   FunctionDecl *FD = Best->Function;
15377   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15378                                         nullptr, HadMultipleCandidates,
15379                                         SuffixInfo.getLoc(),
15380                                         SuffixInfo.getInfo());
15381   if (Fn.isInvalid())
15382     return true;
15383 
15384   // Check the argument types. This should almost always be a no-op, except
15385   // that array-to-pointer decay is applied to string literals.
15386   Expr *ConvArgs[2];
15387   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15388     ExprResult InputInit = PerformCopyInitialization(
15389       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15390       SourceLocation(), Args[ArgIdx]);
15391     if (InputInit.isInvalid())
15392       return true;
15393     ConvArgs[ArgIdx] = InputInit.get();
15394   }
15395 
15396   QualType ResultTy = FD->getReturnType();
15397   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15398   ResultTy = ResultTy.getNonLValueExprType(Context);
15399 
15400   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15401       Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
15402       LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15403 
15404   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15405     return ExprError();
15406 
15407   if (CheckFunctionCall(FD, UDL, nullptr))
15408     return ExprError();
15409 
15410   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15411 }
15412 
15413 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15414 /// given LookupResult is non-empty, it is assumed to describe a member which
15415 /// will be invoked. Otherwise, the function will be found via argument
15416 /// dependent lookup.
15417 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15418 /// otherwise CallExpr is set to ExprError() and some non-success value
15419 /// is returned.
15420 Sema::ForRangeStatus
15421 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15422                                 SourceLocation RangeLoc,
15423                                 const DeclarationNameInfo &NameInfo,
15424                                 LookupResult &MemberLookup,
15425                                 OverloadCandidateSet *CandidateSet,
15426                                 Expr *Range, ExprResult *CallExpr) {
15427   Scope *S = nullptr;
15428 
15429   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15430   if (!MemberLookup.empty()) {
15431     ExprResult MemberRef =
15432         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15433                                  /*IsPtr=*/false, CXXScopeSpec(),
15434                                  /*TemplateKWLoc=*/SourceLocation(),
15435                                  /*FirstQualifierInScope=*/nullptr,
15436                                  MemberLookup,
15437                                  /*TemplateArgs=*/nullptr, S);
15438     if (MemberRef.isInvalid()) {
15439       *CallExpr = ExprError();
15440       return FRS_DiagnosticIssued;
15441     }
15442     *CallExpr =
15443         BuildCallExpr(S, MemberRef.get(), Loc, std::nullopt, Loc, nullptr);
15444     if (CallExpr->isInvalid()) {
15445       *CallExpr = ExprError();
15446       return FRS_DiagnosticIssued;
15447     }
15448   } else {
15449     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15450                                                 NestedNameSpecifierLoc(),
15451                                                 NameInfo, UnresolvedSet<0>());
15452     if (FnR.isInvalid())
15453       return FRS_DiagnosticIssued;
15454     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15455 
15456     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15457                                                     CandidateSet, CallExpr);
15458     if (CandidateSet->empty() || CandidateSetError) {
15459       *CallExpr = ExprError();
15460       return FRS_NoViableFunction;
15461     }
15462     OverloadCandidateSet::iterator Best;
15463     OverloadingResult OverloadResult =
15464         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15465 
15466     if (OverloadResult == OR_No_Viable_Function) {
15467       *CallExpr = ExprError();
15468       return FRS_NoViableFunction;
15469     }
15470     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15471                                          Loc, nullptr, CandidateSet, &Best,
15472                                          OverloadResult,
15473                                          /*AllowTypoCorrection=*/false);
15474     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15475       *CallExpr = ExprError();
15476       return FRS_DiagnosticIssued;
15477     }
15478   }
15479   return FRS_Success;
15480 }
15481 
15482 
15483 /// FixOverloadedFunctionReference - E is an expression that refers to
15484 /// a C++ overloaded function (possibly with some parentheses and
15485 /// perhaps a '&' around it). We have resolved the overloaded function
15486 /// to the function declaration Fn, so patch up the expression E to
15487 /// refer (possibly indirectly) to Fn. Returns the new expr.
15488 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15489                                            FunctionDecl *Fn) {
15490   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15491     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15492                                                    Found, Fn);
15493     if (SubExpr == PE->getSubExpr())
15494       return PE;
15495 
15496     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15497   }
15498 
15499   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15500     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15501                                                    Found, Fn);
15502     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15503                                SubExpr->getType()) &&
15504            "Implicit cast type cannot be determined from overload");
15505     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15506     if (SubExpr == ICE->getSubExpr())
15507       return ICE;
15508 
15509     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15510                                     SubExpr, nullptr, ICE->getValueKind(),
15511                                     CurFPFeatureOverrides());
15512   }
15513 
15514   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15515     if (!GSE->isResultDependent()) {
15516       Expr *SubExpr =
15517           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15518       if (SubExpr == GSE->getResultExpr())
15519         return GSE;
15520 
15521       // Replace the resulting type information before rebuilding the generic
15522       // selection expression.
15523       ArrayRef<Expr *> A = GSE->getAssocExprs();
15524       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15525       unsigned ResultIdx = GSE->getResultIndex();
15526       AssocExprs[ResultIdx] = SubExpr;
15527 
15528       if (GSE->isExprPredicate())
15529         return GenericSelectionExpr::Create(
15530             Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15531             GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15532             GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15533             ResultIdx);
15534       return GenericSelectionExpr::Create(
15535           Context, GSE->getGenericLoc(), GSE->getControllingType(),
15536           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15537           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15538           ResultIdx);
15539     }
15540     // Rather than fall through to the unreachable, return the original generic
15541     // selection expression.
15542     return GSE;
15543   }
15544 
15545   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15546     assert(UnOp->getOpcode() == UO_AddrOf &&
15547            "Can only take the address of an overloaded function");
15548     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15549       if (Method->isStatic()) {
15550         // Do nothing: static member functions aren't any different
15551         // from non-member functions.
15552       } else {
15553         // Fix the subexpression, which really has to be an
15554         // UnresolvedLookupExpr holding an overloaded member function
15555         // or template.
15556         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15557                                                        Found, Fn);
15558         if (SubExpr == UnOp->getSubExpr())
15559           return UnOp;
15560 
15561         assert(isa<DeclRefExpr>(SubExpr)
15562                && "fixed to something other than a decl ref");
15563         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15564                && "fixed to a member ref with no nested name qualifier");
15565 
15566         // We have taken the address of a pointer to member
15567         // function. Perform the computation here so that we get the
15568         // appropriate pointer to member type.
15569         QualType ClassType
15570           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15571         QualType MemPtrType
15572           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15573         // Under the MS ABI, lock down the inheritance model now.
15574         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15575           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15576 
15577         return UnaryOperator::Create(
15578             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15579             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15580       }
15581     }
15582     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15583                                                    Found, Fn);
15584     if (SubExpr == UnOp->getSubExpr())
15585       return UnOp;
15586 
15587     // FIXME: This can't currently fail, but in principle it could.
15588     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15589         .get();
15590   }
15591 
15592   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15593     // FIXME: avoid copy.
15594     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15595     if (ULE->hasExplicitTemplateArgs()) {
15596       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15597       TemplateArgs = &TemplateArgsBuffer;
15598     }
15599 
15600     QualType Type = Fn->getType();
15601     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15602 
15603     // FIXME: Duplicated from BuildDeclarationNameExpr.
15604     if (unsigned BID = Fn->getBuiltinID()) {
15605       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15606         Type = Context.BuiltinFnTy;
15607         ValueKind = VK_PRValue;
15608       }
15609     }
15610 
15611     DeclRefExpr *DRE = BuildDeclRefExpr(
15612         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15613         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15614     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15615     return DRE;
15616   }
15617 
15618   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15619     // FIXME: avoid copy.
15620     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15621     if (MemExpr->hasExplicitTemplateArgs()) {
15622       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15623       TemplateArgs = &TemplateArgsBuffer;
15624     }
15625 
15626     Expr *Base;
15627 
15628     // If we're filling in a static method where we used to have an
15629     // implicit member access, rewrite to a simple decl ref.
15630     if (MemExpr->isImplicitAccess()) {
15631       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15632         DeclRefExpr *DRE = BuildDeclRefExpr(
15633             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15634             MemExpr->getQualifierLoc(), Found.getDecl(),
15635             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15636         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15637         return DRE;
15638       } else {
15639         SourceLocation Loc = MemExpr->getMemberLoc();
15640         if (MemExpr->getQualifier())
15641           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15642         Base =
15643             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15644       }
15645     } else
15646       Base = MemExpr->getBase();
15647 
15648     ExprValueKind valueKind;
15649     QualType type;
15650     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15651       valueKind = VK_LValue;
15652       type = Fn->getType();
15653     } else {
15654       valueKind = VK_PRValue;
15655       type = Context.BoundMemberTy;
15656     }
15657 
15658     return BuildMemberExpr(
15659         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15660         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15661         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15662         type, valueKind, OK_Ordinary, TemplateArgs);
15663   }
15664 
15665   llvm_unreachable("Invalid reference to overloaded function");
15666 }
15667 
15668 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15669                                                 DeclAccessPair Found,
15670                                                 FunctionDecl *Fn) {
15671   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15672 }
15673 
15674 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15675                                   FunctionDecl *Function) {
15676   if (!PartialOverloading || !Function)
15677     return true;
15678   if (Function->isVariadic())
15679     return false;
15680   if (const auto *Proto =
15681           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15682     if (Proto->isTemplateVariadic())
15683       return false;
15684   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15685     if (const auto *Proto =
15686             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15687       if (Proto->isTemplateVariadic())
15688         return false;
15689   return true;
15690 }
15691