1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
43 using AllowedExplicit = Sema::AllowedExplicit;
44 
45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47     return P->hasAttr<PassObjectSizeAttr>();
48   });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult CreateFunctionRefExpr(
53     Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
54     bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
55     const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
56   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
57     return ExprError();
58   // If FoundDecl is different from Fn (such as if one is a template
59   // and the other a specialization), make sure DiagnoseUseOfDecl is
60   // called on both.
61   // FIXME: This would be more comprehensively addressed by modifying
62   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
63   // being used.
64   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
65     return ExprError();
66   DeclRefExpr *DRE = new (S.Context)
67       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
68   if (HadMultipleCandidates)
69     DRE->setHadMultipleCandidates(true);
70 
71   S.MarkDeclRefReferenced(DRE, Base);
72   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
73     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
74       S.ResolveExceptionSpec(Loc, FPT);
75       DRE->setType(Fn->getType());
76     }
77   }
78   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
79                              CK_FunctionToPointerDecay);
80 }
81 
82 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
83                                  bool InOverloadResolution,
84                                  StandardConversionSequence &SCS,
85                                  bool CStyle,
86                                  bool AllowObjCWritebackConversion);
87 
88 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
89                                                  QualType &ToType,
90                                                  bool InOverloadResolution,
91                                                  StandardConversionSequence &SCS,
92                                                  bool CStyle);
93 static OverloadingResult
94 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
95                         UserDefinedConversionSequence& User,
96                         OverloadCandidateSet& Conversions,
97                         AllowedExplicit AllowExplicit,
98                         bool AllowObjCConversionOnExplicit);
99 
100 static ImplicitConversionSequence::CompareKind
101 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
102                                    const StandardConversionSequence& SCS1,
103                                    const StandardConversionSequence& SCS2);
104 
105 static ImplicitConversionSequence::CompareKind
106 CompareQualificationConversions(Sema &S,
107                                 const StandardConversionSequence& SCS1,
108                                 const StandardConversionSequence& SCS2);
109 
110 static ImplicitConversionSequence::CompareKind
111 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
112                                 const StandardConversionSequence& SCS1,
113                                 const StandardConversionSequence& SCS2);
114 
115 /// GetConversionRank - Retrieve the implicit conversion rank
116 /// corresponding to the given implicit conversion kind.
117 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
118   static const ImplicitConversionRank
119     Rank[(int)ICK_Num_Conversion_Kinds] = {
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Promotion,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_OCL_Scalar_Widening,
141     ICR_Complex_Real_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Writeback_Conversion,
145     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146                      // it was omitted by the patch that added
147                      // ICK_Zero_Event_Conversion
148     ICR_C_Conversion,
149     ICR_C_Conversion_Extension
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Function pointer conversion",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "SVE Vector conversion",
178     "Vector splat",
179     "Complex-real conversion",
180     "Block Pointer conversion",
181     "Transparent Union Conversion",
182     "Writeback conversion",
183     "OpenCL Zero Event Conversion",
184     "C specific type conversion",
185     "Incompatible pointer conversion"
186   };
187   return Name[Kind];
188 }
189 
190 /// StandardConversionSequence - Set the standard conversion
191 /// sequence to the identity conversion.
192 void StandardConversionSequence::setAsIdentityConversion() {
193   First = ICK_Identity;
194   Second = ICK_Identity;
195   Third = ICK_Identity;
196   DeprecatedStringLiteralToCharPtr = false;
197   QualificationIncludesObjCLifetime = false;
198   ReferenceBinding = false;
199   DirectBinding = false;
200   IsLvalueReference = true;
201   BindsToFunctionLvalue = false;
202   BindsToRvalue = false;
203   BindsImplicitObjectArgumentWithoutRefQualifier = false;
204   ObjCLifetimeConversionBinding = false;
205   CopyConstructor = nullptr;
206 }
207 
208 /// getRank - Retrieve the rank of this standard conversion sequence
209 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
210 /// implicit conversions.
211 ImplicitConversionRank StandardConversionSequence::getRank() const {
212   ImplicitConversionRank Rank = ICR_Exact_Match;
213   if  (GetConversionRank(First) > Rank)
214     Rank = GetConversionRank(First);
215   if  (GetConversionRank(Second) > Rank)
216     Rank = GetConversionRank(Second);
217   if  (GetConversionRank(Third) > Rank)
218     Rank = GetConversionRank(Third);
219   return Rank;
220 }
221 
222 /// isPointerConversionToBool - Determines whether this conversion is
223 /// a conversion of a pointer or pointer-to-member to bool. This is
224 /// used as part of the ranking of standard conversion sequences
225 /// (C++ 13.3.3.2p4).
226 bool StandardConversionSequence::isPointerConversionToBool() const {
227   // Note that FromType has not necessarily been transformed by the
228   // array-to-pointer or function-to-pointer implicit conversions, so
229   // check for their presence as well as checking whether FromType is
230   // a pointer.
231   if (getToType(1)->isBooleanType() &&
232       (getFromType()->isPointerType() ||
233        getFromType()->isMemberPointerType() ||
234        getFromType()->isObjCObjectPointerType() ||
235        getFromType()->isBlockPointerType() ||
236        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
237     return true;
238 
239   return false;
240 }
241 
242 /// isPointerConversionToVoidPointer - Determines whether this
243 /// conversion is a conversion of a pointer to a void pointer. This is
244 /// used as part of the ranking of standard conversion sequences (C++
245 /// 13.3.3.2p4).
246 bool
247 StandardConversionSequence::
248 isPointerConversionToVoidPointer(ASTContext& Context) const {
249   QualType FromType = getFromType();
250   QualType ToType = getToType(1);
251 
252   // Note that FromType has not necessarily been transformed by the
253   // array-to-pointer implicit conversion, so check for its presence
254   // and redo the conversion to get a pointer.
255   if (First == ICK_Array_To_Pointer)
256     FromType = Context.getArrayDecayedType(FromType);
257 
258   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
259     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
260       return ToPtrType->getPointeeType()->isVoidType();
261 
262   return false;
263 }
264 
265 /// Skip any implicit casts which could be either part of a narrowing conversion
266 /// or after one in an implicit conversion.
267 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
268                                              const Expr *Converted) {
269   // We can have cleanups wrapping the converted expression; these need to be
270   // preserved so that destructors run if necessary.
271   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
272     Expr *Inner =
273         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
274     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275                                     EWC->getObjects());
276   }
277 
278   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
279     switch (ICE->getCastKind()) {
280     case CK_NoOp:
281     case CK_IntegralCast:
282     case CK_IntegralToBoolean:
283     case CK_IntegralToFloating:
284     case CK_BooleanToSignedIntegral:
285     case CK_FloatingToIntegral:
286     case CK_FloatingToBoolean:
287     case CK_FloatingCast:
288       Converted = ICE->getSubExpr();
289       continue;
290 
291     default:
292       return Converted;
293     }
294   }
295 
296   return Converted;
297 }
298 
299 /// Check if this standard conversion sequence represents a narrowing
300 /// conversion, according to C++11 [dcl.init.list]p7.
301 ///
302 /// \param Ctx  The AST context.
303 /// \param Converted  The result of applying this standard conversion sequence.
304 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
305 ///        value of the expression prior to the narrowing conversion.
306 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
307 ///        type of the expression prior to the narrowing conversion.
308 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
309 ///        from floating point types to integral types should be ignored.
310 NarrowingKind StandardConversionSequence::getNarrowingKind(
311     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
312     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
313   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
314 
315   // C++11 [dcl.init.list]p7:
316   //   A narrowing conversion is an implicit conversion ...
317   QualType FromType = getToType(0);
318   QualType ToType = getToType(1);
319 
320   // A conversion to an enumeration type is narrowing if the conversion to
321   // the underlying type is narrowing. This only arises for expressions of
322   // the form 'Enum{init}'.
323   if (auto *ET = ToType->getAs<EnumType>())
324     ToType = ET->getDecl()->getIntegerType();
325 
326   switch (Second) {
327   // 'bool' is an integral type; dispatch to the right place to handle it.
328   case ICK_Boolean_Conversion:
329     if (FromType->isRealFloatingType())
330       goto FloatingIntegralConversion;
331     if (FromType->isIntegralOrUnscopedEnumerationType())
332       goto IntegralConversion;
333     // -- from a pointer type or pointer-to-member type to bool, or
334     return NK_Type_Narrowing;
335 
336   // -- from a floating-point type to an integer type, or
337   //
338   // -- from an integer type or unscoped enumeration type to a floating-point
339   //    type, except where the source is a constant expression and the actual
340   //    value after conversion will fit into the target type and will produce
341   //    the original value when converted back to the original type, or
342   case ICK_Floating_Integral:
343   FloatingIntegralConversion:
344     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
345       return NK_Type_Narrowing;
346     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
347                ToType->isRealFloatingType()) {
348       if (IgnoreFloatToIntegralConversion)
349         return NK_Not_Narrowing;
350       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351       assert(Initializer && "Unknown conversion expression");
352 
353       // If it's value-dependent, we can't tell whether it's narrowing.
354       if (Initializer->isValueDependent())
355         return NK_Dependent_Narrowing;
356 
357       if (Optional<llvm::APSInt> IntConstantValue =
358               Initializer->getIntegerConstantExpr(Ctx)) {
359         // Convert the integer to the floating type.
360         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
361         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
362                                 llvm::APFloat::rmNearestTiesToEven);
363         // And back.
364         llvm::APSInt ConvertedValue = *IntConstantValue;
365         bool ignored;
366         Result.convertToInteger(ConvertedValue,
367                                 llvm::APFloat::rmTowardZero, &ignored);
368         // If the resulting value is different, this was a narrowing conversion.
369         if (*IntConstantValue != ConvertedValue) {
370           ConstantValue = APValue(*IntConstantValue);
371           ConstantType = Initializer->getType();
372           return NK_Constant_Narrowing;
373         }
374       } else {
375         // Variables are always narrowings.
376         return NK_Variable_Narrowing;
377       }
378     }
379     return NK_Not_Narrowing;
380 
381   // -- from long double to double or float, or from double to float, except
382   //    where the source is a constant expression and the actual value after
383   //    conversion is within the range of values that can be represented (even
384   //    if it cannot be represented exactly), or
385   case ICK_Floating_Conversion:
386     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
387         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
388       // FromType is larger than ToType.
389       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
390 
391       // If it's value-dependent, we can't tell whether it's narrowing.
392       if (Initializer->isValueDependent())
393         return NK_Dependent_Narrowing;
394 
395       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
396         // Constant!
397         assert(ConstantValue.isFloat());
398         llvm::APFloat FloatVal = ConstantValue.getFloat();
399         // Convert the source value into the target type.
400         bool ignored;
401         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
402           Ctx.getFloatTypeSemantics(ToType),
403           llvm::APFloat::rmNearestTiesToEven, &ignored);
404         // If there was no overflow, the source value is within the range of
405         // values that can be represented.
406         if (ConvertStatus & llvm::APFloat::opOverflow) {
407           ConstantType = Initializer->getType();
408           return NK_Constant_Narrowing;
409         }
410       } else {
411         return NK_Variable_Narrowing;
412       }
413     }
414     return NK_Not_Narrowing;
415 
416   // -- from an integer type or unscoped enumeration type to an integer type
417   //    that cannot represent all the values of the original type, except where
418   //    the source is a constant expression and the actual value after
419   //    conversion will fit into the target type and will produce the original
420   //    value when converted back to the original type.
421   case ICK_Integral_Conversion:
422   IntegralConversion: {
423     assert(FromType->isIntegralOrUnscopedEnumerationType());
424     assert(ToType->isIntegralOrUnscopedEnumerationType());
425     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
426     const unsigned FromWidth = Ctx.getIntWidth(FromType);
427     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
428     const unsigned ToWidth = Ctx.getIntWidth(ToType);
429 
430     if (FromWidth > ToWidth ||
431         (FromWidth == ToWidth && FromSigned != ToSigned) ||
432         (FromSigned && !ToSigned)) {
433       // Not all values of FromType can be represented in ToType.
434       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436       // If it's value-dependent, we can't tell whether it's narrowing.
437       if (Initializer->isValueDependent())
438         return NK_Dependent_Narrowing;
439 
440       Optional<llvm::APSInt> OptInitializerValue;
441       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
442         // Such conversions on variables are always narrowing.
443         return NK_Variable_Narrowing;
444       }
445       llvm::APSInt &InitializerValue = *OptInitializerValue;
446       bool Narrowing = false;
447       if (FromWidth < ToWidth) {
448         // Negative -> unsigned is narrowing. Otherwise, more bits is never
449         // narrowing.
450         if (InitializerValue.isSigned() && InitializerValue.isNegative())
451           Narrowing = true;
452       } else {
453         // Add a bit to the InitializerValue so we don't have to worry about
454         // signed vs. unsigned comparisons.
455         InitializerValue = InitializerValue.extend(
456           InitializerValue.getBitWidth() + 1);
457         // Convert the initializer to and from the target width and signed-ness.
458         llvm::APSInt ConvertedValue = InitializerValue;
459         ConvertedValue = ConvertedValue.trunc(ToWidth);
460         ConvertedValue.setIsSigned(ToSigned);
461         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
462         ConvertedValue.setIsSigned(InitializerValue.isSigned());
463         // If the result is different, this was a narrowing conversion.
464         if (ConvertedValue != InitializerValue)
465           Narrowing = true;
466       }
467       if (Narrowing) {
468         ConstantType = Initializer->getType();
469         ConstantValue = APValue(InitializerValue);
470         return NK_Constant_Narrowing;
471       }
472     }
473     return NK_Not_Narrowing;
474   }
475 
476   default:
477     // Other kinds of conversions are not narrowings.
478     return NK_Not_Narrowing;
479   }
480 }
481 
482 /// dump - Print this standard conversion sequence to standard
483 /// error. Useful for debugging overloading issues.
484 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
485   raw_ostream &OS = llvm::errs();
486   bool PrintedSomething = false;
487   if (First != ICK_Identity) {
488     OS << GetImplicitConversionName(First);
489     PrintedSomething = true;
490   }
491 
492   if (Second != ICK_Identity) {
493     if (PrintedSomething) {
494       OS << " -> ";
495     }
496     OS << GetImplicitConversionName(Second);
497 
498     if (CopyConstructor) {
499       OS << " (by copy constructor)";
500     } else if (DirectBinding) {
501       OS << " (direct reference binding)";
502     } else if (ReferenceBinding) {
503       OS << " (reference binding)";
504     }
505     PrintedSomething = true;
506   }
507 
508   if (Third != ICK_Identity) {
509     if (PrintedSomething) {
510       OS << " -> ";
511     }
512     OS << GetImplicitConversionName(Third);
513     PrintedSomething = true;
514   }
515 
516   if (!PrintedSomething) {
517     OS << "No conversions required";
518   }
519 }
520 
521 /// dump - Print this user-defined conversion sequence to standard
522 /// error. Useful for debugging overloading issues.
523 void UserDefinedConversionSequence::dump() const {
524   raw_ostream &OS = llvm::errs();
525   if (Before.First || Before.Second || Before.Third) {
526     Before.dump();
527     OS << " -> ";
528   }
529   if (ConversionFunction)
530     OS << '\'' << *ConversionFunction << '\'';
531   else
532     OS << "aggregate initialization";
533   if (After.First || After.Second || After.Third) {
534     OS << " -> ";
535     After.dump();
536   }
537 }
538 
539 /// dump - Print this implicit conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
541 void ImplicitConversionSequence::dump() const {
542   raw_ostream &OS = llvm::errs();
543   if (hasInitializerListContainerType())
544     OS << "Worst list element conversion: ";
545   switch (ConversionKind) {
546   case StandardConversion:
547     OS << "Standard conversion: ";
548     Standard.dump();
549     break;
550   case UserDefinedConversion:
551     OS << "User-defined conversion: ";
552     UserDefined.dump();
553     break;
554   case EllipsisConversion:
555     OS << "Ellipsis conversion";
556     break;
557   case AmbiguousConversion:
558     OS << "Ambiguous conversion";
559     break;
560   case BadConversion:
561     OS << "Bad conversion";
562     break;
563   }
564 
565   OS << "\n";
566 }
567 
568 void AmbiguousConversionSequence::construct() {
569   new (&conversions()) ConversionSet();
570 }
571 
572 void AmbiguousConversionSequence::destruct() {
573   conversions().~ConversionSet();
574 }
575 
576 void
577 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
578   FromTypePtr = O.FromTypePtr;
579   ToTypePtr = O.ToTypePtr;
580   new (&conversions()) ConversionSet(O.conversions());
581 }
582 
583 namespace {
584   // Structure used by DeductionFailureInfo to store
585   // template argument information.
586   struct DFIArguments {
587     TemplateArgument FirstArg;
588     TemplateArgument SecondArg;
589   };
590   // Structure used by DeductionFailureInfo to store
591   // template parameter and template argument information.
592   struct DFIParamWithArguments : DFIArguments {
593     TemplateParameter Param;
594   };
595   // Structure used by DeductionFailureInfo to store template argument
596   // information and the index of the problematic call argument.
597   struct DFIDeducedMismatchArgs : DFIArguments {
598     TemplateArgumentList *TemplateArgs;
599     unsigned CallArgIndex;
600   };
601   // Structure used by DeductionFailureInfo to store information about
602   // unsatisfied constraints.
603   struct CNSInfo {
604     TemplateArgumentList *TemplateArgs;
605     ConstraintSatisfaction Satisfaction;
606   };
607 }
608 
609 /// Convert from Sema's representation of template deduction information
610 /// to the form used in overload-candidate information.
611 DeductionFailureInfo
612 clang::MakeDeductionFailureInfo(ASTContext &Context,
613                                 Sema::TemplateDeductionResult TDK,
614                                 TemplateDeductionInfo &Info) {
615   DeductionFailureInfo Result;
616   Result.Result = static_cast<unsigned>(TDK);
617   Result.HasDiagnostic = false;
618   switch (TDK) {
619   case Sema::TDK_Invalid:
620   case Sema::TDK_InstantiationDepth:
621   case Sema::TDK_TooManyArguments:
622   case Sema::TDK_TooFewArguments:
623   case Sema::TDK_MiscellaneousDeductionFailure:
624   case Sema::TDK_CUDATargetMismatch:
625     Result.Data = nullptr;
626     break;
627 
628   case Sema::TDK_Incomplete:
629   case Sema::TDK_InvalidExplicitArguments:
630     Result.Data = Info.Param.getOpaqueValue();
631     break;
632 
633   case Sema::TDK_DeducedMismatch:
634   case Sema::TDK_DeducedMismatchNested: {
635     // FIXME: Should allocate from normal heap so that we can free this later.
636     auto *Saved = new (Context) DFIDeducedMismatchArgs;
637     Saved->FirstArg = Info.FirstArg;
638     Saved->SecondArg = Info.SecondArg;
639     Saved->TemplateArgs = Info.take();
640     Saved->CallArgIndex = Info.CallArgIndex;
641     Result.Data = Saved;
642     break;
643   }
644 
645   case Sema::TDK_NonDeducedMismatch: {
646     // FIXME: Should allocate from normal heap so that we can free this later.
647     DFIArguments *Saved = new (Context) DFIArguments;
648     Saved->FirstArg = Info.FirstArg;
649     Saved->SecondArg = Info.SecondArg;
650     Result.Data = Saved;
651     break;
652   }
653 
654   case Sema::TDK_IncompletePack:
655     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
656   case Sema::TDK_Inconsistent:
657   case Sema::TDK_Underqualified: {
658     // FIXME: Should allocate from normal heap so that we can free this later.
659     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
660     Saved->Param = Info.Param;
661     Saved->FirstArg = Info.FirstArg;
662     Saved->SecondArg = Info.SecondArg;
663     Result.Data = Saved;
664     break;
665   }
666 
667   case Sema::TDK_SubstitutionFailure:
668     Result.Data = Info.take();
669     if (Info.hasSFINAEDiagnostic()) {
670       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
671           SourceLocation(), PartialDiagnostic::NullDiagnostic());
672       Info.takeSFINAEDiagnostic(*Diag);
673       Result.HasDiagnostic = true;
674     }
675     break;
676 
677   case Sema::TDK_ConstraintsNotSatisfied: {
678     CNSInfo *Saved = new (Context) CNSInfo;
679     Saved->TemplateArgs = Info.take();
680     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
681     Result.Data = Saved;
682     break;
683   }
684 
685   case Sema::TDK_Success:
686   case Sema::TDK_NonDependentConversionFailure:
687     llvm_unreachable("not a deduction failure");
688   }
689 
690   return Result;
691 }
692 
693 void DeductionFailureInfo::Destroy() {
694   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695   case Sema::TDK_Success:
696   case Sema::TDK_Invalid:
697   case Sema::TDK_InstantiationDepth:
698   case Sema::TDK_Incomplete:
699   case Sema::TDK_TooManyArguments:
700   case Sema::TDK_TooFewArguments:
701   case Sema::TDK_InvalidExplicitArguments:
702   case Sema::TDK_CUDATargetMismatch:
703   case Sema::TDK_NonDependentConversionFailure:
704     break;
705 
706   case Sema::TDK_IncompletePack:
707   case Sema::TDK_Inconsistent:
708   case Sema::TDK_Underqualified:
709   case Sema::TDK_DeducedMismatch:
710   case Sema::TDK_DeducedMismatchNested:
711   case Sema::TDK_NonDeducedMismatch:
712     // FIXME: Destroy the data?
713     Data = nullptr;
714     break;
715 
716   case Sema::TDK_SubstitutionFailure:
717     // FIXME: Destroy the template argument list?
718     Data = nullptr;
719     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
720       Diag->~PartialDiagnosticAt();
721       HasDiagnostic = false;
722     }
723     break;
724 
725   case Sema::TDK_ConstraintsNotSatisfied:
726     // FIXME: Destroy the template argument list?
727     Data = nullptr;
728     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
729       Diag->~PartialDiagnosticAt();
730       HasDiagnostic = false;
731     }
732     break;
733 
734   // Unhandled
735   case Sema::TDK_MiscellaneousDeductionFailure:
736     break;
737   }
738 }
739 
740 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
741   if (HasDiagnostic)
742     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
743   return nullptr;
744 }
745 
746 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
747   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
748   case Sema::TDK_Success:
749   case Sema::TDK_Invalid:
750   case Sema::TDK_InstantiationDepth:
751   case Sema::TDK_TooManyArguments:
752   case Sema::TDK_TooFewArguments:
753   case Sema::TDK_SubstitutionFailure:
754   case Sema::TDK_DeducedMismatch:
755   case Sema::TDK_DeducedMismatchNested:
756   case Sema::TDK_NonDeducedMismatch:
757   case Sema::TDK_CUDATargetMismatch:
758   case Sema::TDK_NonDependentConversionFailure:
759   case Sema::TDK_ConstraintsNotSatisfied:
760     return TemplateParameter();
761 
762   case Sema::TDK_Incomplete:
763   case Sema::TDK_InvalidExplicitArguments:
764     return TemplateParameter::getFromOpaqueValue(Data);
765 
766   case Sema::TDK_IncompletePack:
767   case Sema::TDK_Inconsistent:
768   case Sema::TDK_Underqualified:
769     return static_cast<DFIParamWithArguments*>(Data)->Param;
770 
771   // Unhandled
772   case Sema::TDK_MiscellaneousDeductionFailure:
773     break;
774   }
775 
776   return TemplateParameter();
777 }
778 
779 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
780   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
781   case Sema::TDK_Success:
782   case Sema::TDK_Invalid:
783   case Sema::TDK_InstantiationDepth:
784   case Sema::TDK_TooManyArguments:
785   case Sema::TDK_TooFewArguments:
786   case Sema::TDK_Incomplete:
787   case Sema::TDK_IncompletePack:
788   case Sema::TDK_InvalidExplicitArguments:
789   case Sema::TDK_Inconsistent:
790   case Sema::TDK_Underqualified:
791   case Sema::TDK_NonDeducedMismatch:
792   case Sema::TDK_CUDATargetMismatch:
793   case Sema::TDK_NonDependentConversionFailure:
794     return nullptr;
795 
796   case Sema::TDK_DeducedMismatch:
797   case Sema::TDK_DeducedMismatchNested:
798     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
799 
800   case Sema::TDK_SubstitutionFailure:
801     return static_cast<TemplateArgumentList*>(Data);
802 
803   case Sema::TDK_ConstraintsNotSatisfied:
804     return static_cast<CNSInfo*>(Data)->TemplateArgs;
805 
806   // Unhandled
807   case Sema::TDK_MiscellaneousDeductionFailure:
808     break;
809   }
810 
811   return nullptr;
812 }
813 
814 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
815   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
816   case Sema::TDK_Success:
817   case Sema::TDK_Invalid:
818   case Sema::TDK_InstantiationDepth:
819   case Sema::TDK_Incomplete:
820   case Sema::TDK_TooManyArguments:
821   case Sema::TDK_TooFewArguments:
822   case Sema::TDK_InvalidExplicitArguments:
823   case Sema::TDK_SubstitutionFailure:
824   case Sema::TDK_CUDATargetMismatch:
825   case Sema::TDK_NonDependentConversionFailure:
826   case Sema::TDK_ConstraintsNotSatisfied:
827     return nullptr;
828 
829   case Sema::TDK_IncompletePack:
830   case Sema::TDK_Inconsistent:
831   case Sema::TDK_Underqualified:
832   case Sema::TDK_DeducedMismatch:
833   case Sema::TDK_DeducedMismatchNested:
834   case Sema::TDK_NonDeducedMismatch:
835     return &static_cast<DFIArguments*>(Data)->FirstArg;
836 
837   // Unhandled
838   case Sema::TDK_MiscellaneousDeductionFailure:
839     break;
840   }
841 
842   return nullptr;
843 }
844 
845 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
846   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
847   case Sema::TDK_Success:
848   case Sema::TDK_Invalid:
849   case Sema::TDK_InstantiationDepth:
850   case Sema::TDK_Incomplete:
851   case Sema::TDK_IncompletePack:
852   case Sema::TDK_TooManyArguments:
853   case Sema::TDK_TooFewArguments:
854   case Sema::TDK_InvalidExplicitArguments:
855   case Sema::TDK_SubstitutionFailure:
856   case Sema::TDK_CUDATargetMismatch:
857   case Sema::TDK_NonDependentConversionFailure:
858   case Sema::TDK_ConstraintsNotSatisfied:
859     return nullptr;
860 
861   case Sema::TDK_Inconsistent:
862   case Sema::TDK_Underqualified:
863   case Sema::TDK_DeducedMismatch:
864   case Sema::TDK_DeducedMismatchNested:
865   case Sema::TDK_NonDeducedMismatch:
866     return &static_cast<DFIArguments*>(Data)->SecondArg;
867 
868   // Unhandled
869   case Sema::TDK_MiscellaneousDeductionFailure:
870     break;
871   }
872 
873   return nullptr;
874 }
875 
876 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
877   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
878   case Sema::TDK_DeducedMismatch:
879   case Sema::TDK_DeducedMismatchNested:
880     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
881 
882   default:
883     return llvm::None;
884   }
885 }
886 
887 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
888     OverloadedOperatorKind Op) {
889   if (!AllowRewrittenCandidates)
890     return false;
891   return Op == OO_EqualEqual || Op == OO_Spaceship;
892 }
893 
894 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
895     ASTContext &Ctx, const FunctionDecl *FD) {
896   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
897     return false;
898   // Don't bother adding a reversed candidate that can never be a better
899   // match than the non-reversed version.
900   return FD->getNumParams() != 2 ||
901          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
902                                      FD->getParamDecl(1)->getType()) ||
903          FD->hasAttr<EnableIfAttr>();
904 }
905 
906 void OverloadCandidateSet::destroyCandidates() {
907   for (iterator i = begin(), e = end(); i != e; ++i) {
908     for (auto &C : i->Conversions)
909       C.~ImplicitConversionSequence();
910     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
911       i->DeductionFailure.Destroy();
912   }
913 }
914 
915 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
916   destroyCandidates();
917   SlabAllocator.Reset();
918   NumInlineBytesUsed = 0;
919   Candidates.clear();
920   Functions.clear();
921   Kind = CSK;
922 }
923 
924 namespace {
925   class UnbridgedCastsSet {
926     struct Entry {
927       Expr **Addr;
928       Expr *Saved;
929     };
930     SmallVector<Entry, 2> Entries;
931 
932   public:
933     void save(Sema &S, Expr *&E) {
934       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
935       Entry entry = { &E, E };
936       Entries.push_back(entry);
937       E = S.stripARCUnbridgedCast(E);
938     }
939 
940     void restore() {
941       for (SmallVectorImpl<Entry>::iterator
942              i = Entries.begin(), e = Entries.end(); i != e; ++i)
943         *i->Addr = i->Saved;
944     }
945   };
946 }
947 
948 /// checkPlaceholderForOverload - Do any interesting placeholder-like
949 /// preprocessing on the given expression.
950 ///
951 /// \param unbridgedCasts a collection to which to add unbridged casts;
952 ///   without this, they will be immediately diagnosed as errors
953 ///
954 /// Return true on unrecoverable error.
955 static bool
956 checkPlaceholderForOverload(Sema &S, Expr *&E,
957                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
958   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
959     // We can't handle overloaded expressions here because overload
960     // resolution might reasonably tweak them.
961     if (placeholder->getKind() == BuiltinType::Overload) return false;
962 
963     // If the context potentially accepts unbridged ARC casts, strip
964     // the unbridged cast and add it to the collection for later restoration.
965     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
966         unbridgedCasts) {
967       unbridgedCasts->save(S, E);
968       return false;
969     }
970 
971     // Go ahead and check everything else.
972     ExprResult result = S.CheckPlaceholderExpr(E);
973     if (result.isInvalid())
974       return true;
975 
976     E = result.get();
977     return false;
978   }
979 
980   // Nothing to do.
981   return false;
982 }
983 
984 /// checkArgPlaceholdersForOverload - Check a set of call operands for
985 /// placeholders.
986 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
987                                             UnbridgedCastsSet &unbridged) {
988   for (unsigned i = 0, e = Args.size(); i != e; ++i)
989     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
990       return true;
991 
992   return false;
993 }
994 
995 /// Determine whether the given New declaration is an overload of the
996 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
997 /// New and Old cannot be overloaded, e.g., if New has the same signature as
998 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
999 /// functions (or function templates) at all. When it does return Ovl_Match or
1000 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1001 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1002 /// declaration.
1003 ///
1004 /// Example: Given the following input:
1005 ///
1006 ///   void f(int, float); // #1
1007 ///   void f(int, int); // #2
1008 ///   int f(int, int); // #3
1009 ///
1010 /// When we process #1, there is no previous declaration of "f", so IsOverload
1011 /// will not be used.
1012 ///
1013 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1014 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1015 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1016 /// unchanged.
1017 ///
1018 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1019 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1020 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1021 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1022 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1023 ///
1024 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1025 /// by a using declaration. The rules for whether to hide shadow declarations
1026 /// ignore some properties which otherwise figure into a function template's
1027 /// signature.
1028 Sema::OverloadKind
1029 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1030                     NamedDecl *&Match, bool NewIsUsingDecl) {
1031   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1032          I != E; ++I) {
1033     NamedDecl *OldD = *I;
1034 
1035     bool OldIsUsingDecl = false;
1036     if (isa<UsingShadowDecl>(OldD)) {
1037       OldIsUsingDecl = true;
1038 
1039       // We can always introduce two using declarations into the same
1040       // context, even if they have identical signatures.
1041       if (NewIsUsingDecl) continue;
1042 
1043       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1044     }
1045 
1046     // A using-declaration does not conflict with another declaration
1047     // if one of them is hidden.
1048     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1049       continue;
1050 
1051     // If either declaration was introduced by a using declaration,
1052     // we'll need to use slightly different rules for matching.
1053     // Essentially, these rules are the normal rules, except that
1054     // function templates hide function templates with different
1055     // return types or template parameter lists.
1056     bool UseMemberUsingDeclRules =
1057       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1058       !New->getFriendObjectKind();
1059 
1060     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1061       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1062         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1063           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1064           continue;
1065         }
1066 
1067         if (!isa<FunctionTemplateDecl>(OldD) &&
1068             !shouldLinkPossiblyHiddenDecl(*I, New))
1069           continue;
1070 
1071         Match = *I;
1072         return Ovl_Match;
1073       }
1074 
1075       // Builtins that have custom typechecking or have a reference should
1076       // not be overloadable or redeclarable.
1077       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1078         Match = *I;
1079         return Ovl_NonFunction;
1080       }
1081     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1082       // We can overload with these, which can show up when doing
1083       // redeclaration checks for UsingDecls.
1084       assert(Old.getLookupKind() == LookupUsingDeclName);
1085     } else if (isa<TagDecl>(OldD)) {
1086       // We can always overload with tags by hiding them.
1087     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1088       // Optimistically assume that an unresolved using decl will
1089       // overload; if it doesn't, we'll have to diagnose during
1090       // template instantiation.
1091       //
1092       // Exception: if the scope is dependent and this is not a class
1093       // member, the using declaration can only introduce an enumerator.
1094       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1095         Match = *I;
1096         return Ovl_NonFunction;
1097       }
1098     } else {
1099       // (C++ 13p1):
1100       //   Only function declarations can be overloaded; object and type
1101       //   declarations cannot be overloaded.
1102       Match = *I;
1103       return Ovl_NonFunction;
1104     }
1105   }
1106 
1107   // C++ [temp.friend]p1:
1108   //   For a friend function declaration that is not a template declaration:
1109   //    -- if the name of the friend is a qualified or unqualified template-id,
1110   //       [...], otherwise
1111   //    -- if the name of the friend is a qualified-id and a matching
1112   //       non-template function is found in the specified class or namespace,
1113   //       the friend declaration refers to that function, otherwise,
1114   //    -- if the name of the friend is a qualified-id and a matching function
1115   //       template is found in the specified class or namespace, the friend
1116   //       declaration refers to the deduced specialization of that function
1117   //       template, otherwise
1118   //    -- the name shall be an unqualified-id [...]
1119   // If we get here for a qualified friend declaration, we've just reached the
1120   // third bullet. If the type of the friend is dependent, skip this lookup
1121   // until instantiation.
1122   if (New->getFriendObjectKind() && New->getQualifier() &&
1123       !New->getDescribedFunctionTemplate() &&
1124       !New->getDependentSpecializationInfo() &&
1125       !New->getType()->isDependentType()) {
1126     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1127     TemplateSpecResult.addAllDecls(Old);
1128     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1129                                             /*QualifiedFriend*/true)) {
1130       New->setInvalidDecl();
1131       return Ovl_Overload;
1132     }
1133 
1134     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1135     return Ovl_Match;
1136   }
1137 
1138   return Ovl_Overload;
1139 }
1140 
1141 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1142                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1143                       bool ConsiderRequiresClauses) {
1144   // C++ [basic.start.main]p2: This function shall not be overloaded.
1145   if (New->isMain())
1146     return false;
1147 
1148   // MSVCRT user defined entry points cannot be overloaded.
1149   if (New->isMSVCRTEntryPoint())
1150     return false;
1151 
1152   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1153   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1154 
1155   // C++ [temp.fct]p2:
1156   //   A function template can be overloaded with other function templates
1157   //   and with normal (non-template) functions.
1158   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1159     return true;
1160 
1161   // Is the function New an overload of the function Old?
1162   QualType OldQType = Context.getCanonicalType(Old->getType());
1163   QualType NewQType = Context.getCanonicalType(New->getType());
1164 
1165   // Compare the signatures (C++ 1.3.10) of the two functions to
1166   // determine whether they are overloads. If we find any mismatch
1167   // in the signature, they are overloads.
1168 
1169   // If either of these functions is a K&R-style function (no
1170   // prototype), then we consider them to have matching signatures.
1171   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1172       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1173     return false;
1174 
1175   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1176   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1177 
1178   // The signature of a function includes the types of its
1179   // parameters (C++ 1.3.10), which includes the presence or absence
1180   // of the ellipsis; see C++ DR 357).
1181   if (OldQType != NewQType &&
1182       (OldType->getNumParams() != NewType->getNumParams() ||
1183        OldType->isVariadic() != NewType->isVariadic() ||
1184        !FunctionParamTypesAreEqual(OldType, NewType)))
1185     return true;
1186 
1187   // C++ [temp.over.link]p4:
1188   //   The signature of a function template consists of its function
1189   //   signature, its return type and its template parameter list. The names
1190   //   of the template parameters are significant only for establishing the
1191   //   relationship between the template parameters and the rest of the
1192   //   signature.
1193   //
1194   // We check the return type and template parameter lists for function
1195   // templates first; the remaining checks follow.
1196   //
1197   // However, we don't consider either of these when deciding whether
1198   // a member introduced by a shadow declaration is hidden.
1199   if (!UseMemberUsingDeclRules && NewTemplate &&
1200       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1201                                        OldTemplate->getTemplateParameters(),
1202                                        false, TPL_TemplateMatch) ||
1203        !Context.hasSameType(Old->getDeclaredReturnType(),
1204                             New->getDeclaredReturnType())))
1205     return true;
1206 
1207   // If the function is a class member, its signature includes the
1208   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1209   //
1210   // As part of this, also check whether one of the member functions
1211   // is static, in which case they are not overloads (C++
1212   // 13.1p2). While not part of the definition of the signature,
1213   // this check is important to determine whether these functions
1214   // can be overloaded.
1215   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1216   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1217   if (OldMethod && NewMethod &&
1218       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1219     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1220       if (!UseMemberUsingDeclRules &&
1221           (OldMethod->getRefQualifier() == RQ_None ||
1222            NewMethod->getRefQualifier() == RQ_None)) {
1223         // C++0x [over.load]p2:
1224         //   - Member function declarations with the same name and the same
1225         //     parameter-type-list as well as member function template
1226         //     declarations with the same name, the same parameter-type-list, and
1227         //     the same template parameter lists cannot be overloaded if any of
1228         //     them, but not all, have a ref-qualifier (8.3.5).
1229         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1230           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1231         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1232       }
1233       return true;
1234     }
1235 
1236     // We may not have applied the implicit const for a constexpr member
1237     // function yet (because we haven't yet resolved whether this is a static
1238     // or non-static member function). Add it now, on the assumption that this
1239     // is a redeclaration of OldMethod.
1240     auto OldQuals = OldMethod->getMethodQualifiers();
1241     auto NewQuals = NewMethod->getMethodQualifiers();
1242     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1243         !isa<CXXConstructorDecl>(NewMethod))
1244       NewQuals.addConst();
1245     // We do not allow overloading based off of '__restrict'.
1246     OldQuals.removeRestrict();
1247     NewQuals.removeRestrict();
1248     if (OldQuals != NewQuals)
1249       return true;
1250   }
1251 
1252   // Though pass_object_size is placed on parameters and takes an argument, we
1253   // consider it to be a function-level modifier for the sake of function
1254   // identity. Either the function has one or more parameters with
1255   // pass_object_size or it doesn't.
1256   if (functionHasPassObjectSizeParams(New) !=
1257       functionHasPassObjectSizeParams(Old))
1258     return true;
1259 
1260   // enable_if attributes are an order-sensitive part of the signature.
1261   for (specific_attr_iterator<EnableIfAttr>
1262          NewI = New->specific_attr_begin<EnableIfAttr>(),
1263          NewE = New->specific_attr_end<EnableIfAttr>(),
1264          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1265          OldE = Old->specific_attr_end<EnableIfAttr>();
1266        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1267     if (NewI == NewE || OldI == OldE)
1268       return true;
1269     llvm::FoldingSetNodeID NewID, OldID;
1270     NewI->getCond()->Profile(NewID, Context, true);
1271     OldI->getCond()->Profile(OldID, Context, true);
1272     if (NewID != OldID)
1273       return true;
1274   }
1275 
1276   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1277     // Don't allow overloading of destructors.  (In theory we could, but it
1278     // would be a giant change to clang.)
1279     if (!isa<CXXDestructorDecl>(New)) {
1280       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1281                          OldTarget = IdentifyCUDATarget(Old);
1282       if (NewTarget != CFT_InvalidTarget) {
1283         assert((OldTarget != CFT_InvalidTarget) &&
1284                "Unexpected invalid target.");
1285 
1286         // Allow overloading of functions with same signature and different CUDA
1287         // target attributes.
1288         if (NewTarget != OldTarget)
1289           return true;
1290       }
1291     }
1292   }
1293 
1294   if (ConsiderRequiresClauses) {
1295     Expr *NewRC = New->getTrailingRequiresClause(),
1296          *OldRC = Old->getTrailingRequiresClause();
1297     if ((NewRC != nullptr) != (OldRC != nullptr))
1298       // RC are most certainly different - these are overloads.
1299       return true;
1300 
1301     if (NewRC) {
1302       llvm::FoldingSetNodeID NewID, OldID;
1303       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1304       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1305       if (NewID != OldID)
1306         // RCs are not equivalent - these are overloads.
1307         return true;
1308     }
1309   }
1310 
1311   // The signatures match; this is not an overload.
1312   return false;
1313 }
1314 
1315 /// Tries a user-defined conversion from From to ToType.
1316 ///
1317 /// Produces an implicit conversion sequence for when a standard conversion
1318 /// is not an option. See TryImplicitConversion for more information.
1319 static ImplicitConversionSequence
1320 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1321                          bool SuppressUserConversions,
1322                          AllowedExplicit AllowExplicit,
1323                          bool InOverloadResolution,
1324                          bool CStyle,
1325                          bool AllowObjCWritebackConversion,
1326                          bool AllowObjCConversionOnExplicit) {
1327   ImplicitConversionSequence ICS;
1328 
1329   if (SuppressUserConversions) {
1330     // We're not in the case above, so there is no conversion that
1331     // we can perform.
1332     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1333     return ICS;
1334   }
1335 
1336   // Attempt user-defined conversion.
1337   OverloadCandidateSet Conversions(From->getExprLoc(),
1338                                    OverloadCandidateSet::CSK_Normal);
1339   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1340                                   Conversions, AllowExplicit,
1341                                   AllowObjCConversionOnExplicit)) {
1342   case OR_Success:
1343   case OR_Deleted:
1344     ICS.setUserDefined();
1345     // C++ [over.ics.user]p4:
1346     //   A conversion of an expression of class type to the same class
1347     //   type is given Exact Match rank, and a conversion of an
1348     //   expression of class type to a base class of that type is
1349     //   given Conversion rank, in spite of the fact that a copy
1350     //   constructor (i.e., a user-defined conversion function) is
1351     //   called for those cases.
1352     if (CXXConstructorDecl *Constructor
1353           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1354       QualType FromCanon
1355         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1356       QualType ToCanon
1357         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1358       if (Constructor->isCopyConstructor() &&
1359           (FromCanon == ToCanon ||
1360            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1361         // Turn this into a "standard" conversion sequence, so that it
1362         // gets ranked with standard conversion sequences.
1363         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1364         ICS.setStandard();
1365         ICS.Standard.setAsIdentityConversion();
1366         ICS.Standard.setFromType(From->getType());
1367         ICS.Standard.setAllToTypes(ToType);
1368         ICS.Standard.CopyConstructor = Constructor;
1369         ICS.Standard.FoundCopyConstructor = Found;
1370         if (ToCanon != FromCanon)
1371           ICS.Standard.Second = ICK_Derived_To_Base;
1372       }
1373     }
1374     break;
1375 
1376   case OR_Ambiguous:
1377     ICS.setAmbiguous();
1378     ICS.Ambiguous.setFromType(From->getType());
1379     ICS.Ambiguous.setToType(ToType);
1380     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1381          Cand != Conversions.end(); ++Cand)
1382       if (Cand->Best)
1383         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1384     break;
1385 
1386     // Fall through.
1387   case OR_No_Viable_Function:
1388     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1389     break;
1390   }
1391 
1392   return ICS;
1393 }
1394 
1395 /// TryImplicitConversion - Attempt to perform an implicit conversion
1396 /// from the given expression (Expr) to the given type (ToType). This
1397 /// function returns an implicit conversion sequence that can be used
1398 /// to perform the initialization. Given
1399 ///
1400 ///   void f(float f);
1401 ///   void g(int i) { f(i); }
1402 ///
1403 /// this routine would produce an implicit conversion sequence to
1404 /// describe the initialization of f from i, which will be a standard
1405 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1406 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1407 //
1408 /// Note that this routine only determines how the conversion can be
1409 /// performed; it does not actually perform the conversion. As such,
1410 /// it will not produce any diagnostics if no conversion is available,
1411 /// but will instead return an implicit conversion sequence of kind
1412 /// "BadConversion".
1413 ///
1414 /// If @p SuppressUserConversions, then user-defined conversions are
1415 /// not permitted.
1416 /// If @p AllowExplicit, then explicit user-defined conversions are
1417 /// permitted.
1418 ///
1419 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1420 /// writeback conversion, which allows __autoreleasing id* parameters to
1421 /// be initialized with __strong id* or __weak id* arguments.
1422 static ImplicitConversionSequence
1423 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1424                       bool SuppressUserConversions,
1425                       AllowedExplicit AllowExplicit,
1426                       bool InOverloadResolution,
1427                       bool CStyle,
1428                       bool AllowObjCWritebackConversion,
1429                       bool AllowObjCConversionOnExplicit) {
1430   ImplicitConversionSequence ICS;
1431   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1432                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1433     ICS.setStandard();
1434     return ICS;
1435   }
1436 
1437   if (!S.getLangOpts().CPlusPlus) {
1438     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1439     return ICS;
1440   }
1441 
1442   // C++ [over.ics.user]p4:
1443   //   A conversion of an expression of class type to the same class
1444   //   type is given Exact Match rank, and a conversion of an
1445   //   expression of class type to a base class of that type is
1446   //   given Conversion rank, in spite of the fact that a copy/move
1447   //   constructor (i.e., a user-defined conversion function) is
1448   //   called for those cases.
1449   QualType FromType = From->getType();
1450   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1451       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1452        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1453     ICS.setStandard();
1454     ICS.Standard.setAsIdentityConversion();
1455     ICS.Standard.setFromType(FromType);
1456     ICS.Standard.setAllToTypes(ToType);
1457 
1458     // We don't actually check at this point whether there is a valid
1459     // copy/move constructor, since overloading just assumes that it
1460     // exists. When we actually perform initialization, we'll find the
1461     // appropriate constructor to copy the returned object, if needed.
1462     ICS.Standard.CopyConstructor = nullptr;
1463 
1464     // Determine whether this is considered a derived-to-base conversion.
1465     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1466       ICS.Standard.Second = ICK_Derived_To_Base;
1467 
1468     return ICS;
1469   }
1470 
1471   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1472                                   AllowExplicit, InOverloadResolution, CStyle,
1473                                   AllowObjCWritebackConversion,
1474                                   AllowObjCConversionOnExplicit);
1475 }
1476 
1477 ImplicitConversionSequence
1478 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1479                             bool SuppressUserConversions,
1480                             AllowedExplicit AllowExplicit,
1481                             bool InOverloadResolution,
1482                             bool CStyle,
1483                             bool AllowObjCWritebackConversion) {
1484   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1485                                  AllowExplicit, InOverloadResolution, CStyle,
1486                                  AllowObjCWritebackConversion,
1487                                  /*AllowObjCConversionOnExplicit=*/false);
1488 }
1489 
1490 /// PerformImplicitConversion - Perform an implicit conversion of the
1491 /// expression From to the type ToType. Returns the
1492 /// converted expression. Flavor is the kind of conversion we're
1493 /// performing, used in the error message. If @p AllowExplicit,
1494 /// explicit user-defined conversions are permitted.
1495 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                            AssignmentAction Action,
1497                                            bool AllowExplicit) {
1498   if (checkPlaceholderForOverload(*this, From))
1499     return ExprError();
1500 
1501   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1502   bool AllowObjCWritebackConversion
1503     = getLangOpts().ObjCAutoRefCount &&
1504       (Action == AA_Passing || Action == AA_Sending);
1505   if (getLangOpts().ObjC)
1506     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1507                                       From->getType(), From);
1508   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1509       *this, From, ToType,
1510       /*SuppressUserConversions=*/false,
1511       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1512       /*InOverloadResolution=*/false,
1513       /*CStyle=*/false, AllowObjCWritebackConversion,
1514       /*AllowObjCConversionOnExplicit=*/false);
1515   return PerformImplicitConversion(From, ToType, ICS, Action);
1516 }
1517 
1518 /// Determine whether the conversion from FromType to ToType is a valid
1519 /// conversion that strips "noexcept" or "noreturn" off the nested function
1520 /// type.
1521 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1522                                 QualType &ResultTy) {
1523   if (Context.hasSameUnqualifiedType(FromType, ToType))
1524     return false;
1525 
1526   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1527   //                    or F(t noexcept) -> F(t)
1528   // where F adds one of the following at most once:
1529   //   - a pointer
1530   //   - a member pointer
1531   //   - a block pointer
1532   // Changes here need matching changes in FindCompositePointerType.
1533   CanQualType CanTo = Context.getCanonicalType(ToType);
1534   CanQualType CanFrom = Context.getCanonicalType(FromType);
1535   Type::TypeClass TyClass = CanTo->getTypeClass();
1536   if (TyClass != CanFrom->getTypeClass()) return false;
1537   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1538     if (TyClass == Type::Pointer) {
1539       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1540       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1541     } else if (TyClass == Type::BlockPointer) {
1542       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1543       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1544     } else if (TyClass == Type::MemberPointer) {
1545       auto ToMPT = CanTo.castAs<MemberPointerType>();
1546       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1547       // A function pointer conversion cannot change the class of the function.
1548       if (ToMPT->getClass() != FromMPT->getClass())
1549         return false;
1550       CanTo = ToMPT->getPointeeType();
1551       CanFrom = FromMPT->getPointeeType();
1552     } else {
1553       return false;
1554     }
1555 
1556     TyClass = CanTo->getTypeClass();
1557     if (TyClass != CanFrom->getTypeClass()) return false;
1558     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1559       return false;
1560   }
1561 
1562   const auto *FromFn = cast<FunctionType>(CanFrom);
1563   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1564 
1565   const auto *ToFn = cast<FunctionType>(CanTo);
1566   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1567 
1568   bool Changed = false;
1569 
1570   // Drop 'noreturn' if not present in target type.
1571   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1572     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1573     Changed = true;
1574   }
1575 
1576   // Drop 'noexcept' if not present in target type.
1577   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1578     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1579     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1580       FromFn = cast<FunctionType>(
1581           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1582                                                    EST_None)
1583                  .getTypePtr());
1584       Changed = true;
1585     }
1586 
1587     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1588     // only if the ExtParameterInfo lists of the two function prototypes can be
1589     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1590     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1591     bool CanUseToFPT, CanUseFromFPT;
1592     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1593                                       CanUseFromFPT, NewParamInfos) &&
1594         CanUseToFPT && !CanUseFromFPT) {
1595       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1596       ExtInfo.ExtParameterInfos =
1597           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1598       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1599                                             FromFPT->getParamTypes(), ExtInfo);
1600       FromFn = QT->getAs<FunctionType>();
1601       Changed = true;
1602     }
1603   }
1604 
1605   if (!Changed)
1606     return false;
1607 
1608   assert(QualType(FromFn, 0).isCanonical());
1609   if (QualType(FromFn, 0) != CanTo) return false;
1610 
1611   ResultTy = ToType;
1612   return true;
1613 }
1614 
1615 /// Determine whether the conversion from FromType to ToType is a valid
1616 /// vector conversion.
1617 ///
1618 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1619 /// conversion.
1620 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
1621                                ImplicitConversionKind &ICK, Expr *From,
1622                                bool InOverloadResolution) {
1623   // We need at least one of these types to be a vector type to have a vector
1624   // conversion.
1625   if (!ToType->isVectorType() && !FromType->isVectorType())
1626     return false;
1627 
1628   // Identical types require no conversions.
1629   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1630     return false;
1631 
1632   // There are no conversions between extended vector types, only identity.
1633   if (ToType->isExtVectorType()) {
1634     // There are no conversions between extended vector types other than the
1635     // identity conversion.
1636     if (FromType->isExtVectorType())
1637       return false;
1638 
1639     // Vector splat from any arithmetic type to a vector.
1640     if (FromType->isArithmeticType()) {
1641       ICK = ICK_Vector_Splat;
1642       return true;
1643     }
1644   }
1645 
1646   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1647     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1648         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1649       ICK = ICK_SVE_Vector_Conversion;
1650       return true;
1651     }
1652 
1653   // We can perform the conversion between vector types in the following cases:
1654   // 1)vector types are equivalent AltiVec and GCC vector types
1655   // 2)lax vector conversions are permitted and the vector types are of the
1656   //   same size
1657   // 3)the destination type does not have the ARM MVE strict-polymorphism
1658   //   attribute, which inhibits lax vector conversion for overload resolution
1659   //   only
1660   if (ToType->isVectorType() && FromType->isVectorType()) {
1661     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662         (S.isLaxVectorConversion(FromType, ToType) &&
1663          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664       if (S.isLaxVectorConversion(FromType, ToType) &&
1665           S.anyAltivecTypes(FromType, ToType) &&
1666           !S.areSameVectorElemTypes(FromType, ToType) &&
1667           !InOverloadResolution) {
1668         S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
1669             << FromType << ToType;
1670       }
1671       ICK = ICK_Vector_Conversion;
1672       return true;
1673     }
1674   }
1675 
1676   return false;
1677 }
1678 
1679 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1680                                 bool InOverloadResolution,
1681                                 StandardConversionSequence &SCS,
1682                                 bool CStyle);
1683 
1684 /// IsStandardConversion - Determines whether there is a standard
1685 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1686 /// expression From to the type ToType. Standard conversion sequences
1687 /// only consider non-class types; for conversions that involve class
1688 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1689 /// contain the standard conversion sequence required to perform this
1690 /// conversion and this routine will return true. Otherwise, this
1691 /// routine will return false and the value of SCS is unspecified.
1692 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1693                                  bool InOverloadResolution,
1694                                  StandardConversionSequence &SCS,
1695                                  bool CStyle,
1696                                  bool AllowObjCWritebackConversion) {
1697   QualType FromType = From->getType();
1698 
1699   // Standard conversions (C++ [conv])
1700   SCS.setAsIdentityConversion();
1701   SCS.IncompatibleObjC = false;
1702   SCS.setFromType(FromType);
1703   SCS.CopyConstructor = nullptr;
1704 
1705   // There are no standard conversions for class types in C++, so
1706   // abort early. When overloading in C, however, we do permit them.
1707   if (S.getLangOpts().CPlusPlus &&
1708       (FromType->isRecordType() || ToType->isRecordType()))
1709     return false;
1710 
1711   // The first conversion can be an lvalue-to-rvalue conversion,
1712   // array-to-pointer conversion, or function-to-pointer conversion
1713   // (C++ 4p1).
1714 
1715   if (FromType == S.Context.OverloadTy) {
1716     DeclAccessPair AccessPair;
1717     if (FunctionDecl *Fn
1718           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1719                                                  AccessPair)) {
1720       // We were able to resolve the address of the overloaded function,
1721       // so we can convert to the type of that function.
1722       FromType = Fn->getType();
1723       SCS.setFromType(FromType);
1724 
1725       // we can sometimes resolve &foo<int> regardless of ToType, so check
1726       // if the type matches (identity) or we are converting to bool
1727       if (!S.Context.hasSameUnqualifiedType(
1728                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1729         QualType resultTy;
1730         // if the function type matches except for [[noreturn]], it's ok
1731         if (!S.IsFunctionConversion(FromType,
1732               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1733           // otherwise, only a boolean conversion is standard
1734           if (!ToType->isBooleanType())
1735             return false;
1736       }
1737 
1738       // Check if the "from" expression is taking the address of an overloaded
1739       // function and recompute the FromType accordingly. Take advantage of the
1740       // fact that non-static member functions *must* have such an address-of
1741       // expression.
1742       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1743       if (Method && !Method->isStatic()) {
1744         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1745                "Non-unary operator on non-static member address");
1746         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1747                == UO_AddrOf &&
1748                "Non-address-of operator on non-static member address");
1749         const Type *ClassType
1750           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1751         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1752       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1753         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1754                UO_AddrOf &&
1755                "Non-address-of operator for overloaded function expression");
1756         FromType = S.Context.getPointerType(FromType);
1757       }
1758     } else {
1759       return false;
1760     }
1761   }
1762   // Lvalue-to-rvalue conversion (C++11 4.1):
1763   //   A glvalue (3.10) of a non-function, non-array type T can
1764   //   be converted to a prvalue.
1765   bool argIsLValue = From->isGLValue();
1766   if (argIsLValue &&
1767       !FromType->isFunctionType() && !FromType->isArrayType() &&
1768       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769     SCS.First = ICK_Lvalue_To_Rvalue;
1770 
1771     // C11 6.3.2.1p2:
1772     //   ... if the lvalue has atomic type, the value has the non-atomic version
1773     //   of the type of the lvalue ...
1774     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775       FromType = Atomic->getValueType();
1776 
1777     // If T is a non-class type, the type of the rvalue is the
1778     // cv-unqualified version of T. Otherwise, the type of the rvalue
1779     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780     // just strip the qualifiers because they don't matter.
1781     FromType = FromType.getUnqualifiedType();
1782   } else if (FromType->isArrayType()) {
1783     // Array-to-pointer conversion (C++ 4.2)
1784     SCS.First = ICK_Array_To_Pointer;
1785 
1786     // An lvalue or rvalue of type "array of N T" or "array of unknown
1787     // bound of T" can be converted to an rvalue of type "pointer to
1788     // T" (C++ 4.2p1).
1789     FromType = S.Context.getArrayDecayedType(FromType);
1790 
1791     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792       // This conversion is deprecated in C++03 (D.4)
1793       SCS.DeprecatedStringLiteralToCharPtr = true;
1794 
1795       // For the purpose of ranking in overload resolution
1796       // (13.3.3.1.1), this conversion is considered an
1797       // array-to-pointer conversion followed by a qualification
1798       // conversion (4.4). (C++ 4.2p2)
1799       SCS.Second = ICK_Identity;
1800       SCS.Third = ICK_Qualification;
1801       SCS.QualificationIncludesObjCLifetime = false;
1802       SCS.setAllToTypes(FromType);
1803       return true;
1804     }
1805   } else if (FromType->isFunctionType() && argIsLValue) {
1806     // Function-to-pointer conversion (C++ 4.3).
1807     SCS.First = ICK_Function_To_Pointer;
1808 
1809     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811         if (!S.checkAddressOfFunctionIsAvailable(FD))
1812           return false;
1813 
1814     // An lvalue of function type T can be converted to an rvalue of
1815     // type "pointer to T." The result is a pointer to the
1816     // function. (C++ 4.3p1).
1817     FromType = S.Context.getPointerType(FromType);
1818   } else {
1819     // We don't require any conversions for the first step.
1820     SCS.First = ICK_Identity;
1821   }
1822   SCS.setToType(0, FromType);
1823 
1824   // The second conversion can be an integral promotion, floating
1825   // point promotion, integral conversion, floating point conversion,
1826   // floating-integral conversion, pointer conversion,
1827   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828   // For overloading in C, this can also be a "compatible-type"
1829   // conversion.
1830   bool IncompatibleObjC = false;
1831   ImplicitConversionKind SecondICK = ICK_Identity;
1832   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833     // The unqualified versions of the types are the same: there's no
1834     // conversion to do.
1835     SCS.Second = ICK_Identity;
1836   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837     // Integral promotion (C++ 4.5).
1838     SCS.Second = ICK_Integral_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841     // Floating point promotion (C++ 4.6).
1842     SCS.Second = ICK_Floating_Promotion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (S.IsComplexPromotion(FromType, ToType)) {
1845     // Complex promotion (Clang extension)
1846     SCS.Second = ICK_Complex_Promotion;
1847     FromType = ToType.getUnqualifiedType();
1848   } else if (ToType->isBooleanType() &&
1849              (FromType->isArithmeticType() ||
1850               FromType->isAnyPointerType() ||
1851               FromType->isBlockPointerType() ||
1852               FromType->isMemberPointerType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double, __ibm128 and __float128
1872     // if their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874 
1875     // Conversions between bfloat and other floats are not permitted.
1876     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877       return false;
1878 
1879     // Conversions between IEEE-quad and IBM-extended semantics are not
1880     // permitted.
1881     const llvm::fltSemantics &FromSem =
1882         S.Context.getFloatTypeSemantics(FromType);
1883     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1884     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1885          &ToSem == &llvm::APFloat::IEEEquad()) ||
1886         (&FromSem == &llvm::APFloat::IEEEquad() &&
1887          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1888       return false;
1889 
1890     // Floating point conversions (C++ 4.8).
1891     SCS.Second = ICK_Floating_Conversion;
1892     FromType = ToType.getUnqualifiedType();
1893   } else if ((FromType->isRealFloatingType() &&
1894               ToType->isIntegralType(S.Context)) ||
1895              (FromType->isIntegralOrUnscopedEnumerationType() &&
1896               ToType->isRealFloatingType())) {
1897     // Conversions between bfloat and int are not permitted.
1898     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1899       return false;
1900 
1901     // Floating-integral conversions (C++ 4.9).
1902     SCS.Second = ICK_Floating_Integral;
1903     FromType = ToType.getUnqualifiedType();
1904   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1905     SCS.Second = ICK_Block_Pointer_Conversion;
1906   } else if (AllowObjCWritebackConversion &&
1907              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1908     SCS.Second = ICK_Writeback_Conversion;
1909   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1910                                    FromType, IncompatibleObjC)) {
1911     // Pointer conversions (C++ 4.10).
1912     SCS.Second = ICK_Pointer_Conversion;
1913     SCS.IncompatibleObjC = IncompatibleObjC;
1914     FromType = FromType.getUnqualifiedType();
1915   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1916                                          InOverloadResolution, FromType)) {
1917     // Pointer to member conversions (4.11).
1918     SCS.Second = ICK_Pointer_Member;
1919   } else if (IsVectorConversion(S, FromType, ToType, SecondICK, From,
1920                                 InOverloadResolution)) {
1921     SCS.Second = SecondICK;
1922     FromType = ToType.getUnqualifiedType();
1923   } else if (!S.getLangOpts().CPlusPlus &&
1924              S.Context.typesAreCompatible(ToType, FromType)) {
1925     // Compatible conversions (Clang extension for C function overloading)
1926     SCS.Second = ICK_Compatible_Conversion;
1927     FromType = ToType.getUnqualifiedType();
1928   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1929                                              InOverloadResolution,
1930                                              SCS, CStyle)) {
1931     SCS.Second = ICK_TransparentUnionConversion;
1932     FromType = ToType;
1933   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1934                                  CStyle)) {
1935     // tryAtomicConversion has updated the standard conversion sequence
1936     // appropriately.
1937     return true;
1938   } else if (ToType->isEventT() &&
1939              From->isIntegerConstantExpr(S.getASTContext()) &&
1940              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1941     SCS.Second = ICK_Zero_Event_Conversion;
1942     FromType = ToType;
1943   } else if (ToType->isQueueT() &&
1944              From->isIntegerConstantExpr(S.getASTContext()) &&
1945              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1946     SCS.Second = ICK_Zero_Queue_Conversion;
1947     FromType = ToType;
1948   } else if (ToType->isSamplerT() &&
1949              From->isIntegerConstantExpr(S.getASTContext())) {
1950     SCS.Second = ICK_Compatible_Conversion;
1951     FromType = ToType;
1952   } else {
1953     // No second conversion required.
1954     SCS.Second = ICK_Identity;
1955   }
1956   SCS.setToType(1, FromType);
1957 
1958   // The third conversion can be a function pointer conversion or a
1959   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1960   bool ObjCLifetimeConversion;
1961   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1962     // Function pointer conversions (removing 'noexcept') including removal of
1963     // 'noreturn' (Clang extension).
1964     SCS.Third = ICK_Function_Conversion;
1965   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1966                                          ObjCLifetimeConversion)) {
1967     SCS.Third = ICK_Qualification;
1968     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1969     FromType = ToType;
1970   } else {
1971     // No conversion required
1972     SCS.Third = ICK_Identity;
1973   }
1974 
1975   // C++ [over.best.ics]p6:
1976   //   [...] Any difference in top-level cv-qualification is
1977   //   subsumed by the initialization itself and does not constitute
1978   //   a conversion. [...]
1979   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1980   QualType CanonTo = S.Context.getCanonicalType(ToType);
1981   if (CanonFrom.getLocalUnqualifiedType()
1982                                      == CanonTo.getLocalUnqualifiedType() &&
1983       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1984     FromType = ToType;
1985     CanonFrom = CanonTo;
1986   }
1987 
1988   SCS.setToType(2, FromType);
1989 
1990   if (CanonFrom == CanonTo)
1991     return true;
1992 
1993   // If we have not converted the argument type to the parameter type,
1994   // this is a bad conversion sequence, unless we're resolving an overload in C.
1995   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1996     return false;
1997 
1998   ExprResult ER = ExprResult{From};
1999   Sema::AssignConvertType Conv =
2000       S.CheckSingleAssignmentConstraints(ToType, ER,
2001                                          /*Diagnose=*/false,
2002                                          /*DiagnoseCFAudited=*/false,
2003                                          /*ConvertRHS=*/false);
2004   ImplicitConversionKind SecondConv;
2005   switch (Conv) {
2006   case Sema::Compatible:
2007     SecondConv = ICK_C_Only_Conversion;
2008     break;
2009   // For our purposes, discarding qualifiers is just as bad as using an
2010   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2011   // qualifiers, as well.
2012   case Sema::CompatiblePointerDiscardsQualifiers:
2013   case Sema::IncompatiblePointer:
2014   case Sema::IncompatiblePointerSign:
2015     SecondConv = ICK_Incompatible_Pointer_Conversion;
2016     break;
2017   default:
2018     return false;
2019   }
2020 
2021   // First can only be an lvalue conversion, so we pretend that this was the
2022   // second conversion. First should already be valid from earlier in the
2023   // function.
2024   SCS.Second = SecondConv;
2025   SCS.setToType(1, ToType);
2026 
2027   // Third is Identity, because Second should rank us worse than any other
2028   // conversion. This could also be ICK_Qualification, but it's simpler to just
2029   // lump everything in with the second conversion, and we don't gain anything
2030   // from making this ICK_Qualification.
2031   SCS.Third = ICK_Identity;
2032   SCS.setToType(2, ToType);
2033   return true;
2034 }
2035 
2036 static bool
2037 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2038                                      QualType &ToType,
2039                                      bool InOverloadResolution,
2040                                      StandardConversionSequence &SCS,
2041                                      bool CStyle) {
2042 
2043   const RecordType *UT = ToType->getAsUnionType();
2044   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2045     return false;
2046   // The field to initialize within the transparent union.
2047   RecordDecl *UD = UT->getDecl();
2048   // It's compatible if the expression matches any of the fields.
2049   for (const auto *it : UD->fields()) {
2050     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2051                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2052       ToType = it->getType();
2053       return true;
2054     }
2055   }
2056   return false;
2057 }
2058 
2059 /// IsIntegralPromotion - Determines whether the conversion from the
2060 /// expression From (whose potentially-adjusted type is FromType) to
2061 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2062 /// sets PromotedType to the promoted type.
2063 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2064   const BuiltinType *To = ToType->getAs<BuiltinType>();
2065   // All integers are built-in.
2066   if (!To) {
2067     return false;
2068   }
2069 
2070   // An rvalue of type char, signed char, unsigned char, short int, or
2071   // unsigned short int can be converted to an rvalue of type int if
2072   // int can represent all the values of the source type; otherwise,
2073   // the source rvalue can be converted to an rvalue of type unsigned
2074   // int (C++ 4.5p1).
2075   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2076       !FromType->isEnumeralType()) {
2077     if (// We can promote any signed, promotable integer type to an int
2078         (FromType->isSignedIntegerType() ||
2079          // We can promote any unsigned integer type whose size is
2080          // less than int to an int.
2081          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2082       return To->getKind() == BuiltinType::Int;
2083     }
2084 
2085     return To->getKind() == BuiltinType::UInt;
2086   }
2087 
2088   // C++11 [conv.prom]p3:
2089   //   A prvalue of an unscoped enumeration type whose underlying type is not
2090   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2091   //   following types that can represent all the values of the enumeration
2092   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2093   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2094   //   long long int. If none of the types in that list can represent all the
2095   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2096   //   type can be converted to an rvalue a prvalue of the extended integer type
2097   //   with lowest integer conversion rank (4.13) greater than the rank of long
2098   //   long in which all the values of the enumeration can be represented. If
2099   //   there are two such extended types, the signed one is chosen.
2100   // C++11 [conv.prom]p4:
2101   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2102   //   can be converted to a prvalue of its underlying type. Moreover, if
2103   //   integral promotion can be applied to its underlying type, a prvalue of an
2104   //   unscoped enumeration type whose underlying type is fixed can also be
2105   //   converted to a prvalue of the promoted underlying type.
2106   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2107     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2108     // provided for a scoped enumeration.
2109     if (FromEnumType->getDecl()->isScoped())
2110       return false;
2111 
2112     // We can perform an integral promotion to the underlying type of the enum,
2113     // even if that's not the promoted type. Note that the check for promoting
2114     // the underlying type is based on the type alone, and does not consider
2115     // the bitfield-ness of the actual source expression.
2116     if (FromEnumType->getDecl()->isFixed()) {
2117       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2118       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2119              IsIntegralPromotion(nullptr, Underlying, ToType);
2120     }
2121 
2122     // We have already pre-calculated the promotion type, so this is trivial.
2123     if (ToType->isIntegerType() &&
2124         isCompleteType(From->getBeginLoc(), FromType))
2125       return Context.hasSameUnqualifiedType(
2126           ToType, FromEnumType->getDecl()->getPromotionType());
2127 
2128     // C++ [conv.prom]p5:
2129     //   If the bit-field has an enumerated type, it is treated as any other
2130     //   value of that type for promotion purposes.
2131     //
2132     // ... so do not fall through into the bit-field checks below in C++.
2133     if (getLangOpts().CPlusPlus)
2134       return false;
2135   }
2136 
2137   // C++0x [conv.prom]p2:
2138   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2139   //   to an rvalue a prvalue of the first of the following types that can
2140   //   represent all the values of its underlying type: int, unsigned int,
2141   //   long int, unsigned long int, long long int, or unsigned long long int.
2142   //   If none of the types in that list can represent all the values of its
2143   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2144   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2145   //   type.
2146   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2147       ToType->isIntegerType()) {
2148     // Determine whether the type we're converting from is signed or
2149     // unsigned.
2150     bool FromIsSigned = FromType->isSignedIntegerType();
2151     uint64_t FromSize = Context.getTypeSize(FromType);
2152 
2153     // The types we'll try to promote to, in the appropriate
2154     // order. Try each of these types.
2155     QualType PromoteTypes[6] = {
2156       Context.IntTy, Context.UnsignedIntTy,
2157       Context.LongTy, Context.UnsignedLongTy ,
2158       Context.LongLongTy, Context.UnsignedLongLongTy
2159     };
2160     for (int Idx = 0; Idx < 6; ++Idx) {
2161       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2162       if (FromSize < ToSize ||
2163           (FromSize == ToSize &&
2164            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2165         // We found the type that we can promote to. If this is the
2166         // type we wanted, we have a promotion. Otherwise, no
2167         // promotion.
2168         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2169       }
2170     }
2171   }
2172 
2173   // An rvalue for an integral bit-field (9.6) can be converted to an
2174   // rvalue of type int if int can represent all the values of the
2175   // bit-field; otherwise, it can be converted to unsigned int if
2176   // unsigned int can represent all the values of the bit-field. If
2177   // the bit-field is larger yet, no integral promotion applies to
2178   // it. If the bit-field has an enumerated type, it is treated as any
2179   // other value of that type for promotion purposes (C++ 4.5p3).
2180   // FIXME: We should delay checking of bit-fields until we actually perform the
2181   // conversion.
2182   //
2183   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2184   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2185   // bit-fields and those whose underlying type is larger than int) for GCC
2186   // compatibility.
2187   if (From) {
2188     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2189       Optional<llvm::APSInt> BitWidth;
2190       if (FromType->isIntegralType(Context) &&
2191           (BitWidth =
2192                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2193         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2194         ToSize = Context.getTypeSize(ToType);
2195 
2196         // Are we promoting to an int from a bitfield that fits in an int?
2197         if (*BitWidth < ToSize ||
2198             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2199           return To->getKind() == BuiltinType::Int;
2200         }
2201 
2202         // Are we promoting to an unsigned int from an unsigned bitfield
2203         // that fits into an unsigned int?
2204         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2205           return To->getKind() == BuiltinType::UInt;
2206         }
2207 
2208         return false;
2209       }
2210     }
2211   }
2212 
2213   // An rvalue of type bool can be converted to an rvalue of type int,
2214   // with false becoming zero and true becoming one (C++ 4.5p4).
2215   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2216     return true;
2217   }
2218 
2219   return false;
2220 }
2221 
2222 /// IsFloatingPointPromotion - Determines whether the conversion from
2223 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2224 /// returns true and sets PromotedType to the promoted type.
2225 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2226   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2227     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2228       /// An rvalue of type float can be converted to an rvalue of type
2229       /// double. (C++ 4.6p1).
2230       if (FromBuiltin->getKind() == BuiltinType::Float &&
2231           ToBuiltin->getKind() == BuiltinType::Double)
2232         return true;
2233 
2234       // C99 6.3.1.5p1:
2235       //   When a float is promoted to double or long double, or a
2236       //   double is promoted to long double [...].
2237       if (!getLangOpts().CPlusPlus &&
2238           (FromBuiltin->getKind() == BuiltinType::Float ||
2239            FromBuiltin->getKind() == BuiltinType::Double) &&
2240           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2241            ToBuiltin->getKind() == BuiltinType::Float128 ||
2242            ToBuiltin->getKind() == BuiltinType::Ibm128))
2243         return true;
2244 
2245       // Half can be promoted to float.
2246       if (!getLangOpts().NativeHalfType &&
2247            FromBuiltin->getKind() == BuiltinType::Half &&
2248           ToBuiltin->getKind() == BuiltinType::Float)
2249         return true;
2250     }
2251 
2252   return false;
2253 }
2254 
2255 /// Determine if a conversion is a complex promotion.
2256 ///
2257 /// A complex promotion is defined as a complex -> complex conversion
2258 /// where the conversion between the underlying real types is a
2259 /// floating-point or integral promotion.
2260 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2261   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2262   if (!FromComplex)
2263     return false;
2264 
2265   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2266   if (!ToComplex)
2267     return false;
2268 
2269   return IsFloatingPointPromotion(FromComplex->getElementType(),
2270                                   ToComplex->getElementType()) ||
2271     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2272                         ToComplex->getElementType());
2273 }
2274 
2275 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2276 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2277 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2278 /// if non-empty, will be a pointer to ToType that may or may not have
2279 /// the right set of qualifiers on its pointee.
2280 ///
2281 static QualType
2282 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2283                                    QualType ToPointee, QualType ToType,
2284                                    ASTContext &Context,
2285                                    bool StripObjCLifetime = false) {
2286   assert((FromPtr->getTypeClass() == Type::Pointer ||
2287           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2288          "Invalid similarly-qualified pointer type");
2289 
2290   /// Conversions to 'id' subsume cv-qualifier conversions.
2291   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2292     return ToType.getUnqualifiedType();
2293 
2294   QualType CanonFromPointee
2295     = Context.getCanonicalType(FromPtr->getPointeeType());
2296   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2297   Qualifiers Quals = CanonFromPointee.getQualifiers();
2298 
2299   if (StripObjCLifetime)
2300     Quals.removeObjCLifetime();
2301 
2302   // Exact qualifier match -> return the pointer type we're converting to.
2303   if (CanonToPointee.getLocalQualifiers() == Quals) {
2304     // ToType is exactly what we need. Return it.
2305     if (!ToType.isNull())
2306       return ToType.getUnqualifiedType();
2307 
2308     // Build a pointer to ToPointee. It has the right qualifiers
2309     // already.
2310     if (isa<ObjCObjectPointerType>(ToType))
2311       return Context.getObjCObjectPointerType(ToPointee);
2312     return Context.getPointerType(ToPointee);
2313   }
2314 
2315   // Just build a canonical type that has the right qualifiers.
2316   QualType QualifiedCanonToPointee
2317     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2318 
2319   if (isa<ObjCObjectPointerType>(ToType))
2320     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2321   return Context.getPointerType(QualifiedCanonToPointee);
2322 }
2323 
2324 static bool isNullPointerConstantForConversion(Expr *Expr,
2325                                                bool InOverloadResolution,
2326                                                ASTContext &Context) {
2327   // Handle value-dependent integral null pointer constants correctly.
2328   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2329   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2330       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2331     return !InOverloadResolution;
2332 
2333   return Expr->isNullPointerConstant(Context,
2334                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2335                                         : Expr::NPC_ValueDependentIsNull);
2336 }
2337 
2338 /// IsPointerConversion - Determines whether the conversion of the
2339 /// expression From, which has the (possibly adjusted) type FromType,
2340 /// can be converted to the type ToType via a pointer conversion (C++
2341 /// 4.10). If so, returns true and places the converted type (that
2342 /// might differ from ToType in its cv-qualifiers at some level) into
2343 /// ConvertedType.
2344 ///
2345 /// This routine also supports conversions to and from block pointers
2346 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2347 /// pointers to interfaces. FIXME: Once we've determined the
2348 /// appropriate overloading rules for Objective-C, we may want to
2349 /// split the Objective-C checks into a different routine; however,
2350 /// GCC seems to consider all of these conversions to be pointer
2351 /// conversions, so for now they live here. IncompatibleObjC will be
2352 /// set if the conversion is an allowed Objective-C conversion that
2353 /// should result in a warning.
2354 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2355                                bool InOverloadResolution,
2356                                QualType& ConvertedType,
2357                                bool &IncompatibleObjC) {
2358   IncompatibleObjC = false;
2359   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2360                               IncompatibleObjC))
2361     return true;
2362 
2363   // Conversion from a null pointer constant to any Objective-C pointer type.
2364   if (ToType->isObjCObjectPointerType() &&
2365       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2366     ConvertedType = ToType;
2367     return true;
2368   }
2369 
2370   // Blocks: Block pointers can be converted to void*.
2371   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2372       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2373     ConvertedType = ToType;
2374     return true;
2375   }
2376   // Blocks: A null pointer constant can be converted to a block
2377   // pointer type.
2378   if (ToType->isBlockPointerType() &&
2379       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2380     ConvertedType = ToType;
2381     return true;
2382   }
2383 
2384   // If the left-hand-side is nullptr_t, the right side can be a null
2385   // pointer constant.
2386   if (ToType->isNullPtrType() &&
2387       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2388     ConvertedType = ToType;
2389     return true;
2390   }
2391 
2392   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2393   if (!ToTypePtr)
2394     return false;
2395 
2396   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2397   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2398     ConvertedType = ToType;
2399     return true;
2400   }
2401 
2402   // Beyond this point, both types need to be pointers
2403   // , including objective-c pointers.
2404   QualType ToPointeeType = ToTypePtr->getPointeeType();
2405   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2406       !getLangOpts().ObjCAutoRefCount) {
2407     ConvertedType = BuildSimilarlyQualifiedPointerType(
2408         FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2409         Context);
2410     return true;
2411   }
2412   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2413   if (!FromTypePtr)
2414     return false;
2415 
2416   QualType FromPointeeType = FromTypePtr->getPointeeType();
2417 
2418   // If the unqualified pointee types are the same, this can't be a
2419   // pointer conversion, so don't do all of the work below.
2420   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2421     return false;
2422 
2423   // An rvalue of type "pointer to cv T," where T is an object type,
2424   // can be converted to an rvalue of type "pointer to cv void" (C++
2425   // 4.10p2).
2426   if (FromPointeeType->isIncompleteOrObjectType() &&
2427       ToPointeeType->isVoidType()) {
2428     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2429                                                        ToPointeeType,
2430                                                        ToType, Context,
2431                                                    /*StripObjCLifetime=*/true);
2432     return true;
2433   }
2434 
2435   // MSVC allows implicit function to void* type conversion.
2436   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2437       ToPointeeType->isVoidType()) {
2438     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2439                                                        ToPointeeType,
2440                                                        ToType, Context);
2441     return true;
2442   }
2443 
2444   // When we're overloading in C, we allow a special kind of pointer
2445   // conversion for compatible-but-not-identical pointee types.
2446   if (!getLangOpts().CPlusPlus &&
2447       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2448     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2449                                                        ToPointeeType,
2450                                                        ToType, Context);
2451     return true;
2452   }
2453 
2454   // C++ [conv.ptr]p3:
2455   //
2456   //   An rvalue of type "pointer to cv D," where D is a class type,
2457   //   can be converted to an rvalue of type "pointer to cv B," where
2458   //   B is a base class (clause 10) of D. If B is an inaccessible
2459   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2460   //   necessitates this conversion is ill-formed. The result of the
2461   //   conversion is a pointer to the base class sub-object of the
2462   //   derived class object. The null pointer value is converted to
2463   //   the null pointer value of the destination type.
2464   //
2465   // Note that we do not check for ambiguity or inaccessibility
2466   // here. That is handled by CheckPointerConversion.
2467   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2468       ToPointeeType->isRecordType() &&
2469       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2470       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2471     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2472                                                        ToPointeeType,
2473                                                        ToType, Context);
2474     return true;
2475   }
2476 
2477   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2478       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2479     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2480                                                        ToPointeeType,
2481                                                        ToType, Context);
2482     return true;
2483   }
2484 
2485   return false;
2486 }
2487 
2488 /// Adopt the given qualifiers for the given type.
2489 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2490   Qualifiers TQs = T.getQualifiers();
2491 
2492   // Check whether qualifiers already match.
2493   if (TQs == Qs)
2494     return T;
2495 
2496   if (Qs.compatiblyIncludes(TQs))
2497     return Context.getQualifiedType(T, Qs);
2498 
2499   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2500 }
2501 
2502 /// isObjCPointerConversion - Determines whether this is an
2503 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2504 /// with the same arguments and return values.
2505 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2506                                    QualType& ConvertedType,
2507                                    bool &IncompatibleObjC) {
2508   if (!getLangOpts().ObjC)
2509     return false;
2510 
2511   // The set of qualifiers on the type we're converting from.
2512   Qualifiers FromQualifiers = FromType.getQualifiers();
2513 
2514   // First, we handle all conversions on ObjC object pointer types.
2515   const ObjCObjectPointerType* ToObjCPtr =
2516     ToType->getAs<ObjCObjectPointerType>();
2517   const ObjCObjectPointerType *FromObjCPtr =
2518     FromType->getAs<ObjCObjectPointerType>();
2519 
2520   if (ToObjCPtr && FromObjCPtr) {
2521     // If the pointee types are the same (ignoring qualifications),
2522     // then this is not a pointer conversion.
2523     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2524                                        FromObjCPtr->getPointeeType()))
2525       return false;
2526 
2527     // Conversion between Objective-C pointers.
2528     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2529       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2530       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2531       if (getLangOpts().CPlusPlus && LHS && RHS &&
2532           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2533                                                 FromObjCPtr->getPointeeType()))
2534         return false;
2535       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2536                                                    ToObjCPtr->getPointeeType(),
2537                                                          ToType, Context);
2538       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539       return true;
2540     }
2541 
2542     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2543       // Okay: this is some kind of implicit downcast of Objective-C
2544       // interfaces, which is permitted. However, we're going to
2545       // complain about it.
2546       IncompatibleObjC = true;
2547       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2548                                                    ToObjCPtr->getPointeeType(),
2549                                                          ToType, Context);
2550       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2551       return true;
2552     }
2553   }
2554   // Beyond this point, both types need to be C pointers or block pointers.
2555   QualType ToPointeeType;
2556   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2557     ToPointeeType = ToCPtr->getPointeeType();
2558   else if (const BlockPointerType *ToBlockPtr =
2559             ToType->getAs<BlockPointerType>()) {
2560     // Objective C++: We're able to convert from a pointer to any object
2561     // to a block pointer type.
2562     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2563       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2564       return true;
2565     }
2566     ToPointeeType = ToBlockPtr->getPointeeType();
2567   }
2568   else if (FromType->getAs<BlockPointerType>() &&
2569            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2570     // Objective C++: We're able to convert from a block pointer type to a
2571     // pointer to any object.
2572     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2573     return true;
2574   }
2575   else
2576     return false;
2577 
2578   QualType FromPointeeType;
2579   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2580     FromPointeeType = FromCPtr->getPointeeType();
2581   else if (const BlockPointerType *FromBlockPtr =
2582            FromType->getAs<BlockPointerType>())
2583     FromPointeeType = FromBlockPtr->getPointeeType();
2584   else
2585     return false;
2586 
2587   // If we have pointers to pointers, recursively check whether this
2588   // is an Objective-C conversion.
2589   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2590       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2591                               IncompatibleObjC)) {
2592     // We always complain about this conversion.
2593     IncompatibleObjC = true;
2594     ConvertedType = Context.getPointerType(ConvertedType);
2595     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596     return true;
2597   }
2598   // Allow conversion of pointee being objective-c pointer to another one;
2599   // as in I* to id.
2600   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2601       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2602       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2603                               IncompatibleObjC)) {
2604 
2605     ConvertedType = Context.getPointerType(ConvertedType);
2606     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2607     return true;
2608   }
2609 
2610   // If we have pointers to functions or blocks, check whether the only
2611   // differences in the argument and result types are in Objective-C
2612   // pointer conversions. If so, we permit the conversion (but
2613   // complain about it).
2614   const FunctionProtoType *FromFunctionType
2615     = FromPointeeType->getAs<FunctionProtoType>();
2616   const FunctionProtoType *ToFunctionType
2617     = ToPointeeType->getAs<FunctionProtoType>();
2618   if (FromFunctionType && ToFunctionType) {
2619     // If the function types are exactly the same, this isn't an
2620     // Objective-C pointer conversion.
2621     if (Context.getCanonicalType(FromPointeeType)
2622           == Context.getCanonicalType(ToPointeeType))
2623       return false;
2624 
2625     // Perform the quick checks that will tell us whether these
2626     // function types are obviously different.
2627     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2628         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2629         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2630       return false;
2631 
2632     bool HasObjCConversion = false;
2633     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2634         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2635       // Okay, the types match exactly. Nothing to do.
2636     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2637                                        ToFunctionType->getReturnType(),
2638                                        ConvertedType, IncompatibleObjC)) {
2639       // Okay, we have an Objective-C pointer conversion.
2640       HasObjCConversion = true;
2641     } else {
2642       // Function types are too different. Abort.
2643       return false;
2644     }
2645 
2646     // Check argument types.
2647     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2648          ArgIdx != NumArgs; ++ArgIdx) {
2649       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2650       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2651       if (Context.getCanonicalType(FromArgType)
2652             == Context.getCanonicalType(ToArgType)) {
2653         // Okay, the types match exactly. Nothing to do.
2654       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2655                                          ConvertedType, IncompatibleObjC)) {
2656         // Okay, we have an Objective-C pointer conversion.
2657         HasObjCConversion = true;
2658       } else {
2659         // Argument types are too different. Abort.
2660         return false;
2661       }
2662     }
2663 
2664     if (HasObjCConversion) {
2665       // We had an Objective-C conversion. Allow this pointer
2666       // conversion, but complain about it.
2667       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2668       IncompatibleObjC = true;
2669       return true;
2670     }
2671   }
2672 
2673   return false;
2674 }
2675 
2676 /// Determine whether this is an Objective-C writeback conversion,
2677 /// used for parameter passing when performing automatic reference counting.
2678 ///
2679 /// \param FromType The type we're converting form.
2680 ///
2681 /// \param ToType The type we're converting to.
2682 ///
2683 /// \param ConvertedType The type that will be produced after applying
2684 /// this conversion.
2685 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2686                                      QualType &ConvertedType) {
2687   if (!getLangOpts().ObjCAutoRefCount ||
2688       Context.hasSameUnqualifiedType(FromType, ToType))
2689     return false;
2690 
2691   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2692   QualType ToPointee;
2693   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2694     ToPointee = ToPointer->getPointeeType();
2695   else
2696     return false;
2697 
2698   Qualifiers ToQuals = ToPointee.getQualifiers();
2699   if (!ToPointee->isObjCLifetimeType() ||
2700       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2701       !ToQuals.withoutObjCLifetime().empty())
2702     return false;
2703 
2704   // Argument must be a pointer to __strong to __weak.
2705   QualType FromPointee;
2706   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2707     FromPointee = FromPointer->getPointeeType();
2708   else
2709     return false;
2710 
2711   Qualifiers FromQuals = FromPointee.getQualifiers();
2712   if (!FromPointee->isObjCLifetimeType() ||
2713       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2714        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2715     return false;
2716 
2717   // Make sure that we have compatible qualifiers.
2718   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2719   if (!ToQuals.compatiblyIncludes(FromQuals))
2720     return false;
2721 
2722   // Remove qualifiers from the pointee type we're converting from; they
2723   // aren't used in the compatibility check belong, and we'll be adding back
2724   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2725   FromPointee = FromPointee.getUnqualifiedType();
2726 
2727   // The unqualified form of the pointee types must be compatible.
2728   ToPointee = ToPointee.getUnqualifiedType();
2729   bool IncompatibleObjC;
2730   if (Context.typesAreCompatible(FromPointee, ToPointee))
2731     FromPointee = ToPointee;
2732   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2733                                     IncompatibleObjC))
2734     return false;
2735 
2736   /// Construct the type we're converting to, which is a pointer to
2737   /// __autoreleasing pointee.
2738   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2739   ConvertedType = Context.getPointerType(FromPointee);
2740   return true;
2741 }
2742 
2743 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2744                                     QualType& ConvertedType) {
2745   QualType ToPointeeType;
2746   if (const BlockPointerType *ToBlockPtr =
2747         ToType->getAs<BlockPointerType>())
2748     ToPointeeType = ToBlockPtr->getPointeeType();
2749   else
2750     return false;
2751 
2752   QualType FromPointeeType;
2753   if (const BlockPointerType *FromBlockPtr =
2754       FromType->getAs<BlockPointerType>())
2755     FromPointeeType = FromBlockPtr->getPointeeType();
2756   else
2757     return false;
2758   // We have pointer to blocks, check whether the only
2759   // differences in the argument and result types are in Objective-C
2760   // pointer conversions. If so, we permit the conversion.
2761 
2762   const FunctionProtoType *FromFunctionType
2763     = FromPointeeType->getAs<FunctionProtoType>();
2764   const FunctionProtoType *ToFunctionType
2765     = ToPointeeType->getAs<FunctionProtoType>();
2766 
2767   if (!FromFunctionType || !ToFunctionType)
2768     return false;
2769 
2770   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2771     return true;
2772 
2773   // Perform the quick checks that will tell us whether these
2774   // function types are obviously different.
2775   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2776       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2777     return false;
2778 
2779   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2780   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2781   if (FromEInfo != ToEInfo)
2782     return false;
2783 
2784   bool IncompatibleObjC = false;
2785   if (Context.hasSameType(FromFunctionType->getReturnType(),
2786                           ToFunctionType->getReturnType())) {
2787     // Okay, the types match exactly. Nothing to do.
2788   } else {
2789     QualType RHS = FromFunctionType->getReturnType();
2790     QualType LHS = ToFunctionType->getReturnType();
2791     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2792         !RHS.hasQualifiers() && LHS.hasQualifiers())
2793        LHS = LHS.getUnqualifiedType();
2794 
2795      if (Context.hasSameType(RHS,LHS)) {
2796        // OK exact match.
2797      } else if (isObjCPointerConversion(RHS, LHS,
2798                                         ConvertedType, IncompatibleObjC)) {
2799      if (IncompatibleObjC)
2800        return false;
2801      // Okay, we have an Objective-C pointer conversion.
2802      }
2803      else
2804        return false;
2805    }
2806 
2807    // Check argument types.
2808    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2809         ArgIdx != NumArgs; ++ArgIdx) {
2810      IncompatibleObjC = false;
2811      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2812      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2813      if (Context.hasSameType(FromArgType, ToArgType)) {
2814        // Okay, the types match exactly. Nothing to do.
2815      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2816                                         ConvertedType, IncompatibleObjC)) {
2817        if (IncompatibleObjC)
2818          return false;
2819        // Okay, we have an Objective-C pointer conversion.
2820      } else
2821        // Argument types are too different. Abort.
2822        return false;
2823    }
2824 
2825    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2826    bool CanUseToFPT, CanUseFromFPT;
2827    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2828                                       CanUseToFPT, CanUseFromFPT,
2829                                       NewParamInfos))
2830      return false;
2831 
2832    ConvertedType = ToType;
2833    return true;
2834 }
2835 
2836 enum {
2837   ft_default,
2838   ft_different_class,
2839   ft_parameter_arity,
2840   ft_parameter_mismatch,
2841   ft_return_type,
2842   ft_qualifer_mismatch,
2843   ft_noexcept
2844 };
2845 
2846 /// Attempts to get the FunctionProtoType from a Type. Handles
2847 /// MemberFunctionPointers properly.
2848 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2849   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2850     return FPT;
2851 
2852   if (auto *MPT = FromType->getAs<MemberPointerType>())
2853     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2854 
2855   return nullptr;
2856 }
2857 
2858 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2859 /// function types.  Catches different number of parameter, mismatch in
2860 /// parameter types, and different return types.
2861 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2862                                       QualType FromType, QualType ToType) {
2863   // If either type is not valid, include no extra info.
2864   if (FromType.isNull() || ToType.isNull()) {
2865     PDiag << ft_default;
2866     return;
2867   }
2868 
2869   // Get the function type from the pointers.
2870   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2871     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2872                *ToMember = ToType->castAs<MemberPointerType>();
2873     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2874       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2875             << QualType(FromMember->getClass(), 0);
2876       return;
2877     }
2878     FromType = FromMember->getPointeeType();
2879     ToType = ToMember->getPointeeType();
2880   }
2881 
2882   if (FromType->isPointerType())
2883     FromType = FromType->getPointeeType();
2884   if (ToType->isPointerType())
2885     ToType = ToType->getPointeeType();
2886 
2887   // Remove references.
2888   FromType = FromType.getNonReferenceType();
2889   ToType = ToType.getNonReferenceType();
2890 
2891   // Don't print extra info for non-specialized template functions.
2892   if (FromType->isInstantiationDependentType() &&
2893       !FromType->getAs<TemplateSpecializationType>()) {
2894     PDiag << ft_default;
2895     return;
2896   }
2897 
2898   // No extra info for same types.
2899   if (Context.hasSameType(FromType, ToType)) {
2900     PDiag << ft_default;
2901     return;
2902   }
2903 
2904   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2905                           *ToFunction = tryGetFunctionProtoType(ToType);
2906 
2907   // Both types need to be function types.
2908   if (!FromFunction || !ToFunction) {
2909     PDiag << ft_default;
2910     return;
2911   }
2912 
2913   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2914     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2915           << FromFunction->getNumParams();
2916     return;
2917   }
2918 
2919   // Handle different parameter types.
2920   unsigned ArgPos;
2921   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2922     PDiag << ft_parameter_mismatch << ArgPos + 1
2923           << ToFunction->getParamType(ArgPos)
2924           << FromFunction->getParamType(ArgPos);
2925     return;
2926   }
2927 
2928   // Handle different return type.
2929   if (!Context.hasSameType(FromFunction->getReturnType(),
2930                            ToFunction->getReturnType())) {
2931     PDiag << ft_return_type << ToFunction->getReturnType()
2932           << FromFunction->getReturnType();
2933     return;
2934   }
2935 
2936   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2937     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2938           << FromFunction->getMethodQuals();
2939     return;
2940   }
2941 
2942   // Handle exception specification differences on canonical type (in C++17
2943   // onwards).
2944   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow() !=
2946       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2947           ->isNothrow()) {
2948     PDiag << ft_noexcept;
2949     return;
2950   }
2951 
2952   // Unable to find a difference, so add no extra info.
2953   PDiag << ft_default;
2954 }
2955 
2956 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2957 /// for equality of their parameter types. Caller has already checked that
2958 /// they have same number of parameters.  If the parameters are different,
2959 /// ArgPos will have the parameter index of the first different parameter.
2960 /// If `Reversed` is true, the parameters of `NewType` will be compared in
2961 /// reverse order. That's useful if one of the functions is being used as a C++20
2962 /// synthesized operator overload with a reversed parameter order.
2963 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2964                                       const FunctionProtoType *NewType,
2965                                       unsigned *ArgPos, bool Reversed) {
2966   assert(OldType->getNumParams() == NewType->getNumParams() &&
2967          "Can't compare parameters of functions with different number of "
2968          "parameters!");
2969   for (size_t I = 0; I < OldType->getNumParams(); I++) {
2970     // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
2971     size_t J = Reversed ? (OldType->getNumParams() - I - 1) : I;
2972 
2973     // Ignore address spaces in pointee type. This is to disallow overloading
2974     // on __ptr32/__ptr64 address spaces.
2975     QualType Old = Context.removePtrSizeAddrSpace(OldType->getParamType(I).getUnqualifiedType());
2976     QualType New = Context.removePtrSizeAddrSpace(NewType->getParamType(J).getUnqualifiedType());
2977 
2978     if (!Context.hasSameType(Old, New)) {
2979       if (ArgPos)
2980         *ArgPos = I;
2981       return false;
2982     }
2983   }
2984   return true;
2985 }
2986 
2987 /// CheckPointerConversion - Check the pointer conversion from the
2988 /// expression From to the type ToType. This routine checks for
2989 /// ambiguous or inaccessible derived-to-base pointer
2990 /// conversions for which IsPointerConversion has already returned
2991 /// true. It returns true and produces a diagnostic if there was an
2992 /// error, or returns false otherwise.
2993 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2994                                   CastKind &Kind,
2995                                   CXXCastPath& BasePath,
2996                                   bool IgnoreBaseAccess,
2997                                   bool Diagnose) {
2998   QualType FromType = From->getType();
2999   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3000 
3001   Kind = CK_BitCast;
3002 
3003   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3004       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3005           Expr::NPCK_ZeroExpression) {
3006     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3007       DiagRuntimeBehavior(From->getExprLoc(), From,
3008                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3009                             << ToType << From->getSourceRange());
3010     else if (!isUnevaluatedContext())
3011       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3012         << ToType << From->getSourceRange();
3013   }
3014   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3015     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3016       QualType FromPointeeType = FromPtrType->getPointeeType(),
3017                ToPointeeType   = ToPtrType->getPointeeType();
3018 
3019       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3020           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3021         // We must have a derived-to-base conversion. Check an
3022         // ambiguous or inaccessible conversion.
3023         unsigned InaccessibleID = 0;
3024         unsigned AmbiguousID = 0;
3025         if (Diagnose) {
3026           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3027           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3028         }
3029         if (CheckDerivedToBaseConversion(
3030                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3031                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3032                 &BasePath, IgnoreBaseAccess))
3033           return true;
3034 
3035         // The conversion was successful.
3036         Kind = CK_DerivedToBase;
3037       }
3038 
3039       if (Diagnose && !IsCStyleOrFunctionalCast &&
3040           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3041         assert(getLangOpts().MSVCCompat &&
3042                "this should only be possible with MSVCCompat!");
3043         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3044             << From->getSourceRange();
3045       }
3046     }
3047   } else if (const ObjCObjectPointerType *ToPtrType =
3048                ToType->getAs<ObjCObjectPointerType>()) {
3049     if (const ObjCObjectPointerType *FromPtrType =
3050           FromType->getAs<ObjCObjectPointerType>()) {
3051       // Objective-C++ conversions are always okay.
3052       // FIXME: We should have a different class of conversions for the
3053       // Objective-C++ implicit conversions.
3054       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3055         return false;
3056     } else if (FromType->isBlockPointerType()) {
3057       Kind = CK_BlockPointerToObjCPointerCast;
3058     } else {
3059       Kind = CK_CPointerToObjCPointerCast;
3060     }
3061   } else if (ToType->isBlockPointerType()) {
3062     if (!FromType->isBlockPointerType())
3063       Kind = CK_AnyPointerToBlockPointerCast;
3064   }
3065 
3066   // We shouldn't fall into this case unless it's valid for other
3067   // reasons.
3068   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3069     Kind = CK_NullToPointer;
3070 
3071   return false;
3072 }
3073 
3074 /// IsMemberPointerConversion - Determines whether the conversion of the
3075 /// expression From, which has the (possibly adjusted) type FromType, can be
3076 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3077 /// If so, returns true and places the converted type (that might differ from
3078 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3079 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3080                                      QualType ToType,
3081                                      bool InOverloadResolution,
3082                                      QualType &ConvertedType) {
3083   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3084   if (!ToTypePtr)
3085     return false;
3086 
3087   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3088   if (From->isNullPointerConstant(Context,
3089                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3090                                         : Expr::NPC_ValueDependentIsNull)) {
3091     ConvertedType = ToType;
3092     return true;
3093   }
3094 
3095   // Otherwise, both types have to be member pointers.
3096   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3097   if (!FromTypePtr)
3098     return false;
3099 
3100   // A pointer to member of B can be converted to a pointer to member of D,
3101   // where D is derived from B (C++ 4.11p2).
3102   QualType FromClass(FromTypePtr->getClass(), 0);
3103   QualType ToClass(ToTypePtr->getClass(), 0);
3104 
3105   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3106       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3107     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3108                                                  ToClass.getTypePtr());
3109     return true;
3110   }
3111 
3112   return false;
3113 }
3114 
3115 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3116 /// expression From to the type ToType. This routine checks for ambiguous or
3117 /// virtual or inaccessible base-to-derived member pointer conversions
3118 /// for which IsMemberPointerConversion has already returned true. It returns
3119 /// true and produces a diagnostic if there was an error, or returns false
3120 /// otherwise.
3121 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3122                                         CastKind &Kind,
3123                                         CXXCastPath &BasePath,
3124                                         bool IgnoreBaseAccess) {
3125   QualType FromType = From->getType();
3126   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3127   if (!FromPtrType) {
3128     // This must be a null pointer to member pointer conversion
3129     assert(From->isNullPointerConstant(Context,
3130                                        Expr::NPC_ValueDependentIsNull) &&
3131            "Expr must be null pointer constant!");
3132     Kind = CK_NullToMemberPointer;
3133     return false;
3134   }
3135 
3136   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3137   assert(ToPtrType && "No member pointer cast has a target type "
3138                       "that is not a member pointer.");
3139 
3140   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3141   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3142 
3143   // FIXME: What about dependent types?
3144   assert(FromClass->isRecordType() && "Pointer into non-class.");
3145   assert(ToClass->isRecordType() && "Pointer into non-class.");
3146 
3147   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148                      /*DetectVirtual=*/true);
3149   bool DerivationOkay =
3150       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3151   assert(DerivationOkay &&
3152          "Should not have been called if derivation isn't OK.");
3153   (void)DerivationOkay;
3154 
3155   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3156                                   getUnqualifiedType())) {
3157     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3158     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3159       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3160     return true;
3161   }
3162 
3163   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3164     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3165       << FromClass << ToClass << QualType(VBase, 0)
3166       << From->getSourceRange();
3167     return true;
3168   }
3169 
3170   if (!IgnoreBaseAccess)
3171     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3172                          Paths.front(),
3173                          diag::err_downcast_from_inaccessible_base);
3174 
3175   // Must be a base to derived member conversion.
3176   BuildBasePathArray(Paths, BasePath);
3177   Kind = CK_BaseToDerivedMemberPointer;
3178   return false;
3179 }
3180 
3181 /// Determine whether the lifetime conversion between the two given
3182 /// qualifiers sets is nontrivial.
3183 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3184                                                Qualifiers ToQuals) {
3185   // Converting anything to const __unsafe_unretained is trivial.
3186   if (ToQuals.hasConst() &&
3187       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3188     return false;
3189 
3190   return true;
3191 }
3192 
3193 /// Perform a single iteration of the loop for checking if a qualification
3194 /// conversion is valid.
3195 ///
3196 /// Specifically, check whether any change between the qualifiers of \p
3197 /// FromType and \p ToType is permissible, given knowledge about whether every
3198 /// outer layer is const-qualified.
3199 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3200                                           bool CStyle, bool IsTopLevel,
3201                                           bool &PreviousToQualsIncludeConst,
3202                                           bool &ObjCLifetimeConversion) {
3203   Qualifiers FromQuals = FromType.getQualifiers();
3204   Qualifiers ToQuals = ToType.getQualifiers();
3205 
3206   // Ignore __unaligned qualifier.
3207   FromQuals.removeUnaligned();
3208 
3209   // Objective-C ARC:
3210   //   Check Objective-C lifetime conversions.
3211   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3212     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3213       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3214         ObjCLifetimeConversion = true;
3215       FromQuals.removeObjCLifetime();
3216       ToQuals.removeObjCLifetime();
3217     } else {
3218       // Qualification conversions cannot cast between different
3219       // Objective-C lifetime qualifiers.
3220       return false;
3221     }
3222   }
3223 
3224   // Allow addition/removal of GC attributes but not changing GC attributes.
3225   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3226       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3227     FromQuals.removeObjCGCAttr();
3228     ToQuals.removeObjCGCAttr();
3229   }
3230 
3231   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3232   //      2,j, and similarly for volatile.
3233   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3234     return false;
3235 
3236   // If address spaces mismatch:
3237   //  - in top level it is only valid to convert to addr space that is a
3238   //    superset in all cases apart from C-style casts where we allow
3239   //    conversions between overlapping address spaces.
3240   //  - in non-top levels it is not a valid conversion.
3241   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3242       (!IsTopLevel ||
3243        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3244          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3245     return false;
3246 
3247   //   -- if the cv 1,j and cv 2,j are different, then const is in
3248   //      every cv for 0 < k < j.
3249   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3250       !PreviousToQualsIncludeConst)
3251     return false;
3252 
3253   // The following wording is from C++20, where the result of the conversion
3254   // is T3, not T2.
3255   //   -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3256   //      "array of unknown bound of"
3257   if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3258     return false;
3259 
3260   //   -- if the resulting P3,i is different from P1,i [...], then const is
3261   //      added to every cv 3_k for 0 < k < i.
3262   if (!CStyle && FromType->isConstantArrayType() &&
3263       ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3264     return false;
3265 
3266   // Keep track of whether all prior cv-qualifiers in the "to" type
3267   // include const.
3268   PreviousToQualsIncludeConst =
3269       PreviousToQualsIncludeConst && ToQuals.hasConst();
3270   return true;
3271 }
3272 
3273 /// IsQualificationConversion - Determines whether the conversion from
3274 /// an rvalue of type FromType to ToType is a qualification conversion
3275 /// (C++ 4.4).
3276 ///
3277 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3278 /// when the qualification conversion involves a change in the Objective-C
3279 /// object lifetime.
3280 bool
3281 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3282                                 bool CStyle, bool &ObjCLifetimeConversion) {
3283   FromType = Context.getCanonicalType(FromType);
3284   ToType = Context.getCanonicalType(ToType);
3285   ObjCLifetimeConversion = false;
3286 
3287   // If FromType and ToType are the same type, this is not a
3288   // qualification conversion.
3289   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3290     return false;
3291 
3292   // (C++ 4.4p4):
3293   //   A conversion can add cv-qualifiers at levels other than the first
3294   //   in multi-level pointers, subject to the following rules: [...]
3295   bool PreviousToQualsIncludeConst = true;
3296   bool UnwrappedAnyPointer = false;
3297   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3298     if (!isQualificationConversionStep(
3299             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3300             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3301       return false;
3302     UnwrappedAnyPointer = true;
3303   }
3304 
3305   // We are left with FromType and ToType being the pointee types
3306   // after unwrapping the original FromType and ToType the same number
3307   // of times. If we unwrapped any pointers, and if FromType and
3308   // ToType have the same unqualified type (since we checked
3309   // qualifiers above), then this is a qualification conversion.
3310   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3311 }
3312 
3313 /// - Determine whether this is a conversion from a scalar type to an
3314 /// atomic type.
3315 ///
3316 /// If successful, updates \c SCS's second and third steps in the conversion
3317 /// sequence to finish the conversion.
3318 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3319                                 bool InOverloadResolution,
3320                                 StandardConversionSequence &SCS,
3321                                 bool CStyle) {
3322   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3323   if (!ToAtomic)
3324     return false;
3325 
3326   StandardConversionSequence InnerSCS;
3327   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3328                             InOverloadResolution, InnerSCS,
3329                             CStyle, /*AllowObjCWritebackConversion=*/false))
3330     return false;
3331 
3332   SCS.Second = InnerSCS.Second;
3333   SCS.setToType(1, InnerSCS.getToType(1));
3334   SCS.Third = InnerSCS.Third;
3335   SCS.QualificationIncludesObjCLifetime
3336     = InnerSCS.QualificationIncludesObjCLifetime;
3337   SCS.setToType(2, InnerSCS.getToType(2));
3338   return true;
3339 }
3340 
3341 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3342                                               CXXConstructorDecl *Constructor,
3343                                               QualType Type) {
3344   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3345   if (CtorType->getNumParams() > 0) {
3346     QualType FirstArg = CtorType->getParamType(0);
3347     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3348       return true;
3349   }
3350   return false;
3351 }
3352 
3353 static OverloadingResult
3354 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3355                                        CXXRecordDecl *To,
3356                                        UserDefinedConversionSequence &User,
3357                                        OverloadCandidateSet &CandidateSet,
3358                                        bool AllowExplicit) {
3359   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3360   for (auto *D : S.LookupConstructors(To)) {
3361     auto Info = getConstructorInfo(D);
3362     if (!Info)
3363       continue;
3364 
3365     bool Usable = !Info.Constructor->isInvalidDecl() &&
3366                   S.isInitListConstructor(Info.Constructor);
3367     if (Usable) {
3368       bool SuppressUserConversions = false;
3369       if (Info.ConstructorTmpl)
3370         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3371                                        /*ExplicitArgs*/ nullptr, From,
3372                                        CandidateSet, SuppressUserConversions,
3373                                        /*PartialOverloading*/ false,
3374                                        AllowExplicit);
3375       else
3376         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3377                                CandidateSet, SuppressUserConversions,
3378                                /*PartialOverloading*/ false, AllowExplicit);
3379     }
3380   }
3381 
3382   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3383 
3384   OverloadCandidateSet::iterator Best;
3385   switch (auto Result =
3386               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3387   case OR_Deleted:
3388   case OR_Success: {
3389     // Record the standard conversion we used and the conversion function.
3390     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3391     QualType ThisType = Constructor->getThisType();
3392     // Initializer lists don't have conversions as such.
3393     User.Before.setAsIdentityConversion();
3394     User.HadMultipleCandidates = HadMultipleCandidates;
3395     User.ConversionFunction = Constructor;
3396     User.FoundConversionFunction = Best->FoundDecl;
3397     User.After.setAsIdentityConversion();
3398     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3399     User.After.setAllToTypes(ToType);
3400     return Result;
3401   }
3402 
3403   case OR_No_Viable_Function:
3404     return OR_No_Viable_Function;
3405   case OR_Ambiguous:
3406     return OR_Ambiguous;
3407   }
3408 
3409   llvm_unreachable("Invalid OverloadResult!");
3410 }
3411 
3412 /// Determines whether there is a user-defined conversion sequence
3413 /// (C++ [over.ics.user]) that converts expression From to the type
3414 /// ToType. If such a conversion exists, User will contain the
3415 /// user-defined conversion sequence that performs such a conversion
3416 /// and this routine will return true. Otherwise, this routine returns
3417 /// false and User is unspecified.
3418 ///
3419 /// \param AllowExplicit  true if the conversion should consider C++0x
3420 /// "explicit" conversion functions as well as non-explicit conversion
3421 /// functions (C++0x [class.conv.fct]p2).
3422 ///
3423 /// \param AllowObjCConversionOnExplicit true if the conversion should
3424 /// allow an extra Objective-C pointer conversion on uses of explicit
3425 /// constructors. Requires \c AllowExplicit to also be set.
3426 static OverloadingResult
3427 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3428                         UserDefinedConversionSequence &User,
3429                         OverloadCandidateSet &CandidateSet,
3430                         AllowedExplicit AllowExplicit,
3431                         bool AllowObjCConversionOnExplicit) {
3432   assert(AllowExplicit != AllowedExplicit::None ||
3433          !AllowObjCConversionOnExplicit);
3434   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3435 
3436   // Whether we will only visit constructors.
3437   bool ConstructorsOnly = false;
3438 
3439   // If the type we are conversion to is a class type, enumerate its
3440   // constructors.
3441   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3442     // C++ [over.match.ctor]p1:
3443     //   When objects of class type are direct-initialized (8.5), or
3444     //   copy-initialized from an expression of the same or a
3445     //   derived class type (8.5), overload resolution selects the
3446     //   constructor. [...] For copy-initialization, the candidate
3447     //   functions are all the converting constructors (12.3.1) of
3448     //   that class. The argument list is the expression-list within
3449     //   the parentheses of the initializer.
3450     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3451         (From->getType()->getAs<RecordType>() &&
3452          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3453       ConstructorsOnly = true;
3454 
3455     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3456       // We're not going to find any constructors.
3457     } else if (CXXRecordDecl *ToRecordDecl
3458                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3459 
3460       Expr **Args = &From;
3461       unsigned NumArgs = 1;
3462       bool ListInitializing = false;
3463       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3464         // But first, see if there is an init-list-constructor that will work.
3465         OverloadingResult Result = IsInitializerListConstructorConversion(
3466             S, From, ToType, ToRecordDecl, User, CandidateSet,
3467             AllowExplicit == AllowedExplicit::All);
3468         if (Result != OR_No_Viable_Function)
3469           return Result;
3470         // Never mind.
3471         CandidateSet.clear(
3472             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3473 
3474         // If we're list-initializing, we pass the individual elements as
3475         // arguments, not the entire list.
3476         Args = InitList->getInits();
3477         NumArgs = InitList->getNumInits();
3478         ListInitializing = true;
3479       }
3480 
3481       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3482         auto Info = getConstructorInfo(D);
3483         if (!Info)
3484           continue;
3485 
3486         bool Usable = !Info.Constructor->isInvalidDecl();
3487         if (!ListInitializing)
3488           Usable = Usable && Info.Constructor->isConvertingConstructor(
3489                                  /*AllowExplicit*/ true);
3490         if (Usable) {
3491           bool SuppressUserConversions = !ConstructorsOnly;
3492           // C++20 [over.best.ics.general]/4.5:
3493           //   if the target is the first parameter of a constructor [of class
3494           //   X] and the constructor [...] is a candidate by [...] the second
3495           //   phase of [over.match.list] when the initializer list has exactly
3496           //   one element that is itself an initializer list, [...] and the
3497           //   conversion is to X or reference to cv X, user-defined conversion
3498           //   sequences are not cnosidered.
3499           if (SuppressUserConversions && ListInitializing) {
3500             SuppressUserConversions =
3501                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3502                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3503                                                   ToType);
3504           }
3505           if (Info.ConstructorTmpl)
3506             S.AddTemplateOverloadCandidate(
3507                 Info.ConstructorTmpl, Info.FoundDecl,
3508                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3509                 CandidateSet, SuppressUserConversions,
3510                 /*PartialOverloading*/ false,
3511                 AllowExplicit == AllowedExplicit::All);
3512           else
3513             // Allow one user-defined conversion when user specifies a
3514             // From->ToType conversion via an static cast (c-style, etc).
3515             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3516                                    llvm::makeArrayRef(Args, NumArgs),
3517                                    CandidateSet, SuppressUserConversions,
3518                                    /*PartialOverloading*/ false,
3519                                    AllowExplicit == AllowedExplicit::All);
3520         }
3521       }
3522     }
3523   }
3524 
3525   // Enumerate conversion functions, if we're allowed to.
3526   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3527   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3528     // No conversion functions from incomplete types.
3529   } else if (const RecordType *FromRecordType =
3530                  From->getType()->getAs<RecordType>()) {
3531     if (CXXRecordDecl *FromRecordDecl
3532          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3533       // Add all of the conversion functions as candidates.
3534       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3535       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3536         DeclAccessPair FoundDecl = I.getPair();
3537         NamedDecl *D = FoundDecl.getDecl();
3538         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3539         if (isa<UsingShadowDecl>(D))
3540           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3541 
3542         CXXConversionDecl *Conv;
3543         FunctionTemplateDecl *ConvTemplate;
3544         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3545           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3546         else
3547           Conv = cast<CXXConversionDecl>(D);
3548 
3549         if (ConvTemplate)
3550           S.AddTemplateConversionCandidate(
3551               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3552               CandidateSet, AllowObjCConversionOnExplicit,
3553               AllowExplicit != AllowedExplicit::None);
3554         else
3555           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3556                                    CandidateSet, AllowObjCConversionOnExplicit,
3557                                    AllowExplicit != AllowedExplicit::None);
3558       }
3559     }
3560   }
3561 
3562   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3563 
3564   OverloadCandidateSet::iterator Best;
3565   switch (auto Result =
3566               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3567   case OR_Success:
3568   case OR_Deleted:
3569     // Record the standard conversion we used and the conversion function.
3570     if (CXXConstructorDecl *Constructor
3571           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3572       // C++ [over.ics.user]p1:
3573       //   If the user-defined conversion is specified by a
3574       //   constructor (12.3.1), the initial standard conversion
3575       //   sequence converts the source type to the type required by
3576       //   the argument of the constructor.
3577       //
3578       QualType ThisType = Constructor->getThisType();
3579       if (isa<InitListExpr>(From)) {
3580         // Initializer lists don't have conversions as such.
3581         User.Before.setAsIdentityConversion();
3582       } else {
3583         if (Best->Conversions[0].isEllipsis())
3584           User.EllipsisConversion = true;
3585         else {
3586           User.Before = Best->Conversions[0].Standard;
3587           User.EllipsisConversion = false;
3588         }
3589       }
3590       User.HadMultipleCandidates = HadMultipleCandidates;
3591       User.ConversionFunction = Constructor;
3592       User.FoundConversionFunction = Best->FoundDecl;
3593       User.After.setAsIdentityConversion();
3594       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3595       User.After.setAllToTypes(ToType);
3596       return Result;
3597     }
3598     if (CXXConversionDecl *Conversion
3599                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3600       // C++ [over.ics.user]p1:
3601       //
3602       //   [...] If the user-defined conversion is specified by a
3603       //   conversion function (12.3.2), the initial standard
3604       //   conversion sequence converts the source type to the
3605       //   implicit object parameter of the conversion function.
3606       User.Before = Best->Conversions[0].Standard;
3607       User.HadMultipleCandidates = HadMultipleCandidates;
3608       User.ConversionFunction = Conversion;
3609       User.FoundConversionFunction = Best->FoundDecl;
3610       User.EllipsisConversion = false;
3611 
3612       // C++ [over.ics.user]p2:
3613       //   The second standard conversion sequence converts the
3614       //   result of the user-defined conversion to the target type
3615       //   for the sequence. Since an implicit conversion sequence
3616       //   is an initialization, the special rules for
3617       //   initialization by user-defined conversion apply when
3618       //   selecting the best user-defined conversion for a
3619       //   user-defined conversion sequence (see 13.3.3 and
3620       //   13.3.3.1).
3621       User.After = Best->FinalConversion;
3622       return Result;
3623     }
3624     llvm_unreachable("Not a constructor or conversion function?");
3625 
3626   case OR_No_Viable_Function:
3627     return OR_No_Viable_Function;
3628 
3629   case OR_Ambiguous:
3630     return OR_Ambiguous;
3631   }
3632 
3633   llvm_unreachable("Invalid OverloadResult!");
3634 }
3635 
3636 bool
3637 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3638   ImplicitConversionSequence ICS;
3639   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3640                                     OverloadCandidateSet::CSK_Normal);
3641   OverloadingResult OvResult =
3642     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3643                             CandidateSet, AllowedExplicit::None, false);
3644 
3645   if (!(OvResult == OR_Ambiguous ||
3646         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3647     return false;
3648 
3649   auto Cands = CandidateSet.CompleteCandidates(
3650       *this,
3651       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3652       From);
3653   if (OvResult == OR_Ambiguous)
3654     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3655         << From->getType() << ToType << From->getSourceRange();
3656   else { // OR_No_Viable_Function && !CandidateSet.empty()
3657     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3658                              diag::err_typecheck_nonviable_condition_incomplete,
3659                              From->getType(), From->getSourceRange()))
3660       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3661           << false << From->getType() << From->getSourceRange() << ToType;
3662   }
3663 
3664   CandidateSet.NoteCandidates(
3665                               *this, From, Cands);
3666   return true;
3667 }
3668 
3669 // Helper for compareConversionFunctions that gets the FunctionType that the
3670 // conversion-operator return  value 'points' to, or nullptr.
3671 static const FunctionType *
3672 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3673   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3674   const PointerType *RetPtrTy =
3675       ConvFuncTy->getReturnType()->getAs<PointerType>();
3676 
3677   if (!RetPtrTy)
3678     return nullptr;
3679 
3680   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3681 }
3682 
3683 /// Compare the user-defined conversion functions or constructors
3684 /// of two user-defined conversion sequences to determine whether any ordering
3685 /// is possible.
3686 static ImplicitConversionSequence::CompareKind
3687 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3688                            FunctionDecl *Function2) {
3689   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3690   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3691   if (!Conv1 || !Conv2)
3692     return ImplicitConversionSequence::Indistinguishable;
3693 
3694   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3695     return ImplicitConversionSequence::Indistinguishable;
3696 
3697   // Objective-C++:
3698   //   If both conversion functions are implicitly-declared conversions from
3699   //   a lambda closure type to a function pointer and a block pointer,
3700   //   respectively, always prefer the conversion to a function pointer,
3701   //   because the function pointer is more lightweight and is more likely
3702   //   to keep code working.
3703   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3704     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3705     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3706     if (Block1 != Block2)
3707       return Block1 ? ImplicitConversionSequence::Worse
3708                     : ImplicitConversionSequence::Better;
3709   }
3710 
3711   // In order to support multiple calling conventions for the lambda conversion
3712   // operator (such as when the free and member function calling convention is
3713   // different), prefer the 'free' mechanism, followed by the calling-convention
3714   // of operator(). The latter is in place to support the MSVC-like solution of
3715   // defining ALL of the possible conversions in regards to calling-convention.
3716   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3717   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3718 
3719   if (Conv1FuncRet && Conv2FuncRet &&
3720       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3721     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3722     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3723 
3724     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3725     const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
3726 
3727     CallingConv CallOpCC =
3728         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3729     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3730         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3731     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3732         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3733 
3734     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3735     for (CallingConv CC : PrefOrder) {
3736       if (Conv1CC == CC)
3737         return ImplicitConversionSequence::Better;
3738       if (Conv2CC == CC)
3739         return ImplicitConversionSequence::Worse;
3740     }
3741   }
3742 
3743   return ImplicitConversionSequence::Indistinguishable;
3744 }
3745 
3746 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3747     const ImplicitConversionSequence &ICS) {
3748   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3749          (ICS.isUserDefined() &&
3750           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3751 }
3752 
3753 /// CompareImplicitConversionSequences - Compare two implicit
3754 /// conversion sequences to determine whether one is better than the
3755 /// other or if they are indistinguishable (C++ 13.3.3.2).
3756 static ImplicitConversionSequence::CompareKind
3757 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3758                                    const ImplicitConversionSequence& ICS1,
3759                                    const ImplicitConversionSequence& ICS2)
3760 {
3761   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3762   // conversion sequences (as defined in 13.3.3.1)
3763   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3764   //      conversion sequence than a user-defined conversion sequence or
3765   //      an ellipsis conversion sequence, and
3766   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3767   //      conversion sequence than an ellipsis conversion sequence
3768   //      (13.3.3.1.3).
3769   //
3770   // C++0x [over.best.ics]p10:
3771   //   For the purpose of ranking implicit conversion sequences as
3772   //   described in 13.3.3.2, the ambiguous conversion sequence is
3773   //   treated as a user-defined sequence that is indistinguishable
3774   //   from any other user-defined conversion sequence.
3775 
3776   // String literal to 'char *' conversion has been deprecated in C++03. It has
3777   // been removed from C++11. We still accept this conversion, if it happens at
3778   // the best viable function. Otherwise, this conversion is considered worse
3779   // than ellipsis conversion. Consider this as an extension; this is not in the
3780   // standard. For example:
3781   //
3782   // int &f(...);    // #1
3783   // void f(char*);  // #2
3784   // void g() { int &r = f("foo"); }
3785   //
3786   // In C++03, we pick #2 as the best viable function.
3787   // In C++11, we pick #1 as the best viable function, because ellipsis
3788   // conversion is better than string-literal to char* conversion (since there
3789   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3790   // convert arguments, #2 would be the best viable function in C++11.
3791   // If the best viable function has this conversion, a warning will be issued
3792   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3793 
3794   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3795       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3796           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3797       // Ill-formedness must not differ
3798       ICS1.isBad() == ICS2.isBad())
3799     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3800                ? ImplicitConversionSequence::Worse
3801                : ImplicitConversionSequence::Better;
3802 
3803   if (ICS1.getKindRank() < ICS2.getKindRank())
3804     return ImplicitConversionSequence::Better;
3805   if (ICS2.getKindRank() < ICS1.getKindRank())
3806     return ImplicitConversionSequence::Worse;
3807 
3808   // The following checks require both conversion sequences to be of
3809   // the same kind.
3810   if (ICS1.getKind() != ICS2.getKind())
3811     return ImplicitConversionSequence::Indistinguishable;
3812 
3813   ImplicitConversionSequence::CompareKind Result =
3814       ImplicitConversionSequence::Indistinguishable;
3815 
3816   // Two implicit conversion sequences of the same form are
3817   // indistinguishable conversion sequences unless one of the
3818   // following rules apply: (C++ 13.3.3.2p3):
3819 
3820   // List-initialization sequence L1 is a better conversion sequence than
3821   // list-initialization sequence L2 if:
3822   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3823   //   if not that,
3824   // — L1 and L2 convert to arrays of the same element type, and either the
3825   //   number of elements n_1 initialized by L1 is less than the number of
3826   //   elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
3827   //   an array of unknown bound and L1 does not,
3828   // even if one of the other rules in this paragraph would otherwise apply.
3829   if (!ICS1.isBad()) {
3830     bool StdInit1 = false, StdInit2 = false;
3831     if (ICS1.hasInitializerListContainerType())
3832       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3833                                         nullptr);
3834     if (ICS2.hasInitializerListContainerType())
3835       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3836                                         nullptr);
3837     if (StdInit1 != StdInit2)
3838       return StdInit1 ? ImplicitConversionSequence::Better
3839                       : ImplicitConversionSequence::Worse;
3840 
3841     if (ICS1.hasInitializerListContainerType() &&
3842         ICS2.hasInitializerListContainerType())
3843       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3844               ICS1.getInitializerListContainerType()))
3845         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3846                 ICS2.getInitializerListContainerType())) {
3847           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3848                                                CAT2->getElementType())) {
3849             // Both to arrays of the same element type
3850             if (CAT1->getSize() != CAT2->getSize())
3851               // Different sized, the smaller wins
3852               return CAT1->getSize().ult(CAT2->getSize())
3853                          ? ImplicitConversionSequence::Better
3854                          : ImplicitConversionSequence::Worse;
3855             if (ICS1.isInitializerListOfIncompleteArray() !=
3856                 ICS2.isInitializerListOfIncompleteArray())
3857               // One is incomplete, it loses
3858               return ICS2.isInitializerListOfIncompleteArray()
3859                          ? ImplicitConversionSequence::Better
3860                          : ImplicitConversionSequence::Worse;
3861           }
3862         }
3863   }
3864 
3865   if (ICS1.isStandard())
3866     // Standard conversion sequence S1 is a better conversion sequence than
3867     // standard conversion sequence S2 if [...]
3868     Result = CompareStandardConversionSequences(S, Loc,
3869                                                 ICS1.Standard, ICS2.Standard);
3870   else if (ICS1.isUserDefined()) {
3871     // User-defined conversion sequence U1 is a better conversion
3872     // sequence than another user-defined conversion sequence U2 if
3873     // they contain the same user-defined conversion function or
3874     // constructor and if the second standard conversion sequence of
3875     // U1 is better than the second standard conversion sequence of
3876     // U2 (C++ 13.3.3.2p3).
3877     if (ICS1.UserDefined.ConversionFunction ==
3878           ICS2.UserDefined.ConversionFunction)
3879       Result = CompareStandardConversionSequences(S, Loc,
3880                                                   ICS1.UserDefined.After,
3881                                                   ICS2.UserDefined.After);
3882     else
3883       Result = compareConversionFunctions(S,
3884                                           ICS1.UserDefined.ConversionFunction,
3885                                           ICS2.UserDefined.ConversionFunction);
3886   }
3887 
3888   return Result;
3889 }
3890 
3891 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3892 // determine if one is a proper subset of the other.
3893 static ImplicitConversionSequence::CompareKind
3894 compareStandardConversionSubsets(ASTContext &Context,
3895                                  const StandardConversionSequence& SCS1,
3896                                  const StandardConversionSequence& SCS2) {
3897   ImplicitConversionSequence::CompareKind Result
3898     = ImplicitConversionSequence::Indistinguishable;
3899 
3900   // the identity conversion sequence is considered to be a subsequence of
3901   // any non-identity conversion sequence
3902   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3903     return ImplicitConversionSequence::Better;
3904   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3905     return ImplicitConversionSequence::Worse;
3906 
3907   if (SCS1.Second != SCS2.Second) {
3908     if (SCS1.Second == ICK_Identity)
3909       Result = ImplicitConversionSequence::Better;
3910     else if (SCS2.Second == ICK_Identity)
3911       Result = ImplicitConversionSequence::Worse;
3912     else
3913       return ImplicitConversionSequence::Indistinguishable;
3914   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3915     return ImplicitConversionSequence::Indistinguishable;
3916 
3917   if (SCS1.Third == SCS2.Third) {
3918     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3919                              : ImplicitConversionSequence::Indistinguishable;
3920   }
3921 
3922   if (SCS1.Third == ICK_Identity)
3923     return Result == ImplicitConversionSequence::Worse
3924              ? ImplicitConversionSequence::Indistinguishable
3925              : ImplicitConversionSequence::Better;
3926 
3927   if (SCS2.Third == ICK_Identity)
3928     return Result == ImplicitConversionSequence::Better
3929              ? ImplicitConversionSequence::Indistinguishable
3930              : ImplicitConversionSequence::Worse;
3931 
3932   return ImplicitConversionSequence::Indistinguishable;
3933 }
3934 
3935 /// Determine whether one of the given reference bindings is better
3936 /// than the other based on what kind of bindings they are.
3937 static bool
3938 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3939                              const StandardConversionSequence &SCS2) {
3940   // C++0x [over.ics.rank]p3b4:
3941   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3942   //      implicit object parameter of a non-static member function declared
3943   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3944   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3945   //      lvalue reference to a function lvalue and S2 binds an rvalue
3946   //      reference*.
3947   //
3948   // FIXME: Rvalue references. We're going rogue with the above edits,
3949   // because the semantics in the current C++0x working paper (N3225 at the
3950   // time of this writing) break the standard definition of std::forward
3951   // and std::reference_wrapper when dealing with references to functions.
3952   // Proposed wording changes submitted to CWG for consideration.
3953   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3954       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3955     return false;
3956 
3957   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3958           SCS2.IsLvalueReference) ||
3959          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3960           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3961 }
3962 
3963 enum class FixedEnumPromotion {
3964   None,
3965   ToUnderlyingType,
3966   ToPromotedUnderlyingType
3967 };
3968 
3969 /// Returns kind of fixed enum promotion the \a SCS uses.
3970 static FixedEnumPromotion
3971 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3972 
3973   if (SCS.Second != ICK_Integral_Promotion)
3974     return FixedEnumPromotion::None;
3975 
3976   QualType FromType = SCS.getFromType();
3977   if (!FromType->isEnumeralType())
3978     return FixedEnumPromotion::None;
3979 
3980   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3981   if (!Enum->isFixed())
3982     return FixedEnumPromotion::None;
3983 
3984   QualType UnderlyingType = Enum->getIntegerType();
3985   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3986     return FixedEnumPromotion::ToUnderlyingType;
3987 
3988   return FixedEnumPromotion::ToPromotedUnderlyingType;
3989 }
3990 
3991 /// CompareStandardConversionSequences - Compare two standard
3992 /// conversion sequences to determine whether one is better than the
3993 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3994 static ImplicitConversionSequence::CompareKind
3995 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3996                                    const StandardConversionSequence& SCS1,
3997                                    const StandardConversionSequence& SCS2)
3998 {
3999   // Standard conversion sequence S1 is a better conversion sequence
4000   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4001 
4002   //  -- S1 is a proper subsequence of S2 (comparing the conversion
4003   //     sequences in the canonical form defined by 13.3.3.1.1,
4004   //     excluding any Lvalue Transformation; the identity conversion
4005   //     sequence is considered to be a subsequence of any
4006   //     non-identity conversion sequence) or, if not that,
4007   if (ImplicitConversionSequence::CompareKind CK
4008         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4009     return CK;
4010 
4011   //  -- the rank of S1 is better than the rank of S2 (by the rules
4012   //     defined below), or, if not that,
4013   ImplicitConversionRank Rank1 = SCS1.getRank();
4014   ImplicitConversionRank Rank2 = SCS2.getRank();
4015   if (Rank1 < Rank2)
4016     return ImplicitConversionSequence::Better;
4017   else if (Rank2 < Rank1)
4018     return ImplicitConversionSequence::Worse;
4019 
4020   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4021   // are indistinguishable unless one of the following rules
4022   // applies:
4023 
4024   //   A conversion that is not a conversion of a pointer, or
4025   //   pointer to member, to bool is better than another conversion
4026   //   that is such a conversion.
4027   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4028     return SCS2.isPointerConversionToBool()
4029              ? ImplicitConversionSequence::Better
4030              : ImplicitConversionSequence::Worse;
4031 
4032   // C++14 [over.ics.rank]p4b2:
4033   // This is retroactively applied to C++11 by CWG 1601.
4034   //
4035   //   A conversion that promotes an enumeration whose underlying type is fixed
4036   //   to its underlying type is better than one that promotes to the promoted
4037   //   underlying type, if the two are different.
4038   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4039   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4040   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4041       FEP1 != FEP2)
4042     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4043                ? ImplicitConversionSequence::Better
4044                : ImplicitConversionSequence::Worse;
4045 
4046   // C++ [over.ics.rank]p4b2:
4047   //
4048   //   If class B is derived directly or indirectly from class A,
4049   //   conversion of B* to A* is better than conversion of B* to
4050   //   void*, and conversion of A* to void* is better than conversion
4051   //   of B* to void*.
4052   bool SCS1ConvertsToVoid
4053     = SCS1.isPointerConversionToVoidPointer(S.Context);
4054   bool SCS2ConvertsToVoid
4055     = SCS2.isPointerConversionToVoidPointer(S.Context);
4056   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4057     // Exactly one of the conversion sequences is a conversion to
4058     // a void pointer; it's the worse conversion.
4059     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4060                               : ImplicitConversionSequence::Worse;
4061   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4062     // Neither conversion sequence converts to a void pointer; compare
4063     // their derived-to-base conversions.
4064     if (ImplicitConversionSequence::CompareKind DerivedCK
4065           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4066       return DerivedCK;
4067   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4068              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4069     // Both conversion sequences are conversions to void
4070     // pointers. Compare the source types to determine if there's an
4071     // inheritance relationship in their sources.
4072     QualType FromType1 = SCS1.getFromType();
4073     QualType FromType2 = SCS2.getFromType();
4074 
4075     // Adjust the types we're converting from via the array-to-pointer
4076     // conversion, if we need to.
4077     if (SCS1.First == ICK_Array_To_Pointer)
4078       FromType1 = S.Context.getArrayDecayedType(FromType1);
4079     if (SCS2.First == ICK_Array_To_Pointer)
4080       FromType2 = S.Context.getArrayDecayedType(FromType2);
4081 
4082     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4083     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4084 
4085     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4086       return ImplicitConversionSequence::Better;
4087     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4088       return ImplicitConversionSequence::Worse;
4089 
4090     // Objective-C++: If one interface is more specific than the
4091     // other, it is the better one.
4092     const ObjCObjectPointerType* FromObjCPtr1
4093       = FromType1->getAs<ObjCObjectPointerType>();
4094     const ObjCObjectPointerType* FromObjCPtr2
4095       = FromType2->getAs<ObjCObjectPointerType>();
4096     if (FromObjCPtr1 && FromObjCPtr2) {
4097       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4098                                                           FromObjCPtr2);
4099       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4100                                                            FromObjCPtr1);
4101       if (AssignLeft != AssignRight) {
4102         return AssignLeft? ImplicitConversionSequence::Better
4103                          : ImplicitConversionSequence::Worse;
4104       }
4105     }
4106   }
4107 
4108   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4109     // Check for a better reference binding based on the kind of bindings.
4110     if (isBetterReferenceBindingKind(SCS1, SCS2))
4111       return ImplicitConversionSequence::Better;
4112     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4113       return ImplicitConversionSequence::Worse;
4114   }
4115 
4116   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4117   // bullet 3).
4118   if (ImplicitConversionSequence::CompareKind QualCK
4119         = CompareQualificationConversions(S, SCS1, SCS2))
4120     return QualCK;
4121 
4122   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4123     // C++ [over.ics.rank]p3b4:
4124     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4125     //      which the references refer are the same type except for
4126     //      top-level cv-qualifiers, and the type to which the reference
4127     //      initialized by S2 refers is more cv-qualified than the type
4128     //      to which the reference initialized by S1 refers.
4129     QualType T1 = SCS1.getToType(2);
4130     QualType T2 = SCS2.getToType(2);
4131     T1 = S.Context.getCanonicalType(T1);
4132     T2 = S.Context.getCanonicalType(T2);
4133     Qualifiers T1Quals, T2Quals;
4134     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4135     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4136     if (UnqualT1 == UnqualT2) {
4137       // Objective-C++ ARC: If the references refer to objects with different
4138       // lifetimes, prefer bindings that don't change lifetime.
4139       if (SCS1.ObjCLifetimeConversionBinding !=
4140                                           SCS2.ObjCLifetimeConversionBinding) {
4141         return SCS1.ObjCLifetimeConversionBinding
4142                                            ? ImplicitConversionSequence::Worse
4143                                            : ImplicitConversionSequence::Better;
4144       }
4145 
4146       // If the type is an array type, promote the element qualifiers to the
4147       // type for comparison.
4148       if (isa<ArrayType>(T1) && T1Quals)
4149         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4150       if (isa<ArrayType>(T2) && T2Quals)
4151         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4152       if (T2.isMoreQualifiedThan(T1))
4153         return ImplicitConversionSequence::Better;
4154       if (T1.isMoreQualifiedThan(T2))
4155         return ImplicitConversionSequence::Worse;
4156     }
4157   }
4158 
4159   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4160   // floating-to-integral conversion if the integral conversion
4161   // is between types of the same size.
4162   // For example:
4163   // void f(float);
4164   // void f(int);
4165   // int main {
4166   //    long a;
4167   //    f(a);
4168   // }
4169   // Here, MSVC will call f(int) instead of generating a compile error
4170   // as clang will do in standard mode.
4171   if (S.getLangOpts().MSVCCompat &&
4172       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4173       SCS1.Second == ICK_Integral_Conversion &&
4174       SCS2.Second == ICK_Floating_Integral &&
4175       S.Context.getTypeSize(SCS1.getFromType()) ==
4176           S.Context.getTypeSize(SCS1.getToType(2)))
4177     return ImplicitConversionSequence::Better;
4178 
4179   // Prefer a compatible vector conversion over a lax vector conversion
4180   // For example:
4181   //
4182   // typedef float __v4sf __attribute__((__vector_size__(16)));
4183   // void f(vector float);
4184   // void f(vector signed int);
4185   // int main() {
4186   //   __v4sf a;
4187   //   f(a);
4188   // }
4189   // Here, we'd like to choose f(vector float) and not
4190   // report an ambiguous call error
4191   if (SCS1.Second == ICK_Vector_Conversion &&
4192       SCS2.Second == ICK_Vector_Conversion) {
4193     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4194         SCS1.getFromType(), SCS1.getToType(2));
4195     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4196         SCS2.getFromType(), SCS2.getToType(2));
4197 
4198     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4199       return SCS1IsCompatibleVectorConversion
4200                  ? ImplicitConversionSequence::Better
4201                  : ImplicitConversionSequence::Worse;
4202   }
4203 
4204   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4205       SCS2.Second == ICK_SVE_Vector_Conversion) {
4206     bool SCS1IsCompatibleSVEVectorConversion =
4207         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4208     bool SCS2IsCompatibleSVEVectorConversion =
4209         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4210 
4211     if (SCS1IsCompatibleSVEVectorConversion !=
4212         SCS2IsCompatibleSVEVectorConversion)
4213       return SCS1IsCompatibleSVEVectorConversion
4214                  ? ImplicitConversionSequence::Better
4215                  : ImplicitConversionSequence::Worse;
4216   }
4217 
4218   return ImplicitConversionSequence::Indistinguishable;
4219 }
4220 
4221 /// CompareQualificationConversions - Compares two standard conversion
4222 /// sequences to determine whether they can be ranked based on their
4223 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4224 static ImplicitConversionSequence::CompareKind
4225 CompareQualificationConversions(Sema &S,
4226                                 const StandardConversionSequence& SCS1,
4227                                 const StandardConversionSequence& SCS2) {
4228   // C++ [over.ics.rank]p3:
4229   //  -- S1 and S2 differ only in their qualification conversion and
4230   //     yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4231   // [C++98]
4232   //     [...] and the cv-qualification signature of type T1 is a proper subset
4233   //     of the cv-qualification signature of type T2, and S1 is not the
4234   //     deprecated string literal array-to-pointer conversion (4.2).
4235   // [C++2a]
4236   //     [...] where T1 can be converted to T2 by a qualification conversion.
4237   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4238       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4239     return ImplicitConversionSequence::Indistinguishable;
4240 
4241   // FIXME: the example in the standard doesn't use a qualification
4242   // conversion (!)
4243   QualType T1 = SCS1.getToType(2);
4244   QualType T2 = SCS2.getToType(2);
4245   T1 = S.Context.getCanonicalType(T1);
4246   T2 = S.Context.getCanonicalType(T2);
4247   assert(!T1->isReferenceType() && !T2->isReferenceType());
4248   Qualifiers T1Quals, T2Quals;
4249   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4250   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4251 
4252   // If the types are the same, we won't learn anything by unwrapping
4253   // them.
4254   if (UnqualT1 == UnqualT2)
4255     return ImplicitConversionSequence::Indistinguishable;
4256 
4257   // Don't ever prefer a standard conversion sequence that uses the deprecated
4258   // string literal array to pointer conversion.
4259   bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4260   bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4261 
4262   // Objective-C++ ARC:
4263   //   Prefer qualification conversions not involving a change in lifetime
4264   //   to qualification conversions that do change lifetime.
4265   if (SCS1.QualificationIncludesObjCLifetime &&
4266       !SCS2.QualificationIncludesObjCLifetime)
4267     CanPick1 = false;
4268   if (SCS2.QualificationIncludesObjCLifetime &&
4269       !SCS1.QualificationIncludesObjCLifetime)
4270     CanPick2 = false;
4271 
4272   bool ObjCLifetimeConversion;
4273   if (CanPick1 &&
4274       !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4275     CanPick1 = false;
4276   // FIXME: In Objective-C ARC, we can have qualification conversions in both
4277   // directions, so we can't short-cut this second check in general.
4278   if (CanPick2 &&
4279       !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4280     CanPick2 = false;
4281 
4282   if (CanPick1 != CanPick2)
4283     return CanPick1 ? ImplicitConversionSequence::Better
4284                     : ImplicitConversionSequence::Worse;
4285   return ImplicitConversionSequence::Indistinguishable;
4286 }
4287 
4288 /// CompareDerivedToBaseConversions - Compares two standard conversion
4289 /// sequences to determine whether they can be ranked based on their
4290 /// various kinds of derived-to-base conversions (C++
4291 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4292 /// conversions between Objective-C interface types.
4293 static ImplicitConversionSequence::CompareKind
4294 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4295                                 const StandardConversionSequence& SCS1,
4296                                 const StandardConversionSequence& SCS2) {
4297   QualType FromType1 = SCS1.getFromType();
4298   QualType ToType1 = SCS1.getToType(1);
4299   QualType FromType2 = SCS2.getFromType();
4300   QualType ToType2 = SCS2.getToType(1);
4301 
4302   // Adjust the types we're converting from via the array-to-pointer
4303   // conversion, if we need to.
4304   if (SCS1.First == ICK_Array_To_Pointer)
4305     FromType1 = S.Context.getArrayDecayedType(FromType1);
4306   if (SCS2.First == ICK_Array_To_Pointer)
4307     FromType2 = S.Context.getArrayDecayedType(FromType2);
4308 
4309   // Canonicalize all of the types.
4310   FromType1 = S.Context.getCanonicalType(FromType1);
4311   ToType1 = S.Context.getCanonicalType(ToType1);
4312   FromType2 = S.Context.getCanonicalType(FromType2);
4313   ToType2 = S.Context.getCanonicalType(ToType2);
4314 
4315   // C++ [over.ics.rank]p4b3:
4316   //
4317   //   If class B is derived directly or indirectly from class A and
4318   //   class C is derived directly or indirectly from B,
4319   //
4320   // Compare based on pointer conversions.
4321   if (SCS1.Second == ICK_Pointer_Conversion &&
4322       SCS2.Second == ICK_Pointer_Conversion &&
4323       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4324       FromType1->isPointerType() && FromType2->isPointerType() &&
4325       ToType1->isPointerType() && ToType2->isPointerType()) {
4326     QualType FromPointee1 =
4327         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4328     QualType ToPointee1 =
4329         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4330     QualType FromPointee2 =
4331         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4332     QualType ToPointee2 =
4333         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4334 
4335     //   -- conversion of C* to B* is better than conversion of C* to A*,
4336     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4337       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4338         return ImplicitConversionSequence::Better;
4339       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4340         return ImplicitConversionSequence::Worse;
4341     }
4342 
4343     //   -- conversion of B* to A* is better than conversion of C* to A*,
4344     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4345       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4346         return ImplicitConversionSequence::Better;
4347       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4348         return ImplicitConversionSequence::Worse;
4349     }
4350   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4351              SCS2.Second == ICK_Pointer_Conversion) {
4352     const ObjCObjectPointerType *FromPtr1
4353       = FromType1->getAs<ObjCObjectPointerType>();
4354     const ObjCObjectPointerType *FromPtr2
4355       = FromType2->getAs<ObjCObjectPointerType>();
4356     const ObjCObjectPointerType *ToPtr1
4357       = ToType1->getAs<ObjCObjectPointerType>();
4358     const ObjCObjectPointerType *ToPtr2
4359       = ToType2->getAs<ObjCObjectPointerType>();
4360 
4361     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4362       // Apply the same conversion ranking rules for Objective-C pointer types
4363       // that we do for C++ pointers to class types. However, we employ the
4364       // Objective-C pseudo-subtyping relationship used for assignment of
4365       // Objective-C pointer types.
4366       bool FromAssignLeft
4367         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4368       bool FromAssignRight
4369         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4370       bool ToAssignLeft
4371         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4372       bool ToAssignRight
4373         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4374 
4375       // A conversion to an a non-id object pointer type or qualified 'id'
4376       // type is better than a conversion to 'id'.
4377       if (ToPtr1->isObjCIdType() &&
4378           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4379         return ImplicitConversionSequence::Worse;
4380       if (ToPtr2->isObjCIdType() &&
4381           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4382         return ImplicitConversionSequence::Better;
4383 
4384       // A conversion to a non-id object pointer type is better than a
4385       // conversion to a qualified 'id' type
4386       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4387         return ImplicitConversionSequence::Worse;
4388       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4389         return ImplicitConversionSequence::Better;
4390 
4391       // A conversion to an a non-Class object pointer type or qualified 'Class'
4392       // type is better than a conversion to 'Class'.
4393       if (ToPtr1->isObjCClassType() &&
4394           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4395         return ImplicitConversionSequence::Worse;
4396       if (ToPtr2->isObjCClassType() &&
4397           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4398         return ImplicitConversionSequence::Better;
4399 
4400       // A conversion to a non-Class object pointer type is better than a
4401       // conversion to a qualified 'Class' type.
4402       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4403         return ImplicitConversionSequence::Worse;
4404       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4405         return ImplicitConversionSequence::Better;
4406 
4407       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4408       if (S.Context.hasSameType(FromType1, FromType2) &&
4409           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4410           (ToAssignLeft != ToAssignRight)) {
4411         if (FromPtr1->isSpecialized()) {
4412           // "conversion of B<A> * to B * is better than conversion of B * to
4413           // C *.
4414           bool IsFirstSame =
4415               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4416           bool IsSecondSame =
4417               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4418           if (IsFirstSame) {
4419             if (!IsSecondSame)
4420               return ImplicitConversionSequence::Better;
4421           } else if (IsSecondSame)
4422             return ImplicitConversionSequence::Worse;
4423         }
4424         return ToAssignLeft? ImplicitConversionSequence::Worse
4425                            : ImplicitConversionSequence::Better;
4426       }
4427 
4428       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4429       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4430           (FromAssignLeft != FromAssignRight))
4431         return FromAssignLeft? ImplicitConversionSequence::Better
4432         : ImplicitConversionSequence::Worse;
4433     }
4434   }
4435 
4436   // Ranking of member-pointer types.
4437   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4438       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4439       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4440     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4441     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4442     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4443     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4444     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4445     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4446     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4447     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4448     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4449     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4450     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4451     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4452     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4453     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4454       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4455         return ImplicitConversionSequence::Worse;
4456       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4457         return ImplicitConversionSequence::Better;
4458     }
4459     // conversion of B::* to C::* is better than conversion of A::* to C::*
4460     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4461       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4462         return ImplicitConversionSequence::Better;
4463       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4464         return ImplicitConversionSequence::Worse;
4465     }
4466   }
4467 
4468   if (SCS1.Second == ICK_Derived_To_Base) {
4469     //   -- conversion of C to B is better than conversion of C to A,
4470     //   -- binding of an expression of type C to a reference of type
4471     //      B& is better than binding an expression of type C to a
4472     //      reference of type A&,
4473     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4474         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4475       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4476         return ImplicitConversionSequence::Better;
4477       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4478         return ImplicitConversionSequence::Worse;
4479     }
4480 
4481     //   -- conversion of B to A is better than conversion of C to A.
4482     //   -- binding of an expression of type B to a reference of type
4483     //      A& is better than binding an expression of type C to a
4484     //      reference of type A&,
4485     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4486         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4487       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4488         return ImplicitConversionSequence::Better;
4489       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4490         return ImplicitConversionSequence::Worse;
4491     }
4492   }
4493 
4494   return ImplicitConversionSequence::Indistinguishable;
4495 }
4496 
4497 /// Determine whether the given type is valid, e.g., it is not an invalid
4498 /// C++ class.
4499 static bool isTypeValid(QualType T) {
4500   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4501     return !Record->isInvalidDecl();
4502 
4503   return true;
4504 }
4505 
4506 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4507   if (!T.getQualifiers().hasUnaligned())
4508     return T;
4509 
4510   Qualifiers Q;
4511   T = Ctx.getUnqualifiedArrayType(T, Q);
4512   Q.removeUnaligned();
4513   return Ctx.getQualifiedType(T, Q);
4514 }
4515 
4516 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4517 /// determine whether they are reference-compatible,
4518 /// reference-related, or incompatible, for use in C++ initialization by
4519 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4520 /// type, and the first type (T1) is the pointee type of the reference
4521 /// type being initialized.
4522 Sema::ReferenceCompareResult
4523 Sema::CompareReferenceRelationship(SourceLocation Loc,
4524                                    QualType OrigT1, QualType OrigT2,
4525                                    ReferenceConversions *ConvOut) {
4526   assert(!OrigT1->isReferenceType() &&
4527     "T1 must be the pointee type of the reference type");
4528   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4529 
4530   QualType T1 = Context.getCanonicalType(OrigT1);
4531   QualType T2 = Context.getCanonicalType(OrigT2);
4532   Qualifiers T1Quals, T2Quals;
4533   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4534   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4535 
4536   ReferenceConversions ConvTmp;
4537   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4538   Conv = ReferenceConversions();
4539 
4540   // C++2a [dcl.init.ref]p4:
4541   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4542   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4543   //   T1 is a base class of T2.
4544   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4545   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4546   //   "pointer to cv1 T1" via a standard conversion sequence.
4547 
4548   // Check for standard conversions we can apply to pointers: derived-to-base
4549   // conversions, ObjC pointer conversions, and function pointer conversions.
4550   // (Qualification conversions are checked last.)
4551   QualType ConvertedT2;
4552   if (UnqualT1 == UnqualT2) {
4553     // Nothing to do.
4554   } else if (isCompleteType(Loc, OrigT2) &&
4555              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4556              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4557     Conv |= ReferenceConversions::DerivedToBase;
4558   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4559            UnqualT2->isObjCObjectOrInterfaceType() &&
4560            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4561     Conv |= ReferenceConversions::ObjC;
4562   else if (UnqualT2->isFunctionType() &&
4563            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4564     Conv |= ReferenceConversions::Function;
4565     // No need to check qualifiers; function types don't have them.
4566     return Ref_Compatible;
4567   }
4568   bool ConvertedReferent = Conv != 0;
4569 
4570   // We can have a qualification conversion. Compute whether the types are
4571   // similar at the same time.
4572   bool PreviousToQualsIncludeConst = true;
4573   bool TopLevel = true;
4574   do {
4575     if (T1 == T2)
4576       break;
4577 
4578     // We will need a qualification conversion.
4579     Conv |= ReferenceConversions::Qualification;
4580 
4581     // Track whether we performed a qualification conversion anywhere other
4582     // than the top level. This matters for ranking reference bindings in
4583     // overload resolution.
4584     if (!TopLevel)
4585       Conv |= ReferenceConversions::NestedQualification;
4586 
4587     // MS compiler ignores __unaligned qualifier for references; do the same.
4588     T1 = withoutUnaligned(Context, T1);
4589     T2 = withoutUnaligned(Context, T2);
4590 
4591     // If we find a qualifier mismatch, the types are not reference-compatible,
4592     // but are still be reference-related if they're similar.
4593     bool ObjCLifetimeConversion = false;
4594     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4595                                        PreviousToQualsIncludeConst,
4596                                        ObjCLifetimeConversion))
4597       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4598                  ? Ref_Related
4599                  : Ref_Incompatible;
4600 
4601     // FIXME: Should we track this for any level other than the first?
4602     if (ObjCLifetimeConversion)
4603       Conv |= ReferenceConversions::ObjCLifetime;
4604 
4605     TopLevel = false;
4606   } while (Context.UnwrapSimilarTypes(T1, T2));
4607 
4608   // At this point, if the types are reference-related, we must either have the
4609   // same inner type (ignoring qualifiers), or must have already worked out how
4610   // to convert the referent.
4611   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4612              ? Ref_Compatible
4613              : Ref_Incompatible;
4614 }
4615 
4616 /// Look for a user-defined conversion to a value reference-compatible
4617 ///        with DeclType. Return true if something definite is found.
4618 static bool
4619 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4620                          QualType DeclType, SourceLocation DeclLoc,
4621                          Expr *Init, QualType T2, bool AllowRvalues,
4622                          bool AllowExplicit) {
4623   assert(T2->isRecordType() && "Can only find conversions of record types.");
4624   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4625 
4626   OverloadCandidateSet CandidateSet(
4627       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4628   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4629   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4630     NamedDecl *D = *I;
4631     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4632     if (isa<UsingShadowDecl>(D))
4633       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4634 
4635     FunctionTemplateDecl *ConvTemplate
4636       = dyn_cast<FunctionTemplateDecl>(D);
4637     CXXConversionDecl *Conv;
4638     if (ConvTemplate)
4639       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4640     else
4641       Conv = cast<CXXConversionDecl>(D);
4642 
4643     if (AllowRvalues) {
4644       // If we are initializing an rvalue reference, don't permit conversion
4645       // functions that return lvalues.
4646       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4647         const ReferenceType *RefType
4648           = Conv->getConversionType()->getAs<LValueReferenceType>();
4649         if (RefType && !RefType->getPointeeType()->isFunctionType())
4650           continue;
4651       }
4652 
4653       if (!ConvTemplate &&
4654           S.CompareReferenceRelationship(
4655               DeclLoc,
4656               Conv->getConversionType()
4657                   .getNonReferenceType()
4658                   .getUnqualifiedType(),
4659               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4660               Sema::Ref_Incompatible)
4661         continue;
4662     } else {
4663       // If the conversion function doesn't return a reference type,
4664       // it can't be considered for this conversion. An rvalue reference
4665       // is only acceptable if its referencee is a function type.
4666 
4667       const ReferenceType *RefType =
4668         Conv->getConversionType()->getAs<ReferenceType>();
4669       if (!RefType ||
4670           (!RefType->isLValueReferenceType() &&
4671            !RefType->getPointeeType()->isFunctionType()))
4672         continue;
4673     }
4674 
4675     if (ConvTemplate)
4676       S.AddTemplateConversionCandidate(
4677           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4678           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4679     else
4680       S.AddConversionCandidate(
4681           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4682           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4683   }
4684 
4685   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4686 
4687   OverloadCandidateSet::iterator Best;
4688   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4689   case OR_Success:
4690     // C++ [over.ics.ref]p1:
4691     //
4692     //   [...] If the parameter binds directly to the result of
4693     //   applying a conversion function to the argument
4694     //   expression, the implicit conversion sequence is a
4695     //   user-defined conversion sequence (13.3.3.1.2), with the
4696     //   second standard conversion sequence either an identity
4697     //   conversion or, if the conversion function returns an
4698     //   entity of a type that is a derived class of the parameter
4699     //   type, a derived-to-base Conversion.
4700     if (!Best->FinalConversion.DirectBinding)
4701       return false;
4702 
4703     ICS.setUserDefined();
4704     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4705     ICS.UserDefined.After = Best->FinalConversion;
4706     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4707     ICS.UserDefined.ConversionFunction = Best->Function;
4708     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4709     ICS.UserDefined.EllipsisConversion = false;
4710     assert(ICS.UserDefined.After.ReferenceBinding &&
4711            ICS.UserDefined.After.DirectBinding &&
4712            "Expected a direct reference binding!");
4713     return true;
4714 
4715   case OR_Ambiguous:
4716     ICS.setAmbiguous();
4717     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4718          Cand != CandidateSet.end(); ++Cand)
4719       if (Cand->Best)
4720         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4721     return true;
4722 
4723   case OR_No_Viable_Function:
4724   case OR_Deleted:
4725     // There was no suitable conversion, or we found a deleted
4726     // conversion; continue with other checks.
4727     return false;
4728   }
4729 
4730   llvm_unreachable("Invalid OverloadResult!");
4731 }
4732 
4733 /// Compute an implicit conversion sequence for reference
4734 /// initialization.
4735 static ImplicitConversionSequence
4736 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4737                  SourceLocation DeclLoc,
4738                  bool SuppressUserConversions,
4739                  bool AllowExplicit) {
4740   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4741 
4742   // Most paths end in a failed conversion.
4743   ImplicitConversionSequence ICS;
4744   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4745 
4746   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4747   QualType T2 = Init->getType();
4748 
4749   // If the initializer is the address of an overloaded function, try
4750   // to resolve the overloaded function. If all goes well, T2 is the
4751   // type of the resulting function.
4752   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4753     DeclAccessPair Found;
4754     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4755                                                                 false, Found))
4756       T2 = Fn->getType();
4757   }
4758 
4759   // Compute some basic properties of the types and the initializer.
4760   bool isRValRef = DeclType->isRValueReferenceType();
4761   Expr::Classification InitCategory = Init->Classify(S.Context);
4762 
4763   Sema::ReferenceConversions RefConv;
4764   Sema::ReferenceCompareResult RefRelationship =
4765       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4766 
4767   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4768     ICS.setStandard();
4769     ICS.Standard.First = ICK_Identity;
4770     // FIXME: A reference binding can be a function conversion too. We should
4771     // consider that when ordering reference-to-function bindings.
4772     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4773                               ? ICK_Derived_To_Base
4774                               : (RefConv & Sema::ReferenceConversions::ObjC)
4775                                     ? ICK_Compatible_Conversion
4776                                     : ICK_Identity;
4777     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4778     // a reference binding that performs a non-top-level qualification
4779     // conversion as a qualification conversion, not as an identity conversion.
4780     ICS.Standard.Third = (RefConv &
4781                               Sema::ReferenceConversions::NestedQualification)
4782                              ? ICK_Qualification
4783                              : ICK_Identity;
4784     ICS.Standard.setFromType(T2);
4785     ICS.Standard.setToType(0, T2);
4786     ICS.Standard.setToType(1, T1);
4787     ICS.Standard.setToType(2, T1);
4788     ICS.Standard.ReferenceBinding = true;
4789     ICS.Standard.DirectBinding = BindsDirectly;
4790     ICS.Standard.IsLvalueReference = !isRValRef;
4791     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4792     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4793     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4794     ICS.Standard.ObjCLifetimeConversionBinding =
4795         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4796     ICS.Standard.CopyConstructor = nullptr;
4797     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4798   };
4799 
4800   // C++0x [dcl.init.ref]p5:
4801   //   A reference to type "cv1 T1" is initialized by an expression
4802   //   of type "cv2 T2" as follows:
4803 
4804   //     -- If reference is an lvalue reference and the initializer expression
4805   if (!isRValRef) {
4806     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4807     //        reference-compatible with "cv2 T2," or
4808     //
4809     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4810     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4811       // C++ [over.ics.ref]p1:
4812       //   When a parameter of reference type binds directly (8.5.3)
4813       //   to an argument expression, the implicit conversion sequence
4814       //   is the identity conversion, unless the argument expression
4815       //   has a type that is a derived class of the parameter type,
4816       //   in which case the implicit conversion sequence is a
4817       //   derived-to-base Conversion (13.3.3.1).
4818       SetAsReferenceBinding(/*BindsDirectly=*/true);
4819 
4820       // Nothing more to do: the inaccessibility/ambiguity check for
4821       // derived-to-base conversions is suppressed when we're
4822       // computing the implicit conversion sequence (C++
4823       // [over.best.ics]p2).
4824       return ICS;
4825     }
4826 
4827     //       -- has a class type (i.e., T2 is a class type), where T1 is
4828     //          not reference-related to T2, and can be implicitly
4829     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4830     //          is reference-compatible with "cv3 T3" 92) (this
4831     //          conversion is selected by enumerating the applicable
4832     //          conversion functions (13.3.1.6) and choosing the best
4833     //          one through overload resolution (13.3)),
4834     if (!SuppressUserConversions && T2->isRecordType() &&
4835         S.isCompleteType(DeclLoc, T2) &&
4836         RefRelationship == Sema::Ref_Incompatible) {
4837       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4838                                    Init, T2, /*AllowRvalues=*/false,
4839                                    AllowExplicit))
4840         return ICS;
4841     }
4842   }
4843 
4844   //     -- Otherwise, the reference shall be an lvalue reference to a
4845   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4846   //        shall be an rvalue reference.
4847   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4848     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4849       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4850     return ICS;
4851   }
4852 
4853   //       -- If the initializer expression
4854   //
4855   //            -- is an xvalue, class prvalue, array prvalue or function
4856   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4857   if (RefRelationship == Sema::Ref_Compatible &&
4858       (InitCategory.isXValue() ||
4859        (InitCategory.isPRValue() &&
4860           (T2->isRecordType() || T2->isArrayType())) ||
4861        (InitCategory.isLValue() && T2->isFunctionType()))) {
4862     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4863     // binding unless we're binding to a class prvalue.
4864     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4865     // allow the use of rvalue references in C++98/03 for the benefit of
4866     // standard library implementors; therefore, we need the xvalue check here.
4867     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4868                           !(InitCategory.isPRValue() || T2->isRecordType()));
4869     return ICS;
4870   }
4871 
4872   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4873   //               reference-related to T2, and can be implicitly converted to
4874   //               an xvalue, class prvalue, or function lvalue of type
4875   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4876   //               "cv3 T3",
4877   //
4878   //          then the reference is bound to the value of the initializer
4879   //          expression in the first case and to the result of the conversion
4880   //          in the second case (or, in either case, to an appropriate base
4881   //          class subobject).
4882   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4883       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4884       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4885                                Init, T2, /*AllowRvalues=*/true,
4886                                AllowExplicit)) {
4887     // In the second case, if the reference is an rvalue reference
4888     // and the second standard conversion sequence of the
4889     // user-defined conversion sequence includes an lvalue-to-rvalue
4890     // conversion, the program is ill-formed.
4891     if (ICS.isUserDefined() && isRValRef &&
4892         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4893       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4894 
4895     return ICS;
4896   }
4897 
4898   // A temporary of function type cannot be created; don't even try.
4899   if (T1->isFunctionType())
4900     return ICS;
4901 
4902   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4903   //          initialized from the initializer expression using the
4904   //          rules for a non-reference copy initialization (8.5). The
4905   //          reference is then bound to the temporary. If T1 is
4906   //          reference-related to T2, cv1 must be the same
4907   //          cv-qualification as, or greater cv-qualification than,
4908   //          cv2; otherwise, the program is ill-formed.
4909   if (RefRelationship == Sema::Ref_Related) {
4910     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4911     // we would be reference-compatible or reference-compatible with
4912     // added qualification. But that wasn't the case, so the reference
4913     // initialization fails.
4914     //
4915     // Note that we only want to check address spaces and cvr-qualifiers here.
4916     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4917     Qualifiers T1Quals = T1.getQualifiers();
4918     Qualifiers T2Quals = T2.getQualifiers();
4919     T1Quals.removeObjCGCAttr();
4920     T1Quals.removeObjCLifetime();
4921     T2Quals.removeObjCGCAttr();
4922     T2Quals.removeObjCLifetime();
4923     // MS compiler ignores __unaligned qualifier for references; do the same.
4924     T1Quals.removeUnaligned();
4925     T2Quals.removeUnaligned();
4926     if (!T1Quals.compatiblyIncludes(T2Quals))
4927       return ICS;
4928   }
4929 
4930   // If at least one of the types is a class type, the types are not
4931   // related, and we aren't allowed any user conversions, the
4932   // reference binding fails. This case is important for breaking
4933   // recursion, since TryImplicitConversion below will attempt to
4934   // create a temporary through the use of a copy constructor.
4935   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4936       (T1->isRecordType() || T2->isRecordType()))
4937     return ICS;
4938 
4939   // If T1 is reference-related to T2 and the reference is an rvalue
4940   // reference, the initializer expression shall not be an lvalue.
4941   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4942       Init->Classify(S.Context).isLValue()) {
4943     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4944     return ICS;
4945   }
4946 
4947   // C++ [over.ics.ref]p2:
4948   //   When a parameter of reference type is not bound directly to
4949   //   an argument expression, the conversion sequence is the one
4950   //   required to convert the argument expression to the
4951   //   underlying type of the reference according to
4952   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4953   //   to copy-initializing a temporary of the underlying type with
4954   //   the argument expression. Any difference in top-level
4955   //   cv-qualification is subsumed by the initialization itself
4956   //   and does not constitute a conversion.
4957   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4958                               AllowedExplicit::None,
4959                               /*InOverloadResolution=*/false,
4960                               /*CStyle=*/false,
4961                               /*AllowObjCWritebackConversion=*/false,
4962                               /*AllowObjCConversionOnExplicit=*/false);
4963 
4964   // Of course, that's still a reference binding.
4965   if (ICS.isStandard()) {
4966     ICS.Standard.ReferenceBinding = true;
4967     ICS.Standard.IsLvalueReference = !isRValRef;
4968     ICS.Standard.BindsToFunctionLvalue = false;
4969     ICS.Standard.BindsToRvalue = true;
4970     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4971     ICS.Standard.ObjCLifetimeConversionBinding = false;
4972   } else if (ICS.isUserDefined()) {
4973     const ReferenceType *LValRefType =
4974         ICS.UserDefined.ConversionFunction->getReturnType()
4975             ->getAs<LValueReferenceType>();
4976 
4977     // C++ [over.ics.ref]p3:
4978     //   Except for an implicit object parameter, for which see 13.3.1, a
4979     //   standard conversion sequence cannot be formed if it requires [...]
4980     //   binding an rvalue reference to an lvalue other than a function
4981     //   lvalue.
4982     // Note that the function case is not possible here.
4983     if (isRValRef && LValRefType) {
4984       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4985       return ICS;
4986     }
4987 
4988     ICS.UserDefined.After.ReferenceBinding = true;
4989     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4990     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4991     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4992     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4993     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4994   }
4995 
4996   return ICS;
4997 }
4998 
4999 static ImplicitConversionSequence
5000 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5001                       bool SuppressUserConversions,
5002                       bool InOverloadResolution,
5003                       bool AllowObjCWritebackConversion,
5004                       bool AllowExplicit = false);
5005 
5006 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5007 /// initializer list From.
5008 static ImplicitConversionSequence
5009 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5010                   bool SuppressUserConversions,
5011                   bool InOverloadResolution,
5012                   bool AllowObjCWritebackConversion) {
5013   // C++11 [over.ics.list]p1:
5014   //   When an argument is an initializer list, it is not an expression and
5015   //   special rules apply for converting it to a parameter type.
5016 
5017   ImplicitConversionSequence Result;
5018   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5019 
5020   // We need a complete type for what follows.  With one C++20 exception,
5021   // incomplete types can never be initialized from init lists.
5022   QualType InitTy = ToType;
5023   const ArrayType *AT = S.Context.getAsArrayType(ToType);
5024   if (AT && S.getLangOpts().CPlusPlus20)
5025     if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5026       // C++20 allows list initialization of an incomplete array type.
5027       InitTy = IAT->getElementType();
5028   if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5029     return Result;
5030 
5031   // Per DR1467:
5032   //   If the parameter type is a class X and the initializer list has a single
5033   //   element of type cv U, where U is X or a class derived from X, the
5034   //   implicit conversion sequence is the one required to convert the element
5035   //   to the parameter type.
5036   //
5037   //   Otherwise, if the parameter type is a character array [... ]
5038   //   and the initializer list has a single element that is an
5039   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5040   //   implicit conversion sequence is the identity conversion.
5041   if (From->getNumInits() == 1) {
5042     if (ToType->isRecordType()) {
5043       QualType InitType = From->getInit(0)->getType();
5044       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5045           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5046         return TryCopyInitialization(S, From->getInit(0), ToType,
5047                                      SuppressUserConversions,
5048                                      InOverloadResolution,
5049                                      AllowObjCWritebackConversion);
5050     }
5051 
5052     if (AT && S.IsStringInit(From->getInit(0), AT)) {
5053       InitializedEntity Entity =
5054           InitializedEntity::InitializeParameter(S.Context, ToType,
5055                                                  /*Consumed=*/false);
5056       if (S.CanPerformCopyInitialization(Entity, From)) {
5057         Result.setStandard();
5058         Result.Standard.setAsIdentityConversion();
5059         Result.Standard.setFromType(ToType);
5060         Result.Standard.setAllToTypes(ToType);
5061         return Result;
5062       }
5063     }
5064   }
5065 
5066   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5067   // C++11 [over.ics.list]p2:
5068   //   If the parameter type is std::initializer_list<X> or "array of X" and
5069   //   all the elements can be implicitly converted to X, the implicit
5070   //   conversion sequence is the worst conversion necessary to convert an
5071   //   element of the list to X.
5072   //
5073   // C++14 [over.ics.list]p3:
5074   //   Otherwise, if the parameter type is "array of N X", if the initializer
5075   //   list has exactly N elements or if it has fewer than N elements and X is
5076   //   default-constructible, and if all the elements of the initializer list
5077   //   can be implicitly converted to X, the implicit conversion sequence is
5078   //   the worst conversion necessary to convert an element of the list to X.
5079   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5080     unsigned e = From->getNumInits();
5081     ImplicitConversionSequence DfltElt;
5082     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5083                    QualType());
5084     QualType ContTy = ToType;
5085     bool IsUnbounded = false;
5086     if (AT) {
5087       InitTy = AT->getElementType();
5088       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5089         if (CT->getSize().ult(e)) {
5090           // Too many inits, fatally bad
5091           Result.setBad(BadConversionSequence::too_many_initializers, From,
5092                         ToType);
5093           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5094           return Result;
5095         }
5096         if (CT->getSize().ugt(e)) {
5097           // Need an init from empty {}, is there one?
5098           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5099                                  From->getEndLoc());
5100           EmptyList.setType(S.Context.VoidTy);
5101           DfltElt = TryListConversion(
5102               S, &EmptyList, InitTy, SuppressUserConversions,
5103               InOverloadResolution, AllowObjCWritebackConversion);
5104           if (DfltElt.isBad()) {
5105             // No {} init, fatally bad
5106             Result.setBad(BadConversionSequence::too_few_initializers, From,
5107                           ToType);
5108             Result.setInitializerListContainerType(ContTy, IsUnbounded);
5109             return Result;
5110           }
5111         }
5112       } else {
5113         assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5114         IsUnbounded = true;
5115         if (!e) {
5116           // Cannot convert to zero-sized.
5117           Result.setBad(BadConversionSequence::too_few_initializers, From,
5118                         ToType);
5119           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5120           return Result;
5121         }
5122         llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5123         ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5124                                                 ArrayType::Normal, 0);
5125       }
5126     }
5127 
5128     Result.setStandard();
5129     Result.Standard.setAsIdentityConversion();
5130     Result.Standard.setFromType(InitTy);
5131     Result.Standard.setAllToTypes(InitTy);
5132     for (unsigned i = 0; i < e; ++i) {
5133       Expr *Init = From->getInit(i);
5134       ImplicitConversionSequence ICS = TryCopyInitialization(
5135           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5136           AllowObjCWritebackConversion);
5137 
5138       // Keep the worse conversion seen so far.
5139       // FIXME: Sequences are not totally ordered, so 'worse' can be
5140       // ambiguous. CWG has been informed.
5141       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5142                                              Result) ==
5143           ImplicitConversionSequence::Worse) {
5144         Result = ICS;
5145         // Bail as soon as we find something unconvertible.
5146         if (Result.isBad()) {
5147           Result.setInitializerListContainerType(ContTy, IsUnbounded);
5148           return Result;
5149         }
5150       }
5151     }
5152 
5153     // If we needed any implicit {} initialization, compare that now.
5154     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5155     // has been informed that this might not be the best thing.
5156     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5157                                 S, From->getEndLoc(), DfltElt, Result) ==
5158                                 ImplicitConversionSequence::Worse)
5159       Result = DfltElt;
5160     // Record the type being initialized so that we may compare sequences
5161     Result.setInitializerListContainerType(ContTy, IsUnbounded);
5162     return Result;
5163   }
5164 
5165   // C++14 [over.ics.list]p4:
5166   // C++11 [over.ics.list]p3:
5167   //   Otherwise, if the parameter is a non-aggregate class X and overload
5168   //   resolution chooses a single best constructor [...] the implicit
5169   //   conversion sequence is a user-defined conversion sequence. If multiple
5170   //   constructors are viable but none is better than the others, the
5171   //   implicit conversion sequence is a user-defined conversion sequence.
5172   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5173     // This function can deal with initializer lists.
5174     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5175                                     AllowedExplicit::None,
5176                                     InOverloadResolution, /*CStyle=*/false,
5177                                     AllowObjCWritebackConversion,
5178                                     /*AllowObjCConversionOnExplicit=*/false);
5179   }
5180 
5181   // C++14 [over.ics.list]p5:
5182   // C++11 [over.ics.list]p4:
5183   //   Otherwise, if the parameter has an aggregate type which can be
5184   //   initialized from the initializer list [...] the implicit conversion
5185   //   sequence is a user-defined conversion sequence.
5186   if (ToType->isAggregateType()) {
5187     // Type is an aggregate, argument is an init list. At this point it comes
5188     // down to checking whether the initialization works.
5189     // FIXME: Find out whether this parameter is consumed or not.
5190     InitializedEntity Entity =
5191         InitializedEntity::InitializeParameter(S.Context, ToType,
5192                                                /*Consumed=*/false);
5193     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5194                                                                  From)) {
5195       Result.setUserDefined();
5196       Result.UserDefined.Before.setAsIdentityConversion();
5197       // Initializer lists don't have a type.
5198       Result.UserDefined.Before.setFromType(QualType());
5199       Result.UserDefined.Before.setAllToTypes(QualType());
5200 
5201       Result.UserDefined.After.setAsIdentityConversion();
5202       Result.UserDefined.After.setFromType(ToType);
5203       Result.UserDefined.After.setAllToTypes(ToType);
5204       Result.UserDefined.ConversionFunction = nullptr;
5205     }
5206     return Result;
5207   }
5208 
5209   // C++14 [over.ics.list]p6:
5210   // C++11 [over.ics.list]p5:
5211   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5212   if (ToType->isReferenceType()) {
5213     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5214     // mention initializer lists in any way. So we go by what list-
5215     // initialization would do and try to extrapolate from that.
5216 
5217     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5218 
5219     // If the initializer list has a single element that is reference-related
5220     // to the parameter type, we initialize the reference from that.
5221     if (From->getNumInits() == 1) {
5222       Expr *Init = From->getInit(0);
5223 
5224       QualType T2 = Init->getType();
5225 
5226       // If the initializer is the address of an overloaded function, try
5227       // to resolve the overloaded function. If all goes well, T2 is the
5228       // type of the resulting function.
5229       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5230         DeclAccessPair Found;
5231         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5232                                    Init, ToType, false, Found))
5233           T2 = Fn->getType();
5234       }
5235 
5236       // Compute some basic properties of the types and the initializer.
5237       Sema::ReferenceCompareResult RefRelationship =
5238           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5239 
5240       if (RefRelationship >= Sema::Ref_Related) {
5241         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5242                                 SuppressUserConversions,
5243                                 /*AllowExplicit=*/false);
5244       }
5245     }
5246 
5247     // Otherwise, we bind the reference to a temporary created from the
5248     // initializer list.
5249     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5250                                InOverloadResolution,
5251                                AllowObjCWritebackConversion);
5252     if (Result.isFailure())
5253       return Result;
5254     assert(!Result.isEllipsis() &&
5255            "Sub-initialization cannot result in ellipsis conversion.");
5256 
5257     // Can we even bind to a temporary?
5258     if (ToType->isRValueReferenceType() ||
5259         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5260       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5261                                             Result.UserDefined.After;
5262       SCS.ReferenceBinding = true;
5263       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5264       SCS.BindsToRvalue = true;
5265       SCS.BindsToFunctionLvalue = false;
5266       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5267       SCS.ObjCLifetimeConversionBinding = false;
5268     } else
5269       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5270                     From, ToType);
5271     return Result;
5272   }
5273 
5274   // C++14 [over.ics.list]p7:
5275   // C++11 [over.ics.list]p6:
5276   //   Otherwise, if the parameter type is not a class:
5277   if (!ToType->isRecordType()) {
5278     //    - if the initializer list has one element that is not itself an
5279     //      initializer list, the implicit conversion sequence is the one
5280     //      required to convert the element to the parameter type.
5281     unsigned NumInits = From->getNumInits();
5282     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5283       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5284                                      SuppressUserConversions,
5285                                      InOverloadResolution,
5286                                      AllowObjCWritebackConversion);
5287     //    - if the initializer list has no elements, the implicit conversion
5288     //      sequence is the identity conversion.
5289     else if (NumInits == 0) {
5290       Result.setStandard();
5291       Result.Standard.setAsIdentityConversion();
5292       Result.Standard.setFromType(ToType);
5293       Result.Standard.setAllToTypes(ToType);
5294     }
5295     return Result;
5296   }
5297 
5298   // C++14 [over.ics.list]p8:
5299   // C++11 [over.ics.list]p7:
5300   //   In all cases other than those enumerated above, no conversion is possible
5301   return Result;
5302 }
5303 
5304 /// TryCopyInitialization - Try to copy-initialize a value of type
5305 /// ToType from the expression From. Return the implicit conversion
5306 /// sequence required to pass this argument, which may be a bad
5307 /// conversion sequence (meaning that the argument cannot be passed to
5308 /// a parameter of this type). If @p SuppressUserConversions, then we
5309 /// do not permit any user-defined conversion sequences.
5310 static ImplicitConversionSequence
5311 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5312                       bool SuppressUserConversions,
5313                       bool InOverloadResolution,
5314                       bool AllowObjCWritebackConversion,
5315                       bool AllowExplicit) {
5316   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5317     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5318                              InOverloadResolution,AllowObjCWritebackConversion);
5319 
5320   if (ToType->isReferenceType())
5321     return TryReferenceInit(S, From, ToType,
5322                             /*FIXME:*/ From->getBeginLoc(),
5323                             SuppressUserConversions, AllowExplicit);
5324 
5325   return TryImplicitConversion(S, From, ToType,
5326                                SuppressUserConversions,
5327                                AllowedExplicit::None,
5328                                InOverloadResolution,
5329                                /*CStyle=*/false,
5330                                AllowObjCWritebackConversion,
5331                                /*AllowObjCConversionOnExplicit=*/false);
5332 }
5333 
5334 static bool TryCopyInitialization(const CanQualType FromQTy,
5335                                   const CanQualType ToQTy,
5336                                   Sema &S,
5337                                   SourceLocation Loc,
5338                                   ExprValueKind FromVK) {
5339   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5340   ImplicitConversionSequence ICS =
5341     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5342 
5343   return !ICS.isBad();
5344 }
5345 
5346 /// TryObjectArgumentInitialization - Try to initialize the object
5347 /// parameter of the given member function (@c Method) from the
5348 /// expression @p From.
5349 static ImplicitConversionSequence
5350 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5351                                 Expr::Classification FromClassification,
5352                                 CXXMethodDecl *Method,
5353                                 CXXRecordDecl *ActingContext) {
5354   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5355   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5356   //                 const volatile object.
5357   Qualifiers Quals = Method->getMethodQualifiers();
5358   if (isa<CXXDestructorDecl>(Method)) {
5359     Quals.addConst();
5360     Quals.addVolatile();
5361   }
5362 
5363   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5364 
5365   // Set up the conversion sequence as a "bad" conversion, to allow us
5366   // to exit early.
5367   ImplicitConversionSequence ICS;
5368 
5369   // We need to have an object of class type.
5370   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5371     FromType = PT->getPointeeType();
5372 
5373     // When we had a pointer, it's implicitly dereferenced, so we
5374     // better have an lvalue.
5375     assert(FromClassification.isLValue());
5376   }
5377 
5378   assert(FromType->isRecordType());
5379 
5380   // C++0x [over.match.funcs]p4:
5381   //   For non-static member functions, the type of the implicit object
5382   //   parameter is
5383   //
5384   //     - "lvalue reference to cv X" for functions declared without a
5385   //        ref-qualifier or with the & ref-qualifier
5386   //     - "rvalue reference to cv X" for functions declared with the &&
5387   //        ref-qualifier
5388   //
5389   // where X is the class of which the function is a member and cv is the
5390   // cv-qualification on the member function declaration.
5391   //
5392   // However, when finding an implicit conversion sequence for the argument, we
5393   // are not allowed to perform user-defined conversions
5394   // (C++ [over.match.funcs]p5). We perform a simplified version of
5395   // reference binding here, that allows class rvalues to bind to
5396   // non-constant references.
5397 
5398   // First check the qualifiers.
5399   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5400   if (ImplicitParamType.getCVRQualifiers()
5401                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5402       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5403     ICS.setBad(BadConversionSequence::bad_qualifiers,
5404                FromType, ImplicitParamType);
5405     return ICS;
5406   }
5407 
5408   if (FromTypeCanon.hasAddressSpace()) {
5409     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5410     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5411     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5412       ICS.setBad(BadConversionSequence::bad_qualifiers,
5413                  FromType, ImplicitParamType);
5414       return ICS;
5415     }
5416   }
5417 
5418   // Check that we have either the same type or a derived type. It
5419   // affects the conversion rank.
5420   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5421   ImplicitConversionKind SecondKind;
5422   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5423     SecondKind = ICK_Identity;
5424   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5425     SecondKind = ICK_Derived_To_Base;
5426   else {
5427     ICS.setBad(BadConversionSequence::unrelated_class,
5428                FromType, ImplicitParamType);
5429     return ICS;
5430   }
5431 
5432   // Check the ref-qualifier.
5433   switch (Method->getRefQualifier()) {
5434   case RQ_None:
5435     // Do nothing; we don't care about lvalueness or rvalueness.
5436     break;
5437 
5438   case RQ_LValue:
5439     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5440       // non-const lvalue reference cannot bind to an rvalue
5441       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5442                  ImplicitParamType);
5443       return ICS;
5444     }
5445     break;
5446 
5447   case RQ_RValue:
5448     if (!FromClassification.isRValue()) {
5449       // rvalue reference cannot bind to an lvalue
5450       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5451                  ImplicitParamType);
5452       return ICS;
5453     }
5454     break;
5455   }
5456 
5457   // Success. Mark this as a reference binding.
5458   ICS.setStandard();
5459   ICS.Standard.setAsIdentityConversion();
5460   ICS.Standard.Second = SecondKind;
5461   ICS.Standard.setFromType(FromType);
5462   ICS.Standard.setAllToTypes(ImplicitParamType);
5463   ICS.Standard.ReferenceBinding = true;
5464   ICS.Standard.DirectBinding = true;
5465   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5466   ICS.Standard.BindsToFunctionLvalue = false;
5467   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5468   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5469     = (Method->getRefQualifier() == RQ_None);
5470   return ICS;
5471 }
5472 
5473 /// PerformObjectArgumentInitialization - Perform initialization of
5474 /// the implicit object parameter for the given Method with the given
5475 /// expression.
5476 ExprResult
5477 Sema::PerformObjectArgumentInitialization(Expr *From,
5478                                           NestedNameSpecifier *Qualifier,
5479                                           NamedDecl *FoundDecl,
5480                                           CXXMethodDecl *Method) {
5481   QualType FromRecordType, DestType;
5482   QualType ImplicitParamRecordType  =
5483     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5484 
5485   Expr::Classification FromClassification;
5486   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5487     FromRecordType = PT->getPointeeType();
5488     DestType = Method->getThisType();
5489     FromClassification = Expr::Classification::makeSimpleLValue();
5490   } else {
5491     FromRecordType = From->getType();
5492     DestType = ImplicitParamRecordType;
5493     FromClassification = From->Classify(Context);
5494 
5495     // When performing member access on a prvalue, materialize a temporary.
5496     if (From->isPRValue()) {
5497       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5498                                             Method->getRefQualifier() !=
5499                                                 RefQualifierKind::RQ_RValue);
5500     }
5501   }
5502 
5503   // Note that we always use the true parent context when performing
5504   // the actual argument initialization.
5505   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5506       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5507       Method->getParent());
5508   if (ICS.isBad()) {
5509     switch (ICS.Bad.Kind) {
5510     case BadConversionSequence::bad_qualifiers: {
5511       Qualifiers FromQs = FromRecordType.getQualifiers();
5512       Qualifiers ToQs = DestType.getQualifiers();
5513       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5514       if (CVR) {
5515         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5516             << Method->getDeclName() << FromRecordType << (CVR - 1)
5517             << From->getSourceRange();
5518         Diag(Method->getLocation(), diag::note_previous_decl)
5519           << Method->getDeclName();
5520         return ExprError();
5521       }
5522       break;
5523     }
5524 
5525     case BadConversionSequence::lvalue_ref_to_rvalue:
5526     case BadConversionSequence::rvalue_ref_to_lvalue: {
5527       bool IsRValueQualified =
5528         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5529       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5530           << Method->getDeclName() << FromClassification.isRValue()
5531           << IsRValueQualified;
5532       Diag(Method->getLocation(), diag::note_previous_decl)
5533         << Method->getDeclName();
5534       return ExprError();
5535     }
5536 
5537     case BadConversionSequence::no_conversion:
5538     case BadConversionSequence::unrelated_class:
5539       break;
5540 
5541     case BadConversionSequence::too_few_initializers:
5542     case BadConversionSequence::too_many_initializers:
5543       llvm_unreachable("Lists are not objects");
5544     }
5545 
5546     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5547            << ImplicitParamRecordType << FromRecordType
5548            << From->getSourceRange();
5549   }
5550 
5551   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5552     ExprResult FromRes =
5553       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5554     if (FromRes.isInvalid())
5555       return ExprError();
5556     From = FromRes.get();
5557   }
5558 
5559   if (!Context.hasSameType(From->getType(), DestType)) {
5560     CastKind CK;
5561     QualType PteeTy = DestType->getPointeeType();
5562     LangAS DestAS =
5563         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5564     if (FromRecordType.getAddressSpace() != DestAS)
5565       CK = CK_AddressSpaceConversion;
5566     else
5567       CK = CK_NoOp;
5568     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5569   }
5570   return From;
5571 }
5572 
5573 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5574 /// expression From to bool (C++0x [conv]p3).
5575 static ImplicitConversionSequence
5576 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5577   // C++ [dcl.init]/17.8:
5578   //   - Otherwise, if the initialization is direct-initialization, the source
5579   //     type is std::nullptr_t, and the destination type is bool, the initial
5580   //     value of the object being initialized is false.
5581   if (From->getType()->isNullPtrType())
5582     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5583                                                         S.Context.BoolTy,
5584                                                         From->isGLValue());
5585 
5586   // All other direct-initialization of bool is equivalent to an implicit
5587   // conversion to bool in which explicit conversions are permitted.
5588   return TryImplicitConversion(S, From, S.Context.BoolTy,
5589                                /*SuppressUserConversions=*/false,
5590                                AllowedExplicit::Conversions,
5591                                /*InOverloadResolution=*/false,
5592                                /*CStyle=*/false,
5593                                /*AllowObjCWritebackConversion=*/false,
5594                                /*AllowObjCConversionOnExplicit=*/false);
5595 }
5596 
5597 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5598 /// of the expression From to bool (C++0x [conv]p3).
5599 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5600   if (checkPlaceholderForOverload(*this, From))
5601     return ExprError();
5602 
5603   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5604   if (!ICS.isBad())
5605     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5606 
5607   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5608     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5609            << From->getType() << From->getSourceRange();
5610   return ExprError();
5611 }
5612 
5613 /// Check that the specified conversion is permitted in a converted constant
5614 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5615 /// is acceptable.
5616 static bool CheckConvertedConstantConversions(Sema &S,
5617                                               StandardConversionSequence &SCS) {
5618   // Since we know that the target type is an integral or unscoped enumeration
5619   // type, most conversion kinds are impossible. All possible First and Third
5620   // conversions are fine.
5621   switch (SCS.Second) {
5622   case ICK_Identity:
5623   case ICK_Integral_Promotion:
5624   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5625   case ICK_Zero_Queue_Conversion:
5626     return true;
5627 
5628   case ICK_Boolean_Conversion:
5629     // Conversion from an integral or unscoped enumeration type to bool is
5630     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5631     // conversion, so we allow it in a converted constant expression.
5632     //
5633     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5634     // a lot of popular code. We should at least add a warning for this
5635     // (non-conforming) extension.
5636     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5637            SCS.getToType(2)->isBooleanType();
5638 
5639   case ICK_Pointer_Conversion:
5640   case ICK_Pointer_Member:
5641     // C++1z: null pointer conversions and null member pointer conversions are
5642     // only permitted if the source type is std::nullptr_t.
5643     return SCS.getFromType()->isNullPtrType();
5644 
5645   case ICK_Floating_Promotion:
5646   case ICK_Complex_Promotion:
5647   case ICK_Floating_Conversion:
5648   case ICK_Complex_Conversion:
5649   case ICK_Floating_Integral:
5650   case ICK_Compatible_Conversion:
5651   case ICK_Derived_To_Base:
5652   case ICK_Vector_Conversion:
5653   case ICK_SVE_Vector_Conversion:
5654   case ICK_Vector_Splat:
5655   case ICK_Complex_Real:
5656   case ICK_Block_Pointer_Conversion:
5657   case ICK_TransparentUnionConversion:
5658   case ICK_Writeback_Conversion:
5659   case ICK_Zero_Event_Conversion:
5660   case ICK_C_Only_Conversion:
5661   case ICK_Incompatible_Pointer_Conversion:
5662     return false;
5663 
5664   case ICK_Lvalue_To_Rvalue:
5665   case ICK_Array_To_Pointer:
5666   case ICK_Function_To_Pointer:
5667     llvm_unreachable("found a first conversion kind in Second");
5668 
5669   case ICK_Function_Conversion:
5670   case ICK_Qualification:
5671     llvm_unreachable("found a third conversion kind in Second");
5672 
5673   case ICK_Num_Conversion_Kinds:
5674     break;
5675   }
5676 
5677   llvm_unreachable("unknown conversion kind");
5678 }
5679 
5680 /// CheckConvertedConstantExpression - Check that the expression From is a
5681 /// converted constant expression of type T, perform the conversion and produce
5682 /// the converted expression, per C++11 [expr.const]p3.
5683 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5684                                                    QualType T, APValue &Value,
5685                                                    Sema::CCEKind CCE,
5686                                                    bool RequireInt,
5687                                                    NamedDecl *Dest) {
5688   assert(S.getLangOpts().CPlusPlus11 &&
5689          "converted constant expression outside C++11");
5690 
5691   if (checkPlaceholderForOverload(S, From))
5692     return ExprError();
5693 
5694   // C++1z [expr.const]p3:
5695   //  A converted constant expression of type T is an expression,
5696   //  implicitly converted to type T, where the converted
5697   //  expression is a constant expression and the implicit conversion
5698   //  sequence contains only [... list of conversions ...].
5699   ImplicitConversionSequence ICS =
5700       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5701           ? TryContextuallyConvertToBool(S, From)
5702           : TryCopyInitialization(S, From, T,
5703                                   /*SuppressUserConversions=*/false,
5704                                   /*InOverloadResolution=*/false,
5705                                   /*AllowObjCWritebackConversion=*/false,
5706                                   /*AllowExplicit=*/false);
5707   StandardConversionSequence *SCS = nullptr;
5708   switch (ICS.getKind()) {
5709   case ImplicitConversionSequence::StandardConversion:
5710     SCS = &ICS.Standard;
5711     break;
5712   case ImplicitConversionSequence::UserDefinedConversion:
5713     if (T->isRecordType())
5714       SCS = &ICS.UserDefined.Before;
5715     else
5716       SCS = &ICS.UserDefined.After;
5717     break;
5718   case ImplicitConversionSequence::AmbiguousConversion:
5719   case ImplicitConversionSequence::BadConversion:
5720     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5721       return S.Diag(From->getBeginLoc(),
5722                     diag::err_typecheck_converted_constant_expression)
5723              << From->getType() << From->getSourceRange() << T;
5724     return ExprError();
5725 
5726   case ImplicitConversionSequence::EllipsisConversion:
5727     llvm_unreachable("ellipsis conversion in converted constant expression");
5728   }
5729 
5730   // Check that we would only use permitted conversions.
5731   if (!CheckConvertedConstantConversions(S, *SCS)) {
5732     return S.Diag(From->getBeginLoc(),
5733                   diag::err_typecheck_converted_constant_expression_disallowed)
5734            << From->getType() << From->getSourceRange() << T;
5735   }
5736   // [...] and where the reference binding (if any) binds directly.
5737   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5738     return S.Diag(From->getBeginLoc(),
5739                   diag::err_typecheck_converted_constant_expression_indirect)
5740            << From->getType() << From->getSourceRange() << T;
5741   }
5742 
5743   // Usually we can simply apply the ImplicitConversionSequence we formed
5744   // earlier, but that's not guaranteed to work when initializing an object of
5745   // class type.
5746   ExprResult Result;
5747   if (T->isRecordType()) {
5748     assert(CCE == Sema::CCEK_TemplateArg &&
5749            "unexpected class type converted constant expr");
5750     Result = S.PerformCopyInitialization(
5751         InitializedEntity::InitializeTemplateParameter(
5752             T, cast<NonTypeTemplateParmDecl>(Dest)),
5753         SourceLocation(), From);
5754   } else {
5755     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5756   }
5757   if (Result.isInvalid())
5758     return Result;
5759 
5760   // C++2a [intro.execution]p5:
5761   //   A full-expression is [...] a constant-expression [...]
5762   Result =
5763       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5764                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5765   if (Result.isInvalid())
5766     return Result;
5767 
5768   // Check for a narrowing implicit conversion.
5769   bool ReturnPreNarrowingValue = false;
5770   APValue PreNarrowingValue;
5771   QualType PreNarrowingType;
5772   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5773                                 PreNarrowingType)) {
5774   case NK_Dependent_Narrowing:
5775     // Implicit conversion to a narrower type, but the expression is
5776     // value-dependent so we can't tell whether it's actually narrowing.
5777   case NK_Variable_Narrowing:
5778     // Implicit conversion to a narrower type, and the value is not a constant
5779     // expression. We'll diagnose this in a moment.
5780   case NK_Not_Narrowing:
5781     break;
5782 
5783   case NK_Constant_Narrowing:
5784     if (CCE == Sema::CCEK_ArrayBound &&
5785         PreNarrowingType->isIntegralOrEnumerationType() &&
5786         PreNarrowingValue.isInt()) {
5787       // Don't diagnose array bound narrowing here; we produce more precise
5788       // errors by allowing the un-narrowed value through.
5789       ReturnPreNarrowingValue = true;
5790       break;
5791     }
5792     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5793         << CCE << /*Constant*/ 1
5794         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5795     break;
5796 
5797   case NK_Type_Narrowing:
5798     // FIXME: It would be better to diagnose that the expression is not a
5799     // constant expression.
5800     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5801         << CCE << /*Constant*/ 0 << From->getType() << T;
5802     break;
5803   }
5804 
5805   if (Result.get()->isValueDependent()) {
5806     Value = APValue();
5807     return Result;
5808   }
5809 
5810   // Check the expression is a constant expression.
5811   SmallVector<PartialDiagnosticAt, 8> Notes;
5812   Expr::EvalResult Eval;
5813   Eval.Diag = &Notes;
5814 
5815   ConstantExprKind Kind;
5816   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5817     Kind = ConstantExprKind::ClassTemplateArgument;
5818   else if (CCE == Sema::CCEK_TemplateArg)
5819     Kind = ConstantExprKind::NonClassTemplateArgument;
5820   else
5821     Kind = ConstantExprKind::Normal;
5822 
5823   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5824       (RequireInt && !Eval.Val.isInt())) {
5825     // The expression can't be folded, so we can't keep it at this position in
5826     // the AST.
5827     Result = ExprError();
5828   } else {
5829     Value = Eval.Val;
5830 
5831     if (Notes.empty()) {
5832       // It's a constant expression.
5833       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5834       if (ReturnPreNarrowingValue)
5835         Value = std::move(PreNarrowingValue);
5836       return E;
5837     }
5838   }
5839 
5840   // It's not a constant expression. Produce an appropriate diagnostic.
5841   if (Notes.size() == 1 &&
5842       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5843     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5844   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5845                                    diag::note_constexpr_invalid_template_arg) {
5846     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5847     for (unsigned I = 0; I < Notes.size(); ++I)
5848       S.Diag(Notes[I].first, Notes[I].second);
5849   } else {
5850     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5851         << CCE << From->getSourceRange();
5852     for (unsigned I = 0; I < Notes.size(); ++I)
5853       S.Diag(Notes[I].first, Notes[I].second);
5854   }
5855   return ExprError();
5856 }
5857 
5858 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5859                                                   APValue &Value, CCEKind CCE,
5860                                                   NamedDecl *Dest) {
5861   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5862                                             Dest);
5863 }
5864 
5865 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5866                                                   llvm::APSInt &Value,
5867                                                   CCEKind CCE) {
5868   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5869 
5870   APValue V;
5871   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5872                                               /*Dest=*/nullptr);
5873   if (!R.isInvalid() && !R.get()->isValueDependent())
5874     Value = V.getInt();
5875   return R;
5876 }
5877 
5878 
5879 /// dropPointerConversions - If the given standard conversion sequence
5880 /// involves any pointer conversions, remove them.  This may change
5881 /// the result type of the conversion sequence.
5882 static void dropPointerConversion(StandardConversionSequence &SCS) {
5883   if (SCS.Second == ICK_Pointer_Conversion) {
5884     SCS.Second = ICK_Identity;
5885     SCS.Third = ICK_Identity;
5886     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5887   }
5888 }
5889 
5890 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5891 /// convert the expression From to an Objective-C pointer type.
5892 static ImplicitConversionSequence
5893 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5894   // Do an implicit conversion to 'id'.
5895   QualType Ty = S.Context.getObjCIdType();
5896   ImplicitConversionSequence ICS
5897     = TryImplicitConversion(S, From, Ty,
5898                             // FIXME: Are these flags correct?
5899                             /*SuppressUserConversions=*/false,
5900                             AllowedExplicit::Conversions,
5901                             /*InOverloadResolution=*/false,
5902                             /*CStyle=*/false,
5903                             /*AllowObjCWritebackConversion=*/false,
5904                             /*AllowObjCConversionOnExplicit=*/true);
5905 
5906   // Strip off any final conversions to 'id'.
5907   switch (ICS.getKind()) {
5908   case ImplicitConversionSequence::BadConversion:
5909   case ImplicitConversionSequence::AmbiguousConversion:
5910   case ImplicitConversionSequence::EllipsisConversion:
5911     break;
5912 
5913   case ImplicitConversionSequence::UserDefinedConversion:
5914     dropPointerConversion(ICS.UserDefined.After);
5915     break;
5916 
5917   case ImplicitConversionSequence::StandardConversion:
5918     dropPointerConversion(ICS.Standard);
5919     break;
5920   }
5921 
5922   return ICS;
5923 }
5924 
5925 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5926 /// conversion of the expression From to an Objective-C pointer type.
5927 /// Returns a valid but null ExprResult if no conversion sequence exists.
5928 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5929   if (checkPlaceholderForOverload(*this, From))
5930     return ExprError();
5931 
5932   QualType Ty = Context.getObjCIdType();
5933   ImplicitConversionSequence ICS =
5934     TryContextuallyConvertToObjCPointer(*this, From);
5935   if (!ICS.isBad())
5936     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5937   return ExprResult();
5938 }
5939 
5940 /// Determine whether the provided type is an integral type, or an enumeration
5941 /// type of a permitted flavor.
5942 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5943   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5944                                  : T->isIntegralOrUnscopedEnumerationType();
5945 }
5946 
5947 static ExprResult
5948 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5949                             Sema::ContextualImplicitConverter &Converter,
5950                             QualType T, UnresolvedSetImpl &ViableConversions) {
5951 
5952   if (Converter.Suppress)
5953     return ExprError();
5954 
5955   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5956   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5957     CXXConversionDecl *Conv =
5958         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5959     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5960     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5961   }
5962   return From;
5963 }
5964 
5965 static bool
5966 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5967                            Sema::ContextualImplicitConverter &Converter,
5968                            QualType T, bool HadMultipleCandidates,
5969                            UnresolvedSetImpl &ExplicitConversions) {
5970   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5971     DeclAccessPair Found = ExplicitConversions[0];
5972     CXXConversionDecl *Conversion =
5973         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5974 
5975     // The user probably meant to invoke the given explicit
5976     // conversion; use it.
5977     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5978     std::string TypeStr;
5979     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5980 
5981     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5982         << FixItHint::CreateInsertion(From->getBeginLoc(),
5983                                       "static_cast<" + TypeStr + ">(")
5984         << FixItHint::CreateInsertion(
5985                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5986     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5987 
5988     // If we aren't in a SFINAE context, build a call to the
5989     // explicit conversion function.
5990     if (SemaRef.isSFINAEContext())
5991       return true;
5992 
5993     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5994     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5995                                                        HadMultipleCandidates);
5996     if (Result.isInvalid())
5997       return true;
5998     // Record usage of conversion in an implicit cast.
5999     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6000                                     CK_UserDefinedConversion, Result.get(),
6001                                     nullptr, Result.get()->getValueKind(),
6002                                     SemaRef.CurFPFeatureOverrides());
6003   }
6004   return false;
6005 }
6006 
6007 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6008                              Sema::ContextualImplicitConverter &Converter,
6009                              QualType T, bool HadMultipleCandidates,
6010                              DeclAccessPair &Found) {
6011   CXXConversionDecl *Conversion =
6012       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6013   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6014 
6015   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6016   if (!Converter.SuppressConversion) {
6017     if (SemaRef.isSFINAEContext())
6018       return true;
6019 
6020     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6021         << From->getSourceRange();
6022   }
6023 
6024   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6025                                                      HadMultipleCandidates);
6026   if (Result.isInvalid())
6027     return true;
6028   // Record usage of conversion in an implicit cast.
6029   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6030                                   CK_UserDefinedConversion, Result.get(),
6031                                   nullptr, Result.get()->getValueKind(),
6032                                   SemaRef.CurFPFeatureOverrides());
6033   return false;
6034 }
6035 
6036 static ExprResult finishContextualImplicitConversion(
6037     Sema &SemaRef, SourceLocation Loc, Expr *From,
6038     Sema::ContextualImplicitConverter &Converter) {
6039   if (!Converter.match(From->getType()) && !Converter.Suppress)
6040     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6041         << From->getSourceRange();
6042 
6043   return SemaRef.DefaultLvalueConversion(From);
6044 }
6045 
6046 static void
6047 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6048                                   UnresolvedSetImpl &ViableConversions,
6049                                   OverloadCandidateSet &CandidateSet) {
6050   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6051     DeclAccessPair FoundDecl = ViableConversions[I];
6052     NamedDecl *D = FoundDecl.getDecl();
6053     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6054     if (isa<UsingShadowDecl>(D))
6055       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6056 
6057     CXXConversionDecl *Conv;
6058     FunctionTemplateDecl *ConvTemplate;
6059     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6060       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6061     else
6062       Conv = cast<CXXConversionDecl>(D);
6063 
6064     if (ConvTemplate)
6065       SemaRef.AddTemplateConversionCandidate(
6066           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6067           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6068     else
6069       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6070                                      ToType, CandidateSet,
6071                                      /*AllowObjCConversionOnExplicit=*/false,
6072                                      /*AllowExplicit*/ true);
6073   }
6074 }
6075 
6076 /// Attempt to convert the given expression to a type which is accepted
6077 /// by the given converter.
6078 ///
6079 /// This routine will attempt to convert an expression of class type to a
6080 /// type accepted by the specified converter. In C++11 and before, the class
6081 /// must have a single non-explicit conversion function converting to a matching
6082 /// type. In C++1y, there can be multiple such conversion functions, but only
6083 /// one target type.
6084 ///
6085 /// \param Loc The source location of the construct that requires the
6086 /// conversion.
6087 ///
6088 /// \param From The expression we're converting from.
6089 ///
6090 /// \param Converter Used to control and diagnose the conversion process.
6091 ///
6092 /// \returns The expression, converted to an integral or enumeration type if
6093 /// successful.
6094 ExprResult Sema::PerformContextualImplicitConversion(
6095     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6096   // We can't perform any more checking for type-dependent expressions.
6097   if (From->isTypeDependent())
6098     return From;
6099 
6100   // Process placeholders immediately.
6101   if (From->hasPlaceholderType()) {
6102     ExprResult result = CheckPlaceholderExpr(From);
6103     if (result.isInvalid())
6104       return result;
6105     From = result.get();
6106   }
6107 
6108   // If the expression already has a matching type, we're golden.
6109   QualType T = From->getType();
6110   if (Converter.match(T))
6111     return DefaultLvalueConversion(From);
6112 
6113   // FIXME: Check for missing '()' if T is a function type?
6114 
6115   // We can only perform contextual implicit conversions on objects of class
6116   // type.
6117   const RecordType *RecordTy = T->getAs<RecordType>();
6118   if (!RecordTy || !getLangOpts().CPlusPlus) {
6119     if (!Converter.Suppress)
6120       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6121     return From;
6122   }
6123 
6124   // We must have a complete class type.
6125   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6126     ContextualImplicitConverter &Converter;
6127     Expr *From;
6128 
6129     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6130         : Converter(Converter), From(From) {}
6131 
6132     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6133       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6134     }
6135   } IncompleteDiagnoser(Converter, From);
6136 
6137   if (Converter.Suppress ? !isCompleteType(Loc, T)
6138                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6139     return From;
6140 
6141   // Look for a conversion to an integral or enumeration type.
6142   UnresolvedSet<4>
6143       ViableConversions; // These are *potentially* viable in C++1y.
6144   UnresolvedSet<4> ExplicitConversions;
6145   const auto &Conversions =
6146       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6147 
6148   bool HadMultipleCandidates =
6149       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6150 
6151   // To check that there is only one target type, in C++1y:
6152   QualType ToType;
6153   bool HasUniqueTargetType = true;
6154 
6155   // Collect explicit or viable (potentially in C++1y) conversions.
6156   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6157     NamedDecl *D = (*I)->getUnderlyingDecl();
6158     CXXConversionDecl *Conversion;
6159     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6160     if (ConvTemplate) {
6161       if (getLangOpts().CPlusPlus14)
6162         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6163       else
6164         continue; // C++11 does not consider conversion operator templates(?).
6165     } else
6166       Conversion = cast<CXXConversionDecl>(D);
6167 
6168     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6169            "Conversion operator templates are considered potentially "
6170            "viable in C++1y");
6171 
6172     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6173     if (Converter.match(CurToType) || ConvTemplate) {
6174 
6175       if (Conversion->isExplicit()) {
6176         // FIXME: For C++1y, do we need this restriction?
6177         // cf. diagnoseNoViableConversion()
6178         if (!ConvTemplate)
6179           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6180       } else {
6181         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6182           if (ToType.isNull())
6183             ToType = CurToType.getUnqualifiedType();
6184           else if (HasUniqueTargetType &&
6185                    (CurToType.getUnqualifiedType() != ToType))
6186             HasUniqueTargetType = false;
6187         }
6188         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6189       }
6190     }
6191   }
6192 
6193   if (getLangOpts().CPlusPlus14) {
6194     // C++1y [conv]p6:
6195     // ... An expression e of class type E appearing in such a context
6196     // is said to be contextually implicitly converted to a specified
6197     // type T and is well-formed if and only if e can be implicitly
6198     // converted to a type T that is determined as follows: E is searched
6199     // for conversion functions whose return type is cv T or reference to
6200     // cv T such that T is allowed by the context. There shall be
6201     // exactly one such T.
6202 
6203     // If no unique T is found:
6204     if (ToType.isNull()) {
6205       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6206                                      HadMultipleCandidates,
6207                                      ExplicitConversions))
6208         return ExprError();
6209       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6210     }
6211 
6212     // If more than one unique Ts are found:
6213     if (!HasUniqueTargetType)
6214       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6215                                          ViableConversions);
6216 
6217     // If one unique T is found:
6218     // First, build a candidate set from the previously recorded
6219     // potentially viable conversions.
6220     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6221     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6222                                       CandidateSet);
6223 
6224     // Then, perform overload resolution over the candidate set.
6225     OverloadCandidateSet::iterator Best;
6226     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6227     case OR_Success: {
6228       // Apply this conversion.
6229       DeclAccessPair Found =
6230           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6231       if (recordConversion(*this, Loc, From, Converter, T,
6232                            HadMultipleCandidates, Found))
6233         return ExprError();
6234       break;
6235     }
6236     case OR_Ambiguous:
6237       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6238                                          ViableConversions);
6239     case OR_No_Viable_Function:
6240       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6241                                      HadMultipleCandidates,
6242                                      ExplicitConversions))
6243         return ExprError();
6244       LLVM_FALLTHROUGH;
6245     case OR_Deleted:
6246       // We'll complain below about a non-integral condition type.
6247       break;
6248     }
6249   } else {
6250     switch (ViableConversions.size()) {
6251     case 0: {
6252       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6253                                      HadMultipleCandidates,
6254                                      ExplicitConversions))
6255         return ExprError();
6256 
6257       // We'll complain below about a non-integral condition type.
6258       break;
6259     }
6260     case 1: {
6261       // Apply this conversion.
6262       DeclAccessPair Found = ViableConversions[0];
6263       if (recordConversion(*this, Loc, From, Converter, T,
6264                            HadMultipleCandidates, Found))
6265         return ExprError();
6266       break;
6267     }
6268     default:
6269       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6270                                          ViableConversions);
6271     }
6272   }
6273 
6274   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6275 }
6276 
6277 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6278 /// an acceptable non-member overloaded operator for a call whose
6279 /// arguments have types T1 (and, if non-empty, T2). This routine
6280 /// implements the check in C++ [over.match.oper]p3b2 concerning
6281 /// enumeration types.
6282 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6283                                                    FunctionDecl *Fn,
6284                                                    ArrayRef<Expr *> Args) {
6285   QualType T1 = Args[0]->getType();
6286   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6287 
6288   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6289     return true;
6290 
6291   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6292     return true;
6293 
6294   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6295   if (Proto->getNumParams() < 1)
6296     return false;
6297 
6298   if (T1->isEnumeralType()) {
6299     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6300     if (Context.hasSameUnqualifiedType(T1, ArgType))
6301       return true;
6302   }
6303 
6304   if (Proto->getNumParams() < 2)
6305     return false;
6306 
6307   if (!T2.isNull() && T2->isEnumeralType()) {
6308     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6309     if (Context.hasSameUnqualifiedType(T2, ArgType))
6310       return true;
6311   }
6312 
6313   return false;
6314 }
6315 
6316 /// AddOverloadCandidate - Adds the given function to the set of
6317 /// candidate functions, using the given function call arguments.  If
6318 /// @p SuppressUserConversions, then don't allow user-defined
6319 /// conversions via constructors or conversion operators.
6320 ///
6321 /// \param PartialOverloading true if we are performing "partial" overloading
6322 /// based on an incomplete set of function arguments. This feature is used by
6323 /// code completion.
6324 void Sema::AddOverloadCandidate(
6325     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6326     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6327     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6328     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6329     OverloadCandidateParamOrder PO) {
6330   const FunctionProtoType *Proto
6331     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6332   assert(Proto && "Functions without a prototype cannot be overloaded");
6333   assert(!Function->getDescribedFunctionTemplate() &&
6334          "Use AddTemplateOverloadCandidate for function templates");
6335 
6336   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6337     if (!isa<CXXConstructorDecl>(Method)) {
6338       // If we get here, it's because we're calling a member function
6339       // that is named without a member access expression (e.g.,
6340       // "this->f") that was either written explicitly or created
6341       // implicitly. This can happen with a qualified call to a member
6342       // function, e.g., X::f(). We use an empty type for the implied
6343       // object argument (C++ [over.call.func]p3), and the acting context
6344       // is irrelevant.
6345       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6346                          Expr::Classification::makeSimpleLValue(), Args,
6347                          CandidateSet, SuppressUserConversions,
6348                          PartialOverloading, EarlyConversions, PO);
6349       return;
6350     }
6351     // We treat a constructor like a non-member function, since its object
6352     // argument doesn't participate in overload resolution.
6353   }
6354 
6355   if (!CandidateSet.isNewCandidate(Function, PO))
6356     return;
6357 
6358   // C++11 [class.copy]p11: [DR1402]
6359   //   A defaulted move constructor that is defined as deleted is ignored by
6360   //   overload resolution.
6361   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6362   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6363       Constructor->isMoveConstructor())
6364     return;
6365 
6366   // Overload resolution is always an unevaluated context.
6367   EnterExpressionEvaluationContext Unevaluated(
6368       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6369 
6370   // C++ [over.match.oper]p3:
6371   //   if no operand has a class type, only those non-member functions in the
6372   //   lookup set that have a first parameter of type T1 or "reference to
6373   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6374   //   is a right operand) a second parameter of type T2 or "reference to
6375   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6376   //   candidate functions.
6377   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6378       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6379     return;
6380 
6381   // Add this candidate
6382   OverloadCandidate &Candidate =
6383       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6384   Candidate.FoundDecl = FoundDecl;
6385   Candidate.Function = Function;
6386   Candidate.Viable = true;
6387   Candidate.RewriteKind =
6388       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6389   Candidate.IsSurrogate = false;
6390   Candidate.IsADLCandidate = IsADLCandidate;
6391   Candidate.IgnoreObjectArgument = false;
6392   Candidate.ExplicitCallArguments = Args.size();
6393 
6394   // Explicit functions are not actually candidates at all if we're not
6395   // allowing them in this context, but keep them around so we can point
6396   // to them in diagnostics.
6397   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6398     Candidate.Viable = false;
6399     Candidate.FailureKind = ovl_fail_explicit;
6400     return;
6401   }
6402 
6403   // Functions with internal linkage are only viable in the same module unit.
6404   if (auto *MF = Function->getOwningModule()) {
6405     if (getLangOpts().CPlusPlusModules && !MF->isModuleMapModule() &&
6406         !isModuleUnitOfCurrentTU(MF)) {
6407       /// FIXME: Currently, the semantics of linkage in clang is slightly
6408       /// different from the semantics in C++ spec. In C++ spec, only names
6409       /// have linkage. So that all entities of the same should share one
6410       /// linkage. But in clang, different entities of the same could have
6411       /// different linkage.
6412       NamedDecl *ND = Function;
6413       if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6414         ND = SpecInfo->getTemplate();
6415 
6416       if (ND->getFormalLinkage() == Linkage::InternalLinkage) {
6417         Candidate.Viable = false;
6418         Candidate.FailureKind = ovl_fail_module_mismatched;
6419         return;
6420       }
6421     }
6422   }
6423 
6424   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6425       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6426     Candidate.Viable = false;
6427     Candidate.FailureKind = ovl_non_default_multiversion_function;
6428     return;
6429   }
6430 
6431   if (Constructor) {
6432     // C++ [class.copy]p3:
6433     //   A member function template is never instantiated to perform the copy
6434     //   of a class object to an object of its class type.
6435     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6436     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6437         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6438          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6439                        ClassType))) {
6440       Candidate.Viable = false;
6441       Candidate.FailureKind = ovl_fail_illegal_constructor;
6442       return;
6443     }
6444 
6445     // C++ [over.match.funcs]p8: (proposed DR resolution)
6446     //   A constructor inherited from class type C that has a first parameter
6447     //   of type "reference to P" (including such a constructor instantiated
6448     //   from a template) is excluded from the set of candidate functions when
6449     //   constructing an object of type cv D if the argument list has exactly
6450     //   one argument and D is reference-related to P and P is reference-related
6451     //   to C.
6452     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6453     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6454         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6455       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6456       QualType C = Context.getRecordType(Constructor->getParent());
6457       QualType D = Context.getRecordType(Shadow->getParent());
6458       SourceLocation Loc = Args.front()->getExprLoc();
6459       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6460           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6461         Candidate.Viable = false;
6462         Candidate.FailureKind = ovl_fail_inhctor_slice;
6463         return;
6464       }
6465     }
6466 
6467     // Check that the constructor is capable of constructing an object in the
6468     // destination address space.
6469     if (!Qualifiers::isAddressSpaceSupersetOf(
6470             Constructor->getMethodQualifiers().getAddressSpace(),
6471             CandidateSet.getDestAS())) {
6472       Candidate.Viable = false;
6473       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6474     }
6475   }
6476 
6477   unsigned NumParams = Proto->getNumParams();
6478 
6479   // (C++ 13.3.2p2): A candidate function having fewer than m
6480   // parameters is viable only if it has an ellipsis in its parameter
6481   // list (8.3.5).
6482   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6483       !Proto->isVariadic() &&
6484       shouldEnforceArgLimit(PartialOverloading, Function)) {
6485     Candidate.Viable = false;
6486     Candidate.FailureKind = ovl_fail_too_many_arguments;
6487     return;
6488   }
6489 
6490   // (C++ 13.3.2p2): A candidate function having more than m parameters
6491   // is viable only if the (m+1)st parameter has a default argument
6492   // (8.3.6). For the purposes of overload resolution, the
6493   // parameter list is truncated on the right, so that there are
6494   // exactly m parameters.
6495   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6496   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6497     // Not enough arguments.
6498     Candidate.Viable = false;
6499     Candidate.FailureKind = ovl_fail_too_few_arguments;
6500     return;
6501   }
6502 
6503   // (CUDA B.1): Check for invalid calls between targets.
6504   if (getLangOpts().CUDA)
6505     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
6506       // Skip the check for callers that are implicit members, because in this
6507       // case we may not yet know what the member's target is; the target is
6508       // inferred for the member automatically, based on the bases and fields of
6509       // the class.
6510       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6511         Candidate.Viable = false;
6512         Candidate.FailureKind = ovl_fail_bad_target;
6513         return;
6514       }
6515 
6516   if (Function->getTrailingRequiresClause()) {
6517     ConstraintSatisfaction Satisfaction;
6518     if (CheckFunctionConstraints(Function, Satisfaction) ||
6519         !Satisfaction.IsSatisfied) {
6520       Candidate.Viable = false;
6521       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6522       return;
6523     }
6524   }
6525 
6526   // Determine the implicit conversion sequences for each of the
6527   // arguments.
6528   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6529     unsigned ConvIdx =
6530         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6531     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6532       // We already formed a conversion sequence for this parameter during
6533       // template argument deduction.
6534     } else if (ArgIdx < NumParams) {
6535       // (C++ 13.3.2p3): for F to be a viable function, there shall
6536       // exist for each argument an implicit conversion sequence
6537       // (13.3.3.1) that converts that argument to the corresponding
6538       // parameter of F.
6539       QualType ParamType = Proto->getParamType(ArgIdx);
6540       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6541           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6542           /*InOverloadResolution=*/true,
6543           /*AllowObjCWritebackConversion=*/
6544           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6545       if (Candidate.Conversions[ConvIdx].isBad()) {
6546         Candidate.Viable = false;
6547         Candidate.FailureKind = ovl_fail_bad_conversion;
6548         return;
6549       }
6550     } else {
6551       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6552       // argument for which there is no corresponding parameter is
6553       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6554       Candidate.Conversions[ConvIdx].setEllipsis();
6555     }
6556   }
6557 
6558   if (EnableIfAttr *FailedAttr =
6559           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6560     Candidate.Viable = false;
6561     Candidate.FailureKind = ovl_fail_enable_if;
6562     Candidate.DeductionFailure.Data = FailedAttr;
6563     return;
6564   }
6565 }
6566 
6567 ObjCMethodDecl *
6568 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6569                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6570   if (Methods.size() <= 1)
6571     return nullptr;
6572 
6573   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6574     bool Match = true;
6575     ObjCMethodDecl *Method = Methods[b];
6576     unsigned NumNamedArgs = Sel.getNumArgs();
6577     // Method might have more arguments than selector indicates. This is due
6578     // to addition of c-style arguments in method.
6579     if (Method->param_size() > NumNamedArgs)
6580       NumNamedArgs = Method->param_size();
6581     if (Args.size() < NumNamedArgs)
6582       continue;
6583 
6584     for (unsigned i = 0; i < NumNamedArgs; i++) {
6585       // We can't do any type-checking on a type-dependent argument.
6586       if (Args[i]->isTypeDependent()) {
6587         Match = false;
6588         break;
6589       }
6590 
6591       ParmVarDecl *param = Method->parameters()[i];
6592       Expr *argExpr = Args[i];
6593       assert(argExpr && "SelectBestMethod(): missing expression");
6594 
6595       // Strip the unbridged-cast placeholder expression off unless it's
6596       // a consumed argument.
6597       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6598           !param->hasAttr<CFConsumedAttr>())
6599         argExpr = stripARCUnbridgedCast(argExpr);
6600 
6601       // If the parameter is __unknown_anytype, move on to the next method.
6602       if (param->getType() == Context.UnknownAnyTy) {
6603         Match = false;
6604         break;
6605       }
6606 
6607       ImplicitConversionSequence ConversionState
6608         = TryCopyInitialization(*this, argExpr, param->getType(),
6609                                 /*SuppressUserConversions*/false,
6610                                 /*InOverloadResolution=*/true,
6611                                 /*AllowObjCWritebackConversion=*/
6612                                 getLangOpts().ObjCAutoRefCount,
6613                                 /*AllowExplicit*/false);
6614       // This function looks for a reasonably-exact match, so we consider
6615       // incompatible pointer conversions to be a failure here.
6616       if (ConversionState.isBad() ||
6617           (ConversionState.isStandard() &&
6618            ConversionState.Standard.Second ==
6619                ICK_Incompatible_Pointer_Conversion)) {
6620         Match = false;
6621         break;
6622       }
6623     }
6624     // Promote additional arguments to variadic methods.
6625     if (Match && Method->isVariadic()) {
6626       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6627         if (Args[i]->isTypeDependent()) {
6628           Match = false;
6629           break;
6630         }
6631         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6632                                                           nullptr);
6633         if (Arg.isInvalid()) {
6634           Match = false;
6635           break;
6636         }
6637       }
6638     } else {
6639       // Check for extra arguments to non-variadic methods.
6640       if (Args.size() != NumNamedArgs)
6641         Match = false;
6642       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6643         // Special case when selectors have no argument. In this case, select
6644         // one with the most general result type of 'id'.
6645         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6646           QualType ReturnT = Methods[b]->getReturnType();
6647           if (ReturnT->isObjCIdType())
6648             return Methods[b];
6649         }
6650       }
6651     }
6652 
6653     if (Match)
6654       return Method;
6655   }
6656   return nullptr;
6657 }
6658 
6659 static bool convertArgsForAvailabilityChecks(
6660     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6661     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6662     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6663   if (ThisArg) {
6664     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6665     assert(!isa<CXXConstructorDecl>(Method) &&
6666            "Shouldn't have `this` for ctors!");
6667     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6668     ExprResult R = S.PerformObjectArgumentInitialization(
6669         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6670     if (R.isInvalid())
6671       return false;
6672     ConvertedThis = R.get();
6673   } else {
6674     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6675       (void)MD;
6676       assert((MissingImplicitThis || MD->isStatic() ||
6677               isa<CXXConstructorDecl>(MD)) &&
6678              "Expected `this` for non-ctor instance methods");
6679     }
6680     ConvertedThis = nullptr;
6681   }
6682 
6683   // Ignore any variadic arguments. Converting them is pointless, since the
6684   // user can't refer to them in the function condition.
6685   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6686 
6687   // Convert the arguments.
6688   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6689     ExprResult R;
6690     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6691                                         S.Context, Function->getParamDecl(I)),
6692                                     SourceLocation(), Args[I]);
6693 
6694     if (R.isInvalid())
6695       return false;
6696 
6697     ConvertedArgs.push_back(R.get());
6698   }
6699 
6700   if (Trap.hasErrorOccurred())
6701     return false;
6702 
6703   // Push default arguments if needed.
6704   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6705     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6706       ParmVarDecl *P = Function->getParamDecl(i);
6707       if (!P->hasDefaultArg())
6708         return false;
6709       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6710       if (R.isInvalid())
6711         return false;
6712       ConvertedArgs.push_back(R.get());
6713     }
6714 
6715     if (Trap.hasErrorOccurred())
6716       return false;
6717   }
6718   return true;
6719 }
6720 
6721 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6722                                   SourceLocation CallLoc,
6723                                   ArrayRef<Expr *> Args,
6724                                   bool MissingImplicitThis) {
6725   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6726   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6727     return nullptr;
6728 
6729   SFINAETrap Trap(*this);
6730   SmallVector<Expr *, 16> ConvertedArgs;
6731   // FIXME: We should look into making enable_if late-parsed.
6732   Expr *DiscardedThis;
6733   if (!convertArgsForAvailabilityChecks(
6734           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6735           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6736     return *EnableIfAttrs.begin();
6737 
6738   for (auto *EIA : EnableIfAttrs) {
6739     APValue Result;
6740     // FIXME: This doesn't consider value-dependent cases, because doing so is
6741     // very difficult. Ideally, we should handle them more gracefully.
6742     if (EIA->getCond()->isValueDependent() ||
6743         !EIA->getCond()->EvaluateWithSubstitution(
6744             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6745       return EIA;
6746 
6747     if (!Result.isInt() || !Result.getInt().getBoolValue())
6748       return EIA;
6749   }
6750   return nullptr;
6751 }
6752 
6753 template <typename CheckFn>
6754 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6755                                         bool ArgDependent, SourceLocation Loc,
6756                                         CheckFn &&IsSuccessful) {
6757   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6758   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6759     if (ArgDependent == DIA->getArgDependent())
6760       Attrs.push_back(DIA);
6761   }
6762 
6763   // Common case: No diagnose_if attributes, so we can quit early.
6764   if (Attrs.empty())
6765     return false;
6766 
6767   auto WarningBegin = std::stable_partition(
6768       Attrs.begin(), Attrs.end(),
6769       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6770 
6771   // Note that diagnose_if attributes are late-parsed, so they appear in the
6772   // correct order (unlike enable_if attributes).
6773   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6774                                IsSuccessful);
6775   if (ErrAttr != WarningBegin) {
6776     const DiagnoseIfAttr *DIA = *ErrAttr;
6777     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6778     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6779         << DIA->getParent() << DIA->getCond()->getSourceRange();
6780     return true;
6781   }
6782 
6783   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6784     if (IsSuccessful(DIA)) {
6785       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6786       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6787           << DIA->getParent() << DIA->getCond()->getSourceRange();
6788     }
6789 
6790   return false;
6791 }
6792 
6793 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6794                                                const Expr *ThisArg,
6795                                                ArrayRef<const Expr *> Args,
6796                                                SourceLocation Loc) {
6797   return diagnoseDiagnoseIfAttrsWith(
6798       *this, Function, /*ArgDependent=*/true, Loc,
6799       [&](const DiagnoseIfAttr *DIA) {
6800         APValue Result;
6801         // It's sane to use the same Args for any redecl of this function, since
6802         // EvaluateWithSubstitution only cares about the position of each
6803         // argument in the arg list, not the ParmVarDecl* it maps to.
6804         if (!DIA->getCond()->EvaluateWithSubstitution(
6805                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6806           return false;
6807         return Result.isInt() && Result.getInt().getBoolValue();
6808       });
6809 }
6810 
6811 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6812                                                  SourceLocation Loc) {
6813   return diagnoseDiagnoseIfAttrsWith(
6814       *this, ND, /*ArgDependent=*/false, Loc,
6815       [&](const DiagnoseIfAttr *DIA) {
6816         bool Result;
6817         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6818                Result;
6819       });
6820 }
6821 
6822 /// Add all of the function declarations in the given function set to
6823 /// the overload candidate set.
6824 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6825                                  ArrayRef<Expr *> Args,
6826                                  OverloadCandidateSet &CandidateSet,
6827                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6828                                  bool SuppressUserConversions,
6829                                  bool PartialOverloading,
6830                                  bool FirstArgumentIsBase) {
6831   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6832     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6833     ArrayRef<Expr *> FunctionArgs = Args;
6834 
6835     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6836     FunctionDecl *FD =
6837         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6838 
6839     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6840       QualType ObjectType;
6841       Expr::Classification ObjectClassification;
6842       if (Args.size() > 0) {
6843         if (Expr *E = Args[0]) {
6844           // Use the explicit base to restrict the lookup:
6845           ObjectType = E->getType();
6846           // Pointers in the object arguments are implicitly dereferenced, so we
6847           // always classify them as l-values.
6848           if (!ObjectType.isNull() && ObjectType->isPointerType())
6849             ObjectClassification = Expr::Classification::makeSimpleLValue();
6850           else
6851             ObjectClassification = E->Classify(Context);
6852         } // .. else there is an implicit base.
6853         FunctionArgs = Args.slice(1);
6854       }
6855       if (FunTmpl) {
6856         AddMethodTemplateCandidate(
6857             FunTmpl, F.getPair(),
6858             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6859             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6860             FunctionArgs, CandidateSet, SuppressUserConversions,
6861             PartialOverloading);
6862       } else {
6863         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6864                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6865                            ObjectClassification, FunctionArgs, CandidateSet,
6866                            SuppressUserConversions, PartialOverloading);
6867       }
6868     } else {
6869       // This branch handles both standalone functions and static methods.
6870 
6871       // Slice the first argument (which is the base) when we access
6872       // static method as non-static.
6873       if (Args.size() > 0 &&
6874           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6875                         !isa<CXXConstructorDecl>(FD)))) {
6876         assert(cast<CXXMethodDecl>(FD)->isStatic());
6877         FunctionArgs = Args.slice(1);
6878       }
6879       if (FunTmpl) {
6880         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6881                                      ExplicitTemplateArgs, FunctionArgs,
6882                                      CandidateSet, SuppressUserConversions,
6883                                      PartialOverloading);
6884       } else {
6885         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6886                              SuppressUserConversions, PartialOverloading);
6887       }
6888     }
6889   }
6890 }
6891 
6892 /// AddMethodCandidate - Adds a named decl (which is some kind of
6893 /// method) as a method candidate to the given overload set.
6894 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6895                               Expr::Classification ObjectClassification,
6896                               ArrayRef<Expr *> Args,
6897                               OverloadCandidateSet &CandidateSet,
6898                               bool SuppressUserConversions,
6899                               OverloadCandidateParamOrder PO) {
6900   NamedDecl *Decl = FoundDecl.getDecl();
6901   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6902 
6903   if (isa<UsingShadowDecl>(Decl))
6904     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6905 
6906   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6907     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6908            "Expected a member function template");
6909     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6910                                /*ExplicitArgs*/ nullptr, ObjectType,
6911                                ObjectClassification, Args, CandidateSet,
6912                                SuppressUserConversions, false, PO);
6913   } else {
6914     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6915                        ObjectType, ObjectClassification, Args, CandidateSet,
6916                        SuppressUserConversions, false, None, PO);
6917   }
6918 }
6919 
6920 /// AddMethodCandidate - Adds the given C++ member function to the set
6921 /// of candidate functions, using the given function call arguments
6922 /// and the object argument (@c Object). For example, in a call
6923 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6924 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6925 /// allow user-defined conversions via constructors or conversion
6926 /// operators.
6927 void
6928 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6929                          CXXRecordDecl *ActingContext, QualType ObjectType,
6930                          Expr::Classification ObjectClassification,
6931                          ArrayRef<Expr *> Args,
6932                          OverloadCandidateSet &CandidateSet,
6933                          bool SuppressUserConversions,
6934                          bool PartialOverloading,
6935                          ConversionSequenceList EarlyConversions,
6936                          OverloadCandidateParamOrder PO) {
6937   const FunctionProtoType *Proto
6938     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6939   assert(Proto && "Methods without a prototype cannot be overloaded");
6940   assert(!isa<CXXConstructorDecl>(Method) &&
6941          "Use AddOverloadCandidate for constructors");
6942 
6943   if (!CandidateSet.isNewCandidate(Method, PO))
6944     return;
6945 
6946   // C++11 [class.copy]p23: [DR1402]
6947   //   A defaulted move assignment operator that is defined as deleted is
6948   //   ignored by overload resolution.
6949   if (Method->isDefaulted() && Method->isDeleted() &&
6950       Method->isMoveAssignmentOperator())
6951     return;
6952 
6953   // Overload resolution is always an unevaluated context.
6954   EnterExpressionEvaluationContext Unevaluated(
6955       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6956 
6957   // Add this candidate
6958   OverloadCandidate &Candidate =
6959       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6960   Candidate.FoundDecl = FoundDecl;
6961   Candidate.Function = Method;
6962   Candidate.RewriteKind =
6963       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6964   Candidate.IsSurrogate = false;
6965   Candidate.IgnoreObjectArgument = false;
6966   Candidate.ExplicitCallArguments = Args.size();
6967 
6968   unsigned NumParams = Proto->getNumParams();
6969 
6970   // (C++ 13.3.2p2): A candidate function having fewer than m
6971   // parameters is viable only if it has an ellipsis in its parameter
6972   // list (8.3.5).
6973   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6974       !Proto->isVariadic() &&
6975       shouldEnforceArgLimit(PartialOverloading, Method)) {
6976     Candidate.Viable = false;
6977     Candidate.FailureKind = ovl_fail_too_many_arguments;
6978     return;
6979   }
6980 
6981   // (C++ 13.3.2p2): A candidate function having more than m parameters
6982   // is viable only if the (m+1)st parameter has a default argument
6983   // (8.3.6). For the purposes of overload resolution, the
6984   // parameter list is truncated on the right, so that there are
6985   // exactly m parameters.
6986   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6987   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6988     // Not enough arguments.
6989     Candidate.Viable = false;
6990     Candidate.FailureKind = ovl_fail_too_few_arguments;
6991     return;
6992   }
6993 
6994   Candidate.Viable = true;
6995 
6996   if (Method->isStatic() || ObjectType.isNull())
6997     // The implicit object argument is ignored.
6998     Candidate.IgnoreObjectArgument = true;
6999   else {
7000     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7001     // Determine the implicit conversion sequence for the object
7002     // parameter.
7003     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
7004         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7005         Method, ActingContext);
7006     if (Candidate.Conversions[ConvIdx].isBad()) {
7007       Candidate.Viable = false;
7008       Candidate.FailureKind = ovl_fail_bad_conversion;
7009       return;
7010     }
7011   }
7012 
7013   // (CUDA B.1): Check for invalid calls between targets.
7014   if (getLangOpts().CUDA)
7015     if (const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true))
7016       if (!IsAllowedCUDACall(Caller, Method)) {
7017         Candidate.Viable = false;
7018         Candidate.FailureKind = ovl_fail_bad_target;
7019         return;
7020       }
7021 
7022   if (Method->getTrailingRequiresClause()) {
7023     ConstraintSatisfaction Satisfaction;
7024     if (CheckFunctionConstraints(Method, Satisfaction) ||
7025         !Satisfaction.IsSatisfied) {
7026       Candidate.Viable = false;
7027       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7028       return;
7029     }
7030   }
7031 
7032   // Determine the implicit conversion sequences for each of the
7033   // arguments.
7034   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7035     unsigned ConvIdx =
7036         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7037     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7038       // We already formed a conversion sequence for this parameter during
7039       // template argument deduction.
7040     } else if (ArgIdx < NumParams) {
7041       // (C++ 13.3.2p3): for F to be a viable function, there shall
7042       // exist for each argument an implicit conversion sequence
7043       // (13.3.3.1) that converts that argument to the corresponding
7044       // parameter of F.
7045       QualType ParamType = Proto->getParamType(ArgIdx);
7046       Candidate.Conversions[ConvIdx]
7047         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7048                                 SuppressUserConversions,
7049                                 /*InOverloadResolution=*/true,
7050                                 /*AllowObjCWritebackConversion=*/
7051                                   getLangOpts().ObjCAutoRefCount);
7052       if (Candidate.Conversions[ConvIdx].isBad()) {
7053         Candidate.Viable = false;
7054         Candidate.FailureKind = ovl_fail_bad_conversion;
7055         return;
7056       }
7057     } else {
7058       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7059       // argument for which there is no corresponding parameter is
7060       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7061       Candidate.Conversions[ConvIdx].setEllipsis();
7062     }
7063   }
7064 
7065   if (EnableIfAttr *FailedAttr =
7066           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7067     Candidate.Viable = false;
7068     Candidate.FailureKind = ovl_fail_enable_if;
7069     Candidate.DeductionFailure.Data = FailedAttr;
7070     return;
7071   }
7072 
7073   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7074       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7075     Candidate.Viable = false;
7076     Candidate.FailureKind = ovl_non_default_multiversion_function;
7077   }
7078 }
7079 
7080 /// Add a C++ member function template as a candidate to the candidate
7081 /// set, using template argument deduction to produce an appropriate member
7082 /// function template specialization.
7083 void Sema::AddMethodTemplateCandidate(
7084     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7085     CXXRecordDecl *ActingContext,
7086     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7087     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7088     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7089     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7090   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7091     return;
7092 
7093   // C++ [over.match.funcs]p7:
7094   //   In each case where a candidate is a function template, candidate
7095   //   function template specializations are generated using template argument
7096   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7097   //   candidate functions in the usual way.113) A given name can refer to one
7098   //   or more function templates and also to a set of overloaded non-template
7099   //   functions. In such a case, the candidate functions generated from each
7100   //   function template are combined with the set of non-template candidate
7101   //   functions.
7102   TemplateDeductionInfo Info(CandidateSet.getLocation());
7103   FunctionDecl *Specialization = nullptr;
7104   ConversionSequenceList Conversions;
7105   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7106           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7107           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7108             return CheckNonDependentConversions(
7109                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7110                 SuppressUserConversions, ActingContext, ObjectType,
7111                 ObjectClassification, PO);
7112           })) {
7113     OverloadCandidate &Candidate =
7114         CandidateSet.addCandidate(Conversions.size(), Conversions);
7115     Candidate.FoundDecl = FoundDecl;
7116     Candidate.Function = MethodTmpl->getTemplatedDecl();
7117     Candidate.Viable = false;
7118     Candidate.RewriteKind =
7119       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7120     Candidate.IsSurrogate = false;
7121     Candidate.IgnoreObjectArgument =
7122         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7123         ObjectType.isNull();
7124     Candidate.ExplicitCallArguments = Args.size();
7125     if (Result == TDK_NonDependentConversionFailure)
7126       Candidate.FailureKind = ovl_fail_bad_conversion;
7127     else {
7128       Candidate.FailureKind = ovl_fail_bad_deduction;
7129       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7130                                                             Info);
7131     }
7132     return;
7133   }
7134 
7135   // Add the function template specialization produced by template argument
7136   // deduction as a candidate.
7137   assert(Specialization && "Missing member function template specialization?");
7138   assert(isa<CXXMethodDecl>(Specialization) &&
7139          "Specialization is not a member function?");
7140   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7141                      ActingContext, ObjectType, ObjectClassification, Args,
7142                      CandidateSet, SuppressUserConversions, PartialOverloading,
7143                      Conversions, PO);
7144 }
7145 
7146 /// Determine whether a given function template has a simple explicit specifier
7147 /// or a non-value-dependent explicit-specification that evaluates to true.
7148 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7149   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7150 }
7151 
7152 /// Add a C++ function template specialization as a candidate
7153 /// in the candidate set, using template argument deduction to produce
7154 /// an appropriate function template specialization.
7155 void Sema::AddTemplateOverloadCandidate(
7156     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7157     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7158     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7159     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7160     OverloadCandidateParamOrder PO) {
7161   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7162     return;
7163 
7164   // If the function template has a non-dependent explicit specification,
7165   // exclude it now if appropriate; we are not permitted to perform deduction
7166   // and substitution in this case.
7167   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7168     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7169     Candidate.FoundDecl = FoundDecl;
7170     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7171     Candidate.Viable = false;
7172     Candidate.FailureKind = ovl_fail_explicit;
7173     return;
7174   }
7175 
7176   // C++ [over.match.funcs]p7:
7177   //   In each case where a candidate is a function template, candidate
7178   //   function template specializations are generated using template argument
7179   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7180   //   candidate functions in the usual way.113) A given name can refer to one
7181   //   or more function templates and also to a set of overloaded non-template
7182   //   functions. In such a case, the candidate functions generated from each
7183   //   function template are combined with the set of non-template candidate
7184   //   functions.
7185   TemplateDeductionInfo Info(CandidateSet.getLocation());
7186   FunctionDecl *Specialization = nullptr;
7187   ConversionSequenceList Conversions;
7188   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7189           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7190           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7191             return CheckNonDependentConversions(
7192                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7193                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7194           })) {
7195     OverloadCandidate &Candidate =
7196         CandidateSet.addCandidate(Conversions.size(), Conversions);
7197     Candidate.FoundDecl = FoundDecl;
7198     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7199     Candidate.Viable = false;
7200     Candidate.RewriteKind =
7201       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7202     Candidate.IsSurrogate = false;
7203     Candidate.IsADLCandidate = IsADLCandidate;
7204     // Ignore the object argument if there is one, since we don't have an object
7205     // type.
7206     Candidate.IgnoreObjectArgument =
7207         isa<CXXMethodDecl>(Candidate.Function) &&
7208         !isa<CXXConstructorDecl>(Candidate.Function);
7209     Candidate.ExplicitCallArguments = Args.size();
7210     if (Result == TDK_NonDependentConversionFailure)
7211       Candidate.FailureKind = ovl_fail_bad_conversion;
7212     else {
7213       Candidate.FailureKind = ovl_fail_bad_deduction;
7214       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7215                                                             Info);
7216     }
7217     return;
7218   }
7219 
7220   // Add the function template specialization produced by template argument
7221   // deduction as a candidate.
7222   assert(Specialization && "Missing function template specialization?");
7223   AddOverloadCandidate(
7224       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7225       PartialOverloading, AllowExplicit,
7226       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7227 }
7228 
7229 /// Check that implicit conversion sequences can be formed for each argument
7230 /// whose corresponding parameter has a non-dependent type, per DR1391's
7231 /// [temp.deduct.call]p10.
7232 bool Sema::CheckNonDependentConversions(
7233     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7234     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7235     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7236     CXXRecordDecl *ActingContext, QualType ObjectType,
7237     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7238   // FIXME: The cases in which we allow explicit conversions for constructor
7239   // arguments never consider calling a constructor template. It's not clear
7240   // that is correct.
7241   const bool AllowExplicit = false;
7242 
7243   auto *FD = FunctionTemplate->getTemplatedDecl();
7244   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7245   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7246   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7247 
7248   Conversions =
7249       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7250 
7251   // Overload resolution is always an unevaluated context.
7252   EnterExpressionEvaluationContext Unevaluated(
7253       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7254 
7255   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7256   // require that, but this check should never result in a hard error, and
7257   // overload resolution is permitted to sidestep instantiations.
7258   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7259       !ObjectType.isNull()) {
7260     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7261     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7262         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7263         Method, ActingContext);
7264     if (Conversions[ConvIdx].isBad())
7265       return true;
7266   }
7267 
7268   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7269        ++I) {
7270     QualType ParamType = ParamTypes[I];
7271     if (!ParamType->isDependentType()) {
7272       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7273                              ? 0
7274                              : (ThisConversions + I);
7275       Conversions[ConvIdx]
7276         = TryCopyInitialization(*this, Args[I], ParamType,
7277                                 SuppressUserConversions,
7278                                 /*InOverloadResolution=*/true,
7279                                 /*AllowObjCWritebackConversion=*/
7280                                   getLangOpts().ObjCAutoRefCount,
7281                                 AllowExplicit);
7282       if (Conversions[ConvIdx].isBad())
7283         return true;
7284     }
7285   }
7286 
7287   return false;
7288 }
7289 
7290 /// Determine whether this is an allowable conversion from the result
7291 /// of an explicit conversion operator to the expected type, per C++
7292 /// [over.match.conv]p1 and [over.match.ref]p1.
7293 ///
7294 /// \param ConvType The return type of the conversion function.
7295 ///
7296 /// \param ToType The type we are converting to.
7297 ///
7298 /// \param AllowObjCPointerConversion Allow a conversion from one
7299 /// Objective-C pointer to another.
7300 ///
7301 /// \returns true if the conversion is allowable, false otherwise.
7302 static bool isAllowableExplicitConversion(Sema &S,
7303                                           QualType ConvType, QualType ToType,
7304                                           bool AllowObjCPointerConversion) {
7305   QualType ToNonRefType = ToType.getNonReferenceType();
7306 
7307   // Easy case: the types are the same.
7308   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7309     return true;
7310 
7311   // Allow qualification conversions.
7312   bool ObjCLifetimeConversion;
7313   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7314                                   ObjCLifetimeConversion))
7315     return true;
7316 
7317   // If we're not allowed to consider Objective-C pointer conversions,
7318   // we're done.
7319   if (!AllowObjCPointerConversion)
7320     return false;
7321 
7322   // Is this an Objective-C pointer conversion?
7323   bool IncompatibleObjC = false;
7324   QualType ConvertedType;
7325   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7326                                    IncompatibleObjC);
7327 }
7328 
7329 /// AddConversionCandidate - Add a C++ conversion function as a
7330 /// candidate in the candidate set (C++ [over.match.conv],
7331 /// C++ [over.match.copy]). From is the expression we're converting from,
7332 /// and ToType is the type that we're eventually trying to convert to
7333 /// (which may or may not be the same type as the type that the
7334 /// conversion function produces).
7335 void Sema::AddConversionCandidate(
7336     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7337     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7338     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7339     bool AllowExplicit, bool AllowResultConversion) {
7340   assert(!Conversion->getDescribedFunctionTemplate() &&
7341          "Conversion function templates use AddTemplateConversionCandidate");
7342   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7343   if (!CandidateSet.isNewCandidate(Conversion))
7344     return;
7345 
7346   // If the conversion function has an undeduced return type, trigger its
7347   // deduction now.
7348   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7349     if (DeduceReturnType(Conversion, From->getExprLoc()))
7350       return;
7351     ConvType = Conversion->getConversionType().getNonReferenceType();
7352   }
7353 
7354   // If we don't allow any conversion of the result type, ignore conversion
7355   // functions that don't convert to exactly (possibly cv-qualified) T.
7356   if (!AllowResultConversion &&
7357       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7358     return;
7359 
7360   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7361   // operator is only a candidate if its return type is the target type or
7362   // can be converted to the target type with a qualification conversion.
7363   //
7364   // FIXME: Include such functions in the candidate list and explain why we
7365   // can't select them.
7366   if (Conversion->isExplicit() &&
7367       !isAllowableExplicitConversion(*this, ConvType, ToType,
7368                                      AllowObjCConversionOnExplicit))
7369     return;
7370 
7371   // Overload resolution is always an unevaluated context.
7372   EnterExpressionEvaluationContext Unevaluated(
7373       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7374 
7375   // Add this candidate
7376   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7377   Candidate.FoundDecl = FoundDecl;
7378   Candidate.Function = Conversion;
7379   Candidate.IsSurrogate = false;
7380   Candidate.IgnoreObjectArgument = false;
7381   Candidate.FinalConversion.setAsIdentityConversion();
7382   Candidate.FinalConversion.setFromType(ConvType);
7383   Candidate.FinalConversion.setAllToTypes(ToType);
7384   Candidate.Viable = true;
7385   Candidate.ExplicitCallArguments = 1;
7386 
7387   // Explicit functions are not actually candidates at all if we're not
7388   // allowing them in this context, but keep them around so we can point
7389   // to them in diagnostics.
7390   if (!AllowExplicit && Conversion->isExplicit()) {
7391     Candidate.Viable = false;
7392     Candidate.FailureKind = ovl_fail_explicit;
7393     return;
7394   }
7395 
7396   // C++ [over.match.funcs]p4:
7397   //   For conversion functions, the function is considered to be a member of
7398   //   the class of the implicit implied object argument for the purpose of
7399   //   defining the type of the implicit object parameter.
7400   //
7401   // Determine the implicit conversion sequence for the implicit
7402   // object parameter.
7403   QualType ImplicitParamType = From->getType();
7404   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7405     ImplicitParamType = FromPtrType->getPointeeType();
7406   CXXRecordDecl *ConversionContext
7407     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7408 
7409   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7410       *this, CandidateSet.getLocation(), From->getType(),
7411       From->Classify(Context), Conversion, ConversionContext);
7412 
7413   if (Candidate.Conversions[0].isBad()) {
7414     Candidate.Viable = false;
7415     Candidate.FailureKind = ovl_fail_bad_conversion;
7416     return;
7417   }
7418 
7419   if (Conversion->getTrailingRequiresClause()) {
7420     ConstraintSatisfaction Satisfaction;
7421     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7422         !Satisfaction.IsSatisfied) {
7423       Candidate.Viable = false;
7424       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7425       return;
7426     }
7427   }
7428 
7429   // We won't go through a user-defined type conversion function to convert a
7430   // derived to base as such conversions are given Conversion Rank. They only
7431   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7432   QualType FromCanon
7433     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7434   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7435   if (FromCanon == ToCanon ||
7436       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7437     Candidate.Viable = false;
7438     Candidate.FailureKind = ovl_fail_trivial_conversion;
7439     return;
7440   }
7441 
7442   // To determine what the conversion from the result of calling the
7443   // conversion function to the type we're eventually trying to
7444   // convert to (ToType), we need to synthesize a call to the
7445   // conversion function and attempt copy initialization from it. This
7446   // makes sure that we get the right semantics with respect to
7447   // lvalues/rvalues and the type. Fortunately, we can allocate this
7448   // call on the stack and we don't need its arguments to be
7449   // well-formed.
7450   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7451                             VK_LValue, From->getBeginLoc());
7452   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7453                                 Context.getPointerType(Conversion->getType()),
7454                                 CK_FunctionToPointerDecay, &ConversionRef,
7455                                 VK_PRValue, FPOptionsOverride());
7456 
7457   QualType ConversionType = Conversion->getConversionType();
7458   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7459     Candidate.Viable = false;
7460     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7461     return;
7462   }
7463 
7464   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7465 
7466   // Note that it is safe to allocate CallExpr on the stack here because
7467   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7468   // allocator).
7469   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7470 
7471   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7472   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7473       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7474 
7475   ImplicitConversionSequence ICS =
7476       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7477                             /*SuppressUserConversions=*/true,
7478                             /*InOverloadResolution=*/false,
7479                             /*AllowObjCWritebackConversion=*/false);
7480 
7481   switch (ICS.getKind()) {
7482   case ImplicitConversionSequence::StandardConversion:
7483     Candidate.FinalConversion = ICS.Standard;
7484 
7485     // C++ [over.ics.user]p3:
7486     //   If the user-defined conversion is specified by a specialization of a
7487     //   conversion function template, the second standard conversion sequence
7488     //   shall have exact match rank.
7489     if (Conversion->getPrimaryTemplate() &&
7490         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7491       Candidate.Viable = false;
7492       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7493       return;
7494     }
7495 
7496     // C++0x [dcl.init.ref]p5:
7497     //    In the second case, if the reference is an rvalue reference and
7498     //    the second standard conversion sequence of the user-defined
7499     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7500     //    program is ill-formed.
7501     if (ToType->isRValueReferenceType() &&
7502         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7503       Candidate.Viable = false;
7504       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7505       return;
7506     }
7507     break;
7508 
7509   case ImplicitConversionSequence::BadConversion:
7510     Candidate.Viable = false;
7511     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7512     return;
7513 
7514   default:
7515     llvm_unreachable(
7516            "Can only end up with a standard conversion sequence or failure");
7517   }
7518 
7519   if (EnableIfAttr *FailedAttr =
7520           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7521     Candidate.Viable = false;
7522     Candidate.FailureKind = ovl_fail_enable_if;
7523     Candidate.DeductionFailure.Data = FailedAttr;
7524     return;
7525   }
7526 
7527   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7528       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7529     Candidate.Viable = false;
7530     Candidate.FailureKind = ovl_non_default_multiversion_function;
7531   }
7532 }
7533 
7534 /// Adds a conversion function template specialization
7535 /// candidate to the overload set, using template argument deduction
7536 /// to deduce the template arguments of the conversion function
7537 /// template from the type that we are converting to (C++
7538 /// [temp.deduct.conv]).
7539 void Sema::AddTemplateConversionCandidate(
7540     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7541     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7542     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7543     bool AllowExplicit, bool AllowResultConversion) {
7544   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7545          "Only conversion function templates permitted here");
7546 
7547   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7548     return;
7549 
7550   // If the function template has a non-dependent explicit specification,
7551   // exclude it now if appropriate; we are not permitted to perform deduction
7552   // and substitution in this case.
7553   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7554     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7555     Candidate.FoundDecl = FoundDecl;
7556     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7557     Candidate.Viable = false;
7558     Candidate.FailureKind = ovl_fail_explicit;
7559     return;
7560   }
7561 
7562   TemplateDeductionInfo Info(CandidateSet.getLocation());
7563   CXXConversionDecl *Specialization = nullptr;
7564   if (TemplateDeductionResult Result
7565         = DeduceTemplateArguments(FunctionTemplate, ToType,
7566                                   Specialization, Info)) {
7567     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7568     Candidate.FoundDecl = FoundDecl;
7569     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7570     Candidate.Viable = false;
7571     Candidate.FailureKind = ovl_fail_bad_deduction;
7572     Candidate.IsSurrogate = false;
7573     Candidate.IgnoreObjectArgument = false;
7574     Candidate.ExplicitCallArguments = 1;
7575     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7576                                                           Info);
7577     return;
7578   }
7579 
7580   // Add the conversion function template specialization produced by
7581   // template argument deduction as a candidate.
7582   assert(Specialization && "Missing function template specialization?");
7583   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7584                          CandidateSet, AllowObjCConversionOnExplicit,
7585                          AllowExplicit, AllowResultConversion);
7586 }
7587 
7588 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7589 /// converts the given @c Object to a function pointer via the
7590 /// conversion function @c Conversion, and then attempts to call it
7591 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7592 /// the type of function that we'll eventually be calling.
7593 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7594                                  DeclAccessPair FoundDecl,
7595                                  CXXRecordDecl *ActingContext,
7596                                  const FunctionProtoType *Proto,
7597                                  Expr *Object,
7598                                  ArrayRef<Expr *> Args,
7599                                  OverloadCandidateSet& CandidateSet) {
7600   if (!CandidateSet.isNewCandidate(Conversion))
7601     return;
7602 
7603   // Overload resolution is always an unevaluated context.
7604   EnterExpressionEvaluationContext Unevaluated(
7605       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7606 
7607   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7608   Candidate.FoundDecl = FoundDecl;
7609   Candidate.Function = nullptr;
7610   Candidate.Surrogate = Conversion;
7611   Candidate.Viable = true;
7612   Candidate.IsSurrogate = true;
7613   Candidate.IgnoreObjectArgument = false;
7614   Candidate.ExplicitCallArguments = Args.size();
7615 
7616   // Determine the implicit conversion sequence for the implicit
7617   // object parameter.
7618   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7619       *this, CandidateSet.getLocation(), Object->getType(),
7620       Object->Classify(Context), Conversion, ActingContext);
7621   if (ObjectInit.isBad()) {
7622     Candidate.Viable = false;
7623     Candidate.FailureKind = ovl_fail_bad_conversion;
7624     Candidate.Conversions[0] = ObjectInit;
7625     return;
7626   }
7627 
7628   // The first conversion is actually a user-defined conversion whose
7629   // first conversion is ObjectInit's standard conversion (which is
7630   // effectively a reference binding). Record it as such.
7631   Candidate.Conversions[0].setUserDefined();
7632   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7633   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7634   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7635   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7636   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7637   Candidate.Conversions[0].UserDefined.After
7638     = Candidate.Conversions[0].UserDefined.Before;
7639   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7640 
7641   // Find the
7642   unsigned NumParams = Proto->getNumParams();
7643 
7644   // (C++ 13.3.2p2): A candidate function having fewer than m
7645   // parameters is viable only if it has an ellipsis in its parameter
7646   // list (8.3.5).
7647   if (Args.size() > NumParams && !Proto->isVariadic()) {
7648     Candidate.Viable = false;
7649     Candidate.FailureKind = ovl_fail_too_many_arguments;
7650     return;
7651   }
7652 
7653   // Function types don't have any default arguments, so just check if
7654   // we have enough arguments.
7655   if (Args.size() < NumParams) {
7656     // Not enough arguments.
7657     Candidate.Viable = false;
7658     Candidate.FailureKind = ovl_fail_too_few_arguments;
7659     return;
7660   }
7661 
7662   // Determine the implicit conversion sequences for each of the
7663   // arguments.
7664   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7665     if (ArgIdx < NumParams) {
7666       // (C++ 13.3.2p3): for F to be a viable function, there shall
7667       // exist for each argument an implicit conversion sequence
7668       // (13.3.3.1) that converts that argument to the corresponding
7669       // parameter of F.
7670       QualType ParamType = Proto->getParamType(ArgIdx);
7671       Candidate.Conversions[ArgIdx + 1]
7672         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7673                                 /*SuppressUserConversions=*/false,
7674                                 /*InOverloadResolution=*/false,
7675                                 /*AllowObjCWritebackConversion=*/
7676                                   getLangOpts().ObjCAutoRefCount);
7677       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7678         Candidate.Viable = false;
7679         Candidate.FailureKind = ovl_fail_bad_conversion;
7680         return;
7681       }
7682     } else {
7683       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7684       // argument for which there is no corresponding parameter is
7685       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7686       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7687     }
7688   }
7689 
7690   if (EnableIfAttr *FailedAttr =
7691           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7692     Candidate.Viable = false;
7693     Candidate.FailureKind = ovl_fail_enable_if;
7694     Candidate.DeductionFailure.Data = FailedAttr;
7695     return;
7696   }
7697 }
7698 
7699 /// Add all of the non-member operator function declarations in the given
7700 /// function set to the overload candidate set.
7701 void Sema::AddNonMemberOperatorCandidates(
7702     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7703     OverloadCandidateSet &CandidateSet,
7704     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7705   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7706     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7707     ArrayRef<Expr *> FunctionArgs = Args;
7708 
7709     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7710     FunctionDecl *FD =
7711         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7712 
7713     // Don't consider rewritten functions if we're not rewriting.
7714     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7715       continue;
7716 
7717     assert(!isa<CXXMethodDecl>(FD) &&
7718            "unqualified operator lookup found a member function");
7719 
7720     if (FunTmpl) {
7721       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7722                                    FunctionArgs, CandidateSet);
7723       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7724         AddTemplateOverloadCandidate(
7725             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7726             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7727             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7728     } else {
7729       if (ExplicitTemplateArgs)
7730         continue;
7731       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7732       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7733         AddOverloadCandidate(FD, F.getPair(),
7734                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7735                              false, false, true, false, ADLCallKind::NotADL,
7736                              None, OverloadCandidateParamOrder::Reversed);
7737     }
7738   }
7739 }
7740 
7741 /// Add overload candidates for overloaded operators that are
7742 /// member functions.
7743 ///
7744 /// Add the overloaded operator candidates that are member functions
7745 /// for the operator Op that was used in an operator expression such
7746 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7747 /// CandidateSet will store the added overload candidates. (C++
7748 /// [over.match.oper]).
7749 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7750                                        SourceLocation OpLoc,
7751                                        ArrayRef<Expr *> Args,
7752                                        OverloadCandidateSet &CandidateSet,
7753                                        OverloadCandidateParamOrder PO) {
7754   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7755 
7756   // C++ [over.match.oper]p3:
7757   //   For a unary operator @ with an operand of a type whose
7758   //   cv-unqualified version is T1, and for a binary operator @ with
7759   //   a left operand of a type whose cv-unqualified version is T1 and
7760   //   a right operand of a type whose cv-unqualified version is T2,
7761   //   three sets of candidate functions, designated member
7762   //   candidates, non-member candidates and built-in candidates, are
7763   //   constructed as follows:
7764   QualType T1 = Args[0]->getType();
7765 
7766   //     -- If T1 is a complete class type or a class currently being
7767   //        defined, the set of member candidates is the result of the
7768   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7769   //        the set of member candidates is empty.
7770   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7771     // Complete the type if it can be completed.
7772     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7773       return;
7774     // If the type is neither complete nor being defined, bail out now.
7775     if (!T1Rec->getDecl()->getDefinition())
7776       return;
7777 
7778     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7779     LookupQualifiedName(Operators, T1Rec->getDecl());
7780     Operators.suppressDiagnostics();
7781 
7782     for (LookupResult::iterator Oper = Operators.begin(),
7783                              OperEnd = Operators.end();
7784          Oper != OperEnd;
7785          ++Oper)
7786       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7787                          Args[0]->Classify(Context), Args.slice(1),
7788                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7789   }
7790 }
7791 
7792 /// AddBuiltinCandidate - Add a candidate for a built-in
7793 /// operator. ResultTy and ParamTys are the result and parameter types
7794 /// of the built-in candidate, respectively. Args and NumArgs are the
7795 /// arguments being passed to the candidate. IsAssignmentOperator
7796 /// should be true when this built-in candidate is an assignment
7797 /// operator. NumContextualBoolArguments is the number of arguments
7798 /// (at the beginning of the argument list) that will be contextually
7799 /// converted to bool.
7800 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7801                                OverloadCandidateSet& CandidateSet,
7802                                bool IsAssignmentOperator,
7803                                unsigned NumContextualBoolArguments) {
7804   // Overload resolution is always an unevaluated context.
7805   EnterExpressionEvaluationContext Unevaluated(
7806       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7807 
7808   // Add this candidate
7809   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7810   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7811   Candidate.Function = nullptr;
7812   Candidate.IsSurrogate = false;
7813   Candidate.IgnoreObjectArgument = false;
7814   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7815 
7816   // Determine the implicit conversion sequences for each of the
7817   // arguments.
7818   Candidate.Viable = true;
7819   Candidate.ExplicitCallArguments = Args.size();
7820   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7821     // C++ [over.match.oper]p4:
7822     //   For the built-in assignment operators, conversions of the
7823     //   left operand are restricted as follows:
7824     //     -- no temporaries are introduced to hold the left operand, and
7825     //     -- no user-defined conversions are applied to the left
7826     //        operand to achieve a type match with the left-most
7827     //        parameter of a built-in candidate.
7828     //
7829     // We block these conversions by turning off user-defined
7830     // conversions, since that is the only way that initialization of
7831     // a reference to a non-class type can occur from something that
7832     // is not of the same type.
7833     if (ArgIdx < NumContextualBoolArguments) {
7834       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7835              "Contextual conversion to bool requires bool type");
7836       Candidate.Conversions[ArgIdx]
7837         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7838     } else {
7839       Candidate.Conversions[ArgIdx]
7840         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7841                                 ArgIdx == 0 && IsAssignmentOperator,
7842                                 /*InOverloadResolution=*/false,
7843                                 /*AllowObjCWritebackConversion=*/
7844                                   getLangOpts().ObjCAutoRefCount);
7845     }
7846     if (Candidate.Conversions[ArgIdx].isBad()) {
7847       Candidate.Viable = false;
7848       Candidate.FailureKind = ovl_fail_bad_conversion;
7849       break;
7850     }
7851   }
7852 }
7853 
7854 namespace {
7855 
7856 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7857 /// candidate operator functions for built-in operators (C++
7858 /// [over.built]). The types are separated into pointer types and
7859 /// enumeration types.
7860 class BuiltinCandidateTypeSet  {
7861   /// TypeSet - A set of types.
7862   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7863                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7864 
7865   /// PointerTypes - The set of pointer types that will be used in the
7866   /// built-in candidates.
7867   TypeSet PointerTypes;
7868 
7869   /// MemberPointerTypes - The set of member pointer types that will be
7870   /// used in the built-in candidates.
7871   TypeSet MemberPointerTypes;
7872 
7873   /// EnumerationTypes - The set of enumeration types that will be
7874   /// used in the built-in candidates.
7875   TypeSet EnumerationTypes;
7876 
7877   /// The set of vector types that will be used in the built-in
7878   /// candidates.
7879   TypeSet VectorTypes;
7880 
7881   /// The set of matrix types that will be used in the built-in
7882   /// candidates.
7883   TypeSet MatrixTypes;
7884 
7885   /// A flag indicating non-record types are viable candidates
7886   bool HasNonRecordTypes;
7887 
7888   /// A flag indicating whether either arithmetic or enumeration types
7889   /// were present in the candidate set.
7890   bool HasArithmeticOrEnumeralTypes;
7891 
7892   /// A flag indicating whether the nullptr type was present in the
7893   /// candidate set.
7894   bool HasNullPtrType;
7895 
7896   /// Sema - The semantic analysis instance where we are building the
7897   /// candidate type set.
7898   Sema &SemaRef;
7899 
7900   /// Context - The AST context in which we will build the type sets.
7901   ASTContext &Context;
7902 
7903   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7904                                                const Qualifiers &VisibleQuals);
7905   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7906 
7907 public:
7908   /// iterator - Iterates through the types that are part of the set.
7909   typedef TypeSet::iterator iterator;
7910 
7911   BuiltinCandidateTypeSet(Sema &SemaRef)
7912     : HasNonRecordTypes(false),
7913       HasArithmeticOrEnumeralTypes(false),
7914       HasNullPtrType(false),
7915       SemaRef(SemaRef),
7916       Context(SemaRef.Context) { }
7917 
7918   void AddTypesConvertedFrom(QualType Ty,
7919                              SourceLocation Loc,
7920                              bool AllowUserConversions,
7921                              bool AllowExplicitConversions,
7922                              const Qualifiers &VisibleTypeConversionsQuals);
7923 
7924   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7925   llvm::iterator_range<iterator> member_pointer_types() {
7926     return MemberPointerTypes;
7927   }
7928   llvm::iterator_range<iterator> enumeration_types() {
7929     return EnumerationTypes;
7930   }
7931   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7932   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7933 
7934   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7935   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7936   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7937   bool hasNullPtrType() const { return HasNullPtrType; }
7938 };
7939 
7940 } // end anonymous namespace
7941 
7942 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7943 /// the set of pointer types along with any more-qualified variants of
7944 /// that type. For example, if @p Ty is "int const *", this routine
7945 /// will add "int const *", "int const volatile *", "int const
7946 /// restrict *", and "int const volatile restrict *" to the set of
7947 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7948 /// false otherwise.
7949 ///
7950 /// FIXME: what to do about extended qualifiers?
7951 bool
7952 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7953                                              const Qualifiers &VisibleQuals) {
7954 
7955   // Insert this type.
7956   if (!PointerTypes.insert(Ty))
7957     return false;
7958 
7959   QualType PointeeTy;
7960   const PointerType *PointerTy = Ty->getAs<PointerType>();
7961   bool buildObjCPtr = false;
7962   if (!PointerTy) {
7963     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7964     PointeeTy = PTy->getPointeeType();
7965     buildObjCPtr = true;
7966   } else {
7967     PointeeTy = PointerTy->getPointeeType();
7968   }
7969 
7970   // Don't add qualified variants of arrays. For one, they're not allowed
7971   // (the qualifier would sink to the element type), and for another, the
7972   // only overload situation where it matters is subscript or pointer +- int,
7973   // and those shouldn't have qualifier variants anyway.
7974   if (PointeeTy->isArrayType())
7975     return true;
7976 
7977   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7978   bool hasVolatile = VisibleQuals.hasVolatile();
7979   bool hasRestrict = VisibleQuals.hasRestrict();
7980 
7981   // Iterate through all strict supersets of BaseCVR.
7982   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7983     if ((CVR | BaseCVR) != CVR) continue;
7984     // Skip over volatile if no volatile found anywhere in the types.
7985     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7986 
7987     // Skip over restrict if no restrict found anywhere in the types, or if
7988     // the type cannot be restrict-qualified.
7989     if ((CVR & Qualifiers::Restrict) &&
7990         (!hasRestrict ||
7991          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7992       continue;
7993 
7994     // Build qualified pointee type.
7995     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7996 
7997     // Build qualified pointer type.
7998     QualType QPointerTy;
7999     if (!buildObjCPtr)
8000       QPointerTy = Context.getPointerType(QPointeeTy);
8001     else
8002       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8003 
8004     // Insert qualified pointer type.
8005     PointerTypes.insert(QPointerTy);
8006   }
8007 
8008   return true;
8009 }
8010 
8011 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8012 /// to the set of pointer types along with any more-qualified variants of
8013 /// that type. For example, if @p Ty is "int const *", this routine
8014 /// will add "int const *", "int const volatile *", "int const
8015 /// restrict *", and "int const volatile restrict *" to the set of
8016 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8017 /// false otherwise.
8018 ///
8019 /// FIXME: what to do about extended qualifiers?
8020 bool
8021 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8022     QualType Ty) {
8023   // Insert this type.
8024   if (!MemberPointerTypes.insert(Ty))
8025     return false;
8026 
8027   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8028   assert(PointerTy && "type was not a member pointer type!");
8029 
8030   QualType PointeeTy = PointerTy->getPointeeType();
8031   // Don't add qualified variants of arrays. For one, they're not allowed
8032   // (the qualifier would sink to the element type), and for another, the
8033   // only overload situation where it matters is subscript or pointer +- int,
8034   // and those shouldn't have qualifier variants anyway.
8035   if (PointeeTy->isArrayType())
8036     return true;
8037   const Type *ClassTy = PointerTy->getClass();
8038 
8039   // Iterate through all strict supersets of the pointee type's CVR
8040   // qualifiers.
8041   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8042   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8043     if ((CVR | BaseCVR) != CVR) continue;
8044 
8045     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8046     MemberPointerTypes.insert(
8047       Context.getMemberPointerType(QPointeeTy, ClassTy));
8048   }
8049 
8050   return true;
8051 }
8052 
8053 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8054 /// Ty can be implicit converted to the given set of @p Types. We're
8055 /// primarily interested in pointer types and enumeration types. We also
8056 /// take member pointer types, for the conditional operator.
8057 /// AllowUserConversions is true if we should look at the conversion
8058 /// functions of a class type, and AllowExplicitConversions if we
8059 /// should also include the explicit conversion functions of a class
8060 /// type.
8061 void
8062 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8063                                                SourceLocation Loc,
8064                                                bool AllowUserConversions,
8065                                                bool AllowExplicitConversions,
8066                                                const Qualifiers &VisibleQuals) {
8067   // Only deal with canonical types.
8068   Ty = Context.getCanonicalType(Ty);
8069 
8070   // Look through reference types; they aren't part of the type of an
8071   // expression for the purposes of conversions.
8072   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8073     Ty = RefTy->getPointeeType();
8074 
8075   // If we're dealing with an array type, decay to the pointer.
8076   if (Ty->isArrayType())
8077     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8078 
8079   // Otherwise, we don't care about qualifiers on the type.
8080   Ty = Ty.getLocalUnqualifiedType();
8081 
8082   // Flag if we ever add a non-record type.
8083   const RecordType *TyRec = Ty->getAs<RecordType>();
8084   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8085 
8086   // Flag if we encounter an arithmetic type.
8087   HasArithmeticOrEnumeralTypes =
8088     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8089 
8090   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8091     PointerTypes.insert(Ty);
8092   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8093     // Insert our type, and its more-qualified variants, into the set
8094     // of types.
8095     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8096       return;
8097   } else if (Ty->isMemberPointerType()) {
8098     // Member pointers are far easier, since the pointee can't be converted.
8099     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8100       return;
8101   } else if (Ty->isEnumeralType()) {
8102     HasArithmeticOrEnumeralTypes = true;
8103     EnumerationTypes.insert(Ty);
8104   } else if (Ty->isVectorType()) {
8105     // We treat vector types as arithmetic types in many contexts as an
8106     // extension.
8107     HasArithmeticOrEnumeralTypes = true;
8108     VectorTypes.insert(Ty);
8109   } else if (Ty->isMatrixType()) {
8110     // Similar to vector types, we treat vector types as arithmetic types in
8111     // many contexts as an extension.
8112     HasArithmeticOrEnumeralTypes = true;
8113     MatrixTypes.insert(Ty);
8114   } else if (Ty->isNullPtrType()) {
8115     HasNullPtrType = true;
8116   } else if (AllowUserConversions && TyRec) {
8117     // No conversion functions in incomplete types.
8118     if (!SemaRef.isCompleteType(Loc, Ty))
8119       return;
8120 
8121     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8122     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8123       if (isa<UsingShadowDecl>(D))
8124         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8125 
8126       // Skip conversion function templates; they don't tell us anything
8127       // about which builtin types we can convert to.
8128       if (isa<FunctionTemplateDecl>(D))
8129         continue;
8130 
8131       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8132       if (AllowExplicitConversions || !Conv->isExplicit()) {
8133         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8134                               VisibleQuals);
8135       }
8136     }
8137   }
8138 }
8139 /// Helper function for adjusting address spaces for the pointer or reference
8140 /// operands of builtin operators depending on the argument.
8141 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8142                                                         Expr *Arg) {
8143   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8144 }
8145 
8146 /// Helper function for AddBuiltinOperatorCandidates() that adds
8147 /// the volatile- and non-volatile-qualified assignment operators for the
8148 /// given type to the candidate set.
8149 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8150                                                    QualType T,
8151                                                    ArrayRef<Expr *> Args,
8152                                     OverloadCandidateSet &CandidateSet) {
8153   QualType ParamTypes[2];
8154 
8155   // T& operator=(T&, T)
8156   ParamTypes[0] = S.Context.getLValueReferenceType(
8157       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8158   ParamTypes[1] = T;
8159   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8160                         /*IsAssignmentOperator=*/true);
8161 
8162   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8163     // volatile T& operator=(volatile T&, T)
8164     ParamTypes[0] = S.Context.getLValueReferenceType(
8165         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8166                                                 Args[0]));
8167     ParamTypes[1] = T;
8168     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8169                           /*IsAssignmentOperator=*/true);
8170   }
8171 }
8172 
8173 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8174 /// if any, found in visible type conversion functions found in ArgExpr's type.
8175 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8176     Qualifiers VRQuals;
8177     const RecordType *TyRec;
8178     if (const MemberPointerType *RHSMPType =
8179         ArgExpr->getType()->getAs<MemberPointerType>())
8180       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8181     else
8182       TyRec = ArgExpr->getType()->getAs<RecordType>();
8183     if (!TyRec) {
8184       // Just to be safe, assume the worst case.
8185       VRQuals.addVolatile();
8186       VRQuals.addRestrict();
8187       return VRQuals;
8188     }
8189 
8190     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8191     if (!ClassDecl->hasDefinition())
8192       return VRQuals;
8193 
8194     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8195       if (isa<UsingShadowDecl>(D))
8196         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8197       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8198         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8199         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8200           CanTy = ResTypeRef->getPointeeType();
8201         // Need to go down the pointer/mempointer chain and add qualifiers
8202         // as see them.
8203         bool done = false;
8204         while (!done) {
8205           if (CanTy.isRestrictQualified())
8206             VRQuals.addRestrict();
8207           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8208             CanTy = ResTypePtr->getPointeeType();
8209           else if (const MemberPointerType *ResTypeMPtr =
8210                 CanTy->getAs<MemberPointerType>())
8211             CanTy = ResTypeMPtr->getPointeeType();
8212           else
8213             done = true;
8214           if (CanTy.isVolatileQualified())
8215             VRQuals.addVolatile();
8216           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8217             return VRQuals;
8218         }
8219       }
8220     }
8221     return VRQuals;
8222 }
8223 
8224 // Note: We're currently only handling qualifiers that are meaningful for the
8225 // LHS of compound assignment overloading.
8226 static void forAllQualifierCombinationsImpl(
8227     QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8228     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8229   // _Atomic
8230   if (Available.hasAtomic()) {
8231     Available.removeAtomic();
8232     forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8233     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8234     return;
8235   }
8236 
8237   // volatile
8238   if (Available.hasVolatile()) {
8239     Available.removeVolatile();
8240     assert(!Applied.hasVolatile());
8241     forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8242                                     Callback);
8243     forAllQualifierCombinationsImpl(Available, Applied, Callback);
8244     return;
8245   }
8246 
8247   Callback(Applied);
8248 }
8249 
8250 static void forAllQualifierCombinations(
8251     QualifiersAndAtomic Quals,
8252     llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8253   return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8254                                          Callback);
8255 }
8256 
8257 static QualType makeQualifiedLValueReferenceType(QualType Base,
8258                                                  QualifiersAndAtomic Quals,
8259                                                  Sema &S) {
8260   if (Quals.hasAtomic())
8261     Base = S.Context.getAtomicType(Base);
8262   if (Quals.hasVolatile())
8263     Base = S.Context.getVolatileType(Base);
8264   return S.Context.getLValueReferenceType(Base);
8265 }
8266 
8267 namespace {
8268 
8269 /// Helper class to manage the addition of builtin operator overload
8270 /// candidates. It provides shared state and utility methods used throughout
8271 /// the process, as well as a helper method to add each group of builtin
8272 /// operator overloads from the standard to a candidate set.
8273 class BuiltinOperatorOverloadBuilder {
8274   // Common instance state available to all overload candidate addition methods.
8275   Sema &S;
8276   ArrayRef<Expr *> Args;
8277   QualifiersAndAtomic VisibleTypeConversionsQuals;
8278   bool HasArithmeticOrEnumeralCandidateType;
8279   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8280   OverloadCandidateSet &CandidateSet;
8281 
8282   static constexpr int ArithmeticTypesCap = 24;
8283   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8284 
8285   // Define some indices used to iterate over the arithmetic types in
8286   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8287   // types are that preserved by promotion (C++ [over.built]p2).
8288   unsigned FirstIntegralType,
8289            LastIntegralType;
8290   unsigned FirstPromotedIntegralType,
8291            LastPromotedIntegralType;
8292   unsigned FirstPromotedArithmeticType,
8293            LastPromotedArithmeticType;
8294   unsigned NumArithmeticTypes;
8295 
8296   void InitArithmeticTypes() {
8297     // Start of promoted types.
8298     FirstPromotedArithmeticType = 0;
8299     ArithmeticTypes.push_back(S.Context.FloatTy);
8300     ArithmeticTypes.push_back(S.Context.DoubleTy);
8301     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8302     if (S.Context.getTargetInfo().hasFloat128Type())
8303       ArithmeticTypes.push_back(S.Context.Float128Ty);
8304     if (S.Context.getTargetInfo().hasIbm128Type())
8305       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8306 
8307     // Start of integral types.
8308     FirstIntegralType = ArithmeticTypes.size();
8309     FirstPromotedIntegralType = ArithmeticTypes.size();
8310     ArithmeticTypes.push_back(S.Context.IntTy);
8311     ArithmeticTypes.push_back(S.Context.LongTy);
8312     ArithmeticTypes.push_back(S.Context.LongLongTy);
8313     if (S.Context.getTargetInfo().hasInt128Type() ||
8314         (S.Context.getAuxTargetInfo() &&
8315          S.Context.getAuxTargetInfo()->hasInt128Type()))
8316       ArithmeticTypes.push_back(S.Context.Int128Ty);
8317     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8318     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8319     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8320     if (S.Context.getTargetInfo().hasInt128Type() ||
8321         (S.Context.getAuxTargetInfo() &&
8322          S.Context.getAuxTargetInfo()->hasInt128Type()))
8323       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8324     LastPromotedIntegralType = ArithmeticTypes.size();
8325     LastPromotedArithmeticType = ArithmeticTypes.size();
8326     // End of promoted types.
8327 
8328     ArithmeticTypes.push_back(S.Context.BoolTy);
8329     ArithmeticTypes.push_back(S.Context.CharTy);
8330     ArithmeticTypes.push_back(S.Context.WCharTy);
8331     if (S.Context.getLangOpts().Char8)
8332       ArithmeticTypes.push_back(S.Context.Char8Ty);
8333     ArithmeticTypes.push_back(S.Context.Char16Ty);
8334     ArithmeticTypes.push_back(S.Context.Char32Ty);
8335     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8336     ArithmeticTypes.push_back(S.Context.ShortTy);
8337     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8338     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8339     LastIntegralType = ArithmeticTypes.size();
8340     NumArithmeticTypes = ArithmeticTypes.size();
8341     // End of integral types.
8342     // FIXME: What about complex? What about half?
8343 
8344     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8345            "Enough inline storage for all arithmetic types.");
8346   }
8347 
8348   /// Helper method to factor out the common pattern of adding overloads
8349   /// for '++' and '--' builtin operators.
8350   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8351                                            bool HasVolatile,
8352                                            bool HasRestrict) {
8353     QualType ParamTypes[2] = {
8354       S.Context.getLValueReferenceType(CandidateTy),
8355       S.Context.IntTy
8356     };
8357 
8358     // Non-volatile version.
8359     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8360 
8361     // Use a heuristic to reduce number of builtin candidates in the set:
8362     // add volatile version only if there are conversions to a volatile type.
8363     if (HasVolatile) {
8364       ParamTypes[0] =
8365         S.Context.getLValueReferenceType(
8366           S.Context.getVolatileType(CandidateTy));
8367       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8368     }
8369 
8370     // Add restrict version only if there are conversions to a restrict type
8371     // and our candidate type is a non-restrict-qualified pointer.
8372     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8373         !CandidateTy.isRestrictQualified()) {
8374       ParamTypes[0]
8375         = S.Context.getLValueReferenceType(
8376             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8377       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8378 
8379       if (HasVolatile) {
8380         ParamTypes[0]
8381           = S.Context.getLValueReferenceType(
8382               S.Context.getCVRQualifiedType(CandidateTy,
8383                                             (Qualifiers::Volatile |
8384                                              Qualifiers::Restrict)));
8385         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8386       }
8387     }
8388 
8389   }
8390 
8391   /// Helper to add an overload candidate for a binary builtin with types \p L
8392   /// and \p R.
8393   void AddCandidate(QualType L, QualType R) {
8394     QualType LandR[2] = {L, R};
8395     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8396   }
8397 
8398 public:
8399   BuiltinOperatorOverloadBuilder(
8400     Sema &S, ArrayRef<Expr *> Args,
8401     QualifiersAndAtomic VisibleTypeConversionsQuals,
8402     bool HasArithmeticOrEnumeralCandidateType,
8403     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8404     OverloadCandidateSet &CandidateSet)
8405     : S(S), Args(Args),
8406       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8407       HasArithmeticOrEnumeralCandidateType(
8408         HasArithmeticOrEnumeralCandidateType),
8409       CandidateTypes(CandidateTypes),
8410       CandidateSet(CandidateSet) {
8411 
8412     InitArithmeticTypes();
8413   }
8414 
8415   // Increment is deprecated for bool since C++17.
8416   //
8417   // C++ [over.built]p3:
8418   //
8419   //   For every pair (T, VQ), where T is an arithmetic type other
8420   //   than bool, and VQ is either volatile or empty, there exist
8421   //   candidate operator functions of the form
8422   //
8423   //       VQ T&      operator++(VQ T&);
8424   //       T          operator++(VQ T&, int);
8425   //
8426   // C++ [over.built]p4:
8427   //
8428   //   For every pair (T, VQ), where T is an arithmetic type other
8429   //   than bool, and VQ is either volatile or empty, there exist
8430   //   candidate operator functions of the form
8431   //
8432   //       VQ T&      operator--(VQ T&);
8433   //       T          operator--(VQ T&, int);
8434   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8435     if (!HasArithmeticOrEnumeralCandidateType)
8436       return;
8437 
8438     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8439       const auto TypeOfT = ArithmeticTypes[Arith];
8440       if (TypeOfT == S.Context.BoolTy) {
8441         if (Op == OO_MinusMinus)
8442           continue;
8443         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8444           continue;
8445       }
8446       addPlusPlusMinusMinusStyleOverloads(
8447         TypeOfT,
8448         VisibleTypeConversionsQuals.hasVolatile(),
8449         VisibleTypeConversionsQuals.hasRestrict());
8450     }
8451   }
8452 
8453   // C++ [over.built]p5:
8454   //
8455   //   For every pair (T, VQ), where T is a cv-qualified or
8456   //   cv-unqualified object type, and VQ is either volatile or
8457   //   empty, there exist candidate operator functions of the form
8458   //
8459   //       T*VQ&      operator++(T*VQ&);
8460   //       T*VQ&      operator--(T*VQ&);
8461   //       T*         operator++(T*VQ&, int);
8462   //       T*         operator--(T*VQ&, int);
8463   void addPlusPlusMinusMinusPointerOverloads() {
8464     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8465       // Skip pointer types that aren't pointers to object types.
8466       if (!PtrTy->getPointeeType()->isObjectType())
8467         continue;
8468 
8469       addPlusPlusMinusMinusStyleOverloads(
8470           PtrTy,
8471           (!PtrTy.isVolatileQualified() &&
8472            VisibleTypeConversionsQuals.hasVolatile()),
8473           (!PtrTy.isRestrictQualified() &&
8474            VisibleTypeConversionsQuals.hasRestrict()));
8475     }
8476   }
8477 
8478   // C++ [over.built]p6:
8479   //   For every cv-qualified or cv-unqualified object type T, there
8480   //   exist candidate operator functions of the form
8481   //
8482   //       T&         operator*(T*);
8483   //
8484   // C++ [over.built]p7:
8485   //   For every function type T that does not have cv-qualifiers or a
8486   //   ref-qualifier, there exist candidate operator functions of the form
8487   //       T&         operator*(T*);
8488   void addUnaryStarPointerOverloads() {
8489     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8490       QualType PointeeTy = ParamTy->getPointeeType();
8491       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8492         continue;
8493 
8494       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8495         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8496           continue;
8497 
8498       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8499     }
8500   }
8501 
8502   // C++ [over.built]p9:
8503   //  For every promoted arithmetic type T, there exist candidate
8504   //  operator functions of the form
8505   //
8506   //       T         operator+(T);
8507   //       T         operator-(T);
8508   void addUnaryPlusOrMinusArithmeticOverloads() {
8509     if (!HasArithmeticOrEnumeralCandidateType)
8510       return;
8511 
8512     for (unsigned Arith = FirstPromotedArithmeticType;
8513          Arith < LastPromotedArithmeticType; ++Arith) {
8514       QualType ArithTy = ArithmeticTypes[Arith];
8515       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8516     }
8517 
8518     // Extension: We also add these operators for vector types.
8519     for (QualType VecTy : CandidateTypes[0].vector_types())
8520       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8521   }
8522 
8523   // C++ [over.built]p8:
8524   //   For every type T, there exist candidate operator functions of
8525   //   the form
8526   //
8527   //       T*         operator+(T*);
8528   void addUnaryPlusPointerOverloads() {
8529     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8530       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8531   }
8532 
8533   // C++ [over.built]p10:
8534   //   For every promoted integral type T, there exist candidate
8535   //   operator functions of the form
8536   //
8537   //        T         operator~(T);
8538   void addUnaryTildePromotedIntegralOverloads() {
8539     if (!HasArithmeticOrEnumeralCandidateType)
8540       return;
8541 
8542     for (unsigned Int = FirstPromotedIntegralType;
8543          Int < LastPromotedIntegralType; ++Int) {
8544       QualType IntTy = ArithmeticTypes[Int];
8545       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8546     }
8547 
8548     // Extension: We also add this operator for vector types.
8549     for (QualType VecTy : CandidateTypes[0].vector_types())
8550       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8551   }
8552 
8553   // C++ [over.match.oper]p16:
8554   //   For every pointer to member type T or type std::nullptr_t, there
8555   //   exist candidate operator functions of the form
8556   //
8557   //        bool operator==(T,T);
8558   //        bool operator!=(T,T);
8559   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8560     /// Set of (canonical) types that we've already handled.
8561     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8562 
8563     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8564       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8565         // Don't add the same builtin candidate twice.
8566         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8567           continue;
8568 
8569         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8570         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8571       }
8572 
8573       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8574         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8575         if (AddedTypes.insert(NullPtrTy).second) {
8576           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8577           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8578         }
8579       }
8580     }
8581   }
8582 
8583   // C++ [over.built]p15:
8584   //
8585   //   For every T, where T is an enumeration type or a pointer type,
8586   //   there exist candidate operator functions of the form
8587   //
8588   //        bool       operator<(T, T);
8589   //        bool       operator>(T, T);
8590   //        bool       operator<=(T, T);
8591   //        bool       operator>=(T, T);
8592   //        bool       operator==(T, T);
8593   //        bool       operator!=(T, T);
8594   //           R       operator<=>(T, T)
8595   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8596     // C++ [over.match.oper]p3:
8597     //   [...]the built-in candidates include all of the candidate operator
8598     //   functions defined in 13.6 that, compared to the given operator, [...]
8599     //   do not have the same parameter-type-list as any non-template non-member
8600     //   candidate.
8601     //
8602     // Note that in practice, this only affects enumeration types because there
8603     // aren't any built-in candidates of record type, and a user-defined operator
8604     // must have an operand of record or enumeration type. Also, the only other
8605     // overloaded operator with enumeration arguments, operator=,
8606     // cannot be overloaded for enumeration types, so this is the only place
8607     // where we must suppress candidates like this.
8608     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8609       UserDefinedBinaryOperators;
8610 
8611     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8612       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8613         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8614                                          CEnd = CandidateSet.end();
8615              C != CEnd; ++C) {
8616           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8617             continue;
8618 
8619           if (C->Function->isFunctionTemplateSpecialization())
8620             continue;
8621 
8622           // We interpret "same parameter-type-list" as applying to the
8623           // "synthesized candidate, with the order of the two parameters
8624           // reversed", not to the original function.
8625           bool Reversed = C->isReversed();
8626           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8627                                         ->getType()
8628                                         .getUnqualifiedType();
8629           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8630                                          ->getType()
8631                                          .getUnqualifiedType();
8632 
8633           // Skip if either parameter isn't of enumeral type.
8634           if (!FirstParamType->isEnumeralType() ||
8635               !SecondParamType->isEnumeralType())
8636             continue;
8637 
8638           // Add this operator to the set of known user-defined operators.
8639           UserDefinedBinaryOperators.insert(
8640             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8641                            S.Context.getCanonicalType(SecondParamType)));
8642         }
8643       }
8644     }
8645 
8646     /// Set of (canonical) types that we've already handled.
8647     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8648 
8649     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8650       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8651         // Don't add the same builtin candidate twice.
8652         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8653           continue;
8654         if (IsSpaceship && PtrTy->isFunctionPointerType())
8655           continue;
8656 
8657         QualType ParamTypes[2] = {PtrTy, PtrTy};
8658         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8659       }
8660       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8661         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8662 
8663         // Don't add the same builtin candidate twice, or if a user defined
8664         // candidate exists.
8665         if (!AddedTypes.insert(CanonType).second ||
8666             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8667                                                             CanonType)))
8668           continue;
8669         QualType ParamTypes[2] = {EnumTy, EnumTy};
8670         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8671       }
8672     }
8673   }
8674 
8675   // C++ [over.built]p13:
8676   //
8677   //   For every cv-qualified or cv-unqualified object type T
8678   //   there exist candidate operator functions of the form
8679   //
8680   //      T*         operator+(T*, ptrdiff_t);
8681   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8682   //      T*         operator-(T*, ptrdiff_t);
8683   //      T*         operator+(ptrdiff_t, T*);
8684   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8685   //
8686   // C++ [over.built]p14:
8687   //
8688   //   For every T, where T is a pointer to object type, there
8689   //   exist candidate operator functions of the form
8690   //
8691   //      ptrdiff_t  operator-(T, T);
8692   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8693     /// Set of (canonical) types that we've already handled.
8694     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8695 
8696     for (int Arg = 0; Arg < 2; ++Arg) {
8697       QualType AsymmetricParamTypes[2] = {
8698         S.Context.getPointerDiffType(),
8699         S.Context.getPointerDiffType(),
8700       };
8701       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8702         QualType PointeeTy = PtrTy->getPointeeType();
8703         if (!PointeeTy->isObjectType())
8704           continue;
8705 
8706         AsymmetricParamTypes[Arg] = PtrTy;
8707         if (Arg == 0 || Op == OO_Plus) {
8708           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8709           // T* operator+(ptrdiff_t, T*);
8710           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8711         }
8712         if (Op == OO_Minus) {
8713           // ptrdiff_t operator-(T, T);
8714           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8715             continue;
8716 
8717           QualType ParamTypes[2] = {PtrTy, PtrTy};
8718           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8719         }
8720       }
8721     }
8722   }
8723 
8724   // C++ [over.built]p12:
8725   //
8726   //   For every pair of promoted arithmetic types L and R, there
8727   //   exist candidate operator functions of the form
8728   //
8729   //        LR         operator*(L, R);
8730   //        LR         operator/(L, R);
8731   //        LR         operator+(L, R);
8732   //        LR         operator-(L, R);
8733   //        bool       operator<(L, R);
8734   //        bool       operator>(L, R);
8735   //        bool       operator<=(L, R);
8736   //        bool       operator>=(L, R);
8737   //        bool       operator==(L, R);
8738   //        bool       operator!=(L, R);
8739   //
8740   //   where LR is the result of the usual arithmetic conversions
8741   //   between types L and R.
8742   //
8743   // C++ [over.built]p24:
8744   //
8745   //   For every pair of promoted arithmetic types L and R, there exist
8746   //   candidate operator functions of the form
8747   //
8748   //        LR       operator?(bool, L, R);
8749   //
8750   //   where LR is the result of the usual arithmetic conversions
8751   //   between types L and R.
8752   // Our candidates ignore the first parameter.
8753   void addGenericBinaryArithmeticOverloads() {
8754     if (!HasArithmeticOrEnumeralCandidateType)
8755       return;
8756 
8757     for (unsigned Left = FirstPromotedArithmeticType;
8758          Left < LastPromotedArithmeticType; ++Left) {
8759       for (unsigned Right = FirstPromotedArithmeticType;
8760            Right < LastPromotedArithmeticType; ++Right) {
8761         QualType LandR[2] = { ArithmeticTypes[Left],
8762                               ArithmeticTypes[Right] };
8763         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8764       }
8765     }
8766 
8767     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8768     // conditional operator for vector types.
8769     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8770       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8771         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8772         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8773       }
8774   }
8775 
8776   /// Add binary operator overloads for each candidate matrix type M1, M2:
8777   ///  * (M1, M1) -> M1
8778   ///  * (M1, M1.getElementType()) -> M1
8779   ///  * (M2.getElementType(), M2) -> M2
8780   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8781   void addMatrixBinaryArithmeticOverloads() {
8782     if (!HasArithmeticOrEnumeralCandidateType)
8783       return;
8784 
8785     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8786       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8787       AddCandidate(M1, M1);
8788     }
8789 
8790     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8791       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8792       if (!CandidateTypes[0].containsMatrixType(M2))
8793         AddCandidate(M2, M2);
8794     }
8795   }
8796 
8797   // C++2a [over.built]p14:
8798   //
8799   //   For every integral type T there exists a candidate operator function
8800   //   of the form
8801   //
8802   //        std::strong_ordering operator<=>(T, T)
8803   //
8804   // C++2a [over.built]p15:
8805   //
8806   //   For every pair of floating-point types L and R, there exists a candidate
8807   //   operator function of the form
8808   //
8809   //       std::partial_ordering operator<=>(L, R);
8810   //
8811   // FIXME: The current specification for integral types doesn't play nice with
8812   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8813   // comparisons. Under the current spec this can lead to ambiguity during
8814   // overload resolution. For example:
8815   //
8816   //   enum A : int {a};
8817   //   auto x = (a <=> (long)42);
8818   //
8819   //   error: call is ambiguous for arguments 'A' and 'long'.
8820   //   note: candidate operator<=>(int, int)
8821   //   note: candidate operator<=>(long, long)
8822   //
8823   // To avoid this error, this function deviates from the specification and adds
8824   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8825   // arithmetic types (the same as the generic relational overloads).
8826   //
8827   // For now this function acts as a placeholder.
8828   void addThreeWayArithmeticOverloads() {
8829     addGenericBinaryArithmeticOverloads();
8830   }
8831 
8832   // C++ [over.built]p17:
8833   //
8834   //   For every pair of promoted integral types L and R, there
8835   //   exist candidate operator functions of the form
8836   //
8837   //      LR         operator%(L, R);
8838   //      LR         operator&(L, R);
8839   //      LR         operator^(L, R);
8840   //      LR         operator|(L, R);
8841   //      L          operator<<(L, R);
8842   //      L          operator>>(L, R);
8843   //
8844   //   where LR is the result of the usual arithmetic conversions
8845   //   between types L and R.
8846   void addBinaryBitwiseArithmeticOverloads() {
8847     if (!HasArithmeticOrEnumeralCandidateType)
8848       return;
8849 
8850     for (unsigned Left = FirstPromotedIntegralType;
8851          Left < LastPromotedIntegralType; ++Left) {
8852       for (unsigned Right = FirstPromotedIntegralType;
8853            Right < LastPromotedIntegralType; ++Right) {
8854         QualType LandR[2] = { ArithmeticTypes[Left],
8855                               ArithmeticTypes[Right] };
8856         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8857       }
8858     }
8859   }
8860 
8861   // C++ [over.built]p20:
8862   //
8863   //   For every pair (T, VQ), where T is an enumeration or
8864   //   pointer to member type and VQ is either volatile or
8865   //   empty, there exist candidate operator functions of the form
8866   //
8867   //        VQ T&      operator=(VQ T&, T);
8868   void addAssignmentMemberPointerOrEnumeralOverloads() {
8869     /// Set of (canonical) types that we've already handled.
8870     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8871 
8872     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8873       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8874         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8875           continue;
8876 
8877         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8878       }
8879 
8880       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8881         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8882           continue;
8883 
8884         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8885       }
8886     }
8887   }
8888 
8889   // C++ [over.built]p19:
8890   //
8891   //   For every pair (T, VQ), where T is any type and VQ is either
8892   //   volatile or empty, there exist candidate operator functions
8893   //   of the form
8894   //
8895   //        T*VQ&      operator=(T*VQ&, T*);
8896   //
8897   // C++ [over.built]p21:
8898   //
8899   //   For every pair (T, VQ), where T is a cv-qualified or
8900   //   cv-unqualified object type and VQ is either volatile or
8901   //   empty, there exist candidate operator functions of the form
8902   //
8903   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8904   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8905   void addAssignmentPointerOverloads(bool isEqualOp) {
8906     /// Set of (canonical) types that we've already handled.
8907     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8908 
8909     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8910       // If this is operator=, keep track of the builtin candidates we added.
8911       if (isEqualOp)
8912         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8913       else if (!PtrTy->getPointeeType()->isObjectType())
8914         continue;
8915 
8916       // non-volatile version
8917       QualType ParamTypes[2] = {
8918           S.Context.getLValueReferenceType(PtrTy),
8919           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8920       };
8921       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8922                             /*IsAssignmentOperator=*/ isEqualOp);
8923 
8924       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8925                           VisibleTypeConversionsQuals.hasVolatile();
8926       if (NeedVolatile) {
8927         // volatile version
8928         ParamTypes[0] =
8929             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8930         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8931                               /*IsAssignmentOperator=*/isEqualOp);
8932       }
8933 
8934       if (!PtrTy.isRestrictQualified() &&
8935           VisibleTypeConversionsQuals.hasRestrict()) {
8936         // restrict version
8937         ParamTypes[0] =
8938             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8939         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8940                               /*IsAssignmentOperator=*/isEqualOp);
8941 
8942         if (NeedVolatile) {
8943           // volatile restrict version
8944           ParamTypes[0] =
8945               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8946                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8947           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8948                                 /*IsAssignmentOperator=*/isEqualOp);
8949         }
8950       }
8951     }
8952 
8953     if (isEqualOp) {
8954       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8955         // Make sure we don't add the same candidate twice.
8956         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8957           continue;
8958 
8959         QualType ParamTypes[2] = {
8960             S.Context.getLValueReferenceType(PtrTy),
8961             PtrTy,
8962         };
8963 
8964         // non-volatile version
8965         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8966                               /*IsAssignmentOperator=*/true);
8967 
8968         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8969                             VisibleTypeConversionsQuals.hasVolatile();
8970         if (NeedVolatile) {
8971           // volatile version
8972           ParamTypes[0] = S.Context.getLValueReferenceType(
8973               S.Context.getVolatileType(PtrTy));
8974           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8975                                 /*IsAssignmentOperator=*/true);
8976         }
8977 
8978         if (!PtrTy.isRestrictQualified() &&
8979             VisibleTypeConversionsQuals.hasRestrict()) {
8980           // restrict version
8981           ParamTypes[0] = S.Context.getLValueReferenceType(
8982               S.Context.getRestrictType(PtrTy));
8983           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8984                                 /*IsAssignmentOperator=*/true);
8985 
8986           if (NeedVolatile) {
8987             // volatile restrict version
8988             ParamTypes[0] =
8989                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8990                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8991             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8992                                   /*IsAssignmentOperator=*/true);
8993           }
8994         }
8995       }
8996     }
8997   }
8998 
8999   // C++ [over.built]p18:
9000   //
9001   //   For every triple (L, VQ, R), where L is an arithmetic type,
9002   //   VQ is either volatile or empty, and R is a promoted
9003   //   arithmetic type, there exist candidate operator functions of
9004   //   the form
9005   //
9006   //        VQ L&      operator=(VQ L&, R);
9007   //        VQ L&      operator*=(VQ L&, R);
9008   //        VQ L&      operator/=(VQ L&, R);
9009   //        VQ L&      operator+=(VQ L&, R);
9010   //        VQ L&      operator-=(VQ L&, R);
9011   void addAssignmentArithmeticOverloads(bool isEqualOp) {
9012     if (!HasArithmeticOrEnumeralCandidateType)
9013       return;
9014 
9015     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9016       for (unsigned Right = FirstPromotedArithmeticType;
9017            Right < LastPromotedArithmeticType; ++Right) {
9018         QualType ParamTypes[2];
9019         ParamTypes[1] = ArithmeticTypes[Right];
9020         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9021             S, ArithmeticTypes[Left], Args[0]);
9022 
9023         forAllQualifierCombinations(
9024             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9025               ParamTypes[0] =
9026                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9027               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9028                                     /*IsAssignmentOperator=*/isEqualOp);
9029             });
9030       }
9031     }
9032 
9033     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9034     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9035       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9036         QualType ParamTypes[2];
9037         ParamTypes[1] = Vec2Ty;
9038         // Add this built-in operator as a candidate (VQ is empty).
9039         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9040         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9041                               /*IsAssignmentOperator=*/isEqualOp);
9042 
9043         // Add this built-in operator as a candidate (VQ is 'volatile').
9044         if (VisibleTypeConversionsQuals.hasVolatile()) {
9045           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9046           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9047           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9048                                 /*IsAssignmentOperator=*/isEqualOp);
9049         }
9050       }
9051   }
9052 
9053   // C++ [over.built]p22:
9054   //
9055   //   For every triple (L, VQ, R), where L is an integral type, VQ
9056   //   is either volatile or empty, and R is a promoted integral
9057   //   type, there exist candidate operator functions of the form
9058   //
9059   //        VQ L&       operator%=(VQ L&, R);
9060   //        VQ L&       operator<<=(VQ L&, R);
9061   //        VQ L&       operator>>=(VQ L&, R);
9062   //        VQ L&       operator&=(VQ L&, R);
9063   //        VQ L&       operator^=(VQ L&, R);
9064   //        VQ L&       operator|=(VQ L&, R);
9065   void addAssignmentIntegralOverloads() {
9066     if (!HasArithmeticOrEnumeralCandidateType)
9067       return;
9068 
9069     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9070       for (unsigned Right = FirstPromotedIntegralType;
9071            Right < LastPromotedIntegralType; ++Right) {
9072         QualType ParamTypes[2];
9073         ParamTypes[1] = ArithmeticTypes[Right];
9074         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9075             S, ArithmeticTypes[Left], Args[0]);
9076 
9077         forAllQualifierCombinations(
9078             VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9079               ParamTypes[0] =
9080                   makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9081               S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9082             });
9083       }
9084     }
9085   }
9086 
9087   // C++ [over.operator]p23:
9088   //
9089   //   There also exist candidate operator functions of the form
9090   //
9091   //        bool        operator!(bool);
9092   //        bool        operator&&(bool, bool);
9093   //        bool        operator||(bool, bool);
9094   void addExclaimOverload() {
9095     QualType ParamTy = S.Context.BoolTy;
9096     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9097                           /*IsAssignmentOperator=*/false,
9098                           /*NumContextualBoolArguments=*/1);
9099   }
9100   void addAmpAmpOrPipePipeOverload() {
9101     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9102     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9103                           /*IsAssignmentOperator=*/false,
9104                           /*NumContextualBoolArguments=*/2);
9105   }
9106 
9107   // C++ [over.built]p13:
9108   //
9109   //   For every cv-qualified or cv-unqualified object type T there
9110   //   exist candidate operator functions of the form
9111   //
9112   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9113   //        T&         operator[](T*, ptrdiff_t);
9114   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9115   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9116   //        T&         operator[](ptrdiff_t, T*);
9117   void addSubscriptOverloads() {
9118     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9119       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9120       QualType PointeeType = PtrTy->getPointeeType();
9121       if (!PointeeType->isObjectType())
9122         continue;
9123 
9124       // T& operator[](T*, ptrdiff_t)
9125       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9126     }
9127 
9128     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9129       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9130       QualType PointeeType = PtrTy->getPointeeType();
9131       if (!PointeeType->isObjectType())
9132         continue;
9133 
9134       // T& operator[](ptrdiff_t, T*)
9135       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9136     }
9137   }
9138 
9139   // C++ [over.built]p11:
9140   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9141   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9142   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9143   //    there exist candidate operator functions of the form
9144   //
9145   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9146   //
9147   //    where CV12 is the union of CV1 and CV2.
9148   void addArrowStarOverloads() {
9149     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9150       QualType C1Ty = PtrTy;
9151       QualType C1;
9152       QualifierCollector Q1;
9153       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9154       if (!isa<RecordType>(C1))
9155         continue;
9156       // heuristic to reduce number of builtin candidates in the set.
9157       // Add volatile/restrict version only if there are conversions to a
9158       // volatile/restrict type.
9159       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9160         continue;
9161       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9162         continue;
9163       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9164         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9165         QualType C2 = QualType(mptr->getClass(), 0);
9166         C2 = C2.getUnqualifiedType();
9167         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9168           break;
9169         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9170         // build CV12 T&
9171         QualType T = mptr->getPointeeType();
9172         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9173             T.isVolatileQualified())
9174           continue;
9175         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9176             T.isRestrictQualified())
9177           continue;
9178         T = Q1.apply(S.Context, T);
9179         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9180       }
9181     }
9182   }
9183 
9184   // Note that we don't consider the first argument, since it has been
9185   // contextually converted to bool long ago. The candidates below are
9186   // therefore added as binary.
9187   //
9188   // C++ [over.built]p25:
9189   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9190   //   enumeration type, there exist candidate operator functions of the form
9191   //
9192   //        T        operator?(bool, T, T);
9193   //
9194   void addConditionalOperatorOverloads() {
9195     /// Set of (canonical) types that we've already handled.
9196     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9197 
9198     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9199       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9200         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9201           continue;
9202 
9203         QualType ParamTypes[2] = {PtrTy, PtrTy};
9204         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9205       }
9206 
9207       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9208         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9209           continue;
9210 
9211         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9212         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9213       }
9214 
9215       if (S.getLangOpts().CPlusPlus11) {
9216         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9217           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9218             continue;
9219 
9220           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9221             continue;
9222 
9223           QualType ParamTypes[2] = {EnumTy, EnumTy};
9224           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9225         }
9226       }
9227     }
9228   }
9229 };
9230 
9231 } // end anonymous namespace
9232 
9233 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9234 /// operator overloads to the candidate set (C++ [over.built]), based
9235 /// on the operator @p Op and the arguments given. For example, if the
9236 /// operator is a binary '+', this routine might add "int
9237 /// operator+(int, int)" to cover integer addition.
9238 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9239                                         SourceLocation OpLoc,
9240                                         ArrayRef<Expr *> Args,
9241                                         OverloadCandidateSet &CandidateSet) {
9242   // Find all of the types that the arguments can convert to, but only
9243   // if the operator we're looking at has built-in operator candidates
9244   // that make use of these types. Also record whether we encounter non-record
9245   // candidate types or either arithmetic or enumeral candidate types.
9246   QualifiersAndAtomic VisibleTypeConversionsQuals;
9247   VisibleTypeConversionsQuals.addConst();
9248   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9249     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9250     if (Args[ArgIdx]->getType()->isAtomicType())
9251       VisibleTypeConversionsQuals.addAtomic();
9252   }
9253 
9254   bool HasNonRecordCandidateType = false;
9255   bool HasArithmeticOrEnumeralCandidateType = false;
9256   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9257   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9258     CandidateTypes.emplace_back(*this);
9259     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9260                                                  OpLoc,
9261                                                  true,
9262                                                  (Op == OO_Exclaim ||
9263                                                   Op == OO_AmpAmp ||
9264                                                   Op == OO_PipePipe),
9265                                                  VisibleTypeConversionsQuals);
9266     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9267         CandidateTypes[ArgIdx].hasNonRecordTypes();
9268     HasArithmeticOrEnumeralCandidateType =
9269         HasArithmeticOrEnumeralCandidateType ||
9270         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9271   }
9272 
9273   // Exit early when no non-record types have been added to the candidate set
9274   // for any of the arguments to the operator.
9275   //
9276   // We can't exit early for !, ||, or &&, since there we have always have
9277   // 'bool' overloads.
9278   if (!HasNonRecordCandidateType &&
9279       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9280     return;
9281 
9282   // Setup an object to manage the common state for building overloads.
9283   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9284                                            VisibleTypeConversionsQuals,
9285                                            HasArithmeticOrEnumeralCandidateType,
9286                                            CandidateTypes, CandidateSet);
9287 
9288   // Dispatch over the operation to add in only those overloads which apply.
9289   switch (Op) {
9290   case OO_None:
9291   case NUM_OVERLOADED_OPERATORS:
9292     llvm_unreachable("Expected an overloaded operator");
9293 
9294   case OO_New:
9295   case OO_Delete:
9296   case OO_Array_New:
9297   case OO_Array_Delete:
9298   case OO_Call:
9299     llvm_unreachable(
9300                     "Special operators don't use AddBuiltinOperatorCandidates");
9301 
9302   case OO_Comma:
9303   case OO_Arrow:
9304   case OO_Coawait:
9305     // C++ [over.match.oper]p3:
9306     //   -- For the operator ',', the unary operator '&', the
9307     //      operator '->', or the operator 'co_await', the
9308     //      built-in candidates set is empty.
9309     break;
9310 
9311   case OO_Plus: // '+' is either unary or binary
9312     if (Args.size() == 1)
9313       OpBuilder.addUnaryPlusPointerOverloads();
9314     LLVM_FALLTHROUGH;
9315 
9316   case OO_Minus: // '-' is either unary or binary
9317     if (Args.size() == 1) {
9318       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9319     } else {
9320       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9321       OpBuilder.addGenericBinaryArithmeticOverloads();
9322       OpBuilder.addMatrixBinaryArithmeticOverloads();
9323     }
9324     break;
9325 
9326   case OO_Star: // '*' is either unary or binary
9327     if (Args.size() == 1)
9328       OpBuilder.addUnaryStarPointerOverloads();
9329     else {
9330       OpBuilder.addGenericBinaryArithmeticOverloads();
9331       OpBuilder.addMatrixBinaryArithmeticOverloads();
9332     }
9333     break;
9334 
9335   case OO_Slash:
9336     OpBuilder.addGenericBinaryArithmeticOverloads();
9337     break;
9338 
9339   case OO_PlusPlus:
9340   case OO_MinusMinus:
9341     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9342     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9343     break;
9344 
9345   case OO_EqualEqual:
9346   case OO_ExclaimEqual:
9347     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9348     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9349     OpBuilder.addGenericBinaryArithmeticOverloads();
9350     break;
9351 
9352   case OO_Less:
9353   case OO_Greater:
9354   case OO_LessEqual:
9355   case OO_GreaterEqual:
9356     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9357     OpBuilder.addGenericBinaryArithmeticOverloads();
9358     break;
9359 
9360   case OO_Spaceship:
9361     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9362     OpBuilder.addThreeWayArithmeticOverloads();
9363     break;
9364 
9365   case OO_Percent:
9366   case OO_Caret:
9367   case OO_Pipe:
9368   case OO_LessLess:
9369   case OO_GreaterGreater:
9370     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9371     break;
9372 
9373   case OO_Amp: // '&' is either unary or binary
9374     if (Args.size() == 1)
9375       // C++ [over.match.oper]p3:
9376       //   -- For the operator ',', the unary operator '&', or the
9377       //      operator '->', the built-in candidates set is empty.
9378       break;
9379 
9380     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9381     break;
9382 
9383   case OO_Tilde:
9384     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9385     break;
9386 
9387   case OO_Equal:
9388     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9389     LLVM_FALLTHROUGH;
9390 
9391   case OO_PlusEqual:
9392   case OO_MinusEqual:
9393     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9394     LLVM_FALLTHROUGH;
9395 
9396   case OO_StarEqual:
9397   case OO_SlashEqual:
9398     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9399     break;
9400 
9401   case OO_PercentEqual:
9402   case OO_LessLessEqual:
9403   case OO_GreaterGreaterEqual:
9404   case OO_AmpEqual:
9405   case OO_CaretEqual:
9406   case OO_PipeEqual:
9407     OpBuilder.addAssignmentIntegralOverloads();
9408     break;
9409 
9410   case OO_Exclaim:
9411     OpBuilder.addExclaimOverload();
9412     break;
9413 
9414   case OO_AmpAmp:
9415   case OO_PipePipe:
9416     OpBuilder.addAmpAmpOrPipePipeOverload();
9417     break;
9418 
9419   case OO_Subscript:
9420     if (Args.size() == 2)
9421       OpBuilder.addSubscriptOverloads();
9422     break;
9423 
9424   case OO_ArrowStar:
9425     OpBuilder.addArrowStarOverloads();
9426     break;
9427 
9428   case OO_Conditional:
9429     OpBuilder.addConditionalOperatorOverloads();
9430     OpBuilder.addGenericBinaryArithmeticOverloads();
9431     break;
9432   }
9433 }
9434 
9435 /// Add function candidates found via argument-dependent lookup
9436 /// to the set of overloading candidates.
9437 ///
9438 /// This routine performs argument-dependent name lookup based on the
9439 /// given function name (which may also be an operator name) and adds
9440 /// all of the overload candidates found by ADL to the overload
9441 /// candidate set (C++ [basic.lookup.argdep]).
9442 void
9443 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9444                                            SourceLocation Loc,
9445                                            ArrayRef<Expr *> Args,
9446                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9447                                            OverloadCandidateSet& CandidateSet,
9448                                            bool PartialOverloading) {
9449   ADLResult Fns;
9450 
9451   // FIXME: This approach for uniquing ADL results (and removing
9452   // redundant candidates from the set) relies on pointer-equality,
9453   // which means we need to key off the canonical decl.  However,
9454   // always going back to the canonical decl might not get us the
9455   // right set of default arguments.  What default arguments are
9456   // we supposed to consider on ADL candidates, anyway?
9457 
9458   // FIXME: Pass in the explicit template arguments?
9459   ArgumentDependentLookup(Name, Loc, Args, Fns);
9460 
9461   // Erase all of the candidates we already knew about.
9462   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9463                                    CandEnd = CandidateSet.end();
9464        Cand != CandEnd; ++Cand)
9465     if (Cand->Function) {
9466       Fns.erase(Cand->Function);
9467       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9468         Fns.erase(FunTmpl);
9469     }
9470 
9471   // For each of the ADL candidates we found, add it to the overload
9472   // set.
9473   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9474     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9475 
9476     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9477       if (ExplicitTemplateArgs)
9478         continue;
9479 
9480       AddOverloadCandidate(
9481           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9482           PartialOverloading, /*AllowExplicit=*/true,
9483           /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
9484       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9485         AddOverloadCandidate(
9486             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9487             /*SuppressUserConversions=*/false, PartialOverloading,
9488             /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9489             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9490       }
9491     } else {
9492       auto *FTD = cast<FunctionTemplateDecl>(*I);
9493       AddTemplateOverloadCandidate(
9494           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9495           /*SuppressUserConversions=*/false, PartialOverloading,
9496           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9497       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9498               Context, FTD->getTemplatedDecl())) {
9499         AddTemplateOverloadCandidate(
9500             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9501             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9502             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9503             OverloadCandidateParamOrder::Reversed);
9504       }
9505     }
9506   }
9507 }
9508 
9509 namespace {
9510 enum class Comparison { Equal, Better, Worse };
9511 }
9512 
9513 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9514 /// overload resolution.
9515 ///
9516 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9517 /// Cand1's first N enable_if attributes have precisely the same conditions as
9518 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9519 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9520 ///
9521 /// Note that you can have a pair of candidates such that Cand1's enable_if
9522 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9523 /// worse than Cand1's.
9524 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9525                                        const FunctionDecl *Cand2) {
9526   // Common case: One (or both) decls don't have enable_if attrs.
9527   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9528   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9529   if (!Cand1Attr || !Cand2Attr) {
9530     if (Cand1Attr == Cand2Attr)
9531       return Comparison::Equal;
9532     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9533   }
9534 
9535   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9536   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9537 
9538   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9539   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9540     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9541     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9542 
9543     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9544     // has fewer enable_if attributes than Cand2, and vice versa.
9545     if (!Cand1A)
9546       return Comparison::Worse;
9547     if (!Cand2A)
9548       return Comparison::Better;
9549 
9550     Cand1ID.clear();
9551     Cand2ID.clear();
9552 
9553     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9554     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9555     if (Cand1ID != Cand2ID)
9556       return Comparison::Worse;
9557   }
9558 
9559   return Comparison::Equal;
9560 }
9561 
9562 static Comparison
9563 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9564                               const OverloadCandidate &Cand2) {
9565   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9566       !Cand2.Function->isMultiVersion())
9567     return Comparison::Equal;
9568 
9569   // If both are invalid, they are equal. If one of them is invalid, the other
9570   // is better.
9571   if (Cand1.Function->isInvalidDecl()) {
9572     if (Cand2.Function->isInvalidDecl())
9573       return Comparison::Equal;
9574     return Comparison::Worse;
9575   }
9576   if (Cand2.Function->isInvalidDecl())
9577     return Comparison::Better;
9578 
9579   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9580   // cpu_dispatch, else arbitrarily based on the identifiers.
9581   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9582   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9583   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9584   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9585 
9586   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9587     return Comparison::Equal;
9588 
9589   if (Cand1CPUDisp && !Cand2CPUDisp)
9590     return Comparison::Better;
9591   if (Cand2CPUDisp && !Cand1CPUDisp)
9592     return Comparison::Worse;
9593 
9594   if (Cand1CPUSpec && Cand2CPUSpec) {
9595     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9596       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9597                  ? Comparison::Better
9598                  : Comparison::Worse;
9599 
9600     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9601         FirstDiff = std::mismatch(
9602             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9603             Cand2CPUSpec->cpus_begin(),
9604             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9605               return LHS->getName() == RHS->getName();
9606             });
9607 
9608     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9609            "Two different cpu-specific versions should not have the same "
9610            "identifier list, otherwise they'd be the same decl!");
9611     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9612                ? Comparison::Better
9613                : Comparison::Worse;
9614   }
9615   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9616 }
9617 
9618 /// Compute the type of the implicit object parameter for the given function,
9619 /// if any. Returns None if there is no implicit object parameter, and a null
9620 /// QualType if there is a 'matches anything' implicit object parameter.
9621 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9622                                                      const FunctionDecl *F) {
9623   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9624     return llvm::None;
9625 
9626   auto *M = cast<CXXMethodDecl>(F);
9627   // Static member functions' object parameters match all types.
9628   if (M->isStatic())
9629     return QualType();
9630 
9631   QualType T = M->getThisObjectType();
9632   if (M->getRefQualifier() == RQ_RValue)
9633     return Context.getRValueReferenceType(T);
9634   return Context.getLValueReferenceType(T);
9635 }
9636 
9637 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9638                                    const FunctionDecl *F2, unsigned NumParams) {
9639   if (declaresSameEntity(F1, F2))
9640     return true;
9641 
9642   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9643     if (First) {
9644       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9645         return *T;
9646     }
9647     assert(I < F->getNumParams());
9648     return F->getParamDecl(I++)->getType();
9649   };
9650 
9651   unsigned I1 = 0, I2 = 0;
9652   for (unsigned I = 0; I != NumParams; ++I) {
9653     QualType T1 = NextParam(F1, I1, I == 0);
9654     QualType T2 = NextParam(F2, I2, I == 0);
9655     assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
9656     if (!Context.hasSameUnqualifiedType(T1, T2))
9657       return false;
9658   }
9659   return true;
9660 }
9661 
9662 /// We're allowed to use constraints partial ordering only if the candidates
9663 /// have the same parameter types:
9664 /// [temp.func.order]p6.2.2 [...] or if the function parameters that
9665 /// positionally correspond between the two templates are not of the same type,
9666 /// neither template is more specialized than the other.
9667 /// [over.match.best]p2.6
9668 /// F1 and F2 are non-template functions with the same parameter-type-lists,
9669 /// and F1 is more constrained than F2 [...]
9670 static bool canCompareFunctionConstraints(Sema &S,
9671                                           const OverloadCandidate &Cand1,
9672                                           const OverloadCandidate &Cand2) {
9673   // FIXME: Per P2113R0 we also need to compare the template parameter lists
9674   // when comparing template functions.
9675   if (Cand1.Function && Cand2.Function && Cand1.Function->hasPrototype() &&
9676       Cand2.Function->hasPrototype()) {
9677     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9678     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9679     if (PT1->getNumParams() == PT2->getNumParams() &&
9680         PT1->isVariadic() == PT2->isVariadic() &&
9681         S.FunctionParamTypesAreEqual(PT1, PT2, nullptr,
9682                                      Cand1.isReversed() ^ Cand2.isReversed()))
9683       return true;
9684   }
9685   return false;
9686 }
9687 
9688 /// isBetterOverloadCandidate - Determines whether the first overload
9689 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9690 bool clang::isBetterOverloadCandidate(
9691     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9692     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9693   // Define viable functions to be better candidates than non-viable
9694   // functions.
9695   if (!Cand2.Viable)
9696     return Cand1.Viable;
9697   else if (!Cand1.Viable)
9698     return false;
9699 
9700   // [CUDA] A function with 'never' preference is marked not viable, therefore
9701   // is never shown up here. The worst preference shown up here is 'wrong side',
9702   // e.g. an H function called by a HD function in device compilation. This is
9703   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9704   // function which is called only by an H function. A deferred diagnostic will
9705   // be triggered if it is emitted. However a wrong-sided function is still
9706   // a viable candidate here.
9707   //
9708   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9709   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9710   // can be emitted, Cand1 is not better than Cand2. This rule should have
9711   // precedence over other rules.
9712   //
9713   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9714   // other rules should be used to determine which is better. This is because
9715   // host/device based overloading resolution is mostly for determining
9716   // viability of a function. If two functions are both viable, other factors
9717   // should take precedence in preference, e.g. the standard-defined preferences
9718   // like argument conversion ranks or enable_if partial-ordering. The
9719   // preference for pass-object-size parameters is probably most similar to a
9720   // type-based-overloading decision and so should take priority.
9721   //
9722   // If other rules cannot determine which is better, CUDA preference will be
9723   // used again to determine which is better.
9724   //
9725   // TODO: Currently IdentifyCUDAPreference does not return correct values
9726   // for functions called in global variable initializers due to missing
9727   // correct context about device/host. Therefore we can only enforce this
9728   // rule when there is a caller. We should enforce this rule for functions
9729   // in global variable initializers once proper context is added.
9730   //
9731   // TODO: We can only enable the hostness based overloading resolution when
9732   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9733   // overloading resolution diagnostics.
9734   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9735       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9736     if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
9737       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9738       bool IsCand1ImplicitHD =
9739           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9740       bool IsCand2ImplicitHD =
9741           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9742       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9743       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9744       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9745       // The implicit HD function may be a function in a system header which
9746       // is forced by pragma. In device compilation, if we prefer HD candidates
9747       // over wrong-sided candidates, overloading resolution may change, which
9748       // may result in non-deferrable diagnostics. As a workaround, we let
9749       // implicit HD candidates take equal preference as wrong-sided candidates.
9750       // This will preserve the overloading resolution.
9751       // TODO: We still need special handling of implicit HD functions since
9752       // they may incur other diagnostics to be deferred. We should make all
9753       // host/device related diagnostics deferrable and remove special handling
9754       // of implicit HD functions.
9755       auto EmitThreshold =
9756           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9757            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9758               ? Sema::CFP_Never
9759               : Sema::CFP_WrongSide;
9760       auto Cand1Emittable = P1 > EmitThreshold;
9761       auto Cand2Emittable = P2 > EmitThreshold;
9762       if (Cand1Emittable && !Cand2Emittable)
9763         return true;
9764       if (!Cand1Emittable && Cand2Emittable)
9765         return false;
9766     }
9767   }
9768 
9769   // C++ [over.match.best]p1:
9770   //
9771   //   -- if F is a static member function, ICS1(F) is defined such
9772   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9773   //      any function G, and, symmetrically, ICS1(G) is neither
9774   //      better nor worse than ICS1(F).
9775   unsigned StartArg = 0;
9776   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9777     StartArg = 1;
9778 
9779   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9780     // We don't allow incompatible pointer conversions in C++.
9781     if (!S.getLangOpts().CPlusPlus)
9782       return ICS.isStandard() &&
9783              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9784 
9785     // The only ill-formed conversion we allow in C++ is the string literal to
9786     // char* conversion, which is only considered ill-formed after C++11.
9787     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9788            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9789   };
9790 
9791   // Define functions that don't require ill-formed conversions for a given
9792   // argument to be better candidates than functions that do.
9793   unsigned NumArgs = Cand1.Conversions.size();
9794   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9795   bool HasBetterConversion = false;
9796   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9797     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9798     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9799     if (Cand1Bad != Cand2Bad) {
9800       if (Cand1Bad)
9801         return false;
9802       HasBetterConversion = true;
9803     }
9804   }
9805 
9806   if (HasBetterConversion)
9807     return true;
9808 
9809   // C++ [over.match.best]p1:
9810   //   A viable function F1 is defined to be a better function than another
9811   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9812   //   conversion sequence than ICSi(F2), and then...
9813   bool HasWorseConversion = false;
9814   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9815     switch (CompareImplicitConversionSequences(S, Loc,
9816                                                Cand1.Conversions[ArgIdx],
9817                                                Cand2.Conversions[ArgIdx])) {
9818     case ImplicitConversionSequence::Better:
9819       // Cand1 has a better conversion sequence.
9820       HasBetterConversion = true;
9821       break;
9822 
9823     case ImplicitConversionSequence::Worse:
9824       if (Cand1.Function && Cand2.Function &&
9825           Cand1.isReversed() != Cand2.isReversed() &&
9826           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9827                                  NumArgs)) {
9828         // Work around large-scale breakage caused by considering reversed
9829         // forms of operator== in C++20:
9830         //
9831         // When comparing a function against a reversed function with the same
9832         // parameter types, if we have a better conversion for one argument and
9833         // a worse conversion for the other, the implicit conversion sequences
9834         // are treated as being equally good.
9835         //
9836         // This prevents a comparison function from being considered ambiguous
9837         // with a reversed form that is written in the same way.
9838         //
9839         // We diagnose this as an extension from CreateOverloadedBinOp.
9840         HasWorseConversion = true;
9841         break;
9842       }
9843 
9844       // Cand1 can't be better than Cand2.
9845       return false;
9846 
9847     case ImplicitConversionSequence::Indistinguishable:
9848       // Do nothing.
9849       break;
9850     }
9851   }
9852 
9853   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9854   //       ICSj(F2), or, if not that,
9855   if (HasBetterConversion && !HasWorseConversion)
9856     return true;
9857 
9858   //   -- the context is an initialization by user-defined conversion
9859   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9860   //      from the return type of F1 to the destination type (i.e.,
9861   //      the type of the entity being initialized) is a better
9862   //      conversion sequence than the standard conversion sequence
9863   //      from the return type of F2 to the destination type.
9864   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9865       Cand1.Function && Cand2.Function &&
9866       isa<CXXConversionDecl>(Cand1.Function) &&
9867       isa<CXXConversionDecl>(Cand2.Function)) {
9868     // First check whether we prefer one of the conversion functions over the
9869     // other. This only distinguishes the results in non-standard, extension
9870     // cases such as the conversion from a lambda closure type to a function
9871     // pointer or block.
9872     ImplicitConversionSequence::CompareKind Result =
9873         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9874     if (Result == ImplicitConversionSequence::Indistinguishable)
9875       Result = CompareStandardConversionSequences(S, Loc,
9876                                                   Cand1.FinalConversion,
9877                                                   Cand2.FinalConversion);
9878 
9879     if (Result != ImplicitConversionSequence::Indistinguishable)
9880       return Result == ImplicitConversionSequence::Better;
9881 
9882     // FIXME: Compare kind of reference binding if conversion functions
9883     // convert to a reference type used in direct reference binding, per
9884     // C++14 [over.match.best]p1 section 2 bullet 3.
9885   }
9886 
9887   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9888   // as combined with the resolution to CWG issue 243.
9889   //
9890   // When the context is initialization by constructor ([over.match.ctor] or
9891   // either phase of [over.match.list]), a constructor is preferred over
9892   // a conversion function.
9893   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9894       Cand1.Function && Cand2.Function &&
9895       isa<CXXConstructorDecl>(Cand1.Function) !=
9896           isa<CXXConstructorDecl>(Cand2.Function))
9897     return isa<CXXConstructorDecl>(Cand1.Function);
9898 
9899   //    -- F1 is a non-template function and F2 is a function template
9900   //       specialization, or, if not that,
9901   bool Cand1IsSpecialization = Cand1.Function &&
9902                                Cand1.Function->getPrimaryTemplate();
9903   bool Cand2IsSpecialization = Cand2.Function &&
9904                                Cand2.Function->getPrimaryTemplate();
9905   if (Cand1IsSpecialization != Cand2IsSpecialization)
9906     return Cand2IsSpecialization;
9907 
9908   //   -- F1 and F2 are function template specializations, and the function
9909   //      template for F1 is more specialized than the template for F2
9910   //      according to the partial ordering rules described in 14.5.5.2, or,
9911   //      if not that,
9912   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9913     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9914             Cand1.Function->getPrimaryTemplate(),
9915             Cand2.Function->getPrimaryTemplate(), Loc,
9916             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9917                                                    : TPOC_Call,
9918             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9919             Cand1.isReversed() ^ Cand2.isReversed(),
9920             canCompareFunctionConstraints(S, Cand1, Cand2)))
9921       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9922   }
9923 
9924   //   -— F1 and F2 are non-template functions with the same
9925   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9926   if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
9927       canCompareFunctionConstraints(S, Cand1, Cand2)) {
9928     Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9929     Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9930     if (RC1 && RC2) {
9931       bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9932       if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function, {RC2},
9933                                    AtLeastAsConstrained1) ||
9934           S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function, {RC1},
9935                                    AtLeastAsConstrained2))
9936         return false;
9937       if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9938         return AtLeastAsConstrained1;
9939     } else if (RC1 || RC2) {
9940       return RC1 != nullptr;
9941     }
9942   }
9943 
9944   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9945   //      class B of D, and for all arguments the corresponding parameters of
9946   //      F1 and F2 have the same type.
9947   // FIXME: Implement the "all parameters have the same type" check.
9948   bool Cand1IsInherited =
9949       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9950   bool Cand2IsInherited =
9951       isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9952   if (Cand1IsInherited != Cand2IsInherited)
9953     return Cand2IsInherited;
9954   else if (Cand1IsInherited) {
9955     assert(Cand2IsInherited);
9956     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9957     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9958     if (Cand1Class->isDerivedFrom(Cand2Class))
9959       return true;
9960     if (Cand2Class->isDerivedFrom(Cand1Class))
9961       return false;
9962     // Inherited from sibling base classes: still ambiguous.
9963   }
9964 
9965   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9966   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9967   //      with reversed order of parameters and F1 is not
9968   //
9969   // We rank reversed + different operator as worse than just reversed, but
9970   // that comparison can never happen, because we only consider reversing for
9971   // the maximally-rewritten operator (== or <=>).
9972   if (Cand1.RewriteKind != Cand2.RewriteKind)
9973     return Cand1.RewriteKind < Cand2.RewriteKind;
9974 
9975   // Check C++17 tie-breakers for deduction guides.
9976   {
9977     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9978     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9979     if (Guide1 && Guide2) {
9980       //  -- F1 is generated from a deduction-guide and F2 is not
9981       if (Guide1->isImplicit() != Guide2->isImplicit())
9982         return Guide2->isImplicit();
9983 
9984       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9985       if (Guide1->isCopyDeductionCandidate())
9986         return true;
9987     }
9988   }
9989 
9990   // Check for enable_if value-based overload resolution.
9991   if (Cand1.Function && Cand2.Function) {
9992     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9993     if (Cmp != Comparison::Equal)
9994       return Cmp == Comparison::Better;
9995   }
9996 
9997   bool HasPS1 = Cand1.Function != nullptr &&
9998                 functionHasPassObjectSizeParams(Cand1.Function);
9999   bool HasPS2 = Cand2.Function != nullptr &&
10000                 functionHasPassObjectSizeParams(Cand2.Function);
10001   if (HasPS1 != HasPS2 && HasPS1)
10002     return true;
10003 
10004   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10005   if (MV == Comparison::Better)
10006     return true;
10007   if (MV == Comparison::Worse)
10008     return false;
10009 
10010   // If other rules cannot determine which is better, CUDA preference is used
10011   // to determine which is better.
10012   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10013     FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10014     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
10015            S.IdentifyCUDAPreference(Caller, Cand2.Function);
10016   }
10017 
10018   // General member function overloading is handled above, so this only handles
10019   // constructors with address spaces.
10020   // This only handles address spaces since C++ has no other
10021   // qualifier that can be used with constructors.
10022   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10023   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10024   if (CD1 && CD2) {
10025     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10026     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10027     if (AS1 != AS2) {
10028       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10029         return true;
10030       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
10031         return false;
10032     }
10033   }
10034 
10035   return false;
10036 }
10037 
10038 /// Determine whether two declarations are "equivalent" for the purposes of
10039 /// name lookup and overload resolution. This applies when the same internal/no
10040 /// linkage entity is defined by two modules (probably by textually including
10041 /// the same header). In such a case, we don't consider the declarations to
10042 /// declare the same entity, but we also don't want lookups with both
10043 /// declarations visible to be ambiguous in some cases (this happens when using
10044 /// a modularized libstdc++).
10045 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10046                                                   const NamedDecl *B) {
10047   auto *VA = dyn_cast_or_null<ValueDecl>(A);
10048   auto *VB = dyn_cast_or_null<ValueDecl>(B);
10049   if (!VA || !VB)
10050     return false;
10051 
10052   // The declarations must be declaring the same name as an internal linkage
10053   // entity in different modules.
10054   if (!VA->getDeclContext()->getRedeclContext()->Equals(
10055           VB->getDeclContext()->getRedeclContext()) ||
10056       getOwningModule(VA) == getOwningModule(VB) ||
10057       VA->isExternallyVisible() || VB->isExternallyVisible())
10058     return false;
10059 
10060   // Check that the declarations appear to be equivalent.
10061   //
10062   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10063   // For constants and functions, we should check the initializer or body is
10064   // the same. For non-constant variables, we shouldn't allow it at all.
10065   if (Context.hasSameType(VA->getType(), VB->getType()))
10066     return true;
10067 
10068   // Enum constants within unnamed enumerations will have different types, but
10069   // may still be similar enough to be interchangeable for our purposes.
10070   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10071     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10072       // Only handle anonymous enums. If the enumerations were named and
10073       // equivalent, they would have been merged to the same type.
10074       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10075       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10076       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10077           !Context.hasSameType(EnumA->getIntegerType(),
10078                                EnumB->getIntegerType()))
10079         return false;
10080       // Allow this only if the value is the same for both enumerators.
10081       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10082     }
10083   }
10084 
10085   // Nothing else is sufficiently similar.
10086   return false;
10087 }
10088 
10089 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10090     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10091   assert(D && "Unknown declaration");
10092   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10093 
10094   Module *M = getOwningModule(D);
10095   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10096       << !M << (M ? M->getFullModuleName() : "");
10097 
10098   for (auto *E : Equiv) {
10099     Module *M = getOwningModule(E);
10100     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10101         << !M << (M ? M->getFullModuleName() : "");
10102   }
10103 }
10104 
10105 /// Computes the best viable function (C++ 13.3.3)
10106 /// within an overload candidate set.
10107 ///
10108 /// \param Loc The location of the function name (or operator symbol) for
10109 /// which overload resolution occurs.
10110 ///
10111 /// \param Best If overload resolution was successful or found a deleted
10112 /// function, \p Best points to the candidate function found.
10113 ///
10114 /// \returns The result of overload resolution.
10115 OverloadingResult
10116 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10117                                          iterator &Best) {
10118   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10119   std::transform(begin(), end(), std::back_inserter(Candidates),
10120                  [](OverloadCandidate &Cand) { return &Cand; });
10121 
10122   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10123   // are accepted by both clang and NVCC. However, during a particular
10124   // compilation mode only one call variant is viable. We need to
10125   // exclude non-viable overload candidates from consideration based
10126   // only on their host/device attributes. Specifically, if one
10127   // candidate call is WrongSide and the other is SameSide, we ignore
10128   // the WrongSide candidate.
10129   // We only need to remove wrong-sided candidates here if
10130   // -fgpu-exclude-wrong-side-overloads is off. When
10131   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10132   // uniformly in isBetterOverloadCandidate.
10133   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10134     const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10135     bool ContainsSameSideCandidate =
10136         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10137           // Check viable function only.
10138           return Cand->Viable && Cand->Function &&
10139                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10140                      Sema::CFP_SameSide;
10141         });
10142     if (ContainsSameSideCandidate) {
10143       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10144         // Check viable function only to avoid unnecessary data copying/moving.
10145         return Cand->Viable && Cand->Function &&
10146                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10147                    Sema::CFP_WrongSide;
10148       };
10149       llvm::erase_if(Candidates, IsWrongSideCandidate);
10150     }
10151   }
10152 
10153   // Find the best viable function.
10154   Best = end();
10155   for (auto *Cand : Candidates) {
10156     Cand->Best = false;
10157     if (Cand->Viable)
10158       if (Best == end() ||
10159           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10160         Best = Cand;
10161   }
10162 
10163   // If we didn't find any viable functions, abort.
10164   if (Best == end())
10165     return OR_No_Viable_Function;
10166 
10167   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10168 
10169   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10170   PendingBest.push_back(&*Best);
10171   Best->Best = true;
10172 
10173   // Make sure that this function is better than every other viable
10174   // function. If not, we have an ambiguity.
10175   while (!PendingBest.empty()) {
10176     auto *Curr = PendingBest.pop_back_val();
10177     for (auto *Cand : Candidates) {
10178       if (Cand->Viable && !Cand->Best &&
10179           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10180         PendingBest.push_back(Cand);
10181         Cand->Best = true;
10182 
10183         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10184                                                      Curr->Function))
10185           EquivalentCands.push_back(Cand->Function);
10186         else
10187           Best = end();
10188       }
10189     }
10190   }
10191 
10192   // If we found more than one best candidate, this is ambiguous.
10193   if (Best == end())
10194     return OR_Ambiguous;
10195 
10196   // Best is the best viable function.
10197   if (Best->Function && Best->Function->isDeleted())
10198     return OR_Deleted;
10199 
10200   if (!EquivalentCands.empty())
10201     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10202                                                     EquivalentCands);
10203 
10204   return OR_Success;
10205 }
10206 
10207 namespace {
10208 
10209 enum OverloadCandidateKind {
10210   oc_function,
10211   oc_method,
10212   oc_reversed_binary_operator,
10213   oc_constructor,
10214   oc_implicit_default_constructor,
10215   oc_implicit_copy_constructor,
10216   oc_implicit_move_constructor,
10217   oc_implicit_copy_assignment,
10218   oc_implicit_move_assignment,
10219   oc_implicit_equality_comparison,
10220   oc_inherited_constructor
10221 };
10222 
10223 enum OverloadCandidateSelect {
10224   ocs_non_template,
10225   ocs_template,
10226   ocs_described_template,
10227 };
10228 
10229 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10230 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10231                           OverloadCandidateRewriteKind CRK,
10232                           std::string &Description) {
10233 
10234   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10235   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10236     isTemplate = true;
10237     Description = S.getTemplateArgumentBindingsText(
10238         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10239   }
10240 
10241   OverloadCandidateSelect Select = [&]() {
10242     if (!Description.empty())
10243       return ocs_described_template;
10244     return isTemplate ? ocs_template : ocs_non_template;
10245   }();
10246 
10247   OverloadCandidateKind Kind = [&]() {
10248     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10249       return oc_implicit_equality_comparison;
10250 
10251     if (CRK & CRK_Reversed)
10252       return oc_reversed_binary_operator;
10253 
10254     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10255       if (!Ctor->isImplicit()) {
10256         if (isa<ConstructorUsingShadowDecl>(Found))
10257           return oc_inherited_constructor;
10258         else
10259           return oc_constructor;
10260       }
10261 
10262       if (Ctor->isDefaultConstructor())
10263         return oc_implicit_default_constructor;
10264 
10265       if (Ctor->isMoveConstructor())
10266         return oc_implicit_move_constructor;
10267 
10268       assert(Ctor->isCopyConstructor() &&
10269              "unexpected sort of implicit constructor");
10270       return oc_implicit_copy_constructor;
10271     }
10272 
10273     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10274       // This actually gets spelled 'candidate function' for now, but
10275       // it doesn't hurt to split it out.
10276       if (!Meth->isImplicit())
10277         return oc_method;
10278 
10279       if (Meth->isMoveAssignmentOperator())
10280         return oc_implicit_move_assignment;
10281 
10282       if (Meth->isCopyAssignmentOperator())
10283         return oc_implicit_copy_assignment;
10284 
10285       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10286       return oc_method;
10287     }
10288 
10289     return oc_function;
10290   }();
10291 
10292   return std::make_pair(Kind, Select);
10293 }
10294 
10295 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10296   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10297   // set.
10298   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10299     S.Diag(FoundDecl->getLocation(),
10300            diag::note_ovl_candidate_inherited_constructor)
10301       << Shadow->getNominatedBaseClass();
10302 }
10303 
10304 } // end anonymous namespace
10305 
10306 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10307                                     const FunctionDecl *FD) {
10308   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10309     bool AlwaysTrue;
10310     if (EnableIf->getCond()->isValueDependent() ||
10311         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10312       return false;
10313     if (!AlwaysTrue)
10314       return false;
10315   }
10316   return true;
10317 }
10318 
10319 /// Returns true if we can take the address of the function.
10320 ///
10321 /// \param Complain - If true, we'll emit a diagnostic
10322 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10323 ///   we in overload resolution?
10324 /// \param Loc - The location of the statement we're complaining about. Ignored
10325 ///   if we're not complaining, or if we're in overload resolution.
10326 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10327                                               bool Complain,
10328                                               bool InOverloadResolution,
10329                                               SourceLocation Loc) {
10330   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10331     if (Complain) {
10332       if (InOverloadResolution)
10333         S.Diag(FD->getBeginLoc(),
10334                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10335       else
10336         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10337     }
10338     return false;
10339   }
10340 
10341   if (FD->getTrailingRequiresClause()) {
10342     ConstraintSatisfaction Satisfaction;
10343     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10344       return false;
10345     if (!Satisfaction.IsSatisfied) {
10346       if (Complain) {
10347         if (InOverloadResolution) {
10348           SmallString<128> TemplateArgString;
10349           if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
10350             TemplateArgString += " ";
10351             TemplateArgString += S.getTemplateArgumentBindingsText(
10352                 FunTmpl->getTemplateParameters(),
10353                 *FD->getTemplateSpecializationArgs());
10354           }
10355 
10356           S.Diag(FD->getBeginLoc(),
10357                  diag::note_ovl_candidate_unsatisfied_constraints)
10358               << TemplateArgString;
10359         } else
10360           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10361               << FD;
10362         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10363       }
10364       return false;
10365     }
10366   }
10367 
10368   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10369     return P->hasAttr<PassObjectSizeAttr>();
10370   });
10371   if (I == FD->param_end())
10372     return true;
10373 
10374   if (Complain) {
10375     // Add one to ParamNo because it's user-facing
10376     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10377     if (InOverloadResolution)
10378       S.Diag(FD->getLocation(),
10379              diag::note_ovl_candidate_has_pass_object_size_params)
10380           << ParamNo;
10381     else
10382       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10383           << FD << ParamNo;
10384   }
10385   return false;
10386 }
10387 
10388 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10389                                                const FunctionDecl *FD) {
10390   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10391                                            /*InOverloadResolution=*/true,
10392                                            /*Loc=*/SourceLocation());
10393 }
10394 
10395 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10396                                              bool Complain,
10397                                              SourceLocation Loc) {
10398   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10399                                              /*InOverloadResolution=*/false,
10400                                              Loc);
10401 }
10402 
10403 // Don't print candidates other than the one that matches the calling
10404 // convention of the call operator, since that is guaranteed to exist.
10405 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10406   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10407 
10408   if (!ConvD)
10409     return false;
10410   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10411   if (!RD->isLambda())
10412     return false;
10413 
10414   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10415   CallingConv CallOpCC =
10416       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10417   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10418   CallingConv ConvToCC =
10419       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10420 
10421   return ConvToCC != CallOpCC;
10422 }
10423 
10424 // Notes the location of an overload candidate.
10425 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10426                                  OverloadCandidateRewriteKind RewriteKind,
10427                                  QualType DestType, bool TakingAddress) {
10428   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10429     return;
10430   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10431       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10432     return;
10433   if (shouldSkipNotingLambdaConversionDecl(Fn))
10434     return;
10435 
10436   std::string FnDesc;
10437   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10438       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10439   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10440                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10441                          << Fn << FnDesc;
10442 
10443   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10444   Diag(Fn->getLocation(), PD);
10445   MaybeEmitInheritedConstructorNote(*this, Found);
10446 }
10447 
10448 static void
10449 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10450   // Perhaps the ambiguity was caused by two atomic constraints that are
10451   // 'identical' but not equivalent:
10452   //
10453   // void foo() requires (sizeof(T) > 4) { } // #1
10454   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10455   //
10456   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10457   // #2 to subsume #1, but these constraint are not considered equivalent
10458   // according to the subsumption rules because they are not the same
10459   // source-level construct. This behavior is quite confusing and we should try
10460   // to help the user figure out what happened.
10461 
10462   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10463   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10464   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10465     if (!I->Function)
10466       continue;
10467     SmallVector<const Expr *, 3> AC;
10468     if (auto *Template = I->Function->getPrimaryTemplate())
10469       Template->getAssociatedConstraints(AC);
10470     else
10471       I->Function->getAssociatedConstraints(AC);
10472     if (AC.empty())
10473       continue;
10474     if (FirstCand == nullptr) {
10475       FirstCand = I->Function;
10476       FirstAC = AC;
10477     } else if (SecondCand == nullptr) {
10478       SecondCand = I->Function;
10479       SecondAC = AC;
10480     } else {
10481       // We have more than one pair of constrained functions - this check is
10482       // expensive and we'd rather not try to diagnose it.
10483       return;
10484     }
10485   }
10486   if (!SecondCand)
10487     return;
10488   // The diagnostic can only happen if there are associated constraints on
10489   // both sides (there needs to be some identical atomic constraint).
10490   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10491                                                       SecondCand, SecondAC))
10492     // Just show the user one diagnostic, they'll probably figure it out
10493     // from here.
10494     return;
10495 }
10496 
10497 // Notes the location of all overload candidates designated through
10498 // OverloadedExpr
10499 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10500                                      bool TakingAddress) {
10501   assert(OverloadedExpr->getType() == Context.OverloadTy);
10502 
10503   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10504   OverloadExpr *OvlExpr = Ovl.Expression;
10505 
10506   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10507                             IEnd = OvlExpr->decls_end();
10508        I != IEnd; ++I) {
10509     if (FunctionTemplateDecl *FunTmpl =
10510                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10511       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10512                             TakingAddress);
10513     } else if (FunctionDecl *Fun
10514                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10515       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10516     }
10517   }
10518 }
10519 
10520 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10521 /// "lead" diagnostic; it will be given two arguments, the source and
10522 /// target types of the conversion.
10523 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10524                                  Sema &S,
10525                                  SourceLocation CaretLoc,
10526                                  const PartialDiagnostic &PDiag) const {
10527   S.Diag(CaretLoc, PDiag)
10528     << Ambiguous.getFromType() << Ambiguous.getToType();
10529   unsigned CandsShown = 0;
10530   AmbiguousConversionSequence::const_iterator I, E;
10531   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10532     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10533       break;
10534     ++CandsShown;
10535     S.NoteOverloadCandidate(I->first, I->second);
10536   }
10537   S.Diags.overloadCandidatesShown(CandsShown);
10538   if (I != E)
10539     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10540 }
10541 
10542 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10543                                   unsigned I, bool TakingCandidateAddress) {
10544   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10545   assert(Conv.isBad());
10546   assert(Cand->Function && "for now, candidate must be a function");
10547   FunctionDecl *Fn = Cand->Function;
10548 
10549   // There's a conversion slot for the object argument if this is a
10550   // non-constructor method.  Note that 'I' corresponds the
10551   // conversion-slot index.
10552   bool isObjectArgument = false;
10553   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10554     if (I == 0)
10555       isObjectArgument = true;
10556     else
10557       I--;
10558   }
10559 
10560   std::string FnDesc;
10561   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10562       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10563                                 FnDesc);
10564 
10565   Expr *FromExpr = Conv.Bad.FromExpr;
10566   QualType FromTy = Conv.Bad.getFromType();
10567   QualType ToTy = Conv.Bad.getToType();
10568 
10569   if (FromTy == S.Context.OverloadTy) {
10570     assert(FromExpr && "overload set argument came from implicit argument?");
10571     Expr *E = FromExpr->IgnoreParens();
10572     if (isa<UnaryOperator>(E))
10573       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10574     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10575 
10576     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10577         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10578         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10579         << Name << I + 1;
10580     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10581     return;
10582   }
10583 
10584   // Do some hand-waving analysis to see if the non-viability is due
10585   // to a qualifier mismatch.
10586   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10587   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10588   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10589     CToTy = RT->getPointeeType();
10590   else {
10591     // TODO: detect and diagnose the full richness of const mismatches.
10592     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10593       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10594         CFromTy = FromPT->getPointeeType();
10595         CToTy = ToPT->getPointeeType();
10596       }
10597   }
10598 
10599   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10600       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10601     Qualifiers FromQs = CFromTy.getQualifiers();
10602     Qualifiers ToQs = CToTy.getQualifiers();
10603 
10604     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10605       if (isObjectArgument)
10606         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10607             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10608             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10609             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10610       else
10611         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10612             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10613             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10614             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10615             << ToTy->isReferenceType() << I + 1;
10616       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10617       return;
10618     }
10619 
10620     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10621       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10622           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10623           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10624           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10625           << (unsigned)isObjectArgument << I + 1;
10626       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10627       return;
10628     }
10629 
10630     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10631       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10632           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10633           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10634           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10635           << (unsigned)isObjectArgument << I + 1;
10636       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10637       return;
10638     }
10639 
10640     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10641       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10642           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10643           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10644           << FromQs.hasUnaligned() << I + 1;
10645       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10646       return;
10647     }
10648 
10649     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10650     assert(CVR && "expected qualifiers mismatch");
10651 
10652     if (isObjectArgument) {
10653       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10654           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10655           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10656           << (CVR - 1);
10657     } else {
10658       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10659           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10660           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10661           << (CVR - 1) << I + 1;
10662     }
10663     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10664     return;
10665   }
10666 
10667   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10668       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10669     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10670         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10671         << (unsigned)isObjectArgument << I + 1
10672         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10673         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10674     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10675     return;
10676   }
10677 
10678   // Special diagnostic for failure to convert an initializer list, since
10679   // telling the user that it has type void is not useful.
10680   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10681     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10682         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10683         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10684         << ToTy << (unsigned)isObjectArgument << I + 1
10685         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10686             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10687                 ? 2
10688                 : 0);
10689     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10690     return;
10691   }
10692 
10693   // Diagnose references or pointers to incomplete types differently,
10694   // since it's far from impossible that the incompleteness triggered
10695   // the failure.
10696   QualType TempFromTy = FromTy.getNonReferenceType();
10697   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10698     TempFromTy = PTy->getPointeeType();
10699   if (TempFromTy->isIncompleteType()) {
10700     // Emit the generic diagnostic and, optionally, add the hints to it.
10701     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10702         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10703         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10704         << ToTy << (unsigned)isObjectArgument << I + 1
10705         << (unsigned)(Cand->Fix.Kind);
10706 
10707     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10708     return;
10709   }
10710 
10711   // Diagnose base -> derived pointer conversions.
10712   unsigned BaseToDerivedConversion = 0;
10713   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10714     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10715       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10716                                                FromPtrTy->getPointeeType()) &&
10717           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10718           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10719           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10720                           FromPtrTy->getPointeeType()))
10721         BaseToDerivedConversion = 1;
10722     }
10723   } else if (const ObjCObjectPointerType *FromPtrTy
10724                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10725     if (const ObjCObjectPointerType *ToPtrTy
10726                                         = ToTy->getAs<ObjCObjectPointerType>())
10727       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10728         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10729           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10730                                                 FromPtrTy->getPointeeType()) &&
10731               FromIface->isSuperClassOf(ToIface))
10732             BaseToDerivedConversion = 2;
10733   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10734     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10735         !FromTy->isIncompleteType() &&
10736         !ToRefTy->getPointeeType()->isIncompleteType() &&
10737         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10738       BaseToDerivedConversion = 3;
10739     }
10740   }
10741 
10742   if (BaseToDerivedConversion) {
10743     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10744         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10745         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10746         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10747     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10748     return;
10749   }
10750 
10751   if (isa<ObjCObjectPointerType>(CFromTy) &&
10752       isa<PointerType>(CToTy)) {
10753       Qualifiers FromQs = CFromTy.getQualifiers();
10754       Qualifiers ToQs = CToTy.getQualifiers();
10755       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10756         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10757             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10758             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10759             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10760         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10761         return;
10762       }
10763   }
10764 
10765   if (TakingCandidateAddress &&
10766       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10767     return;
10768 
10769   // Emit the generic diagnostic and, optionally, add the hints to it.
10770   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10771   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10772         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10773         << ToTy << (unsigned)isObjectArgument << I + 1
10774         << (unsigned)(Cand->Fix.Kind);
10775 
10776   // If we can fix the conversion, suggest the FixIts.
10777   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10778        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10779     FDiag << *HI;
10780   S.Diag(Fn->getLocation(), FDiag);
10781 
10782   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10783 }
10784 
10785 /// Additional arity mismatch diagnosis specific to a function overload
10786 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10787 /// over a candidate in any candidate set.
10788 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10789                                unsigned NumArgs) {
10790   FunctionDecl *Fn = Cand->Function;
10791   unsigned MinParams = Fn->getMinRequiredArguments();
10792 
10793   // With invalid overloaded operators, it's possible that we think we
10794   // have an arity mismatch when in fact it looks like we have the
10795   // right number of arguments, because only overloaded operators have
10796   // the weird behavior of overloading member and non-member functions.
10797   // Just don't report anything.
10798   if (Fn->isInvalidDecl() &&
10799       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10800     return true;
10801 
10802   if (NumArgs < MinParams) {
10803     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10804            (Cand->FailureKind == ovl_fail_bad_deduction &&
10805             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10806   } else {
10807     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10808            (Cand->FailureKind == ovl_fail_bad_deduction &&
10809             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10810   }
10811 
10812   return false;
10813 }
10814 
10815 /// General arity mismatch diagnosis over a candidate in a candidate set.
10816 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10817                                   unsigned NumFormalArgs) {
10818   assert(isa<FunctionDecl>(D) &&
10819       "The templated declaration should at least be a function"
10820       " when diagnosing bad template argument deduction due to too many"
10821       " or too few arguments");
10822 
10823   FunctionDecl *Fn = cast<FunctionDecl>(D);
10824 
10825   // TODO: treat calls to a missing default constructor as a special case
10826   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10827   unsigned MinParams = Fn->getMinRequiredArguments();
10828 
10829   // at least / at most / exactly
10830   unsigned mode, modeCount;
10831   if (NumFormalArgs < MinParams) {
10832     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10833         FnTy->isTemplateVariadic())
10834       mode = 0; // "at least"
10835     else
10836       mode = 2; // "exactly"
10837     modeCount = MinParams;
10838   } else {
10839     if (MinParams != FnTy->getNumParams())
10840       mode = 1; // "at most"
10841     else
10842       mode = 2; // "exactly"
10843     modeCount = FnTy->getNumParams();
10844   }
10845 
10846   std::string Description;
10847   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10848       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10849 
10850   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10851     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10852         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10853         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10854   else
10855     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10856         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10857         << Description << mode << modeCount << NumFormalArgs;
10858 
10859   MaybeEmitInheritedConstructorNote(S, Found);
10860 }
10861 
10862 /// Arity mismatch diagnosis specific to a function overload candidate.
10863 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10864                                   unsigned NumFormalArgs) {
10865   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10866     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10867 }
10868 
10869 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10870   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10871     return TD;
10872   llvm_unreachable("Unsupported: Getting the described template declaration"
10873                    " for bad deduction diagnosis");
10874 }
10875 
10876 /// Diagnose a failed template-argument deduction.
10877 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10878                                  DeductionFailureInfo &DeductionFailure,
10879                                  unsigned NumArgs,
10880                                  bool TakingCandidateAddress) {
10881   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10882   NamedDecl *ParamD;
10883   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10884   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10885   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10886   switch (DeductionFailure.Result) {
10887   case Sema::TDK_Success:
10888     llvm_unreachable("TDK_success while diagnosing bad deduction");
10889 
10890   case Sema::TDK_Incomplete: {
10891     assert(ParamD && "no parameter found for incomplete deduction result");
10892     S.Diag(Templated->getLocation(),
10893            diag::note_ovl_candidate_incomplete_deduction)
10894         << ParamD->getDeclName();
10895     MaybeEmitInheritedConstructorNote(S, Found);
10896     return;
10897   }
10898 
10899   case Sema::TDK_IncompletePack: {
10900     assert(ParamD && "no parameter found for incomplete deduction result");
10901     S.Diag(Templated->getLocation(),
10902            diag::note_ovl_candidate_incomplete_deduction_pack)
10903         << ParamD->getDeclName()
10904         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10905         << *DeductionFailure.getFirstArg();
10906     MaybeEmitInheritedConstructorNote(S, Found);
10907     return;
10908   }
10909 
10910   case Sema::TDK_Underqualified: {
10911     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10912     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10913 
10914     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10915 
10916     // Param will have been canonicalized, but it should just be a
10917     // qualified version of ParamD, so move the qualifiers to that.
10918     QualifierCollector Qs;
10919     Qs.strip(Param);
10920     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10921     assert(S.Context.hasSameType(Param, NonCanonParam));
10922 
10923     // Arg has also been canonicalized, but there's nothing we can do
10924     // about that.  It also doesn't matter as much, because it won't
10925     // have any template parameters in it (because deduction isn't
10926     // done on dependent types).
10927     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10928 
10929     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10930         << ParamD->getDeclName() << Arg << NonCanonParam;
10931     MaybeEmitInheritedConstructorNote(S, Found);
10932     return;
10933   }
10934 
10935   case Sema::TDK_Inconsistent: {
10936     assert(ParamD && "no parameter found for inconsistent deduction result");
10937     int which = 0;
10938     if (isa<TemplateTypeParmDecl>(ParamD))
10939       which = 0;
10940     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10941       // Deduction might have failed because we deduced arguments of two
10942       // different types for a non-type template parameter.
10943       // FIXME: Use a different TDK value for this.
10944       QualType T1 =
10945           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10946       QualType T2 =
10947           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10948       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10949         S.Diag(Templated->getLocation(),
10950                diag::note_ovl_candidate_inconsistent_deduction_types)
10951           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10952           << *DeductionFailure.getSecondArg() << T2;
10953         MaybeEmitInheritedConstructorNote(S, Found);
10954         return;
10955       }
10956 
10957       which = 1;
10958     } else {
10959       which = 2;
10960     }
10961 
10962     // Tweak the diagnostic if the problem is that we deduced packs of
10963     // different arities. We'll print the actual packs anyway in case that
10964     // includes additional useful information.
10965     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10966         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10967         DeductionFailure.getFirstArg()->pack_size() !=
10968             DeductionFailure.getSecondArg()->pack_size()) {
10969       which = 3;
10970     }
10971 
10972     S.Diag(Templated->getLocation(),
10973            diag::note_ovl_candidate_inconsistent_deduction)
10974         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10975         << *DeductionFailure.getSecondArg();
10976     MaybeEmitInheritedConstructorNote(S, Found);
10977     return;
10978   }
10979 
10980   case Sema::TDK_InvalidExplicitArguments:
10981     assert(ParamD && "no parameter found for invalid explicit arguments");
10982     if (ParamD->getDeclName())
10983       S.Diag(Templated->getLocation(),
10984              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10985           << ParamD->getDeclName();
10986     else {
10987       int index = 0;
10988       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10989         index = TTP->getIndex();
10990       else if (NonTypeTemplateParmDecl *NTTP
10991                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10992         index = NTTP->getIndex();
10993       else
10994         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10995       S.Diag(Templated->getLocation(),
10996              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10997           << (index + 1);
10998     }
10999     MaybeEmitInheritedConstructorNote(S, Found);
11000     return;
11001 
11002   case Sema::TDK_ConstraintsNotSatisfied: {
11003     // Format the template argument list into the argument string.
11004     SmallString<128> TemplateArgString;
11005     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11006     TemplateArgString = " ";
11007     TemplateArgString += S.getTemplateArgumentBindingsText(
11008         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11009     if (TemplateArgString.size() == 1)
11010       TemplateArgString.clear();
11011     S.Diag(Templated->getLocation(),
11012            diag::note_ovl_candidate_unsatisfied_constraints)
11013         << TemplateArgString;
11014 
11015     S.DiagnoseUnsatisfiedConstraint(
11016         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11017     return;
11018   }
11019   case Sema::TDK_TooManyArguments:
11020   case Sema::TDK_TooFewArguments:
11021     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11022     return;
11023 
11024   case Sema::TDK_InstantiationDepth:
11025     S.Diag(Templated->getLocation(),
11026            diag::note_ovl_candidate_instantiation_depth);
11027     MaybeEmitInheritedConstructorNote(S, Found);
11028     return;
11029 
11030   case Sema::TDK_SubstitutionFailure: {
11031     // Format the template argument list into the argument string.
11032     SmallString<128> TemplateArgString;
11033     if (TemplateArgumentList *Args =
11034             DeductionFailure.getTemplateArgumentList()) {
11035       TemplateArgString = " ";
11036       TemplateArgString += S.getTemplateArgumentBindingsText(
11037           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11038       if (TemplateArgString.size() == 1)
11039         TemplateArgString.clear();
11040     }
11041 
11042     // If this candidate was disabled by enable_if, say so.
11043     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11044     if (PDiag && PDiag->second.getDiagID() ==
11045           diag::err_typename_nested_not_found_enable_if) {
11046       // FIXME: Use the source range of the condition, and the fully-qualified
11047       //        name of the enable_if template. These are both present in PDiag.
11048       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11049         << "'enable_if'" << TemplateArgString;
11050       return;
11051     }
11052 
11053     // We found a specific requirement that disabled the enable_if.
11054     if (PDiag && PDiag->second.getDiagID() ==
11055         diag::err_typename_nested_not_found_requirement) {
11056       S.Diag(Templated->getLocation(),
11057              diag::note_ovl_candidate_disabled_by_requirement)
11058         << PDiag->second.getStringArg(0) << TemplateArgString;
11059       return;
11060     }
11061 
11062     // Format the SFINAE diagnostic into the argument string.
11063     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11064     //        formatted message in another diagnostic.
11065     SmallString<128> SFINAEArgString;
11066     SourceRange R;
11067     if (PDiag) {
11068       SFINAEArgString = ": ";
11069       R = SourceRange(PDiag->first, PDiag->first);
11070       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11071     }
11072 
11073     S.Diag(Templated->getLocation(),
11074            diag::note_ovl_candidate_substitution_failure)
11075         << TemplateArgString << SFINAEArgString << R;
11076     MaybeEmitInheritedConstructorNote(S, Found);
11077     return;
11078   }
11079 
11080   case Sema::TDK_DeducedMismatch:
11081   case Sema::TDK_DeducedMismatchNested: {
11082     // Format the template argument list into the argument string.
11083     SmallString<128> TemplateArgString;
11084     if (TemplateArgumentList *Args =
11085             DeductionFailure.getTemplateArgumentList()) {
11086       TemplateArgString = " ";
11087       TemplateArgString += S.getTemplateArgumentBindingsText(
11088           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11089       if (TemplateArgString.size() == 1)
11090         TemplateArgString.clear();
11091     }
11092 
11093     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11094         << (*DeductionFailure.getCallArgIndex() + 1)
11095         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11096         << TemplateArgString
11097         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11098     break;
11099   }
11100 
11101   case Sema::TDK_NonDeducedMismatch: {
11102     // FIXME: Provide a source location to indicate what we couldn't match.
11103     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11104     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11105     if (FirstTA.getKind() == TemplateArgument::Template &&
11106         SecondTA.getKind() == TemplateArgument::Template) {
11107       TemplateName FirstTN = FirstTA.getAsTemplate();
11108       TemplateName SecondTN = SecondTA.getAsTemplate();
11109       if (FirstTN.getKind() == TemplateName::Template &&
11110           SecondTN.getKind() == TemplateName::Template) {
11111         if (FirstTN.getAsTemplateDecl()->getName() ==
11112             SecondTN.getAsTemplateDecl()->getName()) {
11113           // FIXME: This fixes a bad diagnostic where both templates are named
11114           // the same.  This particular case is a bit difficult since:
11115           // 1) It is passed as a string to the diagnostic printer.
11116           // 2) The diagnostic printer only attempts to find a better
11117           //    name for types, not decls.
11118           // Ideally, this should folded into the diagnostic printer.
11119           S.Diag(Templated->getLocation(),
11120                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11121               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11122           return;
11123         }
11124       }
11125     }
11126 
11127     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11128         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11129       return;
11130 
11131     // FIXME: For generic lambda parameters, check if the function is a lambda
11132     // call operator, and if so, emit a prettier and more informative
11133     // diagnostic that mentions 'auto' and lambda in addition to
11134     // (or instead of?) the canonical template type parameters.
11135     S.Diag(Templated->getLocation(),
11136            diag::note_ovl_candidate_non_deduced_mismatch)
11137         << FirstTA << SecondTA;
11138     return;
11139   }
11140   // TODO: diagnose these individually, then kill off
11141   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11142   case Sema::TDK_MiscellaneousDeductionFailure:
11143     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11144     MaybeEmitInheritedConstructorNote(S, Found);
11145     return;
11146   case Sema::TDK_CUDATargetMismatch:
11147     S.Diag(Templated->getLocation(),
11148            diag::note_cuda_ovl_candidate_target_mismatch);
11149     return;
11150   }
11151 }
11152 
11153 /// Diagnose a failed template-argument deduction, for function calls.
11154 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11155                                  unsigned NumArgs,
11156                                  bool TakingCandidateAddress) {
11157   unsigned TDK = Cand->DeductionFailure.Result;
11158   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11159     if (CheckArityMismatch(S, Cand, NumArgs))
11160       return;
11161   }
11162   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11163                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11164 }
11165 
11166 /// CUDA: diagnose an invalid call across targets.
11167 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11168   FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11169   FunctionDecl *Callee = Cand->Function;
11170 
11171   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11172                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11173 
11174   std::string FnDesc;
11175   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11176       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11177                                 Cand->getRewriteKind(), FnDesc);
11178 
11179   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11180       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11181       << FnDesc /* Ignored */
11182       << CalleeTarget << CallerTarget;
11183 
11184   // This could be an implicit constructor for which we could not infer the
11185   // target due to a collsion. Diagnose that case.
11186   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11187   if (Meth != nullptr && Meth->isImplicit()) {
11188     CXXRecordDecl *ParentClass = Meth->getParent();
11189     Sema::CXXSpecialMember CSM;
11190 
11191     switch (FnKindPair.first) {
11192     default:
11193       return;
11194     case oc_implicit_default_constructor:
11195       CSM = Sema::CXXDefaultConstructor;
11196       break;
11197     case oc_implicit_copy_constructor:
11198       CSM = Sema::CXXCopyConstructor;
11199       break;
11200     case oc_implicit_move_constructor:
11201       CSM = Sema::CXXMoveConstructor;
11202       break;
11203     case oc_implicit_copy_assignment:
11204       CSM = Sema::CXXCopyAssignment;
11205       break;
11206     case oc_implicit_move_assignment:
11207       CSM = Sema::CXXMoveAssignment;
11208       break;
11209     };
11210 
11211     bool ConstRHS = false;
11212     if (Meth->getNumParams()) {
11213       if (const ReferenceType *RT =
11214               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11215         ConstRHS = RT->getPointeeType().isConstQualified();
11216       }
11217     }
11218 
11219     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11220                                               /* ConstRHS */ ConstRHS,
11221                                               /* Diagnose */ true);
11222   }
11223 }
11224 
11225 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11226   FunctionDecl *Callee = Cand->Function;
11227   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11228 
11229   S.Diag(Callee->getLocation(),
11230          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11231       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11232 }
11233 
11234 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11235   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11236   assert(ES.isExplicit() && "not an explicit candidate");
11237 
11238   unsigned Kind;
11239   switch (Cand->Function->getDeclKind()) {
11240   case Decl::Kind::CXXConstructor:
11241     Kind = 0;
11242     break;
11243   case Decl::Kind::CXXConversion:
11244     Kind = 1;
11245     break;
11246   case Decl::Kind::CXXDeductionGuide:
11247     Kind = Cand->Function->isImplicit() ? 0 : 2;
11248     break;
11249   default:
11250     llvm_unreachable("invalid Decl");
11251   }
11252 
11253   // Note the location of the first (in-class) declaration; a redeclaration
11254   // (particularly an out-of-class definition) will typically lack the
11255   // 'explicit' specifier.
11256   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11257   FunctionDecl *First = Cand->Function->getFirstDecl();
11258   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11259     First = Pattern->getFirstDecl();
11260 
11261   S.Diag(First->getLocation(),
11262          diag::note_ovl_candidate_explicit)
11263       << Kind << (ES.getExpr() ? 1 : 0)
11264       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11265 }
11266 
11267 /// Generates a 'note' diagnostic for an overload candidate.  We've
11268 /// already generated a primary error at the call site.
11269 ///
11270 /// It really does need to be a single diagnostic with its caret
11271 /// pointed at the candidate declaration.  Yes, this creates some
11272 /// major challenges of technical writing.  Yes, this makes pointing
11273 /// out problems with specific arguments quite awkward.  It's still
11274 /// better than generating twenty screens of text for every failed
11275 /// overload.
11276 ///
11277 /// It would be great to be able to express per-candidate problems
11278 /// more richly for those diagnostic clients that cared, but we'd
11279 /// still have to be just as careful with the default diagnostics.
11280 /// \param CtorDestAS Addr space of object being constructed (for ctor
11281 /// candidates only).
11282 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11283                                   unsigned NumArgs,
11284                                   bool TakingCandidateAddress,
11285                                   LangAS CtorDestAS = LangAS::Default) {
11286   FunctionDecl *Fn = Cand->Function;
11287   if (shouldSkipNotingLambdaConversionDecl(Fn))
11288     return;
11289 
11290   // There is no physical candidate declaration to point to for OpenCL builtins.
11291   // Except for failed conversions, the notes are identical for each candidate,
11292   // so do not generate such notes.
11293   if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
11294       Cand->FailureKind != ovl_fail_bad_conversion)
11295     return;
11296 
11297   // Note deleted candidates, but only if they're viable.
11298   if (Cand->Viable) {
11299     if (Fn->isDeleted()) {
11300       std::string FnDesc;
11301       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11302           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11303                                     Cand->getRewriteKind(), FnDesc);
11304 
11305       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11306           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11307           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11308       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11309       return;
11310     }
11311 
11312     // We don't really have anything else to say about viable candidates.
11313     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11314     return;
11315   }
11316 
11317   switch (Cand->FailureKind) {
11318   case ovl_fail_too_many_arguments:
11319   case ovl_fail_too_few_arguments:
11320     return DiagnoseArityMismatch(S, Cand, NumArgs);
11321 
11322   case ovl_fail_bad_deduction:
11323     return DiagnoseBadDeduction(S, Cand, NumArgs,
11324                                 TakingCandidateAddress);
11325 
11326   case ovl_fail_illegal_constructor: {
11327     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11328       << (Fn->getPrimaryTemplate() ? 1 : 0);
11329     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11330     return;
11331   }
11332 
11333   case ovl_fail_object_addrspace_mismatch: {
11334     Qualifiers QualsForPrinting;
11335     QualsForPrinting.setAddressSpace(CtorDestAS);
11336     S.Diag(Fn->getLocation(),
11337            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11338         << QualsForPrinting;
11339     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11340     return;
11341   }
11342 
11343   case ovl_fail_trivial_conversion:
11344   case ovl_fail_bad_final_conversion:
11345   case ovl_fail_final_conversion_not_exact:
11346     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11347 
11348   case ovl_fail_bad_conversion: {
11349     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11350     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11351       if (Cand->Conversions[I].isBad())
11352         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11353 
11354     // FIXME: this currently happens when we're called from SemaInit
11355     // when user-conversion overload fails.  Figure out how to handle
11356     // those conditions and diagnose them well.
11357     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11358   }
11359 
11360   case ovl_fail_bad_target:
11361     return DiagnoseBadTarget(S, Cand);
11362 
11363   case ovl_fail_enable_if:
11364     return DiagnoseFailedEnableIfAttr(S, Cand);
11365 
11366   case ovl_fail_explicit:
11367     return DiagnoseFailedExplicitSpec(S, Cand);
11368 
11369   case ovl_fail_inhctor_slice:
11370     // It's generally not interesting to note copy/move constructors here.
11371     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11372       return;
11373     S.Diag(Fn->getLocation(),
11374            diag::note_ovl_candidate_inherited_constructor_slice)
11375       << (Fn->getPrimaryTemplate() ? 1 : 0)
11376       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11377     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11378     return;
11379 
11380   case ovl_fail_addr_not_available: {
11381     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11382     (void)Available;
11383     assert(!Available);
11384     break;
11385   }
11386   case ovl_non_default_multiversion_function:
11387     // Do nothing, these should simply be ignored.
11388     break;
11389 
11390   case ovl_fail_constraints_not_satisfied: {
11391     std::string FnDesc;
11392     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11393         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11394                                   Cand->getRewriteKind(), FnDesc);
11395 
11396     S.Diag(Fn->getLocation(),
11397            diag::note_ovl_candidate_constraints_not_satisfied)
11398         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11399         << FnDesc /* Ignored */;
11400     ConstraintSatisfaction Satisfaction;
11401     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11402       break;
11403     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11404   }
11405   }
11406 }
11407 
11408 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11409   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11410     return;
11411 
11412   // Desugar the type of the surrogate down to a function type,
11413   // retaining as many typedefs as possible while still showing
11414   // the function type (and, therefore, its parameter types).
11415   QualType FnType = Cand->Surrogate->getConversionType();
11416   bool isLValueReference = false;
11417   bool isRValueReference = false;
11418   bool isPointer = false;
11419   if (const LValueReferenceType *FnTypeRef =
11420         FnType->getAs<LValueReferenceType>()) {
11421     FnType = FnTypeRef->getPointeeType();
11422     isLValueReference = true;
11423   } else if (const RValueReferenceType *FnTypeRef =
11424                FnType->getAs<RValueReferenceType>()) {
11425     FnType = FnTypeRef->getPointeeType();
11426     isRValueReference = true;
11427   }
11428   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11429     FnType = FnTypePtr->getPointeeType();
11430     isPointer = true;
11431   }
11432   // Desugar down to a function type.
11433   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11434   // Reconstruct the pointer/reference as appropriate.
11435   if (isPointer) FnType = S.Context.getPointerType(FnType);
11436   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11437   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11438 
11439   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11440     << FnType;
11441 }
11442 
11443 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11444                                          SourceLocation OpLoc,
11445                                          OverloadCandidate *Cand) {
11446   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11447   std::string TypeStr("operator");
11448   TypeStr += Opc;
11449   TypeStr += "(";
11450   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11451   if (Cand->Conversions.size() == 1) {
11452     TypeStr += ")";
11453     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11454   } else {
11455     TypeStr += ", ";
11456     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11457     TypeStr += ")";
11458     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11459   }
11460 }
11461 
11462 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11463                                          OverloadCandidate *Cand) {
11464   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11465     if (ICS.isBad()) break; // all meaningless after first invalid
11466     if (!ICS.isAmbiguous()) continue;
11467 
11468     ICS.DiagnoseAmbiguousConversion(
11469         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11470   }
11471 }
11472 
11473 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11474   if (Cand->Function)
11475     return Cand->Function->getLocation();
11476   if (Cand->IsSurrogate)
11477     return Cand->Surrogate->getLocation();
11478   return SourceLocation();
11479 }
11480 
11481 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11482   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11483   case Sema::TDK_Success:
11484   case Sema::TDK_NonDependentConversionFailure:
11485     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11486 
11487   case Sema::TDK_Invalid:
11488   case Sema::TDK_Incomplete:
11489   case Sema::TDK_IncompletePack:
11490     return 1;
11491 
11492   case Sema::TDK_Underqualified:
11493   case Sema::TDK_Inconsistent:
11494     return 2;
11495 
11496   case Sema::TDK_SubstitutionFailure:
11497   case Sema::TDK_DeducedMismatch:
11498   case Sema::TDK_ConstraintsNotSatisfied:
11499   case Sema::TDK_DeducedMismatchNested:
11500   case Sema::TDK_NonDeducedMismatch:
11501   case Sema::TDK_MiscellaneousDeductionFailure:
11502   case Sema::TDK_CUDATargetMismatch:
11503     return 3;
11504 
11505   case Sema::TDK_InstantiationDepth:
11506     return 4;
11507 
11508   case Sema::TDK_InvalidExplicitArguments:
11509     return 5;
11510 
11511   case Sema::TDK_TooManyArguments:
11512   case Sema::TDK_TooFewArguments:
11513     return 6;
11514   }
11515   llvm_unreachable("Unhandled deduction result");
11516 }
11517 
11518 namespace {
11519 struct CompareOverloadCandidatesForDisplay {
11520   Sema &S;
11521   SourceLocation Loc;
11522   size_t NumArgs;
11523   OverloadCandidateSet::CandidateSetKind CSK;
11524 
11525   CompareOverloadCandidatesForDisplay(
11526       Sema &S, SourceLocation Loc, size_t NArgs,
11527       OverloadCandidateSet::CandidateSetKind CSK)
11528       : S(S), NumArgs(NArgs), CSK(CSK) {}
11529 
11530   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11531     // If there are too many or too few arguments, that's the high-order bit we
11532     // want to sort by, even if the immediate failure kind was something else.
11533     if (C->FailureKind == ovl_fail_too_many_arguments ||
11534         C->FailureKind == ovl_fail_too_few_arguments)
11535       return static_cast<OverloadFailureKind>(C->FailureKind);
11536 
11537     if (C->Function) {
11538       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11539         return ovl_fail_too_many_arguments;
11540       if (NumArgs < C->Function->getMinRequiredArguments())
11541         return ovl_fail_too_few_arguments;
11542     }
11543 
11544     return static_cast<OverloadFailureKind>(C->FailureKind);
11545   }
11546 
11547   bool operator()(const OverloadCandidate *L,
11548                   const OverloadCandidate *R) {
11549     // Fast-path this check.
11550     if (L == R) return false;
11551 
11552     // Order first by viability.
11553     if (L->Viable) {
11554       if (!R->Viable) return true;
11555 
11556       // TODO: introduce a tri-valued comparison for overload
11557       // candidates.  Would be more worthwhile if we had a sort
11558       // that could exploit it.
11559       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11560         return true;
11561       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11562         return false;
11563     } else if (R->Viable)
11564       return false;
11565 
11566     assert(L->Viable == R->Viable);
11567 
11568     // Criteria by which we can sort non-viable candidates:
11569     if (!L->Viable) {
11570       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11571       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11572 
11573       // 1. Arity mismatches come after other candidates.
11574       if (LFailureKind == ovl_fail_too_many_arguments ||
11575           LFailureKind == ovl_fail_too_few_arguments) {
11576         if (RFailureKind == ovl_fail_too_many_arguments ||
11577             RFailureKind == ovl_fail_too_few_arguments) {
11578           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11579           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11580           if (LDist == RDist) {
11581             if (LFailureKind == RFailureKind)
11582               // Sort non-surrogates before surrogates.
11583               return !L->IsSurrogate && R->IsSurrogate;
11584             // Sort candidates requiring fewer parameters than there were
11585             // arguments given after candidates requiring more parameters
11586             // than there were arguments given.
11587             return LFailureKind == ovl_fail_too_many_arguments;
11588           }
11589           return LDist < RDist;
11590         }
11591         return false;
11592       }
11593       if (RFailureKind == ovl_fail_too_many_arguments ||
11594           RFailureKind == ovl_fail_too_few_arguments)
11595         return true;
11596 
11597       // 2. Bad conversions come first and are ordered by the number
11598       // of bad conversions and quality of good conversions.
11599       if (LFailureKind == ovl_fail_bad_conversion) {
11600         if (RFailureKind != ovl_fail_bad_conversion)
11601           return true;
11602 
11603         // The conversion that can be fixed with a smaller number of changes,
11604         // comes first.
11605         unsigned numLFixes = L->Fix.NumConversionsFixed;
11606         unsigned numRFixes = R->Fix.NumConversionsFixed;
11607         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11608         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11609         if (numLFixes != numRFixes) {
11610           return numLFixes < numRFixes;
11611         }
11612 
11613         // If there's any ordering between the defined conversions...
11614         // FIXME: this might not be transitive.
11615         assert(L->Conversions.size() == R->Conversions.size());
11616 
11617         int leftBetter = 0;
11618         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11619         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11620           switch (CompareImplicitConversionSequences(S, Loc,
11621                                                      L->Conversions[I],
11622                                                      R->Conversions[I])) {
11623           case ImplicitConversionSequence::Better:
11624             leftBetter++;
11625             break;
11626 
11627           case ImplicitConversionSequence::Worse:
11628             leftBetter--;
11629             break;
11630 
11631           case ImplicitConversionSequence::Indistinguishable:
11632             break;
11633           }
11634         }
11635         if (leftBetter > 0) return true;
11636         if (leftBetter < 0) return false;
11637 
11638       } else if (RFailureKind == ovl_fail_bad_conversion)
11639         return false;
11640 
11641       if (LFailureKind == ovl_fail_bad_deduction) {
11642         if (RFailureKind != ovl_fail_bad_deduction)
11643           return true;
11644 
11645         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11646           return RankDeductionFailure(L->DeductionFailure)
11647                < RankDeductionFailure(R->DeductionFailure);
11648       } else if (RFailureKind == ovl_fail_bad_deduction)
11649         return false;
11650 
11651       // TODO: others?
11652     }
11653 
11654     // Sort everything else by location.
11655     SourceLocation LLoc = GetLocationForCandidate(L);
11656     SourceLocation RLoc = GetLocationForCandidate(R);
11657 
11658     // Put candidates without locations (e.g. builtins) at the end.
11659     if (LLoc.isInvalid()) return false;
11660     if (RLoc.isInvalid()) return true;
11661 
11662     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11663   }
11664 };
11665 }
11666 
11667 /// CompleteNonViableCandidate - Normally, overload resolution only
11668 /// computes up to the first bad conversion. Produces the FixIt set if
11669 /// possible.
11670 static void
11671 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11672                            ArrayRef<Expr *> Args,
11673                            OverloadCandidateSet::CandidateSetKind CSK) {
11674   assert(!Cand->Viable);
11675 
11676   // Don't do anything on failures other than bad conversion.
11677   if (Cand->FailureKind != ovl_fail_bad_conversion)
11678     return;
11679 
11680   // We only want the FixIts if all the arguments can be corrected.
11681   bool Unfixable = false;
11682   // Use a implicit copy initialization to check conversion fixes.
11683   Cand->Fix.setConversionChecker(TryCopyInitialization);
11684 
11685   // Attempt to fix the bad conversion.
11686   unsigned ConvCount = Cand->Conversions.size();
11687   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11688        ++ConvIdx) {
11689     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11690     if (Cand->Conversions[ConvIdx].isInitialized() &&
11691         Cand->Conversions[ConvIdx].isBad()) {
11692       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11693       break;
11694     }
11695   }
11696 
11697   // FIXME: this should probably be preserved from the overload
11698   // operation somehow.
11699   bool SuppressUserConversions = false;
11700 
11701   unsigned ConvIdx = 0;
11702   unsigned ArgIdx = 0;
11703   ArrayRef<QualType> ParamTypes;
11704   bool Reversed = Cand->isReversed();
11705 
11706   if (Cand->IsSurrogate) {
11707     QualType ConvType
11708       = Cand->Surrogate->getConversionType().getNonReferenceType();
11709     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11710       ConvType = ConvPtrType->getPointeeType();
11711     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11712     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11713     ConvIdx = 1;
11714   } else if (Cand->Function) {
11715     ParamTypes =
11716         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11717     if (isa<CXXMethodDecl>(Cand->Function) &&
11718         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11719       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11720       ConvIdx = 1;
11721       if (CSK == OverloadCandidateSet::CSK_Operator &&
11722           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
11723           Cand->Function->getDeclName().getCXXOverloadedOperator() !=
11724               OO_Subscript)
11725         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11726         ArgIdx = 1;
11727     }
11728   } else {
11729     // Builtin operator.
11730     assert(ConvCount <= 3);
11731     ParamTypes = Cand->BuiltinParamTypes;
11732   }
11733 
11734   // Fill in the rest of the conversions.
11735   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11736        ConvIdx != ConvCount;
11737        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11738     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11739     if (Cand->Conversions[ConvIdx].isInitialized()) {
11740       // We've already checked this conversion.
11741     } else if (ParamIdx < ParamTypes.size()) {
11742       if (ParamTypes[ParamIdx]->isDependentType())
11743         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11744             Args[ArgIdx]->getType());
11745       else {
11746         Cand->Conversions[ConvIdx] =
11747             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11748                                   SuppressUserConversions,
11749                                   /*InOverloadResolution=*/true,
11750                                   /*AllowObjCWritebackConversion=*/
11751                                   S.getLangOpts().ObjCAutoRefCount);
11752         // Store the FixIt in the candidate if it exists.
11753         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11754           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11755       }
11756     } else
11757       Cand->Conversions[ConvIdx].setEllipsis();
11758   }
11759 }
11760 
11761 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11762     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11763     SourceLocation OpLoc,
11764     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11765   // Sort the candidates by viability and position.  Sorting directly would
11766   // be prohibitive, so we make a set of pointers and sort those.
11767   SmallVector<OverloadCandidate*, 32> Cands;
11768   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11769   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11770     if (!Filter(*Cand))
11771       continue;
11772     switch (OCD) {
11773     case OCD_AllCandidates:
11774       if (!Cand->Viable) {
11775         if (!Cand->Function && !Cand->IsSurrogate) {
11776           // This a non-viable builtin candidate.  We do not, in general,
11777           // want to list every possible builtin candidate.
11778           continue;
11779         }
11780         CompleteNonViableCandidate(S, Cand, Args, Kind);
11781       }
11782       break;
11783 
11784     case OCD_ViableCandidates:
11785       if (!Cand->Viable)
11786         continue;
11787       break;
11788 
11789     case OCD_AmbiguousCandidates:
11790       if (!Cand->Best)
11791         continue;
11792       break;
11793     }
11794 
11795     Cands.push_back(Cand);
11796   }
11797 
11798   llvm::stable_sort(
11799       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11800 
11801   return Cands;
11802 }
11803 
11804 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11805                                             SourceLocation OpLoc) {
11806   bool DeferHint = false;
11807   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11808     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11809     // host device candidates.
11810     auto WrongSidedCands =
11811         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11812           return (Cand.Viable == false &&
11813                   Cand.FailureKind == ovl_fail_bad_target) ||
11814                  (Cand.Function &&
11815                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11816                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11817         });
11818     DeferHint = !WrongSidedCands.empty();
11819   }
11820   return DeferHint;
11821 }
11822 
11823 /// When overload resolution fails, prints diagnostic messages containing the
11824 /// candidates in the candidate set.
11825 void OverloadCandidateSet::NoteCandidates(
11826     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11827     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11828     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11829 
11830   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11831 
11832   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11833 
11834   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11835 
11836   if (OCD == OCD_AmbiguousCandidates)
11837     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11838 }
11839 
11840 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11841                                           ArrayRef<OverloadCandidate *> Cands,
11842                                           StringRef Opc, SourceLocation OpLoc) {
11843   bool ReportedAmbiguousConversions = false;
11844 
11845   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11846   unsigned CandsShown = 0;
11847   auto I = Cands.begin(), E = Cands.end();
11848   for (; I != E; ++I) {
11849     OverloadCandidate *Cand = *I;
11850 
11851     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11852         ShowOverloads == Ovl_Best) {
11853       break;
11854     }
11855     ++CandsShown;
11856 
11857     if (Cand->Function)
11858       NoteFunctionCandidate(S, Cand, Args.size(),
11859                             /*TakingCandidateAddress=*/false, DestAS);
11860     else if (Cand->IsSurrogate)
11861       NoteSurrogateCandidate(S, Cand);
11862     else {
11863       assert(Cand->Viable &&
11864              "Non-viable built-in candidates are not added to Cands.");
11865       // Generally we only see ambiguities including viable builtin
11866       // operators if overload resolution got screwed up by an
11867       // ambiguous user-defined conversion.
11868       //
11869       // FIXME: It's quite possible for different conversions to see
11870       // different ambiguities, though.
11871       if (!ReportedAmbiguousConversions) {
11872         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11873         ReportedAmbiguousConversions = true;
11874       }
11875 
11876       // If this is a viable builtin, print it.
11877       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11878     }
11879   }
11880 
11881   // Inform S.Diags that we've shown an overload set with N elements.  This may
11882   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11883   S.Diags.overloadCandidatesShown(CandsShown);
11884 
11885   if (I != E)
11886     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11887            shouldDeferDiags(S, Args, OpLoc))
11888         << int(E - I);
11889 }
11890 
11891 static SourceLocation
11892 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11893   return Cand->Specialization ? Cand->Specialization->getLocation()
11894                               : SourceLocation();
11895 }
11896 
11897 namespace {
11898 struct CompareTemplateSpecCandidatesForDisplay {
11899   Sema &S;
11900   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11901 
11902   bool operator()(const TemplateSpecCandidate *L,
11903                   const TemplateSpecCandidate *R) {
11904     // Fast-path this check.
11905     if (L == R)
11906       return false;
11907 
11908     // Assuming that both candidates are not matches...
11909 
11910     // Sort by the ranking of deduction failures.
11911     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11912       return RankDeductionFailure(L->DeductionFailure) <
11913              RankDeductionFailure(R->DeductionFailure);
11914 
11915     // Sort everything else by location.
11916     SourceLocation LLoc = GetLocationForCandidate(L);
11917     SourceLocation RLoc = GetLocationForCandidate(R);
11918 
11919     // Put candidates without locations (e.g. builtins) at the end.
11920     if (LLoc.isInvalid())
11921       return false;
11922     if (RLoc.isInvalid())
11923       return true;
11924 
11925     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11926   }
11927 };
11928 }
11929 
11930 /// Diagnose a template argument deduction failure.
11931 /// We are treating these failures as overload failures due to bad
11932 /// deductions.
11933 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11934                                                  bool ForTakingAddress) {
11935   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11936                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11937 }
11938 
11939 void TemplateSpecCandidateSet::destroyCandidates() {
11940   for (iterator i = begin(), e = end(); i != e; ++i) {
11941     i->DeductionFailure.Destroy();
11942   }
11943 }
11944 
11945 void TemplateSpecCandidateSet::clear() {
11946   destroyCandidates();
11947   Candidates.clear();
11948 }
11949 
11950 /// NoteCandidates - When no template specialization match is found, prints
11951 /// diagnostic messages containing the non-matching specializations that form
11952 /// the candidate set.
11953 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11954 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11955 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11956   // Sort the candidates by position (assuming no candidate is a match).
11957   // Sorting directly would be prohibitive, so we make a set of pointers
11958   // and sort those.
11959   SmallVector<TemplateSpecCandidate *, 32> Cands;
11960   Cands.reserve(size());
11961   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11962     if (Cand->Specialization)
11963       Cands.push_back(Cand);
11964     // Otherwise, this is a non-matching builtin candidate.  We do not,
11965     // in general, want to list every possible builtin candidate.
11966   }
11967 
11968   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11969 
11970   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11971   // for generalization purposes (?).
11972   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11973 
11974   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11975   unsigned CandsShown = 0;
11976   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11977     TemplateSpecCandidate *Cand = *I;
11978 
11979     // Set an arbitrary limit on the number of candidates we'll spam
11980     // the user with.  FIXME: This limit should depend on details of the
11981     // candidate list.
11982     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11983       break;
11984     ++CandsShown;
11985 
11986     assert(Cand->Specialization &&
11987            "Non-matching built-in candidates are not added to Cands.");
11988     Cand->NoteDeductionFailure(S, ForTakingAddress);
11989   }
11990 
11991   if (I != E)
11992     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11993 }
11994 
11995 // [PossiblyAFunctionType]  -->   [Return]
11996 // NonFunctionType --> NonFunctionType
11997 // R (A) --> R(A)
11998 // R (*)(A) --> R (A)
11999 // R (&)(A) --> R (A)
12000 // R (S::*)(A) --> R (A)
12001 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12002   QualType Ret = PossiblyAFunctionType;
12003   if (const PointerType *ToTypePtr =
12004     PossiblyAFunctionType->getAs<PointerType>())
12005     Ret = ToTypePtr->getPointeeType();
12006   else if (const ReferenceType *ToTypeRef =
12007     PossiblyAFunctionType->getAs<ReferenceType>())
12008     Ret = ToTypeRef->getPointeeType();
12009   else if (const MemberPointerType *MemTypePtr =
12010     PossiblyAFunctionType->getAs<MemberPointerType>())
12011     Ret = MemTypePtr->getPointeeType();
12012   Ret =
12013     Context.getCanonicalType(Ret).getUnqualifiedType();
12014   return Ret;
12015 }
12016 
12017 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12018                                  bool Complain = true) {
12019   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12020       S.DeduceReturnType(FD, Loc, Complain))
12021     return true;
12022 
12023   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12024   if (S.getLangOpts().CPlusPlus17 &&
12025       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12026       !S.ResolveExceptionSpec(Loc, FPT))
12027     return true;
12028 
12029   return false;
12030 }
12031 
12032 namespace {
12033 // A helper class to help with address of function resolution
12034 // - allows us to avoid passing around all those ugly parameters
12035 class AddressOfFunctionResolver {
12036   Sema& S;
12037   Expr* SourceExpr;
12038   const QualType& TargetType;
12039   QualType TargetFunctionType; // Extracted function type from target type
12040 
12041   bool Complain;
12042   //DeclAccessPair& ResultFunctionAccessPair;
12043   ASTContext& Context;
12044 
12045   bool TargetTypeIsNonStaticMemberFunction;
12046   bool FoundNonTemplateFunction;
12047   bool StaticMemberFunctionFromBoundPointer;
12048   bool HasComplained;
12049 
12050   OverloadExpr::FindResult OvlExprInfo;
12051   OverloadExpr *OvlExpr;
12052   TemplateArgumentListInfo OvlExplicitTemplateArgs;
12053   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12054   TemplateSpecCandidateSet FailedCandidates;
12055 
12056 public:
12057   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12058                             const QualType &TargetType, bool Complain)
12059       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12060         Complain(Complain), Context(S.getASTContext()),
12061         TargetTypeIsNonStaticMemberFunction(
12062             !!TargetType->getAs<MemberPointerType>()),
12063         FoundNonTemplateFunction(false),
12064         StaticMemberFunctionFromBoundPointer(false),
12065         HasComplained(false),
12066         OvlExprInfo(OverloadExpr::find(SourceExpr)),
12067         OvlExpr(OvlExprInfo.Expression),
12068         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12069     ExtractUnqualifiedFunctionTypeFromTargetType();
12070 
12071     if (TargetFunctionType->isFunctionType()) {
12072       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12073         if (!UME->isImplicitAccess() &&
12074             !S.ResolveSingleFunctionTemplateSpecialization(UME))
12075           StaticMemberFunctionFromBoundPointer = true;
12076     } else if (OvlExpr->hasExplicitTemplateArgs()) {
12077       DeclAccessPair dap;
12078       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12079               OvlExpr, false, &dap)) {
12080         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12081           if (!Method->isStatic()) {
12082             // If the target type is a non-function type and the function found
12083             // is a non-static member function, pretend as if that was the
12084             // target, it's the only possible type to end up with.
12085             TargetTypeIsNonStaticMemberFunction = true;
12086 
12087             // And skip adding the function if its not in the proper form.
12088             // We'll diagnose this due to an empty set of functions.
12089             if (!OvlExprInfo.HasFormOfMemberPointer)
12090               return;
12091           }
12092 
12093         Matches.push_back(std::make_pair(dap, Fn));
12094       }
12095       return;
12096     }
12097 
12098     if (OvlExpr->hasExplicitTemplateArgs())
12099       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12100 
12101     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12102       // C++ [over.over]p4:
12103       //   If more than one function is selected, [...]
12104       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12105         if (FoundNonTemplateFunction)
12106           EliminateAllTemplateMatches();
12107         else
12108           EliminateAllExceptMostSpecializedTemplate();
12109       }
12110     }
12111 
12112     if (S.getLangOpts().CUDA && Matches.size() > 1)
12113       EliminateSuboptimalCudaMatches();
12114   }
12115 
12116   bool hasComplained() const { return HasComplained; }
12117 
12118 private:
12119   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12120     QualType Discard;
12121     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12122            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12123   }
12124 
12125   /// \return true if A is considered a better overload candidate for the
12126   /// desired type than B.
12127   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12128     // If A doesn't have exactly the correct type, we don't want to classify it
12129     // as "better" than anything else. This way, the user is required to
12130     // disambiguate for us if there are multiple candidates and no exact match.
12131     return candidateHasExactlyCorrectType(A) &&
12132            (!candidateHasExactlyCorrectType(B) ||
12133             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12134   }
12135 
12136   /// \return true if we were able to eliminate all but one overload candidate,
12137   /// false otherwise.
12138   bool eliminiateSuboptimalOverloadCandidates() {
12139     // Same algorithm as overload resolution -- one pass to pick the "best",
12140     // another pass to be sure that nothing is better than the best.
12141     auto Best = Matches.begin();
12142     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12143       if (isBetterCandidate(I->second, Best->second))
12144         Best = I;
12145 
12146     const FunctionDecl *BestFn = Best->second;
12147     auto IsBestOrInferiorToBest = [this, BestFn](
12148         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12149       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12150     };
12151 
12152     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12153     // option, so we can potentially give the user a better error
12154     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12155       return false;
12156     Matches[0] = *Best;
12157     Matches.resize(1);
12158     return true;
12159   }
12160 
12161   bool isTargetTypeAFunction() const {
12162     return TargetFunctionType->isFunctionType();
12163   }
12164 
12165   // [ToType]     [Return]
12166 
12167   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12168   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12169   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12170   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12171     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12172   }
12173 
12174   // return true if any matching specializations were found
12175   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12176                                    const DeclAccessPair& CurAccessFunPair) {
12177     if (CXXMethodDecl *Method
12178               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12179       // Skip non-static function templates when converting to pointer, and
12180       // static when converting to member pointer.
12181       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12182         return false;
12183     }
12184     else if (TargetTypeIsNonStaticMemberFunction)
12185       return false;
12186 
12187     // C++ [over.over]p2:
12188     //   If the name is a function template, template argument deduction is
12189     //   done (14.8.2.2), and if the argument deduction succeeds, the
12190     //   resulting template argument list is used to generate a single
12191     //   function template specialization, which is added to the set of
12192     //   overloaded functions considered.
12193     FunctionDecl *Specialization = nullptr;
12194     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12195     if (Sema::TemplateDeductionResult Result
12196           = S.DeduceTemplateArguments(FunctionTemplate,
12197                                       &OvlExplicitTemplateArgs,
12198                                       TargetFunctionType, Specialization,
12199                                       Info, /*IsAddressOfFunction*/true)) {
12200       // Make a note of the failed deduction for diagnostics.
12201       FailedCandidates.addCandidate()
12202           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12203                MakeDeductionFailureInfo(Context, Result, Info));
12204       return false;
12205     }
12206 
12207     // Template argument deduction ensures that we have an exact match or
12208     // compatible pointer-to-function arguments that would be adjusted by ICS.
12209     // This function template specicalization works.
12210     assert(S.isSameOrCompatibleFunctionType(
12211               Context.getCanonicalType(Specialization->getType()),
12212               Context.getCanonicalType(TargetFunctionType)));
12213 
12214     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12215       return false;
12216 
12217     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12218     return true;
12219   }
12220 
12221   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12222                                       const DeclAccessPair& CurAccessFunPair) {
12223     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12224       // Skip non-static functions when converting to pointer, and static
12225       // when converting to member pointer.
12226       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12227         return false;
12228     }
12229     else if (TargetTypeIsNonStaticMemberFunction)
12230       return false;
12231 
12232     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12233       if (S.getLangOpts().CUDA)
12234         if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
12235           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12236             return false;
12237       if (FunDecl->isMultiVersion()) {
12238         const auto *TA = FunDecl->getAttr<TargetAttr>();
12239         if (TA && !TA->isDefaultVersion())
12240           return false;
12241       }
12242 
12243       // If any candidate has a placeholder return type, trigger its deduction
12244       // now.
12245       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12246                                Complain)) {
12247         HasComplained |= Complain;
12248         return false;
12249       }
12250 
12251       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12252         return false;
12253 
12254       // If we're in C, we need to support types that aren't exactly identical.
12255       if (!S.getLangOpts().CPlusPlus ||
12256           candidateHasExactlyCorrectType(FunDecl)) {
12257         Matches.push_back(std::make_pair(
12258             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12259         FoundNonTemplateFunction = true;
12260         return true;
12261       }
12262     }
12263 
12264     return false;
12265   }
12266 
12267   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12268     bool Ret = false;
12269 
12270     // If the overload expression doesn't have the form of a pointer to
12271     // member, don't try to convert it to a pointer-to-member type.
12272     if (IsInvalidFormOfPointerToMemberFunction())
12273       return false;
12274 
12275     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12276                                E = OvlExpr->decls_end();
12277          I != E; ++I) {
12278       // Look through any using declarations to find the underlying function.
12279       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12280 
12281       // C++ [over.over]p3:
12282       //   Non-member functions and static member functions match
12283       //   targets of type "pointer-to-function" or "reference-to-function."
12284       //   Nonstatic member functions match targets of
12285       //   type "pointer-to-member-function."
12286       // Note that according to DR 247, the containing class does not matter.
12287       if (FunctionTemplateDecl *FunctionTemplate
12288                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12289         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12290           Ret = true;
12291       }
12292       // If we have explicit template arguments supplied, skip non-templates.
12293       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12294                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12295         Ret = true;
12296     }
12297     assert(Ret || Matches.empty());
12298     return Ret;
12299   }
12300 
12301   void EliminateAllExceptMostSpecializedTemplate() {
12302     //   [...] and any given function template specialization F1 is
12303     //   eliminated if the set contains a second function template
12304     //   specialization whose function template is more specialized
12305     //   than the function template of F1 according to the partial
12306     //   ordering rules of 14.5.5.2.
12307 
12308     // The algorithm specified above is quadratic. We instead use a
12309     // two-pass algorithm (similar to the one used to identify the
12310     // best viable function in an overload set) that identifies the
12311     // best function template (if it exists).
12312 
12313     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12314     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12315       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12316 
12317     // TODO: It looks like FailedCandidates does not serve much purpose
12318     // here, since the no_viable diagnostic has index 0.
12319     UnresolvedSetIterator Result = S.getMostSpecialized(
12320         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12321         SourceExpr->getBeginLoc(), S.PDiag(),
12322         S.PDiag(diag::err_addr_ovl_ambiguous)
12323             << Matches[0].second->getDeclName(),
12324         S.PDiag(diag::note_ovl_candidate)
12325             << (unsigned)oc_function << (unsigned)ocs_described_template,
12326         Complain, TargetFunctionType);
12327 
12328     if (Result != MatchesCopy.end()) {
12329       // Make it the first and only element
12330       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12331       Matches[0].second = cast<FunctionDecl>(*Result);
12332       Matches.resize(1);
12333     } else
12334       HasComplained |= Complain;
12335   }
12336 
12337   void EliminateAllTemplateMatches() {
12338     //   [...] any function template specializations in the set are
12339     //   eliminated if the set also contains a non-template function, [...]
12340     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12341       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12342         ++I;
12343       else {
12344         Matches[I] = Matches[--N];
12345         Matches.resize(N);
12346       }
12347     }
12348   }
12349 
12350   void EliminateSuboptimalCudaMatches() {
12351     S.EraseUnwantedCUDAMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
12352                                Matches);
12353   }
12354 
12355 public:
12356   void ComplainNoMatchesFound() const {
12357     assert(Matches.empty());
12358     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12359         << OvlExpr->getName() << TargetFunctionType
12360         << OvlExpr->getSourceRange();
12361     if (FailedCandidates.empty())
12362       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12363                                   /*TakingAddress=*/true);
12364     else {
12365       // We have some deduction failure messages. Use them to diagnose
12366       // the function templates, and diagnose the non-template candidates
12367       // normally.
12368       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12369                                  IEnd = OvlExpr->decls_end();
12370            I != IEnd; ++I)
12371         if (FunctionDecl *Fun =
12372                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12373           if (!functionHasPassObjectSizeParams(Fun))
12374             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12375                                     /*TakingAddress=*/true);
12376       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12377     }
12378   }
12379 
12380   bool IsInvalidFormOfPointerToMemberFunction() const {
12381     return TargetTypeIsNonStaticMemberFunction &&
12382       !OvlExprInfo.HasFormOfMemberPointer;
12383   }
12384 
12385   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12386       // TODO: Should we condition this on whether any functions might
12387       // have matched, or is it more appropriate to do that in callers?
12388       // TODO: a fixit wouldn't hurt.
12389       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12390         << TargetType << OvlExpr->getSourceRange();
12391   }
12392 
12393   bool IsStaticMemberFunctionFromBoundPointer() const {
12394     return StaticMemberFunctionFromBoundPointer;
12395   }
12396 
12397   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12398     S.Diag(OvlExpr->getBeginLoc(),
12399            diag::err_invalid_form_pointer_member_function)
12400         << OvlExpr->getSourceRange();
12401   }
12402 
12403   void ComplainOfInvalidConversion() const {
12404     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12405         << OvlExpr->getName() << TargetType;
12406   }
12407 
12408   void ComplainMultipleMatchesFound() const {
12409     assert(Matches.size() > 1);
12410     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12411         << OvlExpr->getName() << OvlExpr->getSourceRange();
12412     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12413                                 /*TakingAddress=*/true);
12414   }
12415 
12416   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12417 
12418   int getNumMatches() const { return Matches.size(); }
12419 
12420   FunctionDecl* getMatchingFunctionDecl() const {
12421     if (Matches.size() != 1) return nullptr;
12422     return Matches[0].second;
12423   }
12424 
12425   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12426     if (Matches.size() != 1) return nullptr;
12427     return &Matches[0].first;
12428   }
12429 };
12430 }
12431 
12432 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12433 /// an overloaded function (C++ [over.over]), where @p From is an
12434 /// expression with overloaded function type and @p ToType is the type
12435 /// we're trying to resolve to. For example:
12436 ///
12437 /// @code
12438 /// int f(double);
12439 /// int f(int);
12440 ///
12441 /// int (*pfd)(double) = f; // selects f(double)
12442 /// @endcode
12443 ///
12444 /// This routine returns the resulting FunctionDecl if it could be
12445 /// resolved, and NULL otherwise. When @p Complain is true, this
12446 /// routine will emit diagnostics if there is an error.
12447 FunctionDecl *
12448 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12449                                          QualType TargetType,
12450                                          bool Complain,
12451                                          DeclAccessPair &FoundResult,
12452                                          bool *pHadMultipleCandidates) {
12453   assert(AddressOfExpr->getType() == Context.OverloadTy);
12454 
12455   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12456                                      Complain);
12457   int NumMatches = Resolver.getNumMatches();
12458   FunctionDecl *Fn = nullptr;
12459   bool ShouldComplain = Complain && !Resolver.hasComplained();
12460   if (NumMatches == 0 && ShouldComplain) {
12461     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12462       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12463     else
12464       Resolver.ComplainNoMatchesFound();
12465   }
12466   else if (NumMatches > 1 && ShouldComplain)
12467     Resolver.ComplainMultipleMatchesFound();
12468   else if (NumMatches == 1) {
12469     Fn = Resolver.getMatchingFunctionDecl();
12470     assert(Fn);
12471     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12472       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12473     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12474     if (Complain) {
12475       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12476         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12477       else
12478         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12479     }
12480   }
12481 
12482   if (pHadMultipleCandidates)
12483     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12484   return Fn;
12485 }
12486 
12487 /// Given an expression that refers to an overloaded function, try to
12488 /// resolve that function to a single function that can have its address taken.
12489 /// This will modify `Pair` iff it returns non-null.
12490 ///
12491 /// This routine can only succeed if from all of the candidates in the overload
12492 /// set for SrcExpr that can have their addresses taken, there is one candidate
12493 /// that is more constrained than the rest.
12494 FunctionDecl *
12495 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12496   OverloadExpr::FindResult R = OverloadExpr::find(E);
12497   OverloadExpr *Ovl = R.Expression;
12498   bool IsResultAmbiguous = false;
12499   FunctionDecl *Result = nullptr;
12500   DeclAccessPair DAP;
12501   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12502 
12503   auto CheckMoreConstrained =
12504       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12505         SmallVector<const Expr *, 1> AC1, AC2;
12506         FD1->getAssociatedConstraints(AC1);
12507         FD2->getAssociatedConstraints(AC2);
12508         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12509         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12510           return None;
12511         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12512           return None;
12513         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12514           return None;
12515         return AtLeastAsConstrained1;
12516       };
12517 
12518   // Don't use the AddressOfResolver because we're specifically looking for
12519   // cases where we have one overload candidate that lacks
12520   // enable_if/pass_object_size/...
12521   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12522     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12523     if (!FD)
12524       return nullptr;
12525 
12526     if (!checkAddressOfFunctionIsAvailable(FD))
12527       continue;
12528 
12529     // We have more than one result - see if it is more constrained than the
12530     // previous one.
12531     if (Result) {
12532       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12533                                                                         Result);
12534       if (!MoreConstrainedThanPrevious) {
12535         IsResultAmbiguous = true;
12536         AmbiguousDecls.push_back(FD);
12537         continue;
12538       }
12539       if (!*MoreConstrainedThanPrevious)
12540         continue;
12541       // FD is more constrained - replace Result with it.
12542     }
12543     IsResultAmbiguous = false;
12544     DAP = I.getPair();
12545     Result = FD;
12546   }
12547 
12548   if (IsResultAmbiguous)
12549     return nullptr;
12550 
12551   if (Result) {
12552     SmallVector<const Expr *, 1> ResultAC;
12553     // We skipped over some ambiguous declarations which might be ambiguous with
12554     // the selected result.
12555     for (FunctionDecl *Skipped : AmbiguousDecls)
12556       if (!CheckMoreConstrained(Skipped, Result))
12557         return nullptr;
12558     Pair = DAP;
12559   }
12560   return Result;
12561 }
12562 
12563 /// Given an overloaded function, tries to turn it into a non-overloaded
12564 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12565 /// will perform access checks, diagnose the use of the resultant decl, and, if
12566 /// requested, potentially perform a function-to-pointer decay.
12567 ///
12568 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12569 /// Otherwise, returns true. This may emit diagnostics and return true.
12570 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12571     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12572   Expr *E = SrcExpr.get();
12573   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12574 
12575   DeclAccessPair DAP;
12576   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12577   if (!Found || Found->isCPUDispatchMultiVersion() ||
12578       Found->isCPUSpecificMultiVersion())
12579     return false;
12580 
12581   // Emitting multiple diagnostics for a function that is both inaccessible and
12582   // unavailable is consistent with our behavior elsewhere. So, always check
12583   // for both.
12584   DiagnoseUseOfDecl(Found, E->getExprLoc());
12585   CheckAddressOfMemberAccess(E, DAP);
12586   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12587   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12588     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12589   else
12590     SrcExpr = Fixed;
12591   return true;
12592 }
12593 
12594 /// Given an expression that refers to an overloaded function, try to
12595 /// resolve that overloaded function expression down to a single function.
12596 ///
12597 /// This routine can only resolve template-ids that refer to a single function
12598 /// template, where that template-id refers to a single template whose template
12599 /// arguments are either provided by the template-id or have defaults,
12600 /// as described in C++0x [temp.arg.explicit]p3.
12601 ///
12602 /// If no template-ids are found, no diagnostics are emitted and NULL is
12603 /// returned.
12604 FunctionDecl *
12605 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12606                                                   bool Complain,
12607                                                   DeclAccessPair *FoundResult) {
12608   // C++ [over.over]p1:
12609   //   [...] [Note: any redundant set of parentheses surrounding the
12610   //   overloaded function name is ignored (5.1). ]
12611   // C++ [over.over]p1:
12612   //   [...] The overloaded function name can be preceded by the &
12613   //   operator.
12614 
12615   // If we didn't actually find any template-ids, we're done.
12616   if (!ovl->hasExplicitTemplateArgs())
12617     return nullptr;
12618 
12619   TemplateArgumentListInfo ExplicitTemplateArgs;
12620   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12621   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12622 
12623   // Look through all of the overloaded functions, searching for one
12624   // whose type matches exactly.
12625   FunctionDecl *Matched = nullptr;
12626   for (UnresolvedSetIterator I = ovl->decls_begin(),
12627          E = ovl->decls_end(); I != E; ++I) {
12628     // C++0x [temp.arg.explicit]p3:
12629     //   [...] In contexts where deduction is done and fails, or in contexts
12630     //   where deduction is not done, if a template argument list is
12631     //   specified and it, along with any default template arguments,
12632     //   identifies a single function template specialization, then the
12633     //   template-id is an lvalue for the function template specialization.
12634     FunctionTemplateDecl *FunctionTemplate
12635       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12636 
12637     // C++ [over.over]p2:
12638     //   If the name is a function template, template argument deduction is
12639     //   done (14.8.2.2), and if the argument deduction succeeds, the
12640     //   resulting template argument list is used to generate a single
12641     //   function template specialization, which is added to the set of
12642     //   overloaded functions considered.
12643     FunctionDecl *Specialization = nullptr;
12644     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12645     if (TemplateDeductionResult Result
12646           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12647                                     Specialization, Info,
12648                                     /*IsAddressOfFunction*/true)) {
12649       // Make a note of the failed deduction for diagnostics.
12650       // TODO: Actually use the failed-deduction info?
12651       FailedCandidates.addCandidate()
12652           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12653                MakeDeductionFailureInfo(Context, Result, Info));
12654       continue;
12655     }
12656 
12657     assert(Specialization && "no specialization and no error?");
12658 
12659     // Multiple matches; we can't resolve to a single declaration.
12660     if (Matched) {
12661       if (Complain) {
12662         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12663           << ovl->getName();
12664         NoteAllOverloadCandidates(ovl);
12665       }
12666       return nullptr;
12667     }
12668 
12669     Matched = Specialization;
12670     if (FoundResult) *FoundResult = I.getPair();
12671   }
12672 
12673   if (Matched &&
12674       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12675     return nullptr;
12676 
12677   return Matched;
12678 }
12679 
12680 // Resolve and fix an overloaded expression that can be resolved
12681 // because it identifies a single function template specialization.
12682 //
12683 // Last three arguments should only be supplied if Complain = true
12684 //
12685 // Return true if it was logically possible to so resolve the
12686 // expression, regardless of whether or not it succeeded.  Always
12687 // returns true if 'complain' is set.
12688 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12689                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12690                       bool complain, SourceRange OpRangeForComplaining,
12691                                            QualType DestTypeForComplaining,
12692                                             unsigned DiagIDForComplaining) {
12693   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12694 
12695   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12696 
12697   DeclAccessPair found;
12698   ExprResult SingleFunctionExpression;
12699   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12700                            ovl.Expression, /*complain*/ false, &found)) {
12701     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12702       SrcExpr = ExprError();
12703       return true;
12704     }
12705 
12706     // It is only correct to resolve to an instance method if we're
12707     // resolving a form that's permitted to be a pointer to member.
12708     // Otherwise we'll end up making a bound member expression, which
12709     // is illegal in all the contexts we resolve like this.
12710     if (!ovl.HasFormOfMemberPointer &&
12711         isa<CXXMethodDecl>(fn) &&
12712         cast<CXXMethodDecl>(fn)->isInstance()) {
12713       if (!complain) return false;
12714 
12715       Diag(ovl.Expression->getExprLoc(),
12716            diag::err_bound_member_function)
12717         << 0 << ovl.Expression->getSourceRange();
12718 
12719       // TODO: I believe we only end up here if there's a mix of
12720       // static and non-static candidates (otherwise the expression
12721       // would have 'bound member' type, not 'overload' type).
12722       // Ideally we would note which candidate was chosen and why
12723       // the static candidates were rejected.
12724       SrcExpr = ExprError();
12725       return true;
12726     }
12727 
12728     // Fix the expression to refer to 'fn'.
12729     SingleFunctionExpression =
12730         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12731 
12732     // If desired, do function-to-pointer decay.
12733     if (doFunctionPointerConverion) {
12734       SingleFunctionExpression =
12735         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12736       if (SingleFunctionExpression.isInvalid()) {
12737         SrcExpr = ExprError();
12738         return true;
12739       }
12740     }
12741   }
12742 
12743   if (!SingleFunctionExpression.isUsable()) {
12744     if (complain) {
12745       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12746         << ovl.Expression->getName()
12747         << DestTypeForComplaining
12748         << OpRangeForComplaining
12749         << ovl.Expression->getQualifierLoc().getSourceRange();
12750       NoteAllOverloadCandidates(SrcExpr.get());
12751 
12752       SrcExpr = ExprError();
12753       return true;
12754     }
12755 
12756     return false;
12757   }
12758 
12759   SrcExpr = SingleFunctionExpression;
12760   return true;
12761 }
12762 
12763 /// Add a single candidate to the overload set.
12764 static void AddOverloadedCallCandidate(Sema &S,
12765                                        DeclAccessPair FoundDecl,
12766                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12767                                        ArrayRef<Expr *> Args,
12768                                        OverloadCandidateSet &CandidateSet,
12769                                        bool PartialOverloading,
12770                                        bool KnownValid) {
12771   NamedDecl *Callee = FoundDecl.getDecl();
12772   if (isa<UsingShadowDecl>(Callee))
12773     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12774 
12775   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12776     if (ExplicitTemplateArgs) {
12777       assert(!KnownValid && "Explicit template arguments?");
12778       return;
12779     }
12780     // Prevent ill-formed function decls to be added as overload candidates.
12781     if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12782       return;
12783 
12784     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12785                            /*SuppressUserConversions=*/false,
12786                            PartialOverloading);
12787     return;
12788   }
12789 
12790   if (FunctionTemplateDecl *FuncTemplate
12791       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12792     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12793                                    ExplicitTemplateArgs, Args, CandidateSet,
12794                                    /*SuppressUserConversions=*/false,
12795                                    PartialOverloading);
12796     return;
12797   }
12798 
12799   assert(!KnownValid && "unhandled case in overloaded call candidate");
12800 }
12801 
12802 /// Add the overload candidates named by callee and/or found by argument
12803 /// dependent lookup to the given overload set.
12804 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12805                                        ArrayRef<Expr *> Args,
12806                                        OverloadCandidateSet &CandidateSet,
12807                                        bool PartialOverloading) {
12808 
12809 #ifndef NDEBUG
12810   // Verify that ArgumentDependentLookup is consistent with the rules
12811   // in C++0x [basic.lookup.argdep]p3:
12812   //
12813   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12814   //   and let Y be the lookup set produced by argument dependent
12815   //   lookup (defined as follows). If X contains
12816   //
12817   //     -- a declaration of a class member, or
12818   //
12819   //     -- a block-scope function declaration that is not a
12820   //        using-declaration, or
12821   //
12822   //     -- a declaration that is neither a function or a function
12823   //        template
12824   //
12825   //   then Y is empty.
12826 
12827   if (ULE->requiresADL()) {
12828     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12829            E = ULE->decls_end(); I != E; ++I) {
12830       assert(!(*I)->getDeclContext()->isRecord());
12831       assert(isa<UsingShadowDecl>(*I) ||
12832              !(*I)->getDeclContext()->isFunctionOrMethod());
12833       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12834     }
12835   }
12836 #endif
12837 
12838   // It would be nice to avoid this copy.
12839   TemplateArgumentListInfo TABuffer;
12840   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12841   if (ULE->hasExplicitTemplateArgs()) {
12842     ULE->copyTemplateArgumentsInto(TABuffer);
12843     ExplicitTemplateArgs = &TABuffer;
12844   }
12845 
12846   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12847          E = ULE->decls_end(); I != E; ++I)
12848     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12849                                CandidateSet, PartialOverloading,
12850                                /*KnownValid*/ true);
12851 
12852   if (ULE->requiresADL())
12853     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12854                                          Args, ExplicitTemplateArgs,
12855                                          CandidateSet, PartialOverloading);
12856 }
12857 
12858 /// Add the call candidates from the given set of lookup results to the given
12859 /// overload set. Non-function lookup results are ignored.
12860 void Sema::AddOverloadedCallCandidates(
12861     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12862     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12863   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12864     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12865                                CandidateSet, false, /*KnownValid*/ false);
12866 }
12867 
12868 /// Determine whether a declaration with the specified name could be moved into
12869 /// a different namespace.
12870 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12871   switch (Name.getCXXOverloadedOperator()) {
12872   case OO_New: case OO_Array_New:
12873   case OO_Delete: case OO_Array_Delete:
12874     return false;
12875 
12876   default:
12877     return true;
12878   }
12879 }
12880 
12881 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12882 /// template, where the non-dependent name was declared after the template
12883 /// was defined. This is common in code written for a compilers which do not
12884 /// correctly implement two-stage name lookup.
12885 ///
12886 /// Returns true if a viable candidate was found and a diagnostic was issued.
12887 static bool DiagnoseTwoPhaseLookup(
12888     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12889     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12890     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12891     CXXRecordDecl **FoundInClass = nullptr) {
12892   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12893     return false;
12894 
12895   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12896     if (DC->isTransparentContext())
12897       continue;
12898 
12899     SemaRef.LookupQualifiedName(R, DC);
12900 
12901     if (!R.empty()) {
12902       R.suppressDiagnostics();
12903 
12904       OverloadCandidateSet Candidates(FnLoc, CSK);
12905       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12906                                           Candidates);
12907 
12908       OverloadCandidateSet::iterator Best;
12909       OverloadingResult OR =
12910           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12911 
12912       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12913         // We either found non-function declarations or a best viable function
12914         // at class scope. A class-scope lookup result disables ADL. Don't
12915         // look past this, but let the caller know that we found something that
12916         // either is, or might be, usable in this class.
12917         if (FoundInClass) {
12918           *FoundInClass = RD;
12919           if (OR == OR_Success) {
12920             R.clear();
12921             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12922             R.resolveKind();
12923           }
12924         }
12925         return false;
12926       }
12927 
12928       if (OR != OR_Success) {
12929         // There wasn't a unique best function or function template.
12930         return false;
12931       }
12932 
12933       // Find the namespaces where ADL would have looked, and suggest
12934       // declaring the function there instead.
12935       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12936       Sema::AssociatedClassSet AssociatedClasses;
12937       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12938                                                  AssociatedNamespaces,
12939                                                  AssociatedClasses);
12940       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12941       if (canBeDeclaredInNamespace(R.getLookupName())) {
12942         DeclContext *Std = SemaRef.getStdNamespace();
12943         for (Sema::AssociatedNamespaceSet::iterator
12944                it = AssociatedNamespaces.begin(),
12945                end = AssociatedNamespaces.end(); it != end; ++it) {
12946           // Never suggest declaring a function within namespace 'std'.
12947           if (Std && Std->Encloses(*it))
12948             continue;
12949 
12950           // Never suggest declaring a function within a namespace with a
12951           // reserved name, like __gnu_cxx.
12952           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12953           if (NS &&
12954               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12955             continue;
12956 
12957           SuggestedNamespaces.insert(*it);
12958         }
12959       }
12960 
12961       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12962         << R.getLookupName();
12963       if (SuggestedNamespaces.empty()) {
12964         SemaRef.Diag(Best->Function->getLocation(),
12965                      diag::note_not_found_by_two_phase_lookup)
12966           << R.getLookupName() << 0;
12967       } else if (SuggestedNamespaces.size() == 1) {
12968         SemaRef.Diag(Best->Function->getLocation(),
12969                      diag::note_not_found_by_two_phase_lookup)
12970           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12971       } else {
12972         // FIXME: It would be useful to list the associated namespaces here,
12973         // but the diagnostics infrastructure doesn't provide a way to produce
12974         // a localized representation of a list of items.
12975         SemaRef.Diag(Best->Function->getLocation(),
12976                      diag::note_not_found_by_two_phase_lookup)
12977           << R.getLookupName() << 2;
12978       }
12979 
12980       // Try to recover by calling this function.
12981       return true;
12982     }
12983 
12984     R.clear();
12985   }
12986 
12987   return false;
12988 }
12989 
12990 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12991 /// template, where the non-dependent operator was declared after the template
12992 /// was defined.
12993 ///
12994 /// Returns true if a viable candidate was found and a diagnostic was issued.
12995 static bool
12996 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12997                                SourceLocation OpLoc,
12998                                ArrayRef<Expr *> Args) {
12999   DeclarationName OpName =
13000     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13001   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13002   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13003                                 OverloadCandidateSet::CSK_Operator,
13004                                 /*ExplicitTemplateArgs=*/nullptr, Args);
13005 }
13006 
13007 namespace {
13008 class BuildRecoveryCallExprRAII {
13009   Sema &SemaRef;
13010 public:
13011   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
13012     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13013     SemaRef.IsBuildingRecoveryCallExpr = true;
13014   }
13015 
13016   ~BuildRecoveryCallExprRAII() {
13017     SemaRef.IsBuildingRecoveryCallExpr = false;
13018   }
13019 };
13020 
13021 }
13022 
13023 /// Attempts to recover from a call where no functions were found.
13024 ///
13025 /// This function will do one of three things:
13026 ///  * Diagnose, recover, and return a recovery expression.
13027 ///  * Diagnose, fail to recover, and return ExprError().
13028 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
13029 ///    expected to diagnose as appropriate.
13030 static ExprResult
13031 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13032                       UnresolvedLookupExpr *ULE,
13033                       SourceLocation LParenLoc,
13034                       MutableArrayRef<Expr *> Args,
13035                       SourceLocation RParenLoc,
13036                       bool EmptyLookup, bool AllowTypoCorrection) {
13037   // Do not try to recover if it is already building a recovery call.
13038   // This stops infinite loops for template instantiations like
13039   //
13040   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13041   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13042   if (SemaRef.IsBuildingRecoveryCallExpr)
13043     return ExprResult();
13044   BuildRecoveryCallExprRAII RCE(SemaRef);
13045 
13046   CXXScopeSpec SS;
13047   SS.Adopt(ULE->getQualifierLoc());
13048   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13049 
13050   TemplateArgumentListInfo TABuffer;
13051   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13052   if (ULE->hasExplicitTemplateArgs()) {
13053     ULE->copyTemplateArgumentsInto(TABuffer);
13054     ExplicitTemplateArgs = &TABuffer;
13055   }
13056 
13057   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13058                  Sema::LookupOrdinaryName);
13059   CXXRecordDecl *FoundInClass = nullptr;
13060   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13061                              OverloadCandidateSet::CSK_Normal,
13062                              ExplicitTemplateArgs, Args, &FoundInClass)) {
13063     // OK, diagnosed a two-phase lookup issue.
13064   } else if (EmptyLookup) {
13065     // Try to recover from an empty lookup with typo correction.
13066     R.clear();
13067     NoTypoCorrectionCCC NoTypoValidator{};
13068     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13069                                                 ExplicitTemplateArgs != nullptr,
13070                                                 dyn_cast<MemberExpr>(Fn));
13071     CorrectionCandidateCallback &Validator =
13072         AllowTypoCorrection
13073             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13074             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13075     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13076                                     Args))
13077       return ExprError();
13078   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13079     // We found a usable declaration of the name in a dependent base of some
13080     // enclosing class.
13081     // FIXME: We should also explain why the candidates found by name lookup
13082     // were not viable.
13083     if (SemaRef.DiagnoseDependentMemberLookup(R))
13084       return ExprError();
13085   } else {
13086     // We had viable candidates and couldn't recover; let the caller diagnose
13087     // this.
13088     return ExprResult();
13089   }
13090 
13091   // If we get here, we should have issued a diagnostic and formed a recovery
13092   // lookup result.
13093   assert(!R.empty() && "lookup results empty despite recovery");
13094 
13095   // If recovery created an ambiguity, just bail out.
13096   if (R.isAmbiguous()) {
13097     R.suppressDiagnostics();
13098     return ExprError();
13099   }
13100 
13101   // Build an implicit member call if appropriate.  Just drop the
13102   // casts and such from the call, we don't really care.
13103   ExprResult NewFn = ExprError();
13104   if ((*R.begin())->isCXXClassMember())
13105     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13106                                                     ExplicitTemplateArgs, S);
13107   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13108     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13109                                         ExplicitTemplateArgs);
13110   else
13111     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13112 
13113   if (NewFn.isInvalid())
13114     return ExprError();
13115 
13116   // This shouldn't cause an infinite loop because we're giving it
13117   // an expression with viable lookup results, which should never
13118   // end up here.
13119   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13120                                MultiExprArg(Args.data(), Args.size()),
13121                                RParenLoc);
13122 }
13123 
13124 /// Constructs and populates an OverloadedCandidateSet from
13125 /// the given function.
13126 /// \returns true when an the ExprResult output parameter has been set.
13127 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13128                                   UnresolvedLookupExpr *ULE,
13129                                   MultiExprArg Args,
13130                                   SourceLocation RParenLoc,
13131                                   OverloadCandidateSet *CandidateSet,
13132                                   ExprResult *Result) {
13133 #ifndef NDEBUG
13134   if (ULE->requiresADL()) {
13135     // To do ADL, we must have found an unqualified name.
13136     assert(!ULE->getQualifier() && "qualified name with ADL");
13137 
13138     // We don't perform ADL for implicit declarations of builtins.
13139     // Verify that this was correctly set up.
13140     FunctionDecl *F;
13141     if (ULE->decls_begin() != ULE->decls_end() &&
13142         ULE->decls_begin() + 1 == ULE->decls_end() &&
13143         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13144         F->getBuiltinID() && F->isImplicit())
13145       llvm_unreachable("performing ADL for builtin");
13146 
13147     // We don't perform ADL in C.
13148     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13149   }
13150 #endif
13151 
13152   UnbridgedCastsSet UnbridgedCasts;
13153   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13154     *Result = ExprError();
13155     return true;
13156   }
13157 
13158   // Add the functions denoted by the callee to the set of candidate
13159   // functions, including those from argument-dependent lookup.
13160   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13161 
13162   if (getLangOpts().MSVCCompat &&
13163       CurContext->isDependentContext() && !isSFINAEContext() &&
13164       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13165 
13166     OverloadCandidateSet::iterator Best;
13167     if (CandidateSet->empty() ||
13168         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13169             OR_No_Viable_Function) {
13170       // In Microsoft mode, if we are inside a template class member function
13171       // then create a type dependent CallExpr. The goal is to postpone name
13172       // lookup to instantiation time to be able to search into type dependent
13173       // base classes.
13174       CallExpr *CE =
13175           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13176                            RParenLoc, CurFPFeatureOverrides());
13177       CE->markDependentForPostponedNameLookup();
13178       *Result = CE;
13179       return true;
13180     }
13181   }
13182 
13183   if (CandidateSet->empty())
13184     return false;
13185 
13186   UnbridgedCasts.restore();
13187   return false;
13188 }
13189 
13190 // Guess at what the return type for an unresolvable overload should be.
13191 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13192                                    OverloadCandidateSet::iterator *Best) {
13193   llvm::Optional<QualType> Result;
13194   // Adjust Type after seeing a candidate.
13195   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13196     if (!Candidate.Function)
13197       return;
13198     if (Candidate.Function->isInvalidDecl())
13199       return;
13200     QualType T = Candidate.Function->getReturnType();
13201     if (T.isNull())
13202       return;
13203     if (!Result)
13204       Result = T;
13205     else if (Result != T)
13206       Result = QualType();
13207   };
13208 
13209   // Look for an unambiguous type from a progressively larger subset.
13210   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13211   //
13212   // First, consider only the best candidate.
13213   if (Best && *Best != CS.end())
13214     ConsiderCandidate(**Best);
13215   // Next, consider only viable candidates.
13216   if (!Result)
13217     for (const auto &C : CS)
13218       if (C.Viable)
13219         ConsiderCandidate(C);
13220   // Finally, consider all candidates.
13221   if (!Result)
13222     for (const auto &C : CS)
13223       ConsiderCandidate(C);
13224 
13225   if (!Result)
13226     return QualType();
13227   auto Value = *Result;
13228   if (Value.isNull() || Value->isUndeducedType())
13229     return QualType();
13230   return Value;
13231 }
13232 
13233 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13234 /// the completed call expression. If overload resolution fails, emits
13235 /// diagnostics and returns ExprError()
13236 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13237                                            UnresolvedLookupExpr *ULE,
13238                                            SourceLocation LParenLoc,
13239                                            MultiExprArg Args,
13240                                            SourceLocation RParenLoc,
13241                                            Expr *ExecConfig,
13242                                            OverloadCandidateSet *CandidateSet,
13243                                            OverloadCandidateSet::iterator *Best,
13244                                            OverloadingResult OverloadResult,
13245                                            bool AllowTypoCorrection) {
13246   switch (OverloadResult) {
13247   case OR_Success: {
13248     FunctionDecl *FDecl = (*Best)->Function;
13249     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13250     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13251       return ExprError();
13252     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13253     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13254                                          ExecConfig, /*IsExecConfig=*/false,
13255                                          (*Best)->IsADLCandidate);
13256   }
13257 
13258   case OR_No_Viable_Function: {
13259     // Try to recover by looking for viable functions which the user might
13260     // have meant to call.
13261     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13262                                                 Args, RParenLoc,
13263                                                 CandidateSet->empty(),
13264                                                 AllowTypoCorrection);
13265     if (Recovery.isInvalid() || Recovery.isUsable())
13266       return Recovery;
13267 
13268     // If the user passes in a function that we can't take the address of, we
13269     // generally end up emitting really bad error messages. Here, we attempt to
13270     // emit better ones.
13271     for (const Expr *Arg : Args) {
13272       if (!Arg->getType()->isFunctionType())
13273         continue;
13274       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13275         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13276         if (FD &&
13277             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13278                                                        Arg->getExprLoc()))
13279           return ExprError();
13280       }
13281     }
13282 
13283     CandidateSet->NoteCandidates(
13284         PartialDiagnosticAt(
13285             Fn->getBeginLoc(),
13286             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13287                 << ULE->getName() << Fn->getSourceRange()),
13288         SemaRef, OCD_AllCandidates, Args);
13289     break;
13290   }
13291 
13292   case OR_Ambiguous:
13293     CandidateSet->NoteCandidates(
13294         PartialDiagnosticAt(Fn->getBeginLoc(),
13295                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13296                                 << ULE->getName() << Fn->getSourceRange()),
13297         SemaRef, OCD_AmbiguousCandidates, Args);
13298     break;
13299 
13300   case OR_Deleted: {
13301     CandidateSet->NoteCandidates(
13302         PartialDiagnosticAt(Fn->getBeginLoc(),
13303                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13304                                 << ULE->getName() << Fn->getSourceRange()),
13305         SemaRef, OCD_AllCandidates, Args);
13306 
13307     // We emitted an error for the unavailable/deleted function call but keep
13308     // the call in the AST.
13309     FunctionDecl *FDecl = (*Best)->Function;
13310     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13311     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13312                                          ExecConfig, /*IsExecConfig=*/false,
13313                                          (*Best)->IsADLCandidate);
13314   }
13315   }
13316 
13317   // Overload resolution failed, try to recover.
13318   SmallVector<Expr *, 8> SubExprs = {Fn};
13319   SubExprs.append(Args.begin(), Args.end());
13320   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13321                                     chooseRecoveryType(*CandidateSet, Best));
13322 }
13323 
13324 static void markUnaddressableCandidatesUnviable(Sema &S,
13325                                                 OverloadCandidateSet &CS) {
13326   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13327     if (I->Viable &&
13328         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13329       I->Viable = false;
13330       I->FailureKind = ovl_fail_addr_not_available;
13331     }
13332   }
13333 }
13334 
13335 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13336 /// (which eventually refers to the declaration Func) and the call
13337 /// arguments Args/NumArgs, attempt to resolve the function call down
13338 /// to a specific function. If overload resolution succeeds, returns
13339 /// the call expression produced by overload resolution.
13340 /// Otherwise, emits diagnostics and returns ExprError.
13341 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13342                                          UnresolvedLookupExpr *ULE,
13343                                          SourceLocation LParenLoc,
13344                                          MultiExprArg Args,
13345                                          SourceLocation RParenLoc,
13346                                          Expr *ExecConfig,
13347                                          bool AllowTypoCorrection,
13348                                          bool CalleesAddressIsTaken) {
13349   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13350                                     OverloadCandidateSet::CSK_Normal);
13351   ExprResult result;
13352 
13353   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13354                              &result))
13355     return result;
13356 
13357   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13358   // functions that aren't addressible are considered unviable.
13359   if (CalleesAddressIsTaken)
13360     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13361 
13362   OverloadCandidateSet::iterator Best;
13363   OverloadingResult OverloadResult =
13364       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13365 
13366   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13367                                   ExecConfig, &CandidateSet, &Best,
13368                                   OverloadResult, AllowTypoCorrection);
13369 }
13370 
13371 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13372   return Functions.size() > 1 ||
13373          (Functions.size() == 1 &&
13374           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13375 }
13376 
13377 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13378                                             NestedNameSpecifierLoc NNSLoc,
13379                                             DeclarationNameInfo DNI,
13380                                             const UnresolvedSetImpl &Fns,
13381                                             bool PerformADL) {
13382   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13383                                       PerformADL, IsOverloaded(Fns),
13384                                       Fns.begin(), Fns.end());
13385 }
13386 
13387 /// Create a unary operation that may resolve to an overloaded
13388 /// operator.
13389 ///
13390 /// \param OpLoc The location of the operator itself (e.g., '*').
13391 ///
13392 /// \param Opc The UnaryOperatorKind that describes this operator.
13393 ///
13394 /// \param Fns The set of non-member functions that will be
13395 /// considered by overload resolution. The caller needs to build this
13396 /// set based on the context using, e.g.,
13397 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13398 /// set should not contain any member functions; those will be added
13399 /// by CreateOverloadedUnaryOp().
13400 ///
13401 /// \param Input The input argument.
13402 ExprResult
13403 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13404                               const UnresolvedSetImpl &Fns,
13405                               Expr *Input, bool PerformADL) {
13406   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13407   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13408   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13409   // TODO: provide better source location info.
13410   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13411 
13412   if (checkPlaceholderForOverload(*this, Input))
13413     return ExprError();
13414 
13415   Expr *Args[2] = { Input, nullptr };
13416   unsigned NumArgs = 1;
13417 
13418   // For post-increment and post-decrement, add the implicit '0' as
13419   // the second argument, so that we know this is a post-increment or
13420   // post-decrement.
13421   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13422     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13423     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13424                                      SourceLocation());
13425     NumArgs = 2;
13426   }
13427 
13428   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13429 
13430   if (Input->isTypeDependent()) {
13431     if (Fns.empty())
13432       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13433                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13434                                    CurFPFeatureOverrides());
13435 
13436     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13437     ExprResult Fn = CreateUnresolvedLookupExpr(
13438         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13439     if (Fn.isInvalid())
13440       return ExprError();
13441     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13442                                        Context.DependentTy, VK_PRValue, OpLoc,
13443                                        CurFPFeatureOverrides());
13444   }
13445 
13446   // Build an empty overload set.
13447   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13448 
13449   // Add the candidates from the given function set.
13450   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13451 
13452   // Add operator candidates that are member functions.
13453   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13454 
13455   // Add candidates from ADL.
13456   if (PerformADL) {
13457     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13458                                          /*ExplicitTemplateArgs*/nullptr,
13459                                          CandidateSet);
13460   }
13461 
13462   // Add builtin operator candidates.
13463   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13464 
13465   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13466 
13467   // Perform overload resolution.
13468   OverloadCandidateSet::iterator Best;
13469   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13470   case OR_Success: {
13471     // We found a built-in operator or an overloaded operator.
13472     FunctionDecl *FnDecl = Best->Function;
13473 
13474     if (FnDecl) {
13475       Expr *Base = nullptr;
13476       // We matched an overloaded operator. Build a call to that
13477       // operator.
13478 
13479       // Convert the arguments.
13480       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13481         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13482 
13483         ExprResult InputRes =
13484           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13485                                               Best->FoundDecl, Method);
13486         if (InputRes.isInvalid())
13487           return ExprError();
13488         Base = Input = InputRes.get();
13489       } else {
13490         // Convert the arguments.
13491         ExprResult InputInit
13492           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13493                                                       Context,
13494                                                       FnDecl->getParamDecl(0)),
13495                                       SourceLocation(),
13496                                       Input);
13497         if (InputInit.isInvalid())
13498           return ExprError();
13499         Input = InputInit.get();
13500       }
13501 
13502       // Build the actual expression node.
13503       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13504                                                 Base, HadMultipleCandidates,
13505                                                 OpLoc);
13506       if (FnExpr.isInvalid())
13507         return ExprError();
13508 
13509       // Determine the result type.
13510       QualType ResultTy = FnDecl->getReturnType();
13511       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13512       ResultTy = ResultTy.getNonLValueExprType(Context);
13513 
13514       Args[0] = Input;
13515       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13516           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13517           CurFPFeatureOverrides(), Best->IsADLCandidate);
13518 
13519       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13520         return ExprError();
13521 
13522       if (CheckFunctionCall(FnDecl, TheCall,
13523                             FnDecl->getType()->castAs<FunctionProtoType>()))
13524         return ExprError();
13525       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13526     } else {
13527       // We matched a built-in operator. Convert the arguments, then
13528       // break out so that we will build the appropriate built-in
13529       // operator node.
13530       ExprResult InputRes = PerformImplicitConversion(
13531           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13532           CCK_ForBuiltinOverloadedOp);
13533       if (InputRes.isInvalid())
13534         return ExprError();
13535       Input = InputRes.get();
13536       break;
13537     }
13538   }
13539 
13540   case OR_No_Viable_Function:
13541     // This is an erroneous use of an operator which can be overloaded by
13542     // a non-member function. Check for non-member operators which were
13543     // defined too late to be candidates.
13544     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13545       // FIXME: Recover by calling the found function.
13546       return ExprError();
13547 
13548     // No viable function; fall through to handling this as a
13549     // built-in operator, which will produce an error message for us.
13550     break;
13551 
13552   case OR_Ambiguous:
13553     CandidateSet.NoteCandidates(
13554         PartialDiagnosticAt(OpLoc,
13555                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13556                                 << UnaryOperator::getOpcodeStr(Opc)
13557                                 << Input->getType() << Input->getSourceRange()),
13558         *this, OCD_AmbiguousCandidates, ArgsArray,
13559         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13560     return ExprError();
13561 
13562   case OR_Deleted:
13563     CandidateSet.NoteCandidates(
13564         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13565                                        << UnaryOperator::getOpcodeStr(Opc)
13566                                        << Input->getSourceRange()),
13567         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13568         OpLoc);
13569     return ExprError();
13570   }
13571 
13572   // Either we found no viable overloaded operator or we matched a
13573   // built-in operator. In either case, fall through to trying to
13574   // build a built-in operation.
13575   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13576 }
13577 
13578 /// Perform lookup for an overloaded binary operator.
13579 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13580                                  OverloadedOperatorKind Op,
13581                                  const UnresolvedSetImpl &Fns,
13582                                  ArrayRef<Expr *> Args, bool PerformADL) {
13583   SourceLocation OpLoc = CandidateSet.getLocation();
13584 
13585   OverloadedOperatorKind ExtraOp =
13586       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13587           ? getRewrittenOverloadedOperator(Op)
13588           : OO_None;
13589 
13590   // Add the candidates from the given function set. This also adds the
13591   // rewritten candidates using these functions if necessary.
13592   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13593 
13594   // Add operator candidates that are member functions.
13595   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13596   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13597     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13598                                 OverloadCandidateParamOrder::Reversed);
13599 
13600   // In C++20, also add any rewritten member candidates.
13601   if (ExtraOp) {
13602     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13603     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13604       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13605                                   CandidateSet,
13606                                   OverloadCandidateParamOrder::Reversed);
13607   }
13608 
13609   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13610   // performed for an assignment operator (nor for operator[] nor operator->,
13611   // which don't get here).
13612   if (Op != OO_Equal && PerformADL) {
13613     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13614     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13615                                          /*ExplicitTemplateArgs*/ nullptr,
13616                                          CandidateSet);
13617     if (ExtraOp) {
13618       DeclarationName ExtraOpName =
13619           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13620       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13621                                            /*ExplicitTemplateArgs*/ nullptr,
13622                                            CandidateSet);
13623     }
13624   }
13625 
13626   // Add builtin operator candidates.
13627   //
13628   // FIXME: We don't add any rewritten candidates here. This is strictly
13629   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13630   // resulting in our selecting a rewritten builtin candidate. For example:
13631   //
13632   //   enum class E { e };
13633   //   bool operator!=(E, E) requires false;
13634   //   bool k = E::e != E::e;
13635   //
13636   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13637   // it seems unreasonable to consider rewritten builtin candidates. A core
13638   // issue has been filed proposing to removed this requirement.
13639   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13640 }
13641 
13642 /// Create a binary operation that may resolve to an overloaded
13643 /// operator.
13644 ///
13645 /// \param OpLoc The location of the operator itself (e.g., '+').
13646 ///
13647 /// \param Opc The BinaryOperatorKind that describes this operator.
13648 ///
13649 /// \param Fns The set of non-member functions that will be
13650 /// considered by overload resolution. The caller needs to build this
13651 /// set based on the context using, e.g.,
13652 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13653 /// set should not contain any member functions; those will be added
13654 /// by CreateOverloadedBinOp().
13655 ///
13656 /// \param LHS Left-hand argument.
13657 /// \param RHS Right-hand argument.
13658 /// \param PerformADL Whether to consider operator candidates found by ADL.
13659 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13660 ///        C++20 operator rewrites.
13661 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13662 ///        the function in question. Such a function is never a candidate in
13663 ///        our overload resolution. This also enables synthesizing a three-way
13664 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13665 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13666                                        BinaryOperatorKind Opc,
13667                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13668                                        Expr *RHS, bool PerformADL,
13669                                        bool AllowRewrittenCandidates,
13670                                        FunctionDecl *DefaultedFn) {
13671   Expr *Args[2] = { LHS, RHS };
13672   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13673 
13674   if (!getLangOpts().CPlusPlus20)
13675     AllowRewrittenCandidates = false;
13676 
13677   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13678 
13679   // If either side is type-dependent, create an appropriate dependent
13680   // expression.
13681   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13682     if (Fns.empty()) {
13683       // If there are no functions to store, just build a dependent
13684       // BinaryOperator or CompoundAssignment.
13685       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13686         return CompoundAssignOperator::Create(
13687             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13688             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13689             Context.DependentTy);
13690       return BinaryOperator::Create(
13691           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13692           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13693     }
13694 
13695     // FIXME: save results of ADL from here?
13696     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13697     // TODO: provide better source location info in DNLoc component.
13698     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13699     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13700     ExprResult Fn = CreateUnresolvedLookupExpr(
13701         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13702     if (Fn.isInvalid())
13703       return ExprError();
13704     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13705                                        Context.DependentTy, VK_PRValue, OpLoc,
13706                                        CurFPFeatureOverrides());
13707   }
13708 
13709   // Always do placeholder-like conversions on the RHS.
13710   if (checkPlaceholderForOverload(*this, Args[1]))
13711     return ExprError();
13712 
13713   // Do placeholder-like conversion on the LHS; note that we should
13714   // not get here with a PseudoObject LHS.
13715   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13716   if (checkPlaceholderForOverload(*this, Args[0]))
13717     return ExprError();
13718 
13719   // If this is the assignment operator, we only perform overload resolution
13720   // if the left-hand side is a class or enumeration type. This is actually
13721   // a hack. The standard requires that we do overload resolution between the
13722   // various built-in candidates, but as DR507 points out, this can lead to
13723   // problems. So we do it this way, which pretty much follows what GCC does.
13724   // Note that we go the traditional code path for compound assignment forms.
13725   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13726     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13727 
13728   // If this is the .* operator, which is not overloadable, just
13729   // create a built-in binary operator.
13730   if (Opc == BO_PtrMemD)
13731     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13732 
13733   // Build the overload set.
13734   OverloadCandidateSet CandidateSet(
13735       OpLoc, OverloadCandidateSet::CSK_Operator,
13736       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13737   if (DefaultedFn)
13738     CandidateSet.exclude(DefaultedFn);
13739   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13740 
13741   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13742 
13743   // Perform overload resolution.
13744   OverloadCandidateSet::iterator Best;
13745   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13746     case OR_Success: {
13747       // We found a built-in operator or an overloaded operator.
13748       FunctionDecl *FnDecl = Best->Function;
13749 
13750       bool IsReversed = Best->isReversed();
13751       if (IsReversed)
13752         std::swap(Args[0], Args[1]);
13753 
13754       if (FnDecl) {
13755         Expr *Base = nullptr;
13756         // We matched an overloaded operator. Build a call to that
13757         // operator.
13758 
13759         OverloadedOperatorKind ChosenOp =
13760             FnDecl->getDeclName().getCXXOverloadedOperator();
13761 
13762         // C++2a [over.match.oper]p9:
13763         //   If a rewritten operator== candidate is selected by overload
13764         //   resolution for an operator@, its return type shall be cv bool
13765         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13766             !FnDecl->getReturnType()->isBooleanType()) {
13767           bool IsExtension =
13768               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13769           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13770                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13771               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13772               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13773           Diag(FnDecl->getLocation(), diag::note_declared_at);
13774           if (!IsExtension)
13775             return ExprError();
13776         }
13777 
13778         if (AllowRewrittenCandidates && !IsReversed &&
13779             CandidateSet.getRewriteInfo().isReversible()) {
13780           // We could have reversed this operator, but didn't. Check if some
13781           // reversed form was a viable candidate, and if so, if it had a
13782           // better conversion for either parameter. If so, this call is
13783           // formally ambiguous, and allowing it is an extension.
13784           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13785           for (OverloadCandidate &Cand : CandidateSet) {
13786             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13787                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13788               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13789                 if (CompareImplicitConversionSequences(
13790                         *this, OpLoc, Cand.Conversions[ArgIdx],
13791                         Best->Conversions[ArgIdx]) ==
13792                     ImplicitConversionSequence::Better) {
13793                   AmbiguousWith.push_back(Cand.Function);
13794                   break;
13795                 }
13796               }
13797             }
13798           }
13799 
13800           if (!AmbiguousWith.empty()) {
13801             bool AmbiguousWithSelf =
13802                 AmbiguousWith.size() == 1 &&
13803                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13804             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13805                 << BinaryOperator::getOpcodeStr(Opc)
13806                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13807                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13808             if (AmbiguousWithSelf) {
13809               Diag(FnDecl->getLocation(),
13810                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13811             } else {
13812               Diag(FnDecl->getLocation(),
13813                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13814               for (auto *F : AmbiguousWith)
13815                 Diag(F->getLocation(),
13816                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13817             }
13818           }
13819         }
13820 
13821         // Convert the arguments.
13822         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13823           // Best->Access is only meaningful for class members.
13824           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13825 
13826           ExprResult Arg1 =
13827             PerformCopyInitialization(
13828               InitializedEntity::InitializeParameter(Context,
13829                                                      FnDecl->getParamDecl(0)),
13830               SourceLocation(), Args[1]);
13831           if (Arg1.isInvalid())
13832             return ExprError();
13833 
13834           ExprResult Arg0 =
13835             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13836                                                 Best->FoundDecl, Method);
13837           if (Arg0.isInvalid())
13838             return ExprError();
13839           Base = Args[0] = Arg0.getAs<Expr>();
13840           Args[1] = RHS = Arg1.getAs<Expr>();
13841         } else {
13842           // Convert the arguments.
13843           ExprResult Arg0 = PerformCopyInitialization(
13844             InitializedEntity::InitializeParameter(Context,
13845                                                    FnDecl->getParamDecl(0)),
13846             SourceLocation(), Args[0]);
13847           if (Arg0.isInvalid())
13848             return ExprError();
13849 
13850           ExprResult Arg1 =
13851             PerformCopyInitialization(
13852               InitializedEntity::InitializeParameter(Context,
13853                                                      FnDecl->getParamDecl(1)),
13854               SourceLocation(), Args[1]);
13855           if (Arg1.isInvalid())
13856             return ExprError();
13857           Args[0] = LHS = Arg0.getAs<Expr>();
13858           Args[1] = RHS = Arg1.getAs<Expr>();
13859         }
13860 
13861         // Build the actual expression node.
13862         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13863                                                   Best->FoundDecl, Base,
13864                                                   HadMultipleCandidates, OpLoc);
13865         if (FnExpr.isInvalid())
13866           return ExprError();
13867 
13868         // Determine the result type.
13869         QualType ResultTy = FnDecl->getReturnType();
13870         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13871         ResultTy = ResultTy.getNonLValueExprType(Context);
13872 
13873         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13874             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13875             CurFPFeatureOverrides(), Best->IsADLCandidate);
13876 
13877         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13878                                 FnDecl))
13879           return ExprError();
13880 
13881         ArrayRef<const Expr *> ArgsArray(Args, 2);
13882         const Expr *ImplicitThis = nullptr;
13883         // Cut off the implicit 'this'.
13884         if (isa<CXXMethodDecl>(FnDecl)) {
13885           ImplicitThis = ArgsArray[0];
13886           ArgsArray = ArgsArray.slice(1);
13887         }
13888 
13889         // Check for a self move.
13890         if (Op == OO_Equal)
13891           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13892 
13893         if (ImplicitThis) {
13894           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13895           QualType ThisTypeFromDecl = Context.getPointerType(
13896               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13897 
13898           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13899                             ThisTypeFromDecl);
13900         }
13901 
13902         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13903                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13904                   VariadicDoesNotApply);
13905 
13906         ExprResult R = MaybeBindToTemporary(TheCall);
13907         if (R.isInvalid())
13908           return ExprError();
13909 
13910         R = CheckForImmediateInvocation(R, FnDecl);
13911         if (R.isInvalid())
13912           return ExprError();
13913 
13914         // For a rewritten candidate, we've already reversed the arguments
13915         // if needed. Perform the rest of the rewrite now.
13916         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13917             (Op == OO_Spaceship && IsReversed)) {
13918           if (Op == OO_ExclaimEqual) {
13919             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13920             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13921           } else {
13922             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13923             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13924             Expr *ZeroLiteral =
13925                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13926 
13927             Sema::CodeSynthesisContext Ctx;
13928             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13929             Ctx.Entity = FnDecl;
13930             pushCodeSynthesisContext(Ctx);
13931 
13932             R = CreateOverloadedBinOp(
13933                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13934                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13935                 /*AllowRewrittenCandidates=*/false);
13936 
13937             popCodeSynthesisContext();
13938           }
13939           if (R.isInvalid())
13940             return ExprError();
13941         } else {
13942           assert(ChosenOp == Op && "unexpected operator name");
13943         }
13944 
13945         // Make a note in the AST if we did any rewriting.
13946         if (Best->RewriteKind != CRK_None)
13947           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13948 
13949         return R;
13950       } else {
13951         // We matched a built-in operator. Convert the arguments, then
13952         // break out so that we will build the appropriate built-in
13953         // operator node.
13954         ExprResult ArgsRes0 = PerformImplicitConversion(
13955             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13956             AA_Passing, CCK_ForBuiltinOverloadedOp);
13957         if (ArgsRes0.isInvalid())
13958           return ExprError();
13959         Args[0] = ArgsRes0.get();
13960 
13961         ExprResult ArgsRes1 = PerformImplicitConversion(
13962             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13963             AA_Passing, CCK_ForBuiltinOverloadedOp);
13964         if (ArgsRes1.isInvalid())
13965           return ExprError();
13966         Args[1] = ArgsRes1.get();
13967         break;
13968       }
13969     }
13970 
13971     case OR_No_Viable_Function: {
13972       // C++ [over.match.oper]p9:
13973       //   If the operator is the operator , [...] and there are no
13974       //   viable functions, then the operator is assumed to be the
13975       //   built-in operator and interpreted according to clause 5.
13976       if (Opc == BO_Comma)
13977         break;
13978 
13979       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13980       // compare result using '==' and '<'.
13981       if (DefaultedFn && Opc == BO_Cmp) {
13982         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13983                                                           Args[1], DefaultedFn);
13984         if (E.isInvalid() || E.isUsable())
13985           return E;
13986       }
13987 
13988       // For class as left operand for assignment or compound assignment
13989       // operator do not fall through to handling in built-in, but report that
13990       // no overloaded assignment operator found
13991       ExprResult Result = ExprError();
13992       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13993       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13994                                                    Args, OpLoc);
13995       DeferDiagsRAII DDR(*this,
13996                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13997       if (Args[0]->getType()->isRecordType() &&
13998           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13999         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
14000              << BinaryOperator::getOpcodeStr(Opc)
14001              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14002         if (Args[0]->getType()->isIncompleteType()) {
14003           Diag(OpLoc, diag::note_assign_lhs_incomplete)
14004             << Args[0]->getType()
14005             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14006         }
14007       } else {
14008         // This is an erroneous use of an operator which can be overloaded by
14009         // a non-member function. Check for non-member operators which were
14010         // defined too late to be candidates.
14011         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14012           // FIXME: Recover by calling the found function.
14013           return ExprError();
14014 
14015         // No viable function; try to create a built-in operation, which will
14016         // produce an error. Then, show the non-viable candidates.
14017         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14018       }
14019       assert(Result.isInvalid() &&
14020              "C++ binary operator overloading is missing candidates!");
14021       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14022       return Result;
14023     }
14024 
14025     case OR_Ambiguous:
14026       CandidateSet.NoteCandidates(
14027           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14028                                          << BinaryOperator::getOpcodeStr(Opc)
14029                                          << Args[0]->getType()
14030                                          << Args[1]->getType()
14031                                          << Args[0]->getSourceRange()
14032                                          << Args[1]->getSourceRange()),
14033           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14034           OpLoc);
14035       return ExprError();
14036 
14037     case OR_Deleted:
14038       if (isImplicitlyDeleted(Best->Function)) {
14039         FunctionDecl *DeletedFD = Best->Function;
14040         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14041         if (DFK.isSpecialMember()) {
14042           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14043             << Args[0]->getType() << DFK.asSpecialMember();
14044         } else {
14045           assert(DFK.isComparison());
14046           Diag(OpLoc, diag::err_ovl_deleted_comparison)
14047             << Args[0]->getType() << DeletedFD;
14048         }
14049 
14050         // The user probably meant to call this special member. Just
14051         // explain why it's deleted.
14052         NoteDeletedFunction(DeletedFD);
14053         return ExprError();
14054       }
14055       CandidateSet.NoteCandidates(
14056           PartialDiagnosticAt(
14057               OpLoc, PDiag(diag::err_ovl_deleted_oper)
14058                          << getOperatorSpelling(Best->Function->getDeclName()
14059                                                     .getCXXOverloadedOperator())
14060                          << Args[0]->getSourceRange()
14061                          << Args[1]->getSourceRange()),
14062           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14063           OpLoc);
14064       return ExprError();
14065   }
14066 
14067   // We matched a built-in operator; build it.
14068   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14069 }
14070 
14071 ExprResult Sema::BuildSynthesizedThreeWayComparison(
14072     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
14073     FunctionDecl *DefaultedFn) {
14074   const ComparisonCategoryInfo *Info =
14075       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
14076   // If we're not producing a known comparison category type, we can't
14077   // synthesize a three-way comparison. Let the caller diagnose this.
14078   if (!Info)
14079     return ExprResult((Expr*)nullptr);
14080 
14081   // If we ever want to perform this synthesis more generally, we will need to
14082   // apply the temporary materialization conversion to the operands.
14083   assert(LHS->isGLValue() && RHS->isGLValue() &&
14084          "cannot use prvalue expressions more than once");
14085   Expr *OrigLHS = LHS;
14086   Expr *OrigRHS = RHS;
14087 
14088   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14089   // each of them multiple times below.
14090   LHS = new (Context)
14091       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
14092                       LHS->getObjectKind(), LHS);
14093   RHS = new (Context)
14094       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
14095                       RHS->getObjectKind(), RHS);
14096 
14097   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
14098                                         DefaultedFn);
14099   if (Eq.isInvalid())
14100     return ExprError();
14101 
14102   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
14103                                           true, DefaultedFn);
14104   if (Less.isInvalid())
14105     return ExprError();
14106 
14107   ExprResult Greater;
14108   if (Info->isPartial()) {
14109     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14110                                     DefaultedFn);
14111     if (Greater.isInvalid())
14112       return ExprError();
14113   }
14114 
14115   // Form the list of comparisons we're going to perform.
14116   struct Comparison {
14117     ExprResult Cmp;
14118     ComparisonCategoryResult Result;
14119   } Comparisons[4] =
14120   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14121                           : ComparisonCategoryResult::Equivalent},
14122     {Less, ComparisonCategoryResult::Less},
14123     {Greater, ComparisonCategoryResult::Greater},
14124     {ExprResult(), ComparisonCategoryResult::Unordered},
14125   };
14126 
14127   int I = Info->isPartial() ? 3 : 2;
14128 
14129   // Combine the comparisons with suitable conditional expressions.
14130   ExprResult Result;
14131   for (; I >= 0; --I) {
14132     // Build a reference to the comparison category constant.
14133     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14134     // FIXME: Missing a constant for a comparison category. Diagnose this?
14135     if (!VI)
14136       return ExprResult((Expr*)nullptr);
14137     ExprResult ThisResult =
14138         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14139     if (ThisResult.isInvalid())
14140       return ExprError();
14141 
14142     // Build a conditional unless this is the final case.
14143     if (Result.get()) {
14144       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14145                                   ThisResult.get(), Result.get());
14146       if (Result.isInvalid())
14147         return ExprError();
14148     } else {
14149       Result = ThisResult;
14150     }
14151   }
14152 
14153   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14154   // bind the OpaqueValueExprs before they're (repeatedly) used.
14155   Expr *SyntacticForm = BinaryOperator::Create(
14156       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14157       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14158       CurFPFeatureOverrides());
14159   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14160   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14161 }
14162 
14163 static bool PrepareArgumentsForCallToObjectOfClassType(
14164     Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
14165     MultiExprArg Args, SourceLocation LParenLoc) {
14166 
14167   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14168   unsigned NumParams = Proto->getNumParams();
14169   unsigned NumArgsSlots =
14170       MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
14171   // Build the full argument list for the method call (the implicit object
14172   // parameter is placed at the beginning of the list).
14173   MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
14174   bool IsError = false;
14175   // Initialize the implicit object parameter.
14176   // Check the argument types.
14177   for (unsigned i = 0; i != NumParams; i++) {
14178     Expr *Arg;
14179     if (i < Args.size()) {
14180       Arg = Args[i];
14181       ExprResult InputInit =
14182           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14183                                           S.Context, Method->getParamDecl(i)),
14184                                       SourceLocation(), Arg);
14185       IsError |= InputInit.isInvalid();
14186       Arg = InputInit.getAs<Expr>();
14187     } else {
14188       ExprResult DefArg =
14189           S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14190       if (DefArg.isInvalid()) {
14191         IsError = true;
14192         break;
14193       }
14194       Arg = DefArg.getAs<Expr>();
14195     }
14196 
14197     MethodArgs.push_back(Arg);
14198   }
14199   return IsError;
14200 }
14201 
14202 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14203                                                     SourceLocation RLoc,
14204                                                     Expr *Base,
14205                                                     MultiExprArg ArgExpr) {
14206   SmallVector<Expr *, 2> Args;
14207   Args.push_back(Base);
14208   for (auto e : ArgExpr) {
14209     Args.push_back(e);
14210   }
14211   DeclarationName OpName =
14212       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14213 
14214   SourceRange Range = ArgExpr.empty()
14215                           ? SourceRange{}
14216                           : SourceRange(ArgExpr.front()->getBeginLoc(),
14217                                         ArgExpr.back()->getEndLoc());
14218 
14219   // If either side is type-dependent, create an appropriate dependent
14220   // expression.
14221   if (Expr::hasAnyTypeDependentArguments(Args)) {
14222 
14223     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14224     // CHECKME: no 'operator' keyword?
14225     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14226     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14227     ExprResult Fn = CreateUnresolvedLookupExpr(
14228         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14229     if (Fn.isInvalid())
14230       return ExprError();
14231     // Can't add any actual overloads yet
14232 
14233     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14234                                        Context.DependentTy, VK_PRValue, RLoc,
14235                                        CurFPFeatureOverrides());
14236   }
14237 
14238   // Handle placeholders
14239   UnbridgedCastsSet UnbridgedCasts;
14240   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14241     return ExprError();
14242   }
14243   // Build an empty overload set.
14244   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14245 
14246   // Subscript can only be overloaded as a member function.
14247 
14248   // Add operator candidates that are member functions.
14249   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14250 
14251   // Add builtin operator candidates.
14252   if (Args.size() == 2)
14253     AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14254 
14255   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14256 
14257   // Perform overload resolution.
14258   OverloadCandidateSet::iterator Best;
14259   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14260     case OR_Success: {
14261       // We found a built-in operator or an overloaded operator.
14262       FunctionDecl *FnDecl = Best->Function;
14263 
14264       if (FnDecl) {
14265         // We matched an overloaded operator. Build a call to that
14266         // operator.
14267 
14268         CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
14269 
14270         // Convert the arguments.
14271         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14272         SmallVector<Expr *, 2> MethodArgs;
14273         ExprResult Arg0 = PerformObjectArgumentInitialization(
14274             Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14275         if (Arg0.isInvalid())
14276           return ExprError();
14277 
14278         MethodArgs.push_back(Arg0.get());
14279         bool IsError = PrepareArgumentsForCallToObjectOfClassType(
14280             *this, MethodArgs, Method, ArgExpr, LLoc);
14281         if (IsError)
14282           return ExprError();
14283 
14284         // Build the actual expression node.
14285         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14286         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14287         ExprResult FnExpr = CreateFunctionRefExpr(
14288             *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
14289             OpLocInfo.getLoc(), OpLocInfo.getInfo());
14290         if (FnExpr.isInvalid())
14291           return ExprError();
14292 
14293         // Determine the result type
14294         QualType ResultTy = FnDecl->getReturnType();
14295         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14296         ResultTy = ResultTy.getNonLValueExprType(Context);
14297 
14298         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14299             Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
14300             CurFPFeatureOverrides());
14301         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14302           return ExprError();
14303 
14304         if (CheckFunctionCall(Method, TheCall,
14305                               Method->getType()->castAs<FunctionProtoType>()))
14306           return ExprError();
14307 
14308         return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14309                                            FnDecl);
14310       } else {
14311         // We matched a built-in operator. Convert the arguments, then
14312         // break out so that we will build the appropriate built-in
14313         // operator node.
14314         ExprResult ArgsRes0 = PerformImplicitConversion(
14315             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14316             AA_Passing, CCK_ForBuiltinOverloadedOp);
14317         if (ArgsRes0.isInvalid())
14318           return ExprError();
14319         Args[0] = ArgsRes0.get();
14320 
14321         ExprResult ArgsRes1 = PerformImplicitConversion(
14322             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14323             AA_Passing, CCK_ForBuiltinOverloadedOp);
14324         if (ArgsRes1.isInvalid())
14325           return ExprError();
14326         Args[1] = ArgsRes1.get();
14327 
14328         break;
14329       }
14330     }
14331 
14332     case OR_No_Viable_Function: {
14333       PartialDiagnostic PD =
14334           CandidateSet.empty()
14335               ? (PDiag(diag::err_ovl_no_oper)
14336                  << Args[0]->getType() << /*subscript*/ 0
14337                  << Args[0]->getSourceRange() << Range)
14338               : (PDiag(diag::err_ovl_no_viable_subscript)
14339                  << Args[0]->getType() << Args[0]->getSourceRange() << Range);
14340       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14341                                   OCD_AllCandidates, ArgExpr, "[]", LLoc);
14342       return ExprError();
14343     }
14344 
14345     case OR_Ambiguous:
14346       if (Args.size() == 2) {
14347         CandidateSet.NoteCandidates(
14348             PartialDiagnosticAt(
14349                 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14350                           << "[]" << Args[0]->getType() << Args[1]->getType()
14351                           << Args[0]->getSourceRange() << Range),
14352             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14353       } else {
14354         CandidateSet.NoteCandidates(
14355             PartialDiagnosticAt(LLoc,
14356                                 PDiag(diag::err_ovl_ambiguous_subscript_call)
14357                                     << Args[0]->getType()
14358                                     << Args[0]->getSourceRange() << Range),
14359             *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14360       }
14361       return ExprError();
14362 
14363     case OR_Deleted:
14364       CandidateSet.NoteCandidates(
14365           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14366                                         << "[]" << Args[0]->getSourceRange()
14367                                         << Range),
14368           *this, OCD_AllCandidates, Args, "[]", LLoc);
14369       return ExprError();
14370     }
14371 
14372   // We matched a built-in operator; build it.
14373   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14374 }
14375 
14376 /// BuildCallToMemberFunction - Build a call to a member
14377 /// function. MemExpr is the expression that refers to the member
14378 /// function (and includes the object parameter), Args/NumArgs are the
14379 /// arguments to the function call (not including the object
14380 /// parameter). The caller needs to validate that the member
14381 /// expression refers to a non-static member function or an overloaded
14382 /// member function.
14383 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14384                                            SourceLocation LParenLoc,
14385                                            MultiExprArg Args,
14386                                            SourceLocation RParenLoc,
14387                                            Expr *ExecConfig, bool IsExecConfig,
14388                                            bool AllowRecovery) {
14389   assert(MemExprE->getType() == Context.BoundMemberTy ||
14390          MemExprE->getType() == Context.OverloadTy);
14391 
14392   // Dig out the member expression. This holds both the object
14393   // argument and the member function we're referring to.
14394   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14395 
14396   // Determine whether this is a call to a pointer-to-member function.
14397   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14398     assert(op->getType() == Context.BoundMemberTy);
14399     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14400 
14401     QualType fnType =
14402       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14403 
14404     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14405     QualType resultType = proto->getCallResultType(Context);
14406     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14407 
14408     // Check that the object type isn't more qualified than the
14409     // member function we're calling.
14410     Qualifiers funcQuals = proto->getMethodQuals();
14411 
14412     QualType objectType = op->getLHS()->getType();
14413     if (op->getOpcode() == BO_PtrMemI)
14414       objectType = objectType->castAs<PointerType>()->getPointeeType();
14415     Qualifiers objectQuals = objectType.getQualifiers();
14416 
14417     Qualifiers difference = objectQuals - funcQuals;
14418     difference.removeObjCGCAttr();
14419     difference.removeAddressSpace();
14420     if (difference) {
14421       std::string qualsString = difference.getAsString();
14422       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14423         << fnType.getUnqualifiedType()
14424         << qualsString
14425         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14426     }
14427 
14428     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14429         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14430         CurFPFeatureOverrides(), proto->getNumParams());
14431 
14432     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14433                             call, nullptr))
14434       return ExprError();
14435 
14436     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14437       return ExprError();
14438 
14439     if (CheckOtherCall(call, proto))
14440       return ExprError();
14441 
14442     return MaybeBindToTemporary(call);
14443   }
14444 
14445   // We only try to build a recovery expr at this level if we can preserve
14446   // the return type, otherwise we return ExprError() and let the caller
14447   // recover.
14448   auto BuildRecoveryExpr = [&](QualType Type) {
14449     if (!AllowRecovery)
14450       return ExprError();
14451     std::vector<Expr *> SubExprs = {MemExprE};
14452     llvm::append_range(SubExprs, Args);
14453     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14454                               Type);
14455   };
14456   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14457     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14458                             RParenLoc, CurFPFeatureOverrides());
14459 
14460   UnbridgedCastsSet UnbridgedCasts;
14461   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14462     return ExprError();
14463 
14464   MemberExpr *MemExpr;
14465   CXXMethodDecl *Method = nullptr;
14466   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14467   NestedNameSpecifier *Qualifier = nullptr;
14468   if (isa<MemberExpr>(NakedMemExpr)) {
14469     MemExpr = cast<MemberExpr>(NakedMemExpr);
14470     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14471     FoundDecl = MemExpr->getFoundDecl();
14472     Qualifier = MemExpr->getQualifier();
14473     UnbridgedCasts.restore();
14474   } else {
14475     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14476     Qualifier = UnresExpr->getQualifier();
14477 
14478     QualType ObjectType = UnresExpr->getBaseType();
14479     Expr::Classification ObjectClassification
14480       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14481                             : UnresExpr->getBase()->Classify(Context);
14482 
14483     // Add overload candidates
14484     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14485                                       OverloadCandidateSet::CSK_Normal);
14486 
14487     // FIXME: avoid copy.
14488     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14489     if (UnresExpr->hasExplicitTemplateArgs()) {
14490       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14491       TemplateArgs = &TemplateArgsBuffer;
14492     }
14493 
14494     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14495            E = UnresExpr->decls_end(); I != E; ++I) {
14496 
14497       NamedDecl *Func = *I;
14498       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14499       if (isa<UsingShadowDecl>(Func))
14500         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14501 
14502 
14503       // Microsoft supports direct constructor calls.
14504       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14505         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14506                              CandidateSet,
14507                              /*SuppressUserConversions*/ false);
14508       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14509         // If explicit template arguments were provided, we can't call a
14510         // non-template member function.
14511         if (TemplateArgs)
14512           continue;
14513 
14514         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14515                            ObjectClassification, Args, CandidateSet,
14516                            /*SuppressUserConversions=*/false);
14517       } else {
14518         AddMethodTemplateCandidate(
14519             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14520             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14521             /*SuppressUserConversions=*/false);
14522       }
14523     }
14524 
14525     DeclarationName DeclName = UnresExpr->getMemberName();
14526 
14527     UnbridgedCasts.restore();
14528 
14529     OverloadCandidateSet::iterator Best;
14530     bool Succeeded = false;
14531     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14532                                             Best)) {
14533     case OR_Success:
14534       Method = cast<CXXMethodDecl>(Best->Function);
14535       FoundDecl = Best->FoundDecl;
14536       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14537       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14538         break;
14539       // If FoundDecl is different from Method (such as if one is a template
14540       // and the other a specialization), make sure DiagnoseUseOfDecl is
14541       // called on both.
14542       // FIXME: This would be more comprehensively addressed by modifying
14543       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14544       // being used.
14545       if (Method != FoundDecl.getDecl() &&
14546                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14547         break;
14548       Succeeded = true;
14549       break;
14550 
14551     case OR_No_Viable_Function:
14552       CandidateSet.NoteCandidates(
14553           PartialDiagnosticAt(
14554               UnresExpr->getMemberLoc(),
14555               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14556                   << DeclName << MemExprE->getSourceRange()),
14557           *this, OCD_AllCandidates, Args);
14558       break;
14559     case OR_Ambiguous:
14560       CandidateSet.NoteCandidates(
14561           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14562                               PDiag(diag::err_ovl_ambiguous_member_call)
14563                                   << DeclName << MemExprE->getSourceRange()),
14564           *this, OCD_AmbiguousCandidates, Args);
14565       break;
14566     case OR_Deleted:
14567       CandidateSet.NoteCandidates(
14568           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14569                               PDiag(diag::err_ovl_deleted_member_call)
14570                                   << DeclName << MemExprE->getSourceRange()),
14571           *this, OCD_AllCandidates, Args);
14572       break;
14573     }
14574     // Overload resolution fails, try to recover.
14575     if (!Succeeded)
14576       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14577 
14578     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14579 
14580     // If overload resolution picked a static member, build a
14581     // non-member call based on that function.
14582     if (Method->isStatic()) {
14583       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14584                                    ExecConfig, IsExecConfig);
14585     }
14586 
14587     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14588   }
14589 
14590   QualType ResultType = Method->getReturnType();
14591   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14592   ResultType = ResultType.getNonLValueExprType(Context);
14593 
14594   assert(Method && "Member call to something that isn't a method?");
14595   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14596   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14597       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14598       CurFPFeatureOverrides(), Proto->getNumParams());
14599 
14600   // Check for a valid return type.
14601   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14602                           TheCall, Method))
14603     return BuildRecoveryExpr(ResultType);
14604 
14605   // Convert the object argument (for a non-static member function call).
14606   // We only need to do this if there was actually an overload; otherwise
14607   // it was done at lookup.
14608   if (!Method->isStatic()) {
14609     ExprResult ObjectArg =
14610       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14611                                           FoundDecl, Method);
14612     if (ObjectArg.isInvalid())
14613       return ExprError();
14614     MemExpr->setBase(ObjectArg.get());
14615   }
14616 
14617   // Convert the rest of the arguments
14618   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14619                               RParenLoc))
14620     return BuildRecoveryExpr(ResultType);
14621 
14622   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14623 
14624   if (CheckFunctionCall(Method, TheCall, Proto))
14625     return ExprError();
14626 
14627   // In the case the method to call was not selected by the overloading
14628   // resolution process, we still need to handle the enable_if attribute. Do
14629   // that here, so it will not hide previous -- and more relevant -- errors.
14630   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14631     if (const EnableIfAttr *Attr =
14632             CheckEnableIf(Method, LParenLoc, Args, true)) {
14633       Diag(MemE->getMemberLoc(),
14634            diag::err_ovl_no_viable_member_function_in_call)
14635           << Method << Method->getSourceRange();
14636       Diag(Method->getLocation(),
14637            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14638           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14639       return ExprError();
14640     }
14641   }
14642 
14643   if ((isa<CXXConstructorDecl>(CurContext) ||
14644        isa<CXXDestructorDecl>(CurContext)) &&
14645       TheCall->getMethodDecl()->isPure()) {
14646     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14647 
14648     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14649         MemExpr->performsVirtualDispatch(getLangOpts())) {
14650       Diag(MemExpr->getBeginLoc(),
14651            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14652           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14653           << MD->getParent();
14654 
14655       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14656       if (getLangOpts().AppleKext)
14657         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14658             << MD->getParent() << MD->getDeclName();
14659     }
14660   }
14661 
14662   if (CXXDestructorDecl *DD =
14663           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14664     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14665     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14666     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14667                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14668                          MemExpr->getMemberLoc());
14669   }
14670 
14671   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14672                                      TheCall->getMethodDecl());
14673 }
14674 
14675 /// BuildCallToObjectOfClassType - Build a call to an object of class
14676 /// type (C++ [over.call.object]), which can end up invoking an
14677 /// overloaded function call operator (@c operator()) or performing a
14678 /// user-defined conversion on the object argument.
14679 ExprResult
14680 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14681                                    SourceLocation LParenLoc,
14682                                    MultiExprArg Args,
14683                                    SourceLocation RParenLoc) {
14684   if (checkPlaceholderForOverload(*this, Obj))
14685     return ExprError();
14686   ExprResult Object = Obj;
14687 
14688   UnbridgedCastsSet UnbridgedCasts;
14689   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14690     return ExprError();
14691 
14692   assert(Object.get()->getType()->isRecordType() &&
14693          "Requires object type argument");
14694 
14695   // C++ [over.call.object]p1:
14696   //  If the primary-expression E in the function call syntax
14697   //  evaluates to a class object of type "cv T", then the set of
14698   //  candidate functions includes at least the function call
14699   //  operators of T. The function call operators of T are obtained by
14700   //  ordinary lookup of the name operator() in the context of
14701   //  (E).operator().
14702   OverloadCandidateSet CandidateSet(LParenLoc,
14703                                     OverloadCandidateSet::CSK_Operator);
14704   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14705 
14706   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14707                           diag::err_incomplete_object_call, Object.get()))
14708     return true;
14709 
14710   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14711   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14712   LookupQualifiedName(R, Record->getDecl());
14713   R.suppressDiagnostics();
14714 
14715   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14716        Oper != OperEnd; ++Oper) {
14717     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14718                        Object.get()->Classify(Context), Args, CandidateSet,
14719                        /*SuppressUserConversion=*/false);
14720   }
14721 
14722   // C++ [over.call.object]p2:
14723   //   In addition, for each (non-explicit in C++0x) conversion function
14724   //   declared in T of the form
14725   //
14726   //        operator conversion-type-id () cv-qualifier;
14727   //
14728   //   where cv-qualifier is the same cv-qualification as, or a
14729   //   greater cv-qualification than, cv, and where conversion-type-id
14730   //   denotes the type "pointer to function of (P1,...,Pn) returning
14731   //   R", or the type "reference to pointer to function of
14732   //   (P1,...,Pn) returning R", or the type "reference to function
14733   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14734   //   is also considered as a candidate function. Similarly,
14735   //   surrogate call functions are added to the set of candidate
14736   //   functions for each conversion function declared in an
14737   //   accessible base class provided the function is not hidden
14738   //   within T by another intervening declaration.
14739   const auto &Conversions =
14740       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14741   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14742     NamedDecl *D = *I;
14743     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14744     if (isa<UsingShadowDecl>(D))
14745       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14746 
14747     // Skip over templated conversion functions; they aren't
14748     // surrogates.
14749     if (isa<FunctionTemplateDecl>(D))
14750       continue;
14751 
14752     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14753     if (!Conv->isExplicit()) {
14754       // Strip the reference type (if any) and then the pointer type (if
14755       // any) to get down to what might be a function type.
14756       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14757       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14758         ConvType = ConvPtrType->getPointeeType();
14759 
14760       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14761       {
14762         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14763                               Object.get(), Args, CandidateSet);
14764       }
14765     }
14766   }
14767 
14768   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14769 
14770   // Perform overload resolution.
14771   OverloadCandidateSet::iterator Best;
14772   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14773                                           Best)) {
14774   case OR_Success:
14775     // Overload resolution succeeded; we'll build the appropriate call
14776     // below.
14777     break;
14778 
14779   case OR_No_Viable_Function: {
14780     PartialDiagnostic PD =
14781         CandidateSet.empty()
14782             ? (PDiag(diag::err_ovl_no_oper)
14783                << Object.get()->getType() << /*call*/ 1
14784                << Object.get()->getSourceRange())
14785             : (PDiag(diag::err_ovl_no_viable_object_call)
14786                << Object.get()->getType() << Object.get()->getSourceRange());
14787     CandidateSet.NoteCandidates(
14788         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14789         OCD_AllCandidates, Args);
14790     break;
14791   }
14792   case OR_Ambiguous:
14793     CandidateSet.NoteCandidates(
14794         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14795                             PDiag(diag::err_ovl_ambiguous_object_call)
14796                                 << Object.get()->getType()
14797                                 << Object.get()->getSourceRange()),
14798         *this, OCD_AmbiguousCandidates, Args);
14799     break;
14800 
14801   case OR_Deleted:
14802     CandidateSet.NoteCandidates(
14803         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14804                             PDiag(diag::err_ovl_deleted_object_call)
14805                                 << Object.get()->getType()
14806                                 << Object.get()->getSourceRange()),
14807         *this, OCD_AllCandidates, Args);
14808     break;
14809   }
14810 
14811   if (Best == CandidateSet.end())
14812     return true;
14813 
14814   UnbridgedCasts.restore();
14815 
14816   if (Best->Function == nullptr) {
14817     // Since there is no function declaration, this is one of the
14818     // surrogate candidates. Dig out the conversion function.
14819     CXXConversionDecl *Conv
14820       = cast<CXXConversionDecl>(
14821                          Best->Conversions[0].UserDefined.ConversionFunction);
14822 
14823     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14824                               Best->FoundDecl);
14825     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14826       return ExprError();
14827     assert(Conv == Best->FoundDecl.getDecl() &&
14828              "Found Decl & conversion-to-functionptr should be same, right?!");
14829     // We selected one of the surrogate functions that converts the
14830     // object parameter to a function pointer. Perform the conversion
14831     // on the object argument, then let BuildCallExpr finish the job.
14832 
14833     // Create an implicit member expr to refer to the conversion operator.
14834     // and then call it.
14835     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14836                                              Conv, HadMultipleCandidates);
14837     if (Call.isInvalid())
14838       return ExprError();
14839     // Record usage of conversion in an implicit cast.
14840     Call = ImplicitCastExpr::Create(
14841         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14842         nullptr, VK_PRValue, CurFPFeatureOverrides());
14843 
14844     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14845   }
14846 
14847   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14848 
14849   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14850   // that calls this method, using Object for the implicit object
14851   // parameter and passing along the remaining arguments.
14852   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14853 
14854   // An error diagnostic has already been printed when parsing the declaration.
14855   if (Method->isInvalidDecl())
14856     return ExprError();
14857 
14858   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14859   unsigned NumParams = Proto->getNumParams();
14860 
14861   DeclarationNameInfo OpLocInfo(
14862                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14863   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14864   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14865                                            Obj, HadMultipleCandidates,
14866                                            OpLocInfo.getLoc(),
14867                                            OpLocInfo.getInfo());
14868   if (NewFn.isInvalid())
14869     return true;
14870 
14871   SmallVector<Expr *, 8> MethodArgs;
14872   MethodArgs.reserve(NumParams + 1);
14873 
14874   bool IsError = false;
14875 
14876   // Initialize the implicit object parameter.
14877   ExprResult ObjRes =
14878     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14879                                         Best->FoundDecl, Method);
14880   if (ObjRes.isInvalid())
14881     IsError = true;
14882   else
14883     Object = ObjRes;
14884   MethodArgs.push_back(Object.get());
14885 
14886   IsError |= PrepareArgumentsForCallToObjectOfClassType(
14887       *this, MethodArgs, Method, Args, LParenLoc);
14888 
14889   // If this is a variadic call, handle args passed through "...".
14890   if (Proto->isVariadic()) {
14891     // Promote the arguments (C99 6.5.2.2p7).
14892     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14893       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14894                                                         nullptr);
14895       IsError |= Arg.isInvalid();
14896       MethodArgs.push_back(Arg.get());
14897     }
14898   }
14899 
14900   if (IsError)
14901     return true;
14902 
14903   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14904 
14905   // Once we've built TheCall, all of the expressions are properly owned.
14906   QualType ResultTy = Method->getReturnType();
14907   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14908   ResultTy = ResultTy.getNonLValueExprType(Context);
14909 
14910   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14911       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14912       CurFPFeatureOverrides());
14913 
14914   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14915     return true;
14916 
14917   if (CheckFunctionCall(Method, TheCall, Proto))
14918     return true;
14919 
14920   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14921 }
14922 
14923 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14924 ///  (if one exists), where @c Base is an expression of class type and
14925 /// @c Member is the name of the member we're trying to find.
14926 ExprResult
14927 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14928                                bool *NoArrowOperatorFound) {
14929   assert(Base->getType()->isRecordType() &&
14930          "left-hand side must have class type");
14931 
14932   if (checkPlaceholderForOverload(*this, Base))
14933     return ExprError();
14934 
14935   SourceLocation Loc = Base->getExprLoc();
14936 
14937   // C++ [over.ref]p1:
14938   //
14939   //   [...] An expression x->m is interpreted as (x.operator->())->m
14940   //   for a class object x of type T if T::operator->() exists and if
14941   //   the operator is selected as the best match function by the
14942   //   overload resolution mechanism (13.3).
14943   DeclarationName OpName =
14944     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14945   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14946 
14947   if (RequireCompleteType(Loc, Base->getType(),
14948                           diag::err_typecheck_incomplete_tag, Base))
14949     return ExprError();
14950 
14951   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14952   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14953   R.suppressDiagnostics();
14954 
14955   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14956        Oper != OperEnd; ++Oper) {
14957     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14958                        None, CandidateSet, /*SuppressUserConversion=*/false);
14959   }
14960 
14961   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14962 
14963   // Perform overload resolution.
14964   OverloadCandidateSet::iterator Best;
14965   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14966   case OR_Success:
14967     // Overload resolution succeeded; we'll build the call below.
14968     break;
14969 
14970   case OR_No_Viable_Function: {
14971     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14972     if (CandidateSet.empty()) {
14973       QualType BaseType = Base->getType();
14974       if (NoArrowOperatorFound) {
14975         // Report this specific error to the caller instead of emitting a
14976         // diagnostic, as requested.
14977         *NoArrowOperatorFound = true;
14978         return ExprError();
14979       }
14980       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14981         << BaseType << Base->getSourceRange();
14982       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14983         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14984           << FixItHint::CreateReplacement(OpLoc, ".");
14985       }
14986     } else
14987       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14988         << "operator->" << Base->getSourceRange();
14989     CandidateSet.NoteCandidates(*this, Base, Cands);
14990     return ExprError();
14991   }
14992   case OR_Ambiguous:
14993     CandidateSet.NoteCandidates(
14994         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14995                                        << "->" << Base->getType()
14996                                        << Base->getSourceRange()),
14997         *this, OCD_AmbiguousCandidates, Base);
14998     return ExprError();
14999 
15000   case OR_Deleted:
15001     CandidateSet.NoteCandidates(
15002         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15003                                        << "->" << Base->getSourceRange()),
15004         *this, OCD_AllCandidates, Base);
15005     return ExprError();
15006   }
15007 
15008   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
15009 
15010   // Convert the object parameter.
15011   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15012   ExprResult BaseResult =
15013     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
15014                                         Best->FoundDecl, Method);
15015   if (BaseResult.isInvalid())
15016     return ExprError();
15017   Base = BaseResult.get();
15018 
15019   // Build the operator call.
15020   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15021                                             Base, HadMultipleCandidates, OpLoc);
15022   if (FnExpr.isInvalid())
15023     return ExprError();
15024 
15025   QualType ResultTy = Method->getReturnType();
15026   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15027   ResultTy = ResultTy.getNonLValueExprType(Context);
15028   CXXOperatorCallExpr *TheCall =
15029       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
15030                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
15031 
15032   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
15033     return ExprError();
15034 
15035   if (CheckFunctionCall(Method, TheCall,
15036                         Method->getType()->castAs<FunctionProtoType>()))
15037     return ExprError();
15038 
15039   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15040 }
15041 
15042 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15043 /// a literal operator described by the provided lookup results.
15044 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
15045                                           DeclarationNameInfo &SuffixInfo,
15046                                           ArrayRef<Expr*> Args,
15047                                           SourceLocation LitEndLoc,
15048                                        TemplateArgumentListInfo *TemplateArgs) {
15049   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
15050 
15051   OverloadCandidateSet CandidateSet(UDSuffixLoc,
15052                                     OverloadCandidateSet::CSK_Normal);
15053   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
15054                                  TemplateArgs);
15055 
15056   bool HadMultipleCandidates = (CandidateSet.size() > 1);
15057 
15058   // Perform overload resolution. This will usually be trivial, but might need
15059   // to perform substitutions for a literal operator template.
15060   OverloadCandidateSet::iterator Best;
15061   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
15062   case OR_Success:
15063   case OR_Deleted:
15064     break;
15065 
15066   case OR_No_Viable_Function:
15067     CandidateSet.NoteCandidates(
15068         PartialDiagnosticAt(UDSuffixLoc,
15069                             PDiag(diag::err_ovl_no_viable_function_in_call)
15070                                 << R.getLookupName()),
15071         *this, OCD_AllCandidates, Args);
15072     return ExprError();
15073 
15074   case OR_Ambiguous:
15075     CandidateSet.NoteCandidates(
15076         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
15077                                                 << R.getLookupName()),
15078         *this, OCD_AmbiguousCandidates, Args);
15079     return ExprError();
15080   }
15081 
15082   FunctionDecl *FD = Best->Function;
15083   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
15084                                         nullptr, HadMultipleCandidates,
15085                                         SuffixInfo.getLoc(),
15086                                         SuffixInfo.getInfo());
15087   if (Fn.isInvalid())
15088     return true;
15089 
15090   // Check the argument types. This should almost always be a no-op, except
15091   // that array-to-pointer decay is applied to string literals.
15092   Expr *ConvArgs[2];
15093   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
15094     ExprResult InputInit = PerformCopyInitialization(
15095       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
15096       SourceLocation(), Args[ArgIdx]);
15097     if (InputInit.isInvalid())
15098       return true;
15099     ConvArgs[ArgIdx] = InputInit.get();
15100   }
15101 
15102   QualType ResultTy = FD->getReturnType();
15103   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15104   ResultTy = ResultTy.getNonLValueExprType(Context);
15105 
15106   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
15107       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
15108       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
15109 
15110   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
15111     return ExprError();
15112 
15113   if (CheckFunctionCall(FD, UDL, nullptr))
15114     return ExprError();
15115 
15116   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
15117 }
15118 
15119 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15120 /// given LookupResult is non-empty, it is assumed to describe a member which
15121 /// will be invoked. Otherwise, the function will be found via argument
15122 /// dependent lookup.
15123 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15124 /// otherwise CallExpr is set to ExprError() and some non-success value
15125 /// is returned.
15126 Sema::ForRangeStatus
15127 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15128                                 SourceLocation RangeLoc,
15129                                 const DeclarationNameInfo &NameInfo,
15130                                 LookupResult &MemberLookup,
15131                                 OverloadCandidateSet *CandidateSet,
15132                                 Expr *Range, ExprResult *CallExpr) {
15133   Scope *S = nullptr;
15134 
15135   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15136   if (!MemberLookup.empty()) {
15137     ExprResult MemberRef =
15138         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15139                                  /*IsPtr=*/false, CXXScopeSpec(),
15140                                  /*TemplateKWLoc=*/SourceLocation(),
15141                                  /*FirstQualifierInScope=*/nullptr,
15142                                  MemberLookup,
15143                                  /*TemplateArgs=*/nullptr, S);
15144     if (MemberRef.isInvalid()) {
15145       *CallExpr = ExprError();
15146       return FRS_DiagnosticIssued;
15147     }
15148     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15149     if (CallExpr->isInvalid()) {
15150       *CallExpr = ExprError();
15151       return FRS_DiagnosticIssued;
15152     }
15153   } else {
15154     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15155                                                 NestedNameSpecifierLoc(),
15156                                                 NameInfo, UnresolvedSet<0>());
15157     if (FnR.isInvalid())
15158       return FRS_DiagnosticIssued;
15159     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15160 
15161     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15162                                                     CandidateSet, CallExpr);
15163     if (CandidateSet->empty() || CandidateSetError) {
15164       *CallExpr = ExprError();
15165       return FRS_NoViableFunction;
15166     }
15167     OverloadCandidateSet::iterator Best;
15168     OverloadingResult OverloadResult =
15169         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15170 
15171     if (OverloadResult == OR_No_Viable_Function) {
15172       *CallExpr = ExprError();
15173       return FRS_NoViableFunction;
15174     }
15175     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15176                                          Loc, nullptr, CandidateSet, &Best,
15177                                          OverloadResult,
15178                                          /*AllowTypoCorrection=*/false);
15179     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15180       *CallExpr = ExprError();
15181       return FRS_DiagnosticIssued;
15182     }
15183   }
15184   return FRS_Success;
15185 }
15186 
15187 
15188 /// FixOverloadedFunctionReference - E is an expression that refers to
15189 /// a C++ overloaded function (possibly with some parentheses and
15190 /// perhaps a '&' around it). We have resolved the overloaded function
15191 /// to the function declaration Fn, so patch up the expression E to
15192 /// refer (possibly indirectly) to Fn. Returns the new expr.
15193 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15194                                            FunctionDecl *Fn) {
15195   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15196     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15197                                                    Found, Fn);
15198     if (SubExpr == PE->getSubExpr())
15199       return PE;
15200 
15201     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15202   }
15203 
15204   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15205     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15206                                                    Found, Fn);
15207     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15208                                SubExpr->getType()) &&
15209            "Implicit cast type cannot be determined from overload");
15210     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15211     if (SubExpr == ICE->getSubExpr())
15212       return ICE;
15213 
15214     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15215                                     SubExpr, nullptr, ICE->getValueKind(),
15216                                     CurFPFeatureOverrides());
15217   }
15218 
15219   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15220     if (!GSE->isResultDependent()) {
15221       Expr *SubExpr =
15222           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15223       if (SubExpr == GSE->getResultExpr())
15224         return GSE;
15225 
15226       // Replace the resulting type information before rebuilding the generic
15227       // selection expression.
15228       ArrayRef<Expr *> A = GSE->getAssocExprs();
15229       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15230       unsigned ResultIdx = GSE->getResultIndex();
15231       AssocExprs[ResultIdx] = SubExpr;
15232 
15233       return GenericSelectionExpr::Create(
15234           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15235           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15236           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15237           ResultIdx);
15238     }
15239     // Rather than fall through to the unreachable, return the original generic
15240     // selection expression.
15241     return GSE;
15242   }
15243 
15244   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15245     assert(UnOp->getOpcode() == UO_AddrOf &&
15246            "Can only take the address of an overloaded function");
15247     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15248       if (Method->isStatic()) {
15249         // Do nothing: static member functions aren't any different
15250         // from non-member functions.
15251       } else {
15252         // Fix the subexpression, which really has to be an
15253         // UnresolvedLookupExpr holding an overloaded member function
15254         // or template.
15255         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15256                                                        Found, Fn);
15257         if (SubExpr == UnOp->getSubExpr())
15258           return UnOp;
15259 
15260         assert(isa<DeclRefExpr>(SubExpr)
15261                && "fixed to something other than a decl ref");
15262         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15263                && "fixed to a member ref with no nested name qualifier");
15264 
15265         // We have taken the address of a pointer to member
15266         // function. Perform the computation here so that we get the
15267         // appropriate pointer to member type.
15268         QualType ClassType
15269           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15270         QualType MemPtrType
15271           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15272         // Under the MS ABI, lock down the inheritance model now.
15273         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15274           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15275 
15276         return UnaryOperator::Create(
15277             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15278             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15279       }
15280     }
15281     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15282                                                    Found, Fn);
15283     if (SubExpr == UnOp->getSubExpr())
15284       return UnOp;
15285 
15286     // FIXME: This can't currently fail, but in principle it could.
15287     return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf, SubExpr)
15288         .get();
15289   }
15290 
15291   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15292     // FIXME: avoid copy.
15293     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15294     if (ULE->hasExplicitTemplateArgs()) {
15295       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15296       TemplateArgs = &TemplateArgsBuffer;
15297     }
15298 
15299     QualType Type = Fn->getType();
15300     ExprValueKind ValueKind = getLangOpts().CPlusPlus ? VK_LValue : VK_PRValue;
15301 
15302     // FIXME: Duplicated from BuildDeclarationNameExpr.
15303     if (unsigned BID = Fn->getBuiltinID()) {
15304       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
15305         Type = Context.BuiltinFnTy;
15306         ValueKind = VK_PRValue;
15307       }
15308     }
15309 
15310     DeclRefExpr *DRE = BuildDeclRefExpr(
15311         Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
15312         Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
15313     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15314     return DRE;
15315   }
15316 
15317   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15318     // FIXME: avoid copy.
15319     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15320     if (MemExpr->hasExplicitTemplateArgs()) {
15321       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15322       TemplateArgs = &TemplateArgsBuffer;
15323     }
15324 
15325     Expr *Base;
15326 
15327     // If we're filling in a static method where we used to have an
15328     // implicit member access, rewrite to a simple decl ref.
15329     if (MemExpr->isImplicitAccess()) {
15330       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15331         DeclRefExpr *DRE = BuildDeclRefExpr(
15332             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15333             MemExpr->getQualifierLoc(), Found.getDecl(),
15334             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15335         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15336         return DRE;
15337       } else {
15338         SourceLocation Loc = MemExpr->getMemberLoc();
15339         if (MemExpr->getQualifier())
15340           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15341         Base =
15342             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15343       }
15344     } else
15345       Base = MemExpr->getBase();
15346 
15347     ExprValueKind valueKind;
15348     QualType type;
15349     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15350       valueKind = VK_LValue;
15351       type = Fn->getType();
15352     } else {
15353       valueKind = VK_PRValue;
15354       type = Context.BoundMemberTy;
15355     }
15356 
15357     return BuildMemberExpr(
15358         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15359         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15360         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15361         type, valueKind, OK_Ordinary, TemplateArgs);
15362   }
15363 
15364   llvm_unreachable("Invalid reference to overloaded function");
15365 }
15366 
15367 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15368                                                 DeclAccessPair Found,
15369                                                 FunctionDecl *Fn) {
15370   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15371 }
15372 
15373 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
15374                                   FunctionDecl *Function) {
15375   if (!PartialOverloading || !Function)
15376     return true;
15377   if (Function->isVariadic())
15378     return false;
15379   if (const auto *Proto =
15380           dyn_cast<FunctionProtoType>(Function->getFunctionType()))
15381     if (Proto->isTemplateVariadic())
15382       return false;
15383   if (auto *Pattern = Function->getTemplateInstantiationPattern())
15384     if (const auto *Proto =
15385             dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
15386       if (Proto->isTemplateVariadic())
15387         return false;
15388   return true;
15389 }
15390