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
53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54                       const Expr *Base, bool HadMultipleCandidates,
55                       SourceLocation Loc = SourceLocation(),
56                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58     return ExprError();
59   // If FoundDecl is different from Fn (such as if one is a template
60   // and the other a specialization), make sure DiagnoseUseOfDecl is
61   // called on both.
62   // FIXME: This would be more comprehensively addressed by modifying
63   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64   // being used.
65   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66     return ExprError();
67   DeclRefExpr *DRE = new (S.Context)
68       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69   if (HadMultipleCandidates)
70     DRE->setHadMultipleCandidates(true);
71 
72   S.MarkDeclRefReferenced(DRE, Base);
73   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75       S.ResolveExceptionSpec(Loc, FPT);
76       DRE->setType(Fn->getType());
77     }
78   }
79   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80                              CK_FunctionToPointerDecay);
81 }
82 
83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84                                  bool InOverloadResolution,
85                                  StandardConversionSequence &SCS,
86                                  bool CStyle,
87                                  bool AllowObjCWritebackConversion);
88 
89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90                                                  QualType &ToType,
91                                                  bool InOverloadResolution,
92                                                  StandardConversionSequence &SCS,
93                                                  bool CStyle);
94 static OverloadingResult
95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96                         UserDefinedConversionSequence& User,
97                         OverloadCandidateSet& Conversions,
98                         AllowedExplicit AllowExplicit,
99                         bool AllowObjCConversionOnExplicit);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103                                    const StandardConversionSequence& SCS1,
104                                    const StandardConversionSequence& SCS2);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareQualificationConversions(Sema &S,
108                                 const StandardConversionSequence& SCS1,
109                                 const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 /// GetConversionRank - Retrieve the implicit conversion rank
117 /// corresponding to the given implicit conversion kind.
118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119   static const ImplicitConversionRank
120     Rank[(int)ICK_Num_Conversion_Kinds] = {
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Promotion,
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_Conversion,
141     ICR_OCL_Scalar_Widening,
142     ICR_Complex_Real_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Writeback_Conversion,
146     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147                      // it was omitted by the patch that added
148                      // ICK_Zero_Event_Conversion
149     ICR_C_Conversion,
150     ICR_C_Conversion_Extension
151   };
152   return Rank[(int)Kind];
153 }
154 
155 /// GetImplicitConversionName - Return the name of this kind of
156 /// implicit conversion.
157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159     "No conversion",
160     "Lvalue-to-rvalue",
161     "Array-to-pointer",
162     "Function-to-pointer",
163     "Function pointer conversion",
164     "Qualification",
165     "Integral promotion",
166     "Floating point promotion",
167     "Complex promotion",
168     "Integral conversion",
169     "Floating conversion",
170     "Complex conversion",
171     "Floating-integral conversion",
172     "Pointer conversion",
173     "Pointer-to-member conversion",
174     "Boolean conversion",
175     "Compatible-types conversion",
176     "Derived-to-base conversion",
177     "Vector conversion",
178     "SVE Vector conversion",
179     "Vector splat",
180     "Complex-real conversion",
181     "Block Pointer conversion",
182     "Transparent Union Conversion",
183     "Writeback conversion",
184     "OpenCL Zero Event Conversion",
185     "C specific type conversion",
186     "Incompatible pointer conversion"
187   };
188   return Name[Kind];
189 }
190 
191 /// StandardConversionSequence - Set the standard conversion
192 /// sequence to the identity conversion.
193 void StandardConversionSequence::setAsIdentityConversion() {
194   First = ICK_Identity;
195   Second = ICK_Identity;
196   Third = ICK_Identity;
197   DeprecatedStringLiteralToCharPtr = false;
198   QualificationIncludesObjCLifetime = false;
199   ReferenceBinding = false;
200   DirectBinding = false;
201   IsLvalueReference = true;
202   BindsToFunctionLvalue = false;
203   BindsToRvalue = false;
204   BindsImplicitObjectArgumentWithoutRefQualifier = false;
205   ObjCLifetimeConversionBinding = false;
206   CopyConstructor = nullptr;
207 }
208 
209 /// getRank - Retrieve the rank of this standard conversion sequence
210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211 /// implicit conversions.
212 ImplicitConversionRank StandardConversionSequence::getRank() const {
213   ImplicitConversionRank Rank = ICR_Exact_Match;
214   if  (GetConversionRank(First) > Rank)
215     Rank = GetConversionRank(First);
216   if  (GetConversionRank(Second) > Rank)
217     Rank = GetConversionRank(Second);
218   if  (GetConversionRank(Third) > Rank)
219     Rank = GetConversionRank(Third);
220   return Rank;
221 }
222 
223 /// isPointerConversionToBool - Determines whether this conversion is
224 /// a conversion of a pointer or pointer-to-member to bool. This is
225 /// used as part of the ranking of standard conversion sequences
226 /// (C++ 13.3.3.2p4).
227 bool StandardConversionSequence::isPointerConversionToBool() const {
228   // Note that FromType has not necessarily been transformed by the
229   // array-to-pointer or function-to-pointer implicit conversions, so
230   // check for their presence as well as checking whether FromType is
231   // a pointer.
232   if (getToType(1)->isBooleanType() &&
233       (getFromType()->isPointerType() ||
234        getFromType()->isMemberPointerType() ||
235        getFromType()->isObjCObjectPointerType() ||
236        getFromType()->isBlockPointerType() ||
237        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238     return true;
239 
240   return false;
241 }
242 
243 /// isPointerConversionToVoidPointer - Determines whether this
244 /// conversion is a conversion of a pointer to a void pointer. This is
245 /// used as part of the ranking of standard conversion sequences (C++
246 /// 13.3.3.2p4).
247 bool
248 StandardConversionSequence::
249 isPointerConversionToVoidPointer(ASTContext& Context) const {
250   QualType FromType = getFromType();
251   QualType ToType = getToType(1);
252 
253   // Note that FromType has not necessarily been transformed by the
254   // array-to-pointer implicit conversion, so check for its presence
255   // and redo the conversion to get a pointer.
256   if (First == ICK_Array_To_Pointer)
257     FromType = Context.getArrayDecayedType(FromType);
258 
259   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261       return ToPtrType->getPointeeType()->isVoidType();
262 
263   return false;
264 }
265 
266 /// Skip any implicit casts which could be either part of a narrowing conversion
267 /// or after one in an implicit conversion.
268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269                                              const Expr *Converted) {
270   // We can have cleanups wrapping the converted expression; these need to be
271   // preserved so that destructors run if necessary.
272   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273     Expr *Inner =
274         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276                                     EWC->getObjects());
277   }
278 
279   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280     switch (ICE->getCastKind()) {
281     case CK_NoOp:
282     case CK_IntegralCast:
283     case CK_IntegralToBoolean:
284     case CK_IntegralToFloating:
285     case CK_BooleanToSignedIntegral:
286     case CK_FloatingToIntegral:
287     case CK_FloatingToBoolean:
288     case CK_FloatingCast:
289       Converted = ICE->getSubExpr();
290       continue;
291 
292     default:
293       return Converted;
294     }
295   }
296 
297   return Converted;
298 }
299 
300 /// Check if this standard conversion sequence represents a narrowing
301 /// conversion, according to C++11 [dcl.init.list]p7.
302 ///
303 /// \param Ctx  The AST context.
304 /// \param Converted  The result of applying this standard conversion sequence.
305 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306 ///        value of the expression prior to the narrowing conversion.
307 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308 ///        type of the expression prior to the narrowing conversion.
309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310 ///        from floating point types to integral types should be ignored.
311 NarrowingKind StandardConversionSequence::getNarrowingKind(
312     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315 
316   // C++11 [dcl.init.list]p7:
317   //   A narrowing conversion is an implicit conversion ...
318   QualType FromType = getToType(0);
319   QualType ToType = getToType(1);
320 
321   // A conversion to an enumeration type is narrowing if the conversion to
322   // the underlying type is narrowing. This only arises for expressions of
323   // the form 'Enum{init}'.
324   if (auto *ET = ToType->getAs<EnumType>())
325     ToType = ET->getDecl()->getIntegerType();
326 
327   switch (Second) {
328   // 'bool' is an integral type; dispatch to the right place to handle it.
329   case ICK_Boolean_Conversion:
330     if (FromType->isRealFloatingType())
331       goto FloatingIntegralConversion;
332     if (FromType->isIntegralOrUnscopedEnumerationType())
333       goto IntegralConversion;
334     // -- from a pointer type or pointer-to-member type to bool, or
335     return NK_Type_Narrowing;
336 
337   // -- from a floating-point type to an integer type, or
338   //
339   // -- from an integer type or unscoped enumeration type to a floating-point
340   //    type, except where the source is a constant expression and the actual
341   //    value after conversion will fit into the target type and will produce
342   //    the original value when converted back to the original type, or
343   case ICK_Floating_Integral:
344   FloatingIntegralConversion:
345     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346       return NK_Type_Narrowing;
347     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348                ToType->isRealFloatingType()) {
349       if (IgnoreFloatToIntegralConversion)
350         return NK_Not_Narrowing;
351       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352       assert(Initializer && "Unknown conversion expression");
353 
354       // If it's value-dependent, we can't tell whether it's narrowing.
355       if (Initializer->isValueDependent())
356         return NK_Dependent_Narrowing;
357 
358       if (Optional<llvm::APSInt> IntConstantValue =
359               Initializer->getIntegerConstantExpr(Ctx)) {
360         // Convert the integer to the floating type.
361         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363                                 llvm::APFloat::rmNearestTiesToEven);
364         // And back.
365         llvm::APSInt ConvertedValue = *IntConstantValue;
366         bool ignored;
367         Result.convertToInteger(ConvertedValue,
368                                 llvm::APFloat::rmTowardZero, &ignored);
369         // If the resulting value is different, this was a narrowing conversion.
370         if (*IntConstantValue != ConvertedValue) {
371           ConstantValue = APValue(*IntConstantValue);
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         // Variables are always narrowings.
377         return NK_Variable_Narrowing;
378       }
379     }
380     return NK_Not_Narrowing;
381 
382   // -- from long double to double or float, or from double to float, except
383   //    where the source is a constant expression and the actual value after
384   //    conversion is within the range of values that can be represented (even
385   //    if it cannot be represented exactly), or
386   case ICK_Floating_Conversion:
387     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389       // FromType is larger than ToType.
390       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391 
392       // If it's value-dependent, we can't tell whether it's narrowing.
393       if (Initializer->isValueDependent())
394         return NK_Dependent_Narrowing;
395 
396       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397         // Constant!
398         assert(ConstantValue.isFloat());
399         llvm::APFloat FloatVal = ConstantValue.getFloat();
400         // Convert the source value into the target type.
401         bool ignored;
402         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403           Ctx.getFloatTypeSemantics(ToType),
404           llvm::APFloat::rmNearestTiesToEven, &ignored);
405         // If there was no overflow, the source value is within the range of
406         // values that can be represented.
407         if (ConvertStatus & llvm::APFloat::opOverflow) {
408           ConstantType = Initializer->getType();
409           return NK_Constant_Narrowing;
410         }
411       } else {
412         return NK_Variable_Narrowing;
413       }
414     }
415     return NK_Not_Narrowing;
416 
417   // -- from an integer type or unscoped enumeration type to an integer type
418   //    that cannot represent all the values of the original type, except where
419   //    the source is a constant expression and the actual value after
420   //    conversion will fit into the target type and will produce the original
421   //    value when converted back to the original type.
422   case ICK_Integral_Conversion:
423   IntegralConversion: {
424     assert(FromType->isIntegralOrUnscopedEnumerationType());
425     assert(ToType->isIntegralOrUnscopedEnumerationType());
426     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427     const unsigned FromWidth = Ctx.getIntWidth(FromType);
428     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429     const unsigned ToWidth = Ctx.getIntWidth(ToType);
430 
431     if (FromWidth > ToWidth ||
432         (FromWidth == ToWidth && FromSigned != ToSigned) ||
433         (FromSigned && !ToSigned)) {
434       // Not all values of FromType can be represented in ToType.
435       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436 
437       // If it's value-dependent, we can't tell whether it's narrowing.
438       if (Initializer->isValueDependent())
439         return NK_Dependent_Narrowing;
440 
441       Optional<llvm::APSInt> OptInitializerValue;
442       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443         // Such conversions on variables are always narrowing.
444         return NK_Variable_Narrowing;
445       }
446       llvm::APSInt &InitializerValue = *OptInitializerValue;
447       bool Narrowing = false;
448       if (FromWidth < ToWidth) {
449         // Negative -> unsigned is narrowing. Otherwise, more bits is never
450         // narrowing.
451         if (InitializerValue.isSigned() && InitializerValue.isNegative())
452           Narrowing = true;
453       } else {
454         // Add a bit to the InitializerValue so we don't have to worry about
455         // signed vs. unsigned comparisons.
456         InitializerValue = InitializerValue.extend(
457           InitializerValue.getBitWidth() + 1);
458         // Convert the initializer to and from the target width and signed-ness.
459         llvm::APSInt ConvertedValue = InitializerValue;
460         ConvertedValue = ConvertedValue.trunc(ToWidth);
461         ConvertedValue.setIsSigned(ToSigned);
462         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463         ConvertedValue.setIsSigned(InitializerValue.isSigned());
464         // If the result is different, this was a narrowing conversion.
465         if (ConvertedValue != InitializerValue)
466           Narrowing = true;
467       }
468       if (Narrowing) {
469         ConstantType = Initializer->getType();
470         ConstantValue = APValue(InitializerValue);
471         return NK_Constant_Narrowing;
472       }
473     }
474     return NK_Not_Narrowing;
475   }
476 
477   default:
478     // Other kinds of conversions are not narrowings.
479     return NK_Not_Narrowing;
480   }
481 }
482 
483 /// dump - Print this standard conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   bool PrintedSomething = false;
488   if (First != ICK_Identity) {
489     OS << GetImplicitConversionName(First);
490     PrintedSomething = true;
491   }
492 
493   if (Second != ICK_Identity) {
494     if (PrintedSomething) {
495       OS << " -> ";
496     }
497     OS << GetImplicitConversionName(Second);
498 
499     if (CopyConstructor) {
500       OS << " (by copy constructor)";
501     } else if (DirectBinding) {
502       OS << " (direct reference binding)";
503     } else if (ReferenceBinding) {
504       OS << " (reference binding)";
505     }
506     PrintedSomething = true;
507   }
508 
509   if (Third != ICK_Identity) {
510     if (PrintedSomething) {
511       OS << " -> ";
512     }
513     OS << GetImplicitConversionName(Third);
514     PrintedSomething = true;
515   }
516 
517   if (!PrintedSomething) {
518     OS << "No conversions required";
519   }
520 }
521 
522 /// dump - Print this user-defined conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void UserDefinedConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (Before.First || Before.Second || Before.Third) {
527     Before.dump();
528     OS << " -> ";
529   }
530   if (ConversionFunction)
531     OS << '\'' << *ConversionFunction << '\'';
532   else
533     OS << "aggregate initialization";
534   if (After.First || After.Second || After.Third) {
535     OS << " -> ";
536     After.dump();
537   }
538 }
539 
540 /// dump - Print this implicit conversion sequence to standard
541 /// error. Useful for debugging overloading issues.
542 void ImplicitConversionSequence::dump() const {
543   raw_ostream &OS = llvm::errs();
544   if (hasInitializerListContainerType())
545     OS << "Worst list element conversion: ";
546   switch (ConversionKind) {
547   case StandardConversion:
548     OS << "Standard conversion: ";
549     Standard.dump();
550     break;
551   case UserDefinedConversion:
552     OS << "User-defined conversion: ";
553     UserDefined.dump();
554     break;
555   case EllipsisConversion:
556     OS << "Ellipsis conversion";
557     break;
558   case AmbiguousConversion:
559     OS << "Ambiguous conversion";
560     break;
561   case BadConversion:
562     OS << "Bad conversion";
563     break;
564   }
565 
566   OS << "\n";
567 }
568 
569 void AmbiguousConversionSequence::construct() {
570   new (&conversions()) ConversionSet();
571 }
572 
573 void AmbiguousConversionSequence::destruct() {
574   conversions().~ConversionSet();
575 }
576 
577 void
578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579   FromTypePtr = O.FromTypePtr;
580   ToTypePtr = O.ToTypePtr;
581   new (&conversions()) ConversionSet(O.conversions());
582 }
583 
584 namespace {
585   // Structure used by DeductionFailureInfo to store
586   // template argument information.
587   struct DFIArguments {
588     TemplateArgument FirstArg;
589     TemplateArgument SecondArg;
590   };
591   // Structure used by DeductionFailureInfo to store
592   // template parameter and template argument information.
593   struct DFIParamWithArguments : DFIArguments {
594     TemplateParameter Param;
595   };
596   // Structure used by DeductionFailureInfo to store template argument
597   // information and the index of the problematic call argument.
598   struct DFIDeducedMismatchArgs : DFIArguments {
599     TemplateArgumentList *TemplateArgs;
600     unsigned CallArgIndex;
601   };
602   // Structure used by DeductionFailureInfo to store information about
603   // unsatisfied constraints.
604   struct CNSInfo {
605     TemplateArgumentList *TemplateArgs;
606     ConstraintSatisfaction Satisfaction;
607   };
608 }
609 
610 /// Convert from Sema's representation of template deduction information
611 /// to the form used in overload-candidate information.
612 DeductionFailureInfo
613 clang::MakeDeductionFailureInfo(ASTContext &Context,
614                                 Sema::TemplateDeductionResult TDK,
615                                 TemplateDeductionInfo &Info) {
616   DeductionFailureInfo Result;
617   Result.Result = static_cast<unsigned>(TDK);
618   Result.HasDiagnostic = false;
619   switch (TDK) {
620   case Sema::TDK_Invalid:
621   case Sema::TDK_InstantiationDepth:
622   case Sema::TDK_TooManyArguments:
623   case Sema::TDK_TooFewArguments:
624   case Sema::TDK_MiscellaneousDeductionFailure:
625   case Sema::TDK_CUDATargetMismatch:
626     Result.Data = nullptr;
627     break;
628 
629   case Sema::TDK_Incomplete:
630   case Sema::TDK_InvalidExplicitArguments:
631     Result.Data = Info.Param.getOpaqueValue();
632     break;
633 
634   case Sema::TDK_DeducedMismatch:
635   case Sema::TDK_DeducedMismatchNested: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     auto *Saved = new (Context) DFIDeducedMismatchArgs;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Saved->TemplateArgs = Info.take();
641     Saved->CallArgIndex = Info.CallArgIndex;
642     Result.Data = Saved;
643     break;
644   }
645 
646   case Sema::TDK_NonDeducedMismatch: {
647     // FIXME: Should allocate from normal heap so that we can free this later.
648     DFIArguments *Saved = new (Context) DFIArguments;
649     Saved->FirstArg = Info.FirstArg;
650     Saved->SecondArg = Info.SecondArg;
651     Result.Data = Saved;
652     break;
653   }
654 
655   case Sema::TDK_IncompletePack:
656     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657   case Sema::TDK_Inconsistent:
658   case Sema::TDK_Underqualified: {
659     // FIXME: Should allocate from normal heap so that we can free this later.
660     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661     Saved->Param = Info.Param;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_SubstitutionFailure:
669     Result.Data = Info.take();
670     if (Info.hasSFINAEDiagnostic()) {
671       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672           SourceLocation(), PartialDiagnostic::NullDiagnostic());
673       Info.takeSFINAEDiagnostic(*Diag);
674       Result.HasDiagnostic = true;
675     }
676     break;
677 
678   case Sema::TDK_ConstraintsNotSatisfied: {
679     CNSInfo *Saved = new (Context) CNSInfo;
680     Saved->TemplateArgs = Info.take();
681     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682     Result.Data = Saved;
683     break;
684   }
685 
686   case Sema::TDK_Success:
687   case Sema::TDK_NonDependentConversionFailure:
688     llvm_unreachable("not a deduction failure");
689   }
690 
691   return Result;
692 }
693 
694 void DeductionFailureInfo::Destroy() {
695   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696   case Sema::TDK_Success:
697   case Sema::TDK_Invalid:
698   case Sema::TDK_InstantiationDepth:
699   case Sema::TDK_Incomplete:
700   case Sema::TDK_TooManyArguments:
701   case Sema::TDK_TooFewArguments:
702   case Sema::TDK_InvalidExplicitArguments:
703   case Sema::TDK_CUDATargetMismatch:
704   case Sema::TDK_NonDependentConversionFailure:
705     break;
706 
707   case Sema::TDK_IncompletePack:
708   case Sema::TDK_Inconsistent:
709   case Sema::TDK_Underqualified:
710   case Sema::TDK_DeducedMismatch:
711   case Sema::TDK_DeducedMismatchNested:
712   case Sema::TDK_NonDeducedMismatch:
713     // FIXME: Destroy the data?
714     Data = nullptr;
715     break;
716 
717   case Sema::TDK_SubstitutionFailure:
718     // FIXME: Destroy the template argument list?
719     Data = nullptr;
720     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721       Diag->~PartialDiagnosticAt();
722       HasDiagnostic = false;
723     }
724     break;
725 
726   case Sema::TDK_ConstraintsNotSatisfied:
727     // FIXME: Destroy the template argument list?
728     Data = nullptr;
729     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730       Diag->~PartialDiagnosticAt();
731       HasDiagnostic = false;
732     }
733     break;
734 
735   // Unhandled
736   case Sema::TDK_MiscellaneousDeductionFailure:
737     break;
738   }
739 }
740 
741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742   if (HasDiagnostic)
743     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744   return nullptr;
745 }
746 
747 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749   case Sema::TDK_Success:
750   case Sema::TDK_Invalid:
751   case Sema::TDK_InstantiationDepth:
752   case Sema::TDK_TooManyArguments:
753   case Sema::TDK_TooFewArguments:
754   case Sema::TDK_SubstitutionFailure:
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757   case Sema::TDK_NonDeducedMismatch:
758   case Sema::TDK_CUDATargetMismatch:
759   case Sema::TDK_NonDependentConversionFailure:
760   case Sema::TDK_ConstraintsNotSatisfied:
761     return TemplateParameter();
762 
763   case Sema::TDK_Incomplete:
764   case Sema::TDK_InvalidExplicitArguments:
765     return TemplateParameter::getFromOpaqueValue(Data);
766 
767   case Sema::TDK_IncompletePack:
768   case Sema::TDK_Inconsistent:
769   case Sema::TDK_Underqualified:
770     return static_cast<DFIParamWithArguments*>(Data)->Param;
771 
772   // Unhandled
773   case Sema::TDK_MiscellaneousDeductionFailure:
774     break;
775   }
776 
777   return TemplateParameter();
778 }
779 
780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782   case Sema::TDK_Success:
783   case Sema::TDK_Invalid:
784   case Sema::TDK_InstantiationDepth:
785   case Sema::TDK_TooManyArguments:
786   case Sema::TDK_TooFewArguments:
787   case Sema::TDK_Incomplete:
788   case Sema::TDK_IncompletePack:
789   case Sema::TDK_InvalidExplicitArguments:
790   case Sema::TDK_Inconsistent:
791   case Sema::TDK_Underqualified:
792   case Sema::TDK_NonDeducedMismatch:
793   case Sema::TDK_CUDATargetMismatch:
794   case Sema::TDK_NonDependentConversionFailure:
795     return nullptr;
796 
797   case Sema::TDK_DeducedMismatch:
798   case Sema::TDK_DeducedMismatchNested:
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800 
801   case Sema::TDK_SubstitutionFailure:
802     return static_cast<TemplateArgumentList*>(Data);
803 
804   case Sema::TDK_ConstraintsNotSatisfied:
805     return static_cast<CNSInfo*>(Data)->TemplateArgs;
806 
807   // Unhandled
808   case Sema::TDK_MiscellaneousDeductionFailure:
809     break;
810   }
811 
812   return nullptr;
813 }
814 
815 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817   case Sema::TDK_Success:
818   case Sema::TDK_Invalid:
819   case Sema::TDK_InstantiationDepth:
820   case Sema::TDK_Incomplete:
821   case Sema::TDK_TooManyArguments:
822   case Sema::TDK_TooFewArguments:
823   case Sema::TDK_InvalidExplicitArguments:
824   case Sema::TDK_SubstitutionFailure:
825   case Sema::TDK_CUDATargetMismatch:
826   case Sema::TDK_NonDependentConversionFailure:
827   case Sema::TDK_ConstraintsNotSatisfied:
828     return nullptr;
829 
830   case Sema::TDK_IncompletePack:
831   case Sema::TDK_Inconsistent:
832   case Sema::TDK_Underqualified:
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835   case Sema::TDK_NonDeducedMismatch:
836     return &static_cast<DFIArguments*>(Data)->FirstArg;
837 
838   // Unhandled
839   case Sema::TDK_MiscellaneousDeductionFailure:
840     break;
841   }
842 
843   return nullptr;
844 }
845 
846 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848   case Sema::TDK_Success:
849   case Sema::TDK_Invalid:
850   case Sema::TDK_InstantiationDepth:
851   case Sema::TDK_Incomplete:
852   case Sema::TDK_IncompletePack:
853   case Sema::TDK_TooManyArguments:
854   case Sema::TDK_TooFewArguments:
855   case Sema::TDK_InvalidExplicitArguments:
856   case Sema::TDK_SubstitutionFailure:
857   case Sema::TDK_CUDATargetMismatch:
858   case Sema::TDK_NonDependentConversionFailure:
859   case Sema::TDK_ConstraintsNotSatisfied:
860     return nullptr;
861 
862   case Sema::TDK_Inconsistent:
863   case Sema::TDK_Underqualified:
864   case Sema::TDK_DeducedMismatch:
865   case Sema::TDK_DeducedMismatchNested:
866   case Sema::TDK_NonDeducedMismatch:
867     return &static_cast<DFIArguments*>(Data)->SecondArg;
868 
869   // Unhandled
870   case Sema::TDK_MiscellaneousDeductionFailure:
871     break;
872   }
873 
874   return nullptr;
875 }
876 
877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879   case Sema::TDK_DeducedMismatch:
880   case Sema::TDK_DeducedMismatchNested:
881     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882 
883   default:
884     return llvm::None;
885   }
886 }
887 
888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889     OverloadedOperatorKind Op) {
890   if (!AllowRewrittenCandidates)
891     return false;
892   return Op == OO_EqualEqual || Op == OO_Spaceship;
893 }
894 
895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896     ASTContext &Ctx, const FunctionDecl *FD) {
897   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898     return false;
899   // Don't bother adding a reversed candidate that can never be a better
900   // match than the non-reversed version.
901   return FD->getNumParams() != 2 ||
902          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903                                      FD->getParamDecl(1)->getType()) ||
904          FD->hasAttr<EnableIfAttr>();
905 }
906 
907 void OverloadCandidateSet::destroyCandidates() {
908   for (iterator i = begin(), e = end(); i != e; ++i) {
909     for (auto &C : i->Conversions)
910       C.~ImplicitConversionSequence();
911     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912       i->DeductionFailure.Destroy();
913   }
914 }
915 
916 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917   destroyCandidates();
918   SlabAllocator.Reset();
919   NumInlineBytesUsed = 0;
920   Candidates.clear();
921   Functions.clear();
922   Kind = CSK;
923 }
924 
925 namespace {
926   class UnbridgedCastsSet {
927     struct Entry {
928       Expr **Addr;
929       Expr *Saved;
930     };
931     SmallVector<Entry, 2> Entries;
932 
933   public:
934     void save(Sema &S, Expr *&E) {
935       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
936       Entry entry = { &E, E };
937       Entries.push_back(entry);
938       E = S.stripARCUnbridgedCast(E);
939     }
940 
941     void restore() {
942       for (SmallVectorImpl<Entry>::iterator
943              i = Entries.begin(), e = Entries.end(); i != e; ++i)
944         *i->Addr = i->Saved;
945     }
946   };
947 }
948 
949 /// checkPlaceholderForOverload - Do any interesting placeholder-like
950 /// preprocessing on the given expression.
951 ///
952 /// \param unbridgedCasts a collection to which to add unbridged casts;
953 ///   without this, they will be immediately diagnosed as errors
954 ///
955 /// Return true on unrecoverable error.
956 static bool
957 checkPlaceholderForOverload(Sema &S, Expr *&E,
958                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
959   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
960     // We can't handle overloaded expressions here because overload
961     // resolution might reasonably tweak them.
962     if (placeholder->getKind() == BuiltinType::Overload) return false;
963 
964     // If the context potentially accepts unbridged ARC casts, strip
965     // the unbridged cast and add it to the collection for later restoration.
966     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967         unbridgedCasts) {
968       unbridgedCasts->save(S, E);
969       return false;
970     }
971 
972     // Go ahead and check everything else.
973     ExprResult result = S.CheckPlaceholderExpr(E);
974     if (result.isInvalid())
975       return true;
976 
977     E = result.get();
978     return false;
979   }
980 
981   // Nothing to do.
982   return false;
983 }
984 
985 /// checkArgPlaceholdersForOverload - Check a set of call operands for
986 /// placeholders.
987 static bool checkArgPlaceholdersForOverload(Sema &S,
988                                             MultiExprArg Args,
989                                             UnbridgedCastsSet &unbridged) {
990   for (unsigned i = 0, e = Args.size(); i != e; ++i)
991     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992       return true;
993 
994   return false;
995 }
996 
997 /// Determine whether the given New declaration is an overload of the
998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001 /// functions (or function templates) at all. When it does return Ovl_Match or
1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004 /// declaration.
1005 ///
1006 /// Example: Given the following input:
1007 ///
1008 ///   void f(int, float); // #1
1009 ///   void f(int, int); // #2
1010 ///   int f(int, int); // #3
1011 ///
1012 /// When we process #1, there is no previous declaration of "f", so IsOverload
1013 /// will not be used.
1014 ///
1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018 /// unchanged.
1019 ///
1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1024 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1025 ///
1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027 /// by a using declaration. The rules for whether to hide shadow declarations
1028 /// ignore some properties which otherwise figure into a function template's
1029 /// signature.
1030 Sema::OverloadKind
1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032                     NamedDecl *&Match, bool NewIsUsingDecl) {
1033   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034          I != E; ++I) {
1035     NamedDecl *OldD = *I;
1036 
1037     bool OldIsUsingDecl = false;
1038     if (isa<UsingShadowDecl>(OldD)) {
1039       OldIsUsingDecl = true;
1040 
1041       // We can always introduce two using declarations into the same
1042       // context, even if they have identical signatures.
1043       if (NewIsUsingDecl) continue;
1044 
1045       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046     }
1047 
1048     // A using-declaration does not conflict with another declaration
1049     // if one of them is hidden.
1050     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051       continue;
1052 
1053     // If either declaration was introduced by a using declaration,
1054     // we'll need to use slightly different rules for matching.
1055     // Essentially, these rules are the normal rules, except that
1056     // function templates hide function templates with different
1057     // return types or template parameter lists.
1058     bool UseMemberUsingDeclRules =
1059       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060       !New->getFriendObjectKind();
1061 
1062     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066           continue;
1067         }
1068 
1069         if (!isa<FunctionTemplateDecl>(OldD) &&
1070             !shouldLinkPossiblyHiddenDecl(*I, New))
1071           continue;
1072 
1073         Match = *I;
1074         return Ovl_Match;
1075       }
1076 
1077       // Builtins that have custom typechecking or have a reference should
1078       // not be overloadable or redeclarable.
1079       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080         Match = *I;
1081         return Ovl_NonFunction;
1082       }
1083     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084       // We can overload with these, which can show up when doing
1085       // redeclaration checks for UsingDecls.
1086       assert(Old.getLookupKind() == LookupUsingDeclName);
1087     } else if (isa<TagDecl>(OldD)) {
1088       // We can always overload with tags by hiding them.
1089     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090       // Optimistically assume that an unresolved using decl will
1091       // overload; if it doesn't, we'll have to diagnose during
1092       // template instantiation.
1093       //
1094       // Exception: if the scope is dependent and this is not a class
1095       // member, the using declaration can only introduce an enumerator.
1096       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097         Match = *I;
1098         return Ovl_NonFunction;
1099       }
1100     } else {
1101       // (C++ 13p1):
1102       //   Only function declarations can be overloaded; object and type
1103       //   declarations cannot be overloaded.
1104       Match = *I;
1105       return Ovl_NonFunction;
1106     }
1107   }
1108 
1109   // C++ [temp.friend]p1:
1110   //   For a friend function declaration that is not a template declaration:
1111   //    -- if the name of the friend is a qualified or unqualified template-id,
1112   //       [...], otherwise
1113   //    -- if the name of the friend is a qualified-id and a matching
1114   //       non-template function is found in the specified class or namespace,
1115   //       the friend declaration refers to that function, otherwise,
1116   //    -- if the name of the friend is a qualified-id and a matching function
1117   //       template is found in the specified class or namespace, the friend
1118   //       declaration refers to the deduced specialization of that function
1119   //       template, otherwise
1120   //    -- the name shall be an unqualified-id [...]
1121   // If we get here for a qualified friend declaration, we've just reached the
1122   // third bullet. If the type of the friend is dependent, skip this lookup
1123   // until instantiation.
1124   if (New->getFriendObjectKind() && New->getQualifier() &&
1125       !New->getDescribedFunctionTemplate() &&
1126       !New->getDependentSpecializationInfo() &&
1127       !New->getType()->isDependentType()) {
1128     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129     TemplateSpecResult.addAllDecls(Old);
1130     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131                                             /*QualifiedFriend*/true)) {
1132       New->setInvalidDecl();
1133       return Ovl_Overload;
1134     }
1135 
1136     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137     return Ovl_Match;
1138   }
1139 
1140   return Ovl_Overload;
1141 }
1142 
1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145                       bool ConsiderRequiresClauses) {
1146   // C++ [basic.start.main]p2: This function shall not be overloaded.
1147   if (New->isMain())
1148     return false;
1149 
1150   // MSVCRT user defined entry points cannot be overloaded.
1151   if (New->isMSVCRTEntryPoint())
1152     return false;
1153 
1154   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156 
1157   // C++ [temp.fct]p2:
1158   //   A function template can be overloaded with other function templates
1159   //   and with normal (non-template) functions.
1160   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161     return true;
1162 
1163   // Is the function New an overload of the function Old?
1164   QualType OldQType = Context.getCanonicalType(Old->getType());
1165   QualType NewQType = Context.getCanonicalType(New->getType());
1166 
1167   // Compare the signatures (C++ 1.3.10) of the two functions to
1168   // determine whether they are overloads. If we find any mismatch
1169   // in the signature, they are overloads.
1170 
1171   // If either of these functions is a K&R-style function (no
1172   // prototype), then we consider them to have matching signatures.
1173   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175     return false;
1176 
1177   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179 
1180   // The signature of a function includes the types of its
1181   // parameters (C++ 1.3.10), which includes the presence or absence
1182   // of the ellipsis; see C++ DR 357).
1183   if (OldQType != NewQType &&
1184       (OldType->getNumParams() != NewType->getNumParams() ||
1185        OldType->isVariadic() != NewType->isVariadic() ||
1186        !FunctionParamTypesAreEqual(OldType, NewType)))
1187     return true;
1188 
1189   // C++ [temp.over.link]p4:
1190   //   The signature of a function template consists of its function
1191   //   signature, its return type and its template parameter list. The names
1192   //   of the template parameters are significant only for establishing the
1193   //   relationship between the template parameters and the rest of the
1194   //   signature.
1195   //
1196   // We check the return type and template parameter lists for function
1197   // templates first; the remaining checks follow.
1198   //
1199   // However, we don't consider either of these when deciding whether
1200   // a member introduced by a shadow declaration is hidden.
1201   if (!UseMemberUsingDeclRules && NewTemplate &&
1202       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203                                        OldTemplate->getTemplateParameters(),
1204                                        false, TPL_TemplateMatch) ||
1205        !Context.hasSameType(Old->getDeclaredReturnType(),
1206                             New->getDeclaredReturnType())))
1207     return true;
1208 
1209   // If the function is a class member, its signature includes the
1210   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211   //
1212   // As part of this, also check whether one of the member functions
1213   // is static, in which case they are not overloads (C++
1214   // 13.1p2). While not part of the definition of the signature,
1215   // this check is important to determine whether these functions
1216   // can be overloaded.
1217   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219   if (OldMethod && NewMethod &&
1220       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222       if (!UseMemberUsingDeclRules &&
1223           (OldMethod->getRefQualifier() == RQ_None ||
1224            NewMethod->getRefQualifier() == RQ_None)) {
1225         // C++0x [over.load]p2:
1226         //   - Member function declarations with the same name and the same
1227         //     parameter-type-list as well as member function template
1228         //     declarations with the same name, the same parameter-type-list, and
1229         //     the same template parameter lists cannot be overloaded if any of
1230         //     them, but not all, have a ref-qualifier (8.3.5).
1231         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234       }
1235       return true;
1236     }
1237 
1238     // We may not have applied the implicit const for a constexpr member
1239     // function yet (because we haven't yet resolved whether this is a static
1240     // or non-static member function). Add it now, on the assumption that this
1241     // is a redeclaration of OldMethod.
1242     auto OldQuals = OldMethod->getMethodQualifiers();
1243     auto NewQuals = NewMethod->getMethodQualifiers();
1244     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245         !isa<CXXConstructorDecl>(NewMethod))
1246       NewQuals.addConst();
1247     // We do not allow overloading based off of '__restrict'.
1248     OldQuals.removeRestrict();
1249     NewQuals.removeRestrict();
1250     if (OldQuals != NewQuals)
1251       return true;
1252   }
1253 
1254   // Though pass_object_size is placed on parameters and takes an argument, we
1255   // consider it to be a function-level modifier for the sake of function
1256   // identity. Either the function has one or more parameters with
1257   // pass_object_size or it doesn't.
1258   if (functionHasPassObjectSizeParams(New) !=
1259       functionHasPassObjectSizeParams(Old))
1260     return true;
1261 
1262   // enable_if attributes are an order-sensitive part of the signature.
1263   for (specific_attr_iterator<EnableIfAttr>
1264          NewI = New->specific_attr_begin<EnableIfAttr>(),
1265          NewE = New->specific_attr_end<EnableIfAttr>(),
1266          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267          OldE = Old->specific_attr_end<EnableIfAttr>();
1268        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269     if (NewI == NewE || OldI == OldE)
1270       return true;
1271     llvm::FoldingSetNodeID NewID, OldID;
1272     NewI->getCond()->Profile(NewID, Context, true);
1273     OldI->getCond()->Profile(OldID, Context, true);
1274     if (NewID != OldID)
1275       return true;
1276   }
1277 
1278   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279     // Don't allow overloading of destructors.  (In theory we could, but it
1280     // would be a giant change to clang.)
1281     if (!isa<CXXDestructorDecl>(New)) {
1282       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283                          OldTarget = IdentifyCUDATarget(Old);
1284       if (NewTarget != CFT_InvalidTarget) {
1285         assert((OldTarget != CFT_InvalidTarget) &&
1286                "Unexpected invalid target.");
1287 
1288         // Allow overloading of functions with same signature and different CUDA
1289         // target attributes.
1290         if (NewTarget != OldTarget)
1291           return true;
1292       }
1293     }
1294   }
1295 
1296   if (ConsiderRequiresClauses) {
1297     Expr *NewRC = New->getTrailingRequiresClause(),
1298          *OldRC = Old->getTrailingRequiresClause();
1299     if ((NewRC != nullptr) != (OldRC != nullptr))
1300       // RC are most certainly different - these are overloads.
1301       return true;
1302 
1303     if (NewRC) {
1304       llvm::FoldingSetNodeID NewID, OldID;
1305       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307       if (NewID != OldID)
1308         // RCs are not equivalent - these are overloads.
1309         return true;
1310     }
1311   }
1312 
1313   // The signatures match; this is not an overload.
1314   return false;
1315 }
1316 
1317 /// Tries a user-defined conversion from From to ToType.
1318 ///
1319 /// Produces an implicit conversion sequence for when a standard conversion
1320 /// is not an option. See TryImplicitConversion for more information.
1321 static ImplicitConversionSequence
1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323                          bool SuppressUserConversions,
1324                          AllowedExplicit AllowExplicit,
1325                          bool InOverloadResolution,
1326                          bool CStyle,
1327                          bool AllowObjCWritebackConversion,
1328                          bool AllowObjCConversionOnExplicit) {
1329   ImplicitConversionSequence ICS;
1330 
1331   if (SuppressUserConversions) {
1332     // We're not in the case above, so there is no conversion that
1333     // we can perform.
1334     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335     return ICS;
1336   }
1337 
1338   // Attempt user-defined conversion.
1339   OverloadCandidateSet Conversions(From->getExprLoc(),
1340                                    OverloadCandidateSet::CSK_Normal);
1341   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342                                   Conversions, AllowExplicit,
1343                                   AllowObjCConversionOnExplicit)) {
1344   case OR_Success:
1345   case OR_Deleted:
1346     ICS.setUserDefined();
1347     // C++ [over.ics.user]p4:
1348     //   A conversion of an expression of class type to the same class
1349     //   type is given Exact Match rank, and a conversion of an
1350     //   expression of class type to a base class of that type is
1351     //   given Conversion rank, in spite of the fact that a copy
1352     //   constructor (i.e., a user-defined conversion function) is
1353     //   called for those cases.
1354     if (CXXConstructorDecl *Constructor
1355           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356       QualType FromCanon
1357         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358       QualType ToCanon
1359         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360       if (Constructor->isCopyConstructor() &&
1361           (FromCanon == ToCanon ||
1362            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363         // Turn this into a "standard" conversion sequence, so that it
1364         // gets ranked with standard conversion sequences.
1365         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366         ICS.setStandard();
1367         ICS.Standard.setAsIdentityConversion();
1368         ICS.Standard.setFromType(From->getType());
1369         ICS.Standard.setAllToTypes(ToType);
1370         ICS.Standard.CopyConstructor = Constructor;
1371         ICS.Standard.FoundCopyConstructor = Found;
1372         if (ToCanon != FromCanon)
1373           ICS.Standard.Second = ICK_Derived_To_Base;
1374       }
1375     }
1376     break;
1377 
1378   case OR_Ambiguous:
1379     ICS.setAmbiguous();
1380     ICS.Ambiguous.setFromType(From->getType());
1381     ICS.Ambiguous.setToType(ToType);
1382     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383          Cand != Conversions.end(); ++Cand)
1384       if (Cand->Best)
1385         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386     break;
1387 
1388     // Fall through.
1389   case OR_No_Viable_Function:
1390     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391     break;
1392   }
1393 
1394   return ICS;
1395 }
1396 
1397 /// TryImplicitConversion - Attempt to perform an implicit conversion
1398 /// from the given expression (Expr) to the given type (ToType). This
1399 /// function returns an implicit conversion sequence that can be used
1400 /// to perform the initialization. Given
1401 ///
1402 ///   void f(float f);
1403 ///   void g(int i) { f(i); }
1404 ///
1405 /// this routine would produce an implicit conversion sequence to
1406 /// describe the initialization of f from i, which will be a standard
1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409 //
1410 /// Note that this routine only determines how the conversion can be
1411 /// performed; it does not actually perform the conversion. As such,
1412 /// it will not produce any diagnostics if no conversion is available,
1413 /// but will instead return an implicit conversion sequence of kind
1414 /// "BadConversion".
1415 ///
1416 /// If @p SuppressUserConversions, then user-defined conversions are
1417 /// not permitted.
1418 /// If @p AllowExplicit, then explicit user-defined conversions are
1419 /// permitted.
1420 ///
1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422 /// writeback conversion, which allows __autoreleasing id* parameters to
1423 /// be initialized with __strong id* or __weak id* arguments.
1424 static ImplicitConversionSequence
1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426                       bool SuppressUserConversions,
1427                       AllowedExplicit AllowExplicit,
1428                       bool InOverloadResolution,
1429                       bool CStyle,
1430                       bool AllowObjCWritebackConversion,
1431                       bool AllowObjCConversionOnExplicit) {
1432   ImplicitConversionSequence ICS;
1433   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435     ICS.setStandard();
1436     return ICS;
1437   }
1438 
1439   if (!S.getLangOpts().CPlusPlus) {
1440     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441     return ICS;
1442   }
1443 
1444   // C++ [over.ics.user]p4:
1445   //   A conversion of an expression of class type to the same class
1446   //   type is given Exact Match rank, and a conversion of an
1447   //   expression of class type to a base class of that type is
1448   //   given Conversion rank, in spite of the fact that a copy/move
1449   //   constructor (i.e., a user-defined conversion function) is
1450   //   called for those cases.
1451   QualType FromType = From->getType();
1452   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455     ICS.setStandard();
1456     ICS.Standard.setAsIdentityConversion();
1457     ICS.Standard.setFromType(FromType);
1458     ICS.Standard.setAllToTypes(ToType);
1459 
1460     // We don't actually check at this point whether there is a valid
1461     // copy/move constructor, since overloading just assumes that it
1462     // exists. When we actually perform initialization, we'll find the
1463     // appropriate constructor to copy the returned object, if needed.
1464     ICS.Standard.CopyConstructor = nullptr;
1465 
1466     // Determine whether this is considered a derived-to-base conversion.
1467     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468       ICS.Standard.Second = ICK_Derived_To_Base;
1469 
1470     return ICS;
1471   }
1472 
1473   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474                                   AllowExplicit, InOverloadResolution, CStyle,
1475                                   AllowObjCWritebackConversion,
1476                                   AllowObjCConversionOnExplicit);
1477 }
1478 
1479 ImplicitConversionSequence
1480 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481                             bool SuppressUserConversions,
1482                             AllowedExplicit AllowExplicit,
1483                             bool InOverloadResolution,
1484                             bool CStyle,
1485                             bool AllowObjCWritebackConversion) {
1486   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487                                  AllowExplicit, InOverloadResolution, CStyle,
1488                                  AllowObjCWritebackConversion,
1489                                  /*AllowObjCConversionOnExplicit=*/false);
1490 }
1491 
1492 /// PerformImplicitConversion - Perform an implicit conversion of the
1493 /// expression From to the type ToType. Returns the
1494 /// converted expression. Flavor is the kind of conversion we're
1495 /// performing, used in the error message. If @p AllowExplicit,
1496 /// explicit user-defined conversions are permitted.
1497 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498                                            AssignmentAction Action,
1499                                            bool AllowExplicit) {
1500   if (checkPlaceholderForOverload(*this, From))
1501     return ExprError();
1502 
1503   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504   bool AllowObjCWritebackConversion
1505     = getLangOpts().ObjCAutoRefCount &&
1506       (Action == AA_Passing || Action == AA_Sending);
1507   if (getLangOpts().ObjC)
1508     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509                                       From->getType(), From);
1510   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511       *this, From, ToType,
1512       /*SuppressUserConversions=*/false,
1513       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514       /*InOverloadResolution=*/false,
1515       /*CStyle=*/false, AllowObjCWritebackConversion,
1516       /*AllowObjCConversionOnExplicit=*/false);
1517   return PerformImplicitConversion(From, ToType, ICS, Action);
1518 }
1519 
1520 /// Determine whether the conversion from FromType to ToType is a valid
1521 /// conversion that strips "noexcept" or "noreturn" off the nested function
1522 /// type.
1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524                                 QualType &ResultTy) {
1525   if (Context.hasSameUnqualifiedType(FromType, ToType))
1526     return false;
1527 
1528   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529   //                    or F(t noexcept) -> F(t)
1530   // where F adds one of the following at most once:
1531   //   - a pointer
1532   //   - a member pointer
1533   //   - a block pointer
1534   // Changes here need matching changes in FindCompositePointerType.
1535   CanQualType CanTo = Context.getCanonicalType(ToType);
1536   CanQualType CanFrom = Context.getCanonicalType(FromType);
1537   Type::TypeClass TyClass = CanTo->getTypeClass();
1538   if (TyClass != CanFrom->getTypeClass()) return false;
1539   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540     if (TyClass == Type::Pointer) {
1541       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543     } else if (TyClass == Type::BlockPointer) {
1544       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546     } else if (TyClass == Type::MemberPointer) {
1547       auto ToMPT = CanTo.castAs<MemberPointerType>();
1548       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549       // A function pointer conversion cannot change the class of the function.
1550       if (ToMPT->getClass() != FromMPT->getClass())
1551         return false;
1552       CanTo = ToMPT->getPointeeType();
1553       CanFrom = FromMPT->getPointeeType();
1554     } else {
1555       return false;
1556     }
1557 
1558     TyClass = CanTo->getTypeClass();
1559     if (TyClass != CanFrom->getTypeClass()) return false;
1560     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561       return false;
1562   }
1563 
1564   const auto *FromFn = cast<FunctionType>(CanFrom);
1565   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566 
1567   const auto *ToFn = cast<FunctionType>(CanTo);
1568   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569 
1570   bool Changed = false;
1571 
1572   // Drop 'noreturn' if not present in target type.
1573   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575     Changed = true;
1576   }
1577 
1578   // Drop 'noexcept' if not present in target type.
1579   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582       FromFn = cast<FunctionType>(
1583           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584                                                    EST_None)
1585                  .getTypePtr());
1586       Changed = true;
1587     }
1588 
1589     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590     // only if the ExtParameterInfo lists of the two function prototypes can be
1591     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593     bool CanUseToFPT, CanUseFromFPT;
1594     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595                                       CanUseFromFPT, NewParamInfos) &&
1596         CanUseToFPT && !CanUseFromFPT) {
1597       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598       ExtInfo.ExtParameterInfos =
1599           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601                                             FromFPT->getParamTypes(), ExtInfo);
1602       FromFn = QT->getAs<FunctionType>();
1603       Changed = true;
1604     }
1605   }
1606 
1607   if (!Changed)
1608     return false;
1609 
1610   assert(QualType(FromFn, 0).isCanonical());
1611   if (QualType(FromFn, 0) != CanTo) return false;
1612 
1613   ResultTy = ToType;
1614   return true;
1615 }
1616 
1617 /// Determine whether the conversion from FromType to ToType is a valid
1618 /// vector conversion.
1619 ///
1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1621 /// conversion.
1622 static bool IsVectorConversion(Sema &S, QualType FromType,
1623                                QualType ToType, ImplicitConversionKind &ICK) {
1624   // We need at least one of these types to be a vector type to have a vector
1625   // conversion.
1626   if (!ToType->isVectorType() && !FromType->isVectorType())
1627     return false;
1628 
1629   // Identical types require no conversions.
1630   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631     return false;
1632 
1633   // There are no conversions between extended vector types, only identity.
1634   if (ToType->isExtVectorType()) {
1635     // There are no conversions between extended vector types other than the
1636     // identity conversion.
1637     if (FromType->isExtVectorType())
1638       return false;
1639 
1640     // Vector splat from any arithmetic type to a vector.
1641     if (FromType->isArithmeticType()) {
1642       ICK = ICK_Vector_Splat;
1643       return true;
1644     }
1645   }
1646 
1647   if (ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType())
1648     if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
1649         S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
1650       ICK = ICK_SVE_Vector_Conversion;
1651       return true;
1652     }
1653 
1654   // We can perform the conversion between vector types in the following cases:
1655   // 1)vector types are equivalent AltiVec and GCC vector types
1656   // 2)lax vector conversions are permitted and the vector types are of the
1657   //   same size
1658   // 3)the destination type does not have the ARM MVE strict-polymorphism
1659   //   attribute, which inhibits lax vector conversion for overload resolution
1660   //   only
1661   if (ToType->isVectorType() && FromType->isVectorType()) {
1662     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1663         (S.isLaxVectorConversion(FromType, ToType) &&
1664          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1665       ICK = ICK_Vector_Conversion;
1666       return true;
1667     }
1668   }
1669 
1670   return false;
1671 }
1672 
1673 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1674                                 bool InOverloadResolution,
1675                                 StandardConversionSequence &SCS,
1676                                 bool CStyle);
1677 
1678 /// IsStandardConversion - Determines whether there is a standard
1679 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1680 /// expression From to the type ToType. Standard conversion sequences
1681 /// only consider non-class types; for conversions that involve class
1682 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1683 /// contain the standard conversion sequence required to perform this
1684 /// conversion and this routine will return true. Otherwise, this
1685 /// routine will return false and the value of SCS is unspecified.
1686 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1687                                  bool InOverloadResolution,
1688                                  StandardConversionSequence &SCS,
1689                                  bool CStyle,
1690                                  bool AllowObjCWritebackConversion) {
1691   QualType FromType = From->getType();
1692 
1693   // Standard conversions (C++ [conv])
1694   SCS.setAsIdentityConversion();
1695   SCS.IncompatibleObjC = false;
1696   SCS.setFromType(FromType);
1697   SCS.CopyConstructor = nullptr;
1698 
1699   // There are no standard conversions for class types in C++, so
1700   // abort early. When overloading in C, however, we do permit them.
1701   if (S.getLangOpts().CPlusPlus &&
1702       (FromType->isRecordType() || ToType->isRecordType()))
1703     return false;
1704 
1705   // The first conversion can be an lvalue-to-rvalue conversion,
1706   // array-to-pointer conversion, or function-to-pointer conversion
1707   // (C++ 4p1).
1708 
1709   if (FromType == S.Context.OverloadTy) {
1710     DeclAccessPair AccessPair;
1711     if (FunctionDecl *Fn
1712           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1713                                                  AccessPair)) {
1714       // We were able to resolve the address of the overloaded function,
1715       // so we can convert to the type of that function.
1716       FromType = Fn->getType();
1717       SCS.setFromType(FromType);
1718 
1719       // we can sometimes resolve &foo<int> regardless of ToType, so check
1720       // if the type matches (identity) or we are converting to bool
1721       if (!S.Context.hasSameUnqualifiedType(
1722                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1723         QualType resultTy;
1724         // if the function type matches except for [[noreturn]], it's ok
1725         if (!S.IsFunctionConversion(FromType,
1726               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1727           // otherwise, only a boolean conversion is standard
1728           if (!ToType->isBooleanType())
1729             return false;
1730       }
1731 
1732       // Check if the "from" expression is taking the address of an overloaded
1733       // function and recompute the FromType accordingly. Take advantage of the
1734       // fact that non-static member functions *must* have such an address-of
1735       // expression.
1736       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1737       if (Method && !Method->isStatic()) {
1738         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1739                "Non-unary operator on non-static member address");
1740         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1741                == UO_AddrOf &&
1742                "Non-address-of operator on non-static member address");
1743         const Type *ClassType
1744           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1745         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1746       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1747         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1748                UO_AddrOf &&
1749                "Non-address-of operator for overloaded function expression");
1750         FromType = S.Context.getPointerType(FromType);
1751       }
1752 
1753       // Check that we've computed the proper type after overload resolution.
1754       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1755       // be calling it from within an NDEBUG block.
1756       assert(S.Context.hasSameType(
1757         FromType,
1758         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1759     } else {
1760       return false;
1761     }
1762   }
1763   // Lvalue-to-rvalue conversion (C++11 4.1):
1764   //   A glvalue (3.10) of a non-function, non-array type T can
1765   //   be converted to a prvalue.
1766   bool argIsLValue = From->isGLValue();
1767   if (argIsLValue &&
1768       !FromType->isFunctionType() && !FromType->isArrayType() &&
1769       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1770     SCS.First = ICK_Lvalue_To_Rvalue;
1771 
1772     // C11 6.3.2.1p2:
1773     //   ... if the lvalue has atomic type, the value has the non-atomic version
1774     //   of the type of the lvalue ...
1775     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1776       FromType = Atomic->getValueType();
1777 
1778     // If T is a non-class type, the type of the rvalue is the
1779     // cv-unqualified version of T. Otherwise, the type of the rvalue
1780     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1781     // just strip the qualifiers because they don't matter.
1782     FromType = FromType.getUnqualifiedType();
1783   } else if (FromType->isArrayType()) {
1784     // Array-to-pointer conversion (C++ 4.2)
1785     SCS.First = ICK_Array_To_Pointer;
1786 
1787     // An lvalue or rvalue of type "array of N T" or "array of unknown
1788     // bound of T" can be converted to an rvalue of type "pointer to
1789     // T" (C++ 4.2p1).
1790     FromType = S.Context.getArrayDecayedType(FromType);
1791 
1792     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1793       // This conversion is deprecated in C++03 (D.4)
1794       SCS.DeprecatedStringLiteralToCharPtr = true;
1795 
1796       // For the purpose of ranking in overload resolution
1797       // (13.3.3.1.1), this conversion is considered an
1798       // array-to-pointer conversion followed by a qualification
1799       // conversion (4.4). (C++ 4.2p2)
1800       SCS.Second = ICK_Identity;
1801       SCS.Third = ICK_Qualification;
1802       SCS.QualificationIncludesObjCLifetime = false;
1803       SCS.setAllToTypes(FromType);
1804       return true;
1805     }
1806   } else if (FromType->isFunctionType() && argIsLValue) {
1807     // Function-to-pointer conversion (C++ 4.3).
1808     SCS.First = ICK_Function_To_Pointer;
1809 
1810     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1811       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1812         if (!S.checkAddressOfFunctionIsAvailable(FD))
1813           return false;
1814 
1815     // An lvalue of function type T can be converted to an rvalue of
1816     // type "pointer to T." The result is a pointer to the
1817     // function. (C++ 4.3p1).
1818     FromType = S.Context.getPointerType(FromType);
1819   } else {
1820     // We don't require any conversions for the first step.
1821     SCS.First = ICK_Identity;
1822   }
1823   SCS.setToType(0, FromType);
1824 
1825   // The second conversion can be an integral promotion, floating
1826   // point promotion, integral conversion, floating point conversion,
1827   // floating-integral conversion, pointer conversion,
1828   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1829   // For overloading in C, this can also be a "compatible-type"
1830   // conversion.
1831   bool IncompatibleObjC = false;
1832   ImplicitConversionKind SecondICK = ICK_Identity;
1833   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1834     // The unqualified versions of the types are the same: there's no
1835     // conversion to do.
1836     SCS.Second = ICK_Identity;
1837   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1838     // Integral promotion (C++ 4.5).
1839     SCS.Second = ICK_Integral_Promotion;
1840     FromType = ToType.getUnqualifiedType();
1841   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1842     // Floating point promotion (C++ 4.6).
1843     SCS.Second = ICK_Floating_Promotion;
1844     FromType = ToType.getUnqualifiedType();
1845   } else if (S.IsComplexPromotion(FromType, ToType)) {
1846     // Complex promotion (Clang extension)
1847     SCS.Second = ICK_Complex_Promotion;
1848     FromType = ToType.getUnqualifiedType();
1849   } else if (ToType->isBooleanType() &&
1850              (FromType->isArithmeticType() ||
1851               FromType->isAnyPointerType() ||
1852               FromType->isBlockPointerType() ||
1853               FromType->isMemberPointerType())) {
1854     // Boolean conversions (C++ 4.12).
1855     SCS.Second = ICK_Boolean_Conversion;
1856     FromType = S.Context.BoolTy;
1857   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1858              ToType->isIntegralType(S.Context)) {
1859     // Integral conversions (C++ 4.7).
1860     SCS.Second = ICK_Integral_Conversion;
1861     FromType = ToType.getUnqualifiedType();
1862   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1863     // Complex conversions (C99 6.3.1.6)
1864     SCS.Second = ICK_Complex_Conversion;
1865     FromType = ToType.getUnqualifiedType();
1866   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1867              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1868     // Complex-real conversions (C99 6.3.1.7)
1869     SCS.Second = ICK_Complex_Real;
1870     FromType = ToType.getUnqualifiedType();
1871   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1872     // FIXME: disable conversions between long double, __ibm128 and __float128
1873     // if their representation is different until there is back end support
1874     // We of course allow this conversion if long double is really double.
1875 
1876     // Conversions between bfloat and other floats are not permitted.
1877     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1878       return false;
1879 
1880     // Conversions between IEEE-quad and IBM-extended semantics are not
1881     // permitted.
1882     const llvm::fltSemantics &FromSem =
1883         S.Context.getFloatTypeSemantics(FromType);
1884     const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1885     if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1886          &ToSem == &llvm::APFloat::IEEEquad()) ||
1887         (&FromSem == &llvm::APFloat::IEEEquad() &&
1888          &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1889       return false;
1890 
1891     // Floating point conversions (C++ 4.8).
1892     SCS.Second = ICK_Floating_Conversion;
1893     FromType = ToType.getUnqualifiedType();
1894   } else if ((FromType->isRealFloatingType() &&
1895               ToType->isIntegralType(S.Context)) ||
1896              (FromType->isIntegralOrUnscopedEnumerationType() &&
1897               ToType->isRealFloatingType())) {
1898     // Conversions between bfloat and int are not permitted.
1899     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1900       return false;
1901 
1902     // Floating-integral conversions (C++ 4.9).
1903     SCS.Second = ICK_Floating_Integral;
1904     FromType = ToType.getUnqualifiedType();
1905   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1906     SCS.Second = ICK_Block_Pointer_Conversion;
1907   } else if (AllowObjCWritebackConversion &&
1908              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1909     SCS.Second = ICK_Writeback_Conversion;
1910   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1911                                    FromType, IncompatibleObjC)) {
1912     // Pointer conversions (C++ 4.10).
1913     SCS.Second = ICK_Pointer_Conversion;
1914     SCS.IncompatibleObjC = IncompatibleObjC;
1915     FromType = FromType.getUnqualifiedType();
1916   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1917                                          InOverloadResolution, FromType)) {
1918     // Pointer to member conversions (4.11).
1919     SCS.Second = ICK_Pointer_Member;
1920   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
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->getAs<ObjCObjectPointerType>(),
2409                                                        ToPointeeType,
2410                                                        ToType, Context);
2411     return true;
2412   }
2413   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2414   if (!FromTypePtr)
2415     return false;
2416 
2417   QualType FromPointeeType = FromTypePtr->getPointeeType();
2418 
2419   // If the unqualified pointee types are the same, this can't be a
2420   // pointer conversion, so don't do all of the work below.
2421   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2422     return false;
2423 
2424   // An rvalue of type "pointer to cv T," where T is an object type,
2425   // can be converted to an rvalue of type "pointer to cv void" (C++
2426   // 4.10p2).
2427   if (FromPointeeType->isIncompleteOrObjectType() &&
2428       ToPointeeType->isVoidType()) {
2429     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2430                                                        ToPointeeType,
2431                                                        ToType, Context,
2432                                                    /*StripObjCLifetime=*/true);
2433     return true;
2434   }
2435 
2436   // MSVC allows implicit function to void* type conversion.
2437   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2438       ToPointeeType->isVoidType()) {
2439     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2440                                                        ToPointeeType,
2441                                                        ToType, Context);
2442     return true;
2443   }
2444 
2445   // When we're overloading in C, we allow a special kind of pointer
2446   // conversion for compatible-but-not-identical pointee types.
2447   if (!getLangOpts().CPlusPlus &&
2448       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2449     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2450                                                        ToPointeeType,
2451                                                        ToType, Context);
2452     return true;
2453   }
2454 
2455   // C++ [conv.ptr]p3:
2456   //
2457   //   An rvalue of type "pointer to cv D," where D is a class type,
2458   //   can be converted to an rvalue of type "pointer to cv B," where
2459   //   B is a base class (clause 10) of D. If B is an inaccessible
2460   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2461   //   necessitates this conversion is ill-formed. The result of the
2462   //   conversion is a pointer to the base class sub-object of the
2463   //   derived class object. The null pointer value is converted to
2464   //   the null pointer value of the destination type.
2465   //
2466   // Note that we do not check for ambiguity or inaccessibility
2467   // here. That is handled by CheckPointerConversion.
2468   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2469       ToPointeeType->isRecordType() &&
2470       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2471       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2472     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2473                                                        ToPointeeType,
2474                                                        ToType, Context);
2475     return true;
2476   }
2477 
2478   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2479       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2480     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2481                                                        ToPointeeType,
2482                                                        ToType, Context);
2483     return true;
2484   }
2485 
2486   return false;
2487 }
2488 
2489 /// Adopt the given qualifiers for the given type.
2490 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2491   Qualifiers TQs = T.getQualifiers();
2492 
2493   // Check whether qualifiers already match.
2494   if (TQs == Qs)
2495     return T;
2496 
2497   if (Qs.compatiblyIncludes(TQs))
2498     return Context.getQualifiedType(T, Qs);
2499 
2500   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2501 }
2502 
2503 /// isObjCPointerConversion - Determines whether this is an
2504 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2505 /// with the same arguments and return values.
2506 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2507                                    QualType& ConvertedType,
2508                                    bool &IncompatibleObjC) {
2509   if (!getLangOpts().ObjC)
2510     return false;
2511 
2512   // The set of qualifiers on the type we're converting from.
2513   Qualifiers FromQualifiers = FromType.getQualifiers();
2514 
2515   // First, we handle all conversions on ObjC object pointer types.
2516   const ObjCObjectPointerType* ToObjCPtr =
2517     ToType->getAs<ObjCObjectPointerType>();
2518   const ObjCObjectPointerType *FromObjCPtr =
2519     FromType->getAs<ObjCObjectPointerType>();
2520 
2521   if (ToObjCPtr && FromObjCPtr) {
2522     // If the pointee types are the same (ignoring qualifications),
2523     // then this is not a pointer conversion.
2524     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2525                                        FromObjCPtr->getPointeeType()))
2526       return false;
2527 
2528     // Conversion between Objective-C pointers.
2529     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2530       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2531       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2532       if (getLangOpts().CPlusPlus && LHS && RHS &&
2533           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2534                                                 FromObjCPtr->getPointeeType()))
2535         return false;
2536       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537                                                    ToObjCPtr->getPointeeType(),
2538                                                          ToType, Context);
2539       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540       return true;
2541     }
2542 
2543     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2544       // Okay: this is some kind of implicit downcast of Objective-C
2545       // interfaces, which is permitted. However, we're going to
2546       // complain about it.
2547       IncompatibleObjC = true;
2548       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2549                                                    ToObjCPtr->getPointeeType(),
2550                                                          ToType, Context);
2551       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2552       return true;
2553     }
2554   }
2555   // Beyond this point, both types need to be C pointers or block pointers.
2556   QualType ToPointeeType;
2557   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2558     ToPointeeType = ToCPtr->getPointeeType();
2559   else if (const BlockPointerType *ToBlockPtr =
2560             ToType->getAs<BlockPointerType>()) {
2561     // Objective C++: We're able to convert from a pointer to any object
2562     // to a block pointer type.
2563     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2564       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2565       return true;
2566     }
2567     ToPointeeType = ToBlockPtr->getPointeeType();
2568   }
2569   else if (FromType->getAs<BlockPointerType>() &&
2570            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2571     // Objective C++: We're able to convert from a block pointer type to a
2572     // pointer to any object.
2573     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2574     return true;
2575   }
2576   else
2577     return false;
2578 
2579   QualType FromPointeeType;
2580   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2581     FromPointeeType = FromCPtr->getPointeeType();
2582   else if (const BlockPointerType *FromBlockPtr =
2583            FromType->getAs<BlockPointerType>())
2584     FromPointeeType = FromBlockPtr->getPointeeType();
2585   else
2586     return false;
2587 
2588   // If we have pointers to pointers, recursively check whether this
2589   // is an Objective-C conversion.
2590   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2591       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592                               IncompatibleObjC)) {
2593     // We always complain about this conversion.
2594     IncompatibleObjC = true;
2595     ConvertedType = Context.getPointerType(ConvertedType);
2596     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2597     return true;
2598   }
2599   // Allow conversion of pointee being objective-c pointer to another one;
2600   // as in I* to id.
2601   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2602       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2603       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2604                               IncompatibleObjC)) {
2605 
2606     ConvertedType = Context.getPointerType(ConvertedType);
2607     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2608     return true;
2609   }
2610 
2611   // If we have pointers to functions or blocks, check whether the only
2612   // differences in the argument and result types are in Objective-C
2613   // pointer conversions. If so, we permit the conversion (but
2614   // complain about it).
2615   const FunctionProtoType *FromFunctionType
2616     = FromPointeeType->getAs<FunctionProtoType>();
2617   const FunctionProtoType *ToFunctionType
2618     = ToPointeeType->getAs<FunctionProtoType>();
2619   if (FromFunctionType && ToFunctionType) {
2620     // If the function types are exactly the same, this isn't an
2621     // Objective-C pointer conversion.
2622     if (Context.getCanonicalType(FromPointeeType)
2623           == Context.getCanonicalType(ToPointeeType))
2624       return false;
2625 
2626     // Perform the quick checks that will tell us whether these
2627     // function types are obviously different.
2628     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2629         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2630         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2631       return false;
2632 
2633     bool HasObjCConversion = false;
2634     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2635         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2636       // Okay, the types match exactly. Nothing to do.
2637     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2638                                        ToFunctionType->getReturnType(),
2639                                        ConvertedType, IncompatibleObjC)) {
2640       // Okay, we have an Objective-C pointer conversion.
2641       HasObjCConversion = true;
2642     } else {
2643       // Function types are too different. Abort.
2644       return false;
2645     }
2646 
2647     // Check argument types.
2648     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2649          ArgIdx != NumArgs; ++ArgIdx) {
2650       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2651       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2652       if (Context.getCanonicalType(FromArgType)
2653             == Context.getCanonicalType(ToArgType)) {
2654         // Okay, the types match exactly. Nothing to do.
2655       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2656                                          ConvertedType, IncompatibleObjC)) {
2657         // Okay, we have an Objective-C pointer conversion.
2658         HasObjCConversion = true;
2659       } else {
2660         // Argument types are too different. Abort.
2661         return false;
2662       }
2663     }
2664 
2665     if (HasObjCConversion) {
2666       // We had an Objective-C conversion. Allow this pointer
2667       // conversion, but complain about it.
2668       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2669       IncompatibleObjC = true;
2670       return true;
2671     }
2672   }
2673 
2674   return false;
2675 }
2676 
2677 /// Determine whether this is an Objective-C writeback conversion,
2678 /// used for parameter passing when performing automatic reference counting.
2679 ///
2680 /// \param FromType The type we're converting form.
2681 ///
2682 /// \param ToType The type we're converting to.
2683 ///
2684 /// \param ConvertedType The type that will be produced after applying
2685 /// this conversion.
2686 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2687                                      QualType &ConvertedType) {
2688   if (!getLangOpts().ObjCAutoRefCount ||
2689       Context.hasSameUnqualifiedType(FromType, ToType))
2690     return false;
2691 
2692   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2693   QualType ToPointee;
2694   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2695     ToPointee = ToPointer->getPointeeType();
2696   else
2697     return false;
2698 
2699   Qualifiers ToQuals = ToPointee.getQualifiers();
2700   if (!ToPointee->isObjCLifetimeType() ||
2701       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2702       !ToQuals.withoutObjCLifetime().empty())
2703     return false;
2704 
2705   // Argument must be a pointer to __strong to __weak.
2706   QualType FromPointee;
2707   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2708     FromPointee = FromPointer->getPointeeType();
2709   else
2710     return false;
2711 
2712   Qualifiers FromQuals = FromPointee.getQualifiers();
2713   if (!FromPointee->isObjCLifetimeType() ||
2714       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2715        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2716     return false;
2717 
2718   // Make sure that we have compatible qualifiers.
2719   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2720   if (!ToQuals.compatiblyIncludes(FromQuals))
2721     return false;
2722 
2723   // Remove qualifiers from the pointee type we're converting from; they
2724   // aren't used in the compatibility check belong, and we'll be adding back
2725   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2726   FromPointee = FromPointee.getUnqualifiedType();
2727 
2728   // The unqualified form of the pointee types must be compatible.
2729   ToPointee = ToPointee.getUnqualifiedType();
2730   bool IncompatibleObjC;
2731   if (Context.typesAreCompatible(FromPointee, ToPointee))
2732     FromPointee = ToPointee;
2733   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2734                                     IncompatibleObjC))
2735     return false;
2736 
2737   /// Construct the type we're converting to, which is a pointer to
2738   /// __autoreleasing pointee.
2739   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2740   ConvertedType = Context.getPointerType(FromPointee);
2741   return true;
2742 }
2743 
2744 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2745                                     QualType& ConvertedType) {
2746   QualType ToPointeeType;
2747   if (const BlockPointerType *ToBlockPtr =
2748         ToType->getAs<BlockPointerType>())
2749     ToPointeeType = ToBlockPtr->getPointeeType();
2750   else
2751     return false;
2752 
2753   QualType FromPointeeType;
2754   if (const BlockPointerType *FromBlockPtr =
2755       FromType->getAs<BlockPointerType>())
2756     FromPointeeType = FromBlockPtr->getPointeeType();
2757   else
2758     return false;
2759   // We have pointer to blocks, check whether the only
2760   // differences in the argument and result types are in Objective-C
2761   // pointer conversions. If so, we permit the conversion.
2762 
2763   const FunctionProtoType *FromFunctionType
2764     = FromPointeeType->getAs<FunctionProtoType>();
2765   const FunctionProtoType *ToFunctionType
2766     = ToPointeeType->getAs<FunctionProtoType>();
2767 
2768   if (!FromFunctionType || !ToFunctionType)
2769     return false;
2770 
2771   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2772     return true;
2773 
2774   // Perform the quick checks that will tell us whether these
2775   // function types are obviously different.
2776   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2777       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2778     return false;
2779 
2780   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2781   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2782   if (FromEInfo != ToEInfo)
2783     return false;
2784 
2785   bool IncompatibleObjC = false;
2786   if (Context.hasSameType(FromFunctionType->getReturnType(),
2787                           ToFunctionType->getReturnType())) {
2788     // Okay, the types match exactly. Nothing to do.
2789   } else {
2790     QualType RHS = FromFunctionType->getReturnType();
2791     QualType LHS = ToFunctionType->getReturnType();
2792     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2793         !RHS.hasQualifiers() && LHS.hasQualifiers())
2794        LHS = LHS.getUnqualifiedType();
2795 
2796      if (Context.hasSameType(RHS,LHS)) {
2797        // OK exact match.
2798      } else if (isObjCPointerConversion(RHS, LHS,
2799                                         ConvertedType, IncompatibleObjC)) {
2800      if (IncompatibleObjC)
2801        return false;
2802      // Okay, we have an Objective-C pointer conversion.
2803      }
2804      else
2805        return false;
2806    }
2807 
2808    // Check argument types.
2809    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2810         ArgIdx != NumArgs; ++ArgIdx) {
2811      IncompatibleObjC = false;
2812      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2813      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2814      if (Context.hasSameType(FromArgType, ToArgType)) {
2815        // Okay, the types match exactly. Nothing to do.
2816      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2817                                         ConvertedType, IncompatibleObjC)) {
2818        if (IncompatibleObjC)
2819          return false;
2820        // Okay, we have an Objective-C pointer conversion.
2821      } else
2822        // Argument types are too different. Abort.
2823        return false;
2824    }
2825 
2826    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2827    bool CanUseToFPT, CanUseFromFPT;
2828    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2829                                       CanUseToFPT, CanUseFromFPT,
2830                                       NewParamInfos))
2831      return false;
2832 
2833    ConvertedType = ToType;
2834    return true;
2835 }
2836 
2837 enum {
2838   ft_default,
2839   ft_different_class,
2840   ft_parameter_arity,
2841   ft_parameter_mismatch,
2842   ft_return_type,
2843   ft_qualifer_mismatch,
2844   ft_noexcept
2845 };
2846 
2847 /// Attempts to get the FunctionProtoType from a Type. Handles
2848 /// MemberFunctionPointers properly.
2849 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2850   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2851     return FPT;
2852 
2853   if (auto *MPT = FromType->getAs<MemberPointerType>())
2854     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2855 
2856   return nullptr;
2857 }
2858 
2859 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2860 /// function types.  Catches different number of parameter, mismatch in
2861 /// parameter types, and different return types.
2862 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2863                                       QualType FromType, QualType ToType) {
2864   // If either type is not valid, include no extra info.
2865   if (FromType.isNull() || ToType.isNull()) {
2866     PDiag << ft_default;
2867     return;
2868   }
2869 
2870   // Get the function type from the pointers.
2871   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2872     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2873                *ToMember = ToType->castAs<MemberPointerType>();
2874     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2875       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2876             << QualType(FromMember->getClass(), 0);
2877       return;
2878     }
2879     FromType = FromMember->getPointeeType();
2880     ToType = ToMember->getPointeeType();
2881   }
2882 
2883   if (FromType->isPointerType())
2884     FromType = FromType->getPointeeType();
2885   if (ToType->isPointerType())
2886     ToType = ToType->getPointeeType();
2887 
2888   // Remove references.
2889   FromType = FromType.getNonReferenceType();
2890   ToType = ToType.getNonReferenceType();
2891 
2892   // Don't print extra info for non-specialized template functions.
2893   if (FromType->isInstantiationDependentType() &&
2894       !FromType->getAs<TemplateSpecializationType>()) {
2895     PDiag << ft_default;
2896     return;
2897   }
2898 
2899   // No extra info for same types.
2900   if (Context.hasSameType(FromType, ToType)) {
2901     PDiag << ft_default;
2902     return;
2903   }
2904 
2905   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2906                           *ToFunction = tryGetFunctionProtoType(ToType);
2907 
2908   // Both types need to be function types.
2909   if (!FromFunction || !ToFunction) {
2910     PDiag << ft_default;
2911     return;
2912   }
2913 
2914   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2915     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2916           << FromFunction->getNumParams();
2917     return;
2918   }
2919 
2920   // Handle different parameter types.
2921   unsigned ArgPos;
2922   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2923     PDiag << ft_parameter_mismatch << ArgPos + 1
2924           << ToFunction->getParamType(ArgPos)
2925           << FromFunction->getParamType(ArgPos);
2926     return;
2927   }
2928 
2929   // Handle different return type.
2930   if (!Context.hasSameType(FromFunction->getReturnType(),
2931                            ToFunction->getReturnType())) {
2932     PDiag << ft_return_type << ToFunction->getReturnType()
2933           << FromFunction->getReturnType();
2934     return;
2935   }
2936 
2937   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2938     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2939           << FromFunction->getMethodQuals();
2940     return;
2941   }
2942 
2943   // Handle exception specification differences on canonical type (in C++17
2944   // onwards).
2945   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2946           ->isNothrow() !=
2947       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2948           ->isNothrow()) {
2949     PDiag << ft_noexcept;
2950     return;
2951   }
2952 
2953   // Unable to find a difference, so add no extra info.
2954   PDiag << ft_default;
2955 }
2956 
2957 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2958 /// for equality of their argument types. Caller has already checked that
2959 /// they have same number of arguments.  If the parameters are different,
2960 /// ArgPos will have the parameter index of the first different parameter.
2961 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2962                                       const FunctionProtoType *NewType,
2963                                       unsigned *ArgPos) {
2964   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2965                                               N = NewType->param_type_begin(),
2966                                               E = OldType->param_type_end();
2967        O && (O != E); ++O, ++N) {
2968     // Ignore address spaces in pointee type. This is to disallow overloading
2969     // on __ptr32/__ptr64 address spaces.
2970     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2971     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2972 
2973     if (!Context.hasSameType(Old, New)) {
2974       if (ArgPos)
2975         *ArgPos = O - OldType->param_type_begin();
2976       return false;
2977     }
2978   }
2979   return true;
2980 }
2981 
2982 /// CheckPointerConversion - Check the pointer conversion from the
2983 /// expression From to the type ToType. This routine checks for
2984 /// ambiguous or inaccessible derived-to-base pointer
2985 /// conversions for which IsPointerConversion has already returned
2986 /// true. It returns true and produces a diagnostic if there was an
2987 /// error, or returns false otherwise.
2988 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2989                                   CastKind &Kind,
2990                                   CXXCastPath& BasePath,
2991                                   bool IgnoreBaseAccess,
2992                                   bool Diagnose) {
2993   QualType FromType = From->getType();
2994   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2995 
2996   Kind = CK_BitCast;
2997 
2998   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2999       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3000           Expr::NPCK_ZeroExpression) {
3001     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3002       DiagRuntimeBehavior(From->getExprLoc(), From,
3003                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3004                             << ToType << From->getSourceRange());
3005     else if (!isUnevaluatedContext())
3006       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3007         << ToType << From->getSourceRange();
3008   }
3009   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3010     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3011       QualType FromPointeeType = FromPtrType->getPointeeType(),
3012                ToPointeeType   = ToPtrType->getPointeeType();
3013 
3014       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3015           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3016         // We must have a derived-to-base conversion. Check an
3017         // ambiguous or inaccessible conversion.
3018         unsigned InaccessibleID = 0;
3019         unsigned AmbiguousID = 0;
3020         if (Diagnose) {
3021           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3022           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3023         }
3024         if (CheckDerivedToBaseConversion(
3025                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3026                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3027                 &BasePath, IgnoreBaseAccess))
3028           return true;
3029 
3030         // The conversion was successful.
3031         Kind = CK_DerivedToBase;
3032       }
3033 
3034       if (Diagnose && !IsCStyleOrFunctionalCast &&
3035           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3036         assert(getLangOpts().MSVCCompat &&
3037                "this should only be possible with MSVCCompat!");
3038         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3039             << From->getSourceRange();
3040       }
3041     }
3042   } else if (const ObjCObjectPointerType *ToPtrType =
3043                ToType->getAs<ObjCObjectPointerType>()) {
3044     if (const ObjCObjectPointerType *FromPtrType =
3045           FromType->getAs<ObjCObjectPointerType>()) {
3046       // Objective-C++ conversions are always okay.
3047       // FIXME: We should have a different class of conversions for the
3048       // Objective-C++ implicit conversions.
3049       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3050         return false;
3051     } else if (FromType->isBlockPointerType()) {
3052       Kind = CK_BlockPointerToObjCPointerCast;
3053     } else {
3054       Kind = CK_CPointerToObjCPointerCast;
3055     }
3056   } else if (ToType->isBlockPointerType()) {
3057     if (!FromType->isBlockPointerType())
3058       Kind = CK_AnyPointerToBlockPointerCast;
3059   }
3060 
3061   // We shouldn't fall into this case unless it's valid for other
3062   // reasons.
3063   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3064     Kind = CK_NullToPointer;
3065 
3066   return false;
3067 }
3068 
3069 /// IsMemberPointerConversion - Determines whether the conversion of the
3070 /// expression From, which has the (possibly adjusted) type FromType, can be
3071 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3072 /// If so, returns true and places the converted type (that might differ from
3073 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3074 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3075                                      QualType ToType,
3076                                      bool InOverloadResolution,
3077                                      QualType &ConvertedType) {
3078   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3079   if (!ToTypePtr)
3080     return false;
3081 
3082   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3083   if (From->isNullPointerConstant(Context,
3084                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3085                                         : Expr::NPC_ValueDependentIsNull)) {
3086     ConvertedType = ToType;
3087     return true;
3088   }
3089 
3090   // Otherwise, both types have to be member pointers.
3091   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3092   if (!FromTypePtr)
3093     return false;
3094 
3095   // A pointer to member of B can be converted to a pointer to member of D,
3096   // where D is derived from B (C++ 4.11p2).
3097   QualType FromClass(FromTypePtr->getClass(), 0);
3098   QualType ToClass(ToTypePtr->getClass(), 0);
3099 
3100   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3101       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3102     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3103                                                  ToClass.getTypePtr());
3104     return true;
3105   }
3106 
3107   return false;
3108 }
3109 
3110 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3111 /// expression From to the type ToType. This routine checks for ambiguous or
3112 /// virtual or inaccessible base-to-derived member pointer conversions
3113 /// for which IsMemberPointerConversion has already returned true. It returns
3114 /// true and produces a diagnostic if there was an error, or returns false
3115 /// otherwise.
3116 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3117                                         CastKind &Kind,
3118                                         CXXCastPath &BasePath,
3119                                         bool IgnoreBaseAccess) {
3120   QualType FromType = From->getType();
3121   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3122   if (!FromPtrType) {
3123     // This must be a null pointer to member pointer conversion
3124     assert(From->isNullPointerConstant(Context,
3125                                        Expr::NPC_ValueDependentIsNull) &&
3126            "Expr must be null pointer constant!");
3127     Kind = CK_NullToMemberPointer;
3128     return false;
3129   }
3130 
3131   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3132   assert(ToPtrType && "No member pointer cast has a target type "
3133                       "that is not a member pointer.");
3134 
3135   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3136   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3137 
3138   // FIXME: What about dependent types?
3139   assert(FromClass->isRecordType() && "Pointer into non-class.");
3140   assert(ToClass->isRecordType() && "Pointer into non-class.");
3141 
3142   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3143                      /*DetectVirtual=*/true);
3144   bool DerivationOkay =
3145       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3146   assert(DerivationOkay &&
3147          "Should not have been called if derivation isn't OK.");
3148   (void)DerivationOkay;
3149 
3150   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3151                                   getUnqualifiedType())) {
3152     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3153     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3154       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3155     return true;
3156   }
3157 
3158   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3159     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3160       << FromClass << ToClass << QualType(VBase, 0)
3161       << From->getSourceRange();
3162     return true;
3163   }
3164 
3165   if (!IgnoreBaseAccess)
3166     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3167                          Paths.front(),
3168                          diag::err_downcast_from_inaccessible_base);
3169 
3170   // Must be a base to derived member conversion.
3171   BuildBasePathArray(Paths, BasePath);
3172   Kind = CK_BaseToDerivedMemberPointer;
3173   return false;
3174 }
3175 
3176 /// Determine whether the lifetime conversion between the two given
3177 /// qualifiers sets is nontrivial.
3178 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3179                                                Qualifiers ToQuals) {
3180   // Converting anything to const __unsafe_unretained is trivial.
3181   if (ToQuals.hasConst() &&
3182       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3183     return false;
3184 
3185   return true;
3186 }
3187 
3188 /// Perform a single iteration of the loop for checking if a qualification
3189 /// conversion is valid.
3190 ///
3191 /// Specifically, check whether any change between the qualifiers of \p
3192 /// FromType and \p ToType is permissible, given knowledge about whether every
3193 /// outer layer is const-qualified.
3194 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3195                                           bool CStyle, bool IsTopLevel,
3196                                           bool &PreviousToQualsIncludeConst,
3197                                           bool &ObjCLifetimeConversion) {
3198   Qualifiers FromQuals = FromType.getQualifiers();
3199   Qualifiers ToQuals = ToType.getQualifiers();
3200 
3201   // Ignore __unaligned qualifier if this type is void.
3202   if (ToType.getUnqualifiedType()->isVoidType())
3203     FromQuals.removeUnaligned();
3204 
3205   // Objective-C ARC:
3206   //   Check Objective-C lifetime conversions.
3207   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3208     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3209       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3210         ObjCLifetimeConversion = true;
3211       FromQuals.removeObjCLifetime();
3212       ToQuals.removeObjCLifetime();
3213     } else {
3214       // Qualification conversions cannot cast between different
3215       // Objective-C lifetime qualifiers.
3216       return false;
3217     }
3218   }
3219 
3220   // Allow addition/removal of GC attributes but not changing GC attributes.
3221   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3222       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3223     FromQuals.removeObjCGCAttr();
3224     ToQuals.removeObjCGCAttr();
3225   }
3226 
3227   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3228   //      2,j, and similarly for volatile.
3229   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3230     return false;
3231 
3232   // If address spaces mismatch:
3233   //  - in top level it is only valid to convert to addr space that is a
3234   //    superset in all cases apart from C-style casts where we allow
3235   //    conversions between overlapping address spaces.
3236   //  - in non-top levels it is not a valid conversion.
3237   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3238       (!IsTopLevel ||
3239        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3240          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3241     return false;
3242 
3243   //   -- if the cv 1,j and cv 2,j are different, then const is in
3244   //      every cv for 0 < k < j.
3245   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3246       !PreviousToQualsIncludeConst)
3247     return false;
3248 
3249   // Keep track of whether all prior cv-qualifiers in the "to" type
3250   // include const.
3251   PreviousToQualsIncludeConst =
3252       PreviousToQualsIncludeConst && ToQuals.hasConst();
3253   return true;
3254 }
3255 
3256 /// IsQualificationConversion - Determines whether the conversion from
3257 /// an rvalue of type FromType to ToType is a qualification conversion
3258 /// (C++ 4.4).
3259 ///
3260 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3261 /// when the qualification conversion involves a change in the Objective-C
3262 /// object lifetime.
3263 bool
3264 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3265                                 bool CStyle, bool &ObjCLifetimeConversion) {
3266   FromType = Context.getCanonicalType(FromType);
3267   ToType = Context.getCanonicalType(ToType);
3268   ObjCLifetimeConversion = false;
3269 
3270   // If FromType and ToType are the same type, this is not a
3271   // qualification conversion.
3272   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3273     return false;
3274 
3275   // (C++ 4.4p4):
3276   //   A conversion can add cv-qualifiers at levels other than the first
3277   //   in multi-level pointers, subject to the following rules: [...]
3278   bool PreviousToQualsIncludeConst = true;
3279   bool UnwrappedAnyPointer = false;
3280   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3281     if (!isQualificationConversionStep(
3282             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3283             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3284       return false;
3285     UnwrappedAnyPointer = true;
3286   }
3287 
3288   // We are left with FromType and ToType being the pointee types
3289   // after unwrapping the original FromType and ToType the same number
3290   // of times. If we unwrapped any pointers, and if FromType and
3291   // ToType have the same unqualified type (since we checked
3292   // qualifiers above), then this is a qualification conversion.
3293   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3294 }
3295 
3296 /// - Determine whether this is a conversion from a scalar type to an
3297 /// atomic type.
3298 ///
3299 /// If successful, updates \c SCS's second and third steps in the conversion
3300 /// sequence to finish the conversion.
3301 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3302                                 bool InOverloadResolution,
3303                                 StandardConversionSequence &SCS,
3304                                 bool CStyle) {
3305   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3306   if (!ToAtomic)
3307     return false;
3308 
3309   StandardConversionSequence InnerSCS;
3310   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3311                             InOverloadResolution, InnerSCS,
3312                             CStyle, /*AllowObjCWritebackConversion=*/false))
3313     return false;
3314 
3315   SCS.Second = InnerSCS.Second;
3316   SCS.setToType(1, InnerSCS.getToType(1));
3317   SCS.Third = InnerSCS.Third;
3318   SCS.QualificationIncludesObjCLifetime
3319     = InnerSCS.QualificationIncludesObjCLifetime;
3320   SCS.setToType(2, InnerSCS.getToType(2));
3321   return true;
3322 }
3323 
3324 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3325                                               CXXConstructorDecl *Constructor,
3326                                               QualType Type) {
3327   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3328   if (CtorType->getNumParams() > 0) {
3329     QualType FirstArg = CtorType->getParamType(0);
3330     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3331       return true;
3332   }
3333   return false;
3334 }
3335 
3336 static OverloadingResult
3337 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3338                                        CXXRecordDecl *To,
3339                                        UserDefinedConversionSequence &User,
3340                                        OverloadCandidateSet &CandidateSet,
3341                                        bool AllowExplicit) {
3342   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3343   for (auto *D : S.LookupConstructors(To)) {
3344     auto Info = getConstructorInfo(D);
3345     if (!Info)
3346       continue;
3347 
3348     bool Usable = !Info.Constructor->isInvalidDecl() &&
3349                   S.isInitListConstructor(Info.Constructor);
3350     if (Usable) {
3351       bool SuppressUserConversions = false;
3352       if (Info.ConstructorTmpl)
3353         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3354                                        /*ExplicitArgs*/ nullptr, From,
3355                                        CandidateSet, SuppressUserConversions,
3356                                        /*PartialOverloading*/ false,
3357                                        AllowExplicit);
3358       else
3359         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3360                                CandidateSet, SuppressUserConversions,
3361                                /*PartialOverloading*/ false, AllowExplicit);
3362     }
3363   }
3364 
3365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3366 
3367   OverloadCandidateSet::iterator Best;
3368   switch (auto Result =
3369               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3370   case OR_Deleted:
3371   case OR_Success: {
3372     // Record the standard conversion we used and the conversion function.
3373     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3374     QualType ThisType = Constructor->getThisType();
3375     // Initializer lists don't have conversions as such.
3376     User.Before.setAsIdentityConversion();
3377     User.HadMultipleCandidates = HadMultipleCandidates;
3378     User.ConversionFunction = Constructor;
3379     User.FoundConversionFunction = Best->FoundDecl;
3380     User.After.setAsIdentityConversion();
3381     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3382     User.After.setAllToTypes(ToType);
3383     return Result;
3384   }
3385 
3386   case OR_No_Viable_Function:
3387     return OR_No_Viable_Function;
3388   case OR_Ambiguous:
3389     return OR_Ambiguous;
3390   }
3391 
3392   llvm_unreachable("Invalid OverloadResult!");
3393 }
3394 
3395 /// Determines whether there is a user-defined conversion sequence
3396 /// (C++ [over.ics.user]) that converts expression From to the type
3397 /// ToType. If such a conversion exists, User will contain the
3398 /// user-defined conversion sequence that performs such a conversion
3399 /// and this routine will return true. Otherwise, this routine returns
3400 /// false and User is unspecified.
3401 ///
3402 /// \param AllowExplicit  true if the conversion should consider C++0x
3403 /// "explicit" conversion functions as well as non-explicit conversion
3404 /// functions (C++0x [class.conv.fct]p2).
3405 ///
3406 /// \param AllowObjCConversionOnExplicit true if the conversion should
3407 /// allow an extra Objective-C pointer conversion on uses of explicit
3408 /// constructors. Requires \c AllowExplicit to also be set.
3409 static OverloadingResult
3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3411                         UserDefinedConversionSequence &User,
3412                         OverloadCandidateSet &CandidateSet,
3413                         AllowedExplicit AllowExplicit,
3414                         bool AllowObjCConversionOnExplicit) {
3415   assert(AllowExplicit != AllowedExplicit::None ||
3416          !AllowObjCConversionOnExplicit);
3417   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3418 
3419   // Whether we will only visit constructors.
3420   bool ConstructorsOnly = false;
3421 
3422   // If the type we are conversion to is a class type, enumerate its
3423   // constructors.
3424   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3425     // C++ [over.match.ctor]p1:
3426     //   When objects of class type are direct-initialized (8.5), or
3427     //   copy-initialized from an expression of the same or a
3428     //   derived class type (8.5), overload resolution selects the
3429     //   constructor. [...] For copy-initialization, the candidate
3430     //   functions are all the converting constructors (12.3.1) of
3431     //   that class. The argument list is the expression-list within
3432     //   the parentheses of the initializer.
3433     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3434         (From->getType()->getAs<RecordType>() &&
3435          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3436       ConstructorsOnly = true;
3437 
3438     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3439       // We're not going to find any constructors.
3440     } else if (CXXRecordDecl *ToRecordDecl
3441                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3442 
3443       Expr **Args = &From;
3444       unsigned NumArgs = 1;
3445       bool ListInitializing = false;
3446       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3447         // But first, see if there is an init-list-constructor that will work.
3448         OverloadingResult Result = IsInitializerListConstructorConversion(
3449             S, From, ToType, ToRecordDecl, User, CandidateSet,
3450             AllowExplicit == AllowedExplicit::All);
3451         if (Result != OR_No_Viable_Function)
3452           return Result;
3453         // Never mind.
3454         CandidateSet.clear(
3455             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3456 
3457         // If we're list-initializing, we pass the individual elements as
3458         // arguments, not the entire list.
3459         Args = InitList->getInits();
3460         NumArgs = InitList->getNumInits();
3461         ListInitializing = true;
3462       }
3463 
3464       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3465         auto Info = getConstructorInfo(D);
3466         if (!Info)
3467           continue;
3468 
3469         bool Usable = !Info.Constructor->isInvalidDecl();
3470         if (!ListInitializing)
3471           Usable = Usable && Info.Constructor->isConvertingConstructor(
3472                                  /*AllowExplicit*/ true);
3473         if (Usable) {
3474           bool SuppressUserConversions = !ConstructorsOnly;
3475           // C++20 [over.best.ics.general]/4.5:
3476           //   if the target is the first parameter of a constructor [of class
3477           //   X] and the constructor [...] is a candidate by [...] the second
3478           //   phase of [over.match.list] when the initializer list has exactly
3479           //   one element that is itself an initializer list, [...] and the
3480           //   conversion is to X or reference to cv X, user-defined conversion
3481           //   sequences are not cnosidered.
3482           if (SuppressUserConversions && ListInitializing) {
3483             SuppressUserConversions =
3484                 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3485                 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3486                                                   ToType);
3487           }
3488           if (Info.ConstructorTmpl)
3489             S.AddTemplateOverloadCandidate(
3490                 Info.ConstructorTmpl, Info.FoundDecl,
3491                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3492                 CandidateSet, SuppressUserConversions,
3493                 /*PartialOverloading*/ false,
3494                 AllowExplicit == AllowedExplicit::All);
3495           else
3496             // Allow one user-defined conversion when user specifies a
3497             // From->ToType conversion via an static cast (c-style, etc).
3498             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3499                                    llvm::makeArrayRef(Args, NumArgs),
3500                                    CandidateSet, SuppressUserConversions,
3501                                    /*PartialOverloading*/ false,
3502                                    AllowExplicit == AllowedExplicit::All);
3503         }
3504       }
3505     }
3506   }
3507 
3508   // Enumerate conversion functions, if we're allowed to.
3509   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3510   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3511     // No conversion functions from incomplete types.
3512   } else if (const RecordType *FromRecordType =
3513                  From->getType()->getAs<RecordType>()) {
3514     if (CXXRecordDecl *FromRecordDecl
3515          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3516       // Add all of the conversion functions as candidates.
3517       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3518       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3519         DeclAccessPair FoundDecl = I.getPair();
3520         NamedDecl *D = FoundDecl.getDecl();
3521         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3522         if (isa<UsingShadowDecl>(D))
3523           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3524 
3525         CXXConversionDecl *Conv;
3526         FunctionTemplateDecl *ConvTemplate;
3527         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3528           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3529         else
3530           Conv = cast<CXXConversionDecl>(D);
3531 
3532         if (ConvTemplate)
3533           S.AddTemplateConversionCandidate(
3534               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3535               CandidateSet, AllowObjCConversionOnExplicit,
3536               AllowExplicit != AllowedExplicit::None);
3537         else
3538           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3539                                    CandidateSet, AllowObjCConversionOnExplicit,
3540                                    AllowExplicit != AllowedExplicit::None);
3541       }
3542     }
3543   }
3544 
3545   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3546 
3547   OverloadCandidateSet::iterator Best;
3548   switch (auto Result =
3549               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3550   case OR_Success:
3551   case OR_Deleted:
3552     // Record the standard conversion we used and the conversion function.
3553     if (CXXConstructorDecl *Constructor
3554           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3555       // C++ [over.ics.user]p1:
3556       //   If the user-defined conversion is specified by a
3557       //   constructor (12.3.1), the initial standard conversion
3558       //   sequence converts the source type to the type required by
3559       //   the argument of the constructor.
3560       //
3561       QualType ThisType = Constructor->getThisType();
3562       if (isa<InitListExpr>(From)) {
3563         // Initializer lists don't have conversions as such.
3564         User.Before.setAsIdentityConversion();
3565       } else {
3566         if (Best->Conversions[0].isEllipsis())
3567           User.EllipsisConversion = true;
3568         else {
3569           User.Before = Best->Conversions[0].Standard;
3570           User.EllipsisConversion = false;
3571         }
3572       }
3573       User.HadMultipleCandidates = HadMultipleCandidates;
3574       User.ConversionFunction = Constructor;
3575       User.FoundConversionFunction = Best->FoundDecl;
3576       User.After.setAsIdentityConversion();
3577       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3578       User.After.setAllToTypes(ToType);
3579       return Result;
3580     }
3581     if (CXXConversionDecl *Conversion
3582                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3583       // C++ [over.ics.user]p1:
3584       //
3585       //   [...] If the user-defined conversion is specified by a
3586       //   conversion function (12.3.2), the initial standard
3587       //   conversion sequence converts the source type to the
3588       //   implicit object parameter of the conversion function.
3589       User.Before = Best->Conversions[0].Standard;
3590       User.HadMultipleCandidates = HadMultipleCandidates;
3591       User.ConversionFunction = Conversion;
3592       User.FoundConversionFunction = Best->FoundDecl;
3593       User.EllipsisConversion = false;
3594 
3595       // C++ [over.ics.user]p2:
3596       //   The second standard conversion sequence converts the
3597       //   result of the user-defined conversion to the target type
3598       //   for the sequence. Since an implicit conversion sequence
3599       //   is an initialization, the special rules for
3600       //   initialization by user-defined conversion apply when
3601       //   selecting the best user-defined conversion for a
3602       //   user-defined conversion sequence (see 13.3.3 and
3603       //   13.3.3.1).
3604       User.After = Best->FinalConversion;
3605       return Result;
3606     }
3607     llvm_unreachable("Not a constructor or conversion function?");
3608 
3609   case OR_No_Viable_Function:
3610     return OR_No_Viable_Function;
3611 
3612   case OR_Ambiguous:
3613     return OR_Ambiguous;
3614   }
3615 
3616   llvm_unreachable("Invalid OverloadResult!");
3617 }
3618 
3619 bool
3620 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3621   ImplicitConversionSequence ICS;
3622   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3623                                     OverloadCandidateSet::CSK_Normal);
3624   OverloadingResult OvResult =
3625     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3626                             CandidateSet, AllowedExplicit::None, false);
3627 
3628   if (!(OvResult == OR_Ambiguous ||
3629         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3630     return false;
3631 
3632   auto Cands = CandidateSet.CompleteCandidates(
3633       *this,
3634       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3635       From);
3636   if (OvResult == OR_Ambiguous)
3637     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3638         << From->getType() << ToType << From->getSourceRange();
3639   else { // OR_No_Viable_Function && !CandidateSet.empty()
3640     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3641                              diag::err_typecheck_nonviable_condition_incomplete,
3642                              From->getType(), From->getSourceRange()))
3643       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3644           << false << From->getType() << From->getSourceRange() << ToType;
3645   }
3646 
3647   CandidateSet.NoteCandidates(
3648                               *this, From, Cands);
3649   return true;
3650 }
3651 
3652 // Helper for compareConversionFunctions that gets the FunctionType that the
3653 // conversion-operator return  value 'points' to, or nullptr.
3654 static const FunctionType *
3655 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
3656   const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
3657   const PointerType *RetPtrTy =
3658       ConvFuncTy->getReturnType()->getAs<PointerType>();
3659 
3660   if (!RetPtrTy)
3661     return nullptr;
3662 
3663   return RetPtrTy->getPointeeType()->getAs<FunctionType>();
3664 }
3665 
3666 /// Compare the user-defined conversion functions or constructors
3667 /// of two user-defined conversion sequences to determine whether any ordering
3668 /// is possible.
3669 static ImplicitConversionSequence::CompareKind
3670 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3671                            FunctionDecl *Function2) {
3672   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3673   CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
3674   if (!Conv1 || !Conv2)
3675     return ImplicitConversionSequence::Indistinguishable;
3676 
3677   if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
3678     return ImplicitConversionSequence::Indistinguishable;
3679 
3680   // Objective-C++:
3681   //   If both conversion functions are implicitly-declared conversions from
3682   //   a lambda closure type to a function pointer and a block pointer,
3683   //   respectively, always prefer the conversion to a function pointer,
3684   //   because the function pointer is more lightweight and is more likely
3685   //   to keep code working.
3686   if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
3687     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3688     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3689     if (Block1 != Block2)
3690       return Block1 ? ImplicitConversionSequence::Worse
3691                     : ImplicitConversionSequence::Better;
3692   }
3693 
3694   // In order to support multiple calling conventions for the lambda conversion
3695   // operator (such as when the free and member function calling convention is
3696   // different), prefer the 'free' mechanism, followed by the calling-convention
3697   // of operator(). The latter is in place to support the MSVC-like solution of
3698   // defining ALL of the possible conversions in regards to calling-convention.
3699   const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
3700   const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
3701 
3702   if (Conv1FuncRet && Conv2FuncRet &&
3703       Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
3704     CallingConv Conv1CC = Conv1FuncRet->getCallConv();
3705     CallingConv Conv2CC = Conv2FuncRet->getCallConv();
3706 
3707     CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
3708     const FunctionProtoType *CallOpProto =
3709         CallOp->getType()->getAs<FunctionProtoType>();
3710 
3711     CallingConv CallOpCC =
3712         CallOp->getType()->castAs<FunctionType>()->getCallConv();
3713     CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
3714         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
3715     CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
3716         CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
3717 
3718     CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
3719     for (CallingConv CC : PrefOrder) {
3720       if (Conv1CC == CC)
3721         return ImplicitConversionSequence::Better;
3722       if (Conv2CC == CC)
3723         return ImplicitConversionSequence::Worse;
3724     }
3725   }
3726 
3727   return ImplicitConversionSequence::Indistinguishable;
3728 }
3729 
3730 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3731     const ImplicitConversionSequence &ICS) {
3732   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3733          (ICS.isUserDefined() &&
3734           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3735 }
3736 
3737 /// CompareImplicitConversionSequences - Compare two implicit
3738 /// conversion sequences to determine whether one is better than the
3739 /// other or if they are indistinguishable (C++ 13.3.3.2).
3740 static ImplicitConversionSequence::CompareKind
3741 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3742                                    const ImplicitConversionSequence& ICS1,
3743                                    const ImplicitConversionSequence& ICS2)
3744 {
3745   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3746   // conversion sequences (as defined in 13.3.3.1)
3747   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3748   //      conversion sequence than a user-defined conversion sequence or
3749   //      an ellipsis conversion sequence, and
3750   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3751   //      conversion sequence than an ellipsis conversion sequence
3752   //      (13.3.3.1.3).
3753   //
3754   // C++0x [over.best.ics]p10:
3755   //   For the purpose of ranking implicit conversion sequences as
3756   //   described in 13.3.3.2, the ambiguous conversion sequence is
3757   //   treated as a user-defined sequence that is indistinguishable
3758   //   from any other user-defined conversion sequence.
3759 
3760   // String literal to 'char *' conversion has been deprecated in C++03. It has
3761   // been removed from C++11. We still accept this conversion, if it happens at
3762   // the best viable function. Otherwise, this conversion is considered worse
3763   // than ellipsis conversion. Consider this as an extension; this is not in the
3764   // standard. For example:
3765   //
3766   // int &f(...);    // #1
3767   // void f(char*);  // #2
3768   // void g() { int &r = f("foo"); }
3769   //
3770   // In C++03, we pick #2 as the best viable function.
3771   // In C++11, we pick #1 as the best viable function, because ellipsis
3772   // conversion is better than string-literal to char* conversion (since there
3773   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3774   // convert arguments, #2 would be the best viable function in C++11.
3775   // If the best viable function has this conversion, a warning will be issued
3776   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3777 
3778   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3779       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3780           hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
3781       // Ill-formedness must not differ
3782       ICS1.isBad() == ICS2.isBad())
3783     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3784                ? ImplicitConversionSequence::Worse
3785                : ImplicitConversionSequence::Better;
3786 
3787   if (ICS1.getKindRank() < ICS2.getKindRank())
3788     return ImplicitConversionSequence::Better;
3789   if (ICS2.getKindRank() < ICS1.getKindRank())
3790     return ImplicitConversionSequence::Worse;
3791 
3792   // The following checks require both conversion sequences to be of
3793   // the same kind.
3794   if (ICS1.getKind() != ICS2.getKind())
3795     return ImplicitConversionSequence::Indistinguishable;
3796 
3797   ImplicitConversionSequence::CompareKind Result =
3798       ImplicitConversionSequence::Indistinguishable;
3799 
3800   // Two implicit conversion sequences of the same form are
3801   // indistinguishable conversion sequences unless one of the
3802   // following rules apply: (C++ 13.3.3.2p3):
3803 
3804   // List-initialization sequence L1 is a better conversion sequence than
3805   // list-initialization sequence L2 if:
3806   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3807   //   if not that,
3808   // — L1 and L2 convert to arrays of the same element type, and either the
3809   //   number of elements n_1 initialized by L1 is less than the number of
3810   //   elements n_2 initialized by L2, or (unimplemented:C++20) n_1 = n_2 and L2
3811   //   converts to an array of unknown bound and L1 does not,
3812   // even if one of the other rules in this paragraph would otherwise apply.
3813   if (!ICS1.isBad()) {
3814     bool StdInit1 = false, StdInit2 = false;
3815     if (ICS1.hasInitializerListContainerType())
3816       StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
3817                                         nullptr);
3818     if (ICS2.hasInitializerListContainerType())
3819       StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
3820                                         nullptr);
3821     if (StdInit1 != StdInit2)
3822       return StdInit1 ? ImplicitConversionSequence::Better
3823                       : ImplicitConversionSequence::Worse;
3824 
3825     if (ICS1.hasInitializerListContainerType() &&
3826         ICS2.hasInitializerListContainerType())
3827       if (auto *CAT1 = S.Context.getAsConstantArrayType(
3828               ICS1.getInitializerListContainerType()))
3829         if (auto *CAT2 = S.Context.getAsConstantArrayType(
3830                 ICS2.getInitializerListContainerType()))
3831           if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
3832                                                CAT2->getElementType()) &&
3833               CAT1->getSize() != CAT2->getSize())
3834             return CAT1->getSize().ult(CAT2->getSize())
3835                        ? ImplicitConversionSequence::Better
3836                        : ImplicitConversionSequence::Worse;
3837   }
3838 
3839   if (ICS1.isStandard())
3840     // Standard conversion sequence S1 is a better conversion sequence than
3841     // standard conversion sequence S2 if [...]
3842     Result = CompareStandardConversionSequences(S, Loc,
3843                                                 ICS1.Standard, ICS2.Standard);
3844   else if (ICS1.isUserDefined()) {
3845     // User-defined conversion sequence U1 is a better conversion
3846     // sequence than another user-defined conversion sequence U2 if
3847     // they contain the same user-defined conversion function or
3848     // constructor and if the second standard conversion sequence of
3849     // U1 is better than the second standard conversion sequence of
3850     // U2 (C++ 13.3.3.2p3).
3851     if (ICS1.UserDefined.ConversionFunction ==
3852           ICS2.UserDefined.ConversionFunction)
3853       Result = CompareStandardConversionSequences(S, Loc,
3854                                                   ICS1.UserDefined.After,
3855                                                   ICS2.UserDefined.After);
3856     else
3857       Result = compareConversionFunctions(S,
3858                                           ICS1.UserDefined.ConversionFunction,
3859                                           ICS2.UserDefined.ConversionFunction);
3860   }
3861 
3862   return Result;
3863 }
3864 
3865 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3866 // determine if one is a proper subset of the other.
3867 static ImplicitConversionSequence::CompareKind
3868 compareStandardConversionSubsets(ASTContext &Context,
3869                                  const StandardConversionSequence& SCS1,
3870                                  const StandardConversionSequence& SCS2) {
3871   ImplicitConversionSequence::CompareKind Result
3872     = ImplicitConversionSequence::Indistinguishable;
3873 
3874   // the identity conversion sequence is considered to be a subsequence of
3875   // any non-identity conversion sequence
3876   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3877     return ImplicitConversionSequence::Better;
3878   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3879     return ImplicitConversionSequence::Worse;
3880 
3881   if (SCS1.Second != SCS2.Second) {
3882     if (SCS1.Second == ICK_Identity)
3883       Result = ImplicitConversionSequence::Better;
3884     else if (SCS2.Second == ICK_Identity)
3885       Result = ImplicitConversionSequence::Worse;
3886     else
3887       return ImplicitConversionSequence::Indistinguishable;
3888   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3889     return ImplicitConversionSequence::Indistinguishable;
3890 
3891   if (SCS1.Third == SCS2.Third) {
3892     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3893                              : ImplicitConversionSequence::Indistinguishable;
3894   }
3895 
3896   if (SCS1.Third == ICK_Identity)
3897     return Result == ImplicitConversionSequence::Worse
3898              ? ImplicitConversionSequence::Indistinguishable
3899              : ImplicitConversionSequence::Better;
3900 
3901   if (SCS2.Third == ICK_Identity)
3902     return Result == ImplicitConversionSequence::Better
3903              ? ImplicitConversionSequence::Indistinguishable
3904              : ImplicitConversionSequence::Worse;
3905 
3906   return ImplicitConversionSequence::Indistinguishable;
3907 }
3908 
3909 /// Determine whether one of the given reference bindings is better
3910 /// than the other based on what kind of bindings they are.
3911 static bool
3912 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3913                              const StandardConversionSequence &SCS2) {
3914   // C++0x [over.ics.rank]p3b4:
3915   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3916   //      implicit object parameter of a non-static member function declared
3917   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3918   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3919   //      lvalue reference to a function lvalue and S2 binds an rvalue
3920   //      reference*.
3921   //
3922   // FIXME: Rvalue references. We're going rogue with the above edits,
3923   // because the semantics in the current C++0x working paper (N3225 at the
3924   // time of this writing) break the standard definition of std::forward
3925   // and std::reference_wrapper when dealing with references to functions.
3926   // Proposed wording changes submitted to CWG for consideration.
3927   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3928       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3929     return false;
3930 
3931   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3932           SCS2.IsLvalueReference) ||
3933          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3934           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3935 }
3936 
3937 enum class FixedEnumPromotion {
3938   None,
3939   ToUnderlyingType,
3940   ToPromotedUnderlyingType
3941 };
3942 
3943 /// Returns kind of fixed enum promotion the \a SCS uses.
3944 static FixedEnumPromotion
3945 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3946 
3947   if (SCS.Second != ICK_Integral_Promotion)
3948     return FixedEnumPromotion::None;
3949 
3950   QualType FromType = SCS.getFromType();
3951   if (!FromType->isEnumeralType())
3952     return FixedEnumPromotion::None;
3953 
3954   EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
3955   if (!Enum->isFixed())
3956     return FixedEnumPromotion::None;
3957 
3958   QualType UnderlyingType = Enum->getIntegerType();
3959   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3960     return FixedEnumPromotion::ToUnderlyingType;
3961 
3962   return FixedEnumPromotion::ToPromotedUnderlyingType;
3963 }
3964 
3965 /// CompareStandardConversionSequences - Compare two standard
3966 /// conversion sequences to determine whether one is better than the
3967 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3968 static ImplicitConversionSequence::CompareKind
3969 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3970                                    const StandardConversionSequence& SCS1,
3971                                    const StandardConversionSequence& SCS2)
3972 {
3973   // Standard conversion sequence S1 is a better conversion sequence
3974   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3975 
3976   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3977   //     sequences in the canonical form defined by 13.3.3.1.1,
3978   //     excluding any Lvalue Transformation; the identity conversion
3979   //     sequence is considered to be a subsequence of any
3980   //     non-identity conversion sequence) or, if not that,
3981   if (ImplicitConversionSequence::CompareKind CK
3982         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3983     return CK;
3984 
3985   //  -- the rank of S1 is better than the rank of S2 (by the rules
3986   //     defined below), or, if not that,
3987   ImplicitConversionRank Rank1 = SCS1.getRank();
3988   ImplicitConversionRank Rank2 = SCS2.getRank();
3989   if (Rank1 < Rank2)
3990     return ImplicitConversionSequence::Better;
3991   else if (Rank2 < Rank1)
3992     return ImplicitConversionSequence::Worse;
3993 
3994   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3995   // are indistinguishable unless one of the following rules
3996   // applies:
3997 
3998   //   A conversion that is not a conversion of a pointer, or
3999   //   pointer to member, to bool is better than another conversion
4000   //   that is such a conversion.
4001   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4002     return SCS2.isPointerConversionToBool()
4003              ? ImplicitConversionSequence::Better
4004              : ImplicitConversionSequence::Worse;
4005 
4006   // C++14 [over.ics.rank]p4b2:
4007   // This is retroactively applied to C++11 by CWG 1601.
4008   //
4009   //   A conversion that promotes an enumeration whose underlying type is fixed
4010   //   to its underlying type is better than one that promotes to the promoted
4011   //   underlying type, if the two are different.
4012   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4013   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4014   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4015       FEP1 != FEP2)
4016     return FEP1 == FixedEnumPromotion::ToUnderlyingType
4017                ? ImplicitConversionSequence::Better
4018                : ImplicitConversionSequence::Worse;
4019 
4020   // C++ [over.ics.rank]p4b2:
4021   //
4022   //   If class B is derived directly or indirectly from class A,
4023   //   conversion of B* to A* is better than conversion of B* to
4024   //   void*, and conversion of A* to void* is better than conversion
4025   //   of B* to void*.
4026   bool SCS1ConvertsToVoid
4027     = SCS1.isPointerConversionToVoidPointer(S.Context);
4028   bool SCS2ConvertsToVoid
4029     = SCS2.isPointerConversionToVoidPointer(S.Context);
4030   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4031     // Exactly one of the conversion sequences is a conversion to
4032     // a void pointer; it's the worse conversion.
4033     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4034                               : ImplicitConversionSequence::Worse;
4035   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4036     // Neither conversion sequence converts to a void pointer; compare
4037     // their derived-to-base conversions.
4038     if (ImplicitConversionSequence::CompareKind DerivedCK
4039           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4040       return DerivedCK;
4041   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4042              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4043     // Both conversion sequences are conversions to void
4044     // pointers. Compare the source types to determine if there's an
4045     // inheritance relationship in their sources.
4046     QualType FromType1 = SCS1.getFromType();
4047     QualType FromType2 = SCS2.getFromType();
4048 
4049     // Adjust the types we're converting from via the array-to-pointer
4050     // conversion, if we need to.
4051     if (SCS1.First == ICK_Array_To_Pointer)
4052       FromType1 = S.Context.getArrayDecayedType(FromType1);
4053     if (SCS2.First == ICK_Array_To_Pointer)
4054       FromType2 = S.Context.getArrayDecayedType(FromType2);
4055 
4056     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4057     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4058 
4059     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4060       return ImplicitConversionSequence::Better;
4061     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4062       return ImplicitConversionSequence::Worse;
4063 
4064     // Objective-C++: If one interface is more specific than the
4065     // other, it is the better one.
4066     const ObjCObjectPointerType* FromObjCPtr1
4067       = FromType1->getAs<ObjCObjectPointerType>();
4068     const ObjCObjectPointerType* FromObjCPtr2
4069       = FromType2->getAs<ObjCObjectPointerType>();
4070     if (FromObjCPtr1 && FromObjCPtr2) {
4071       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4072                                                           FromObjCPtr2);
4073       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4074                                                            FromObjCPtr1);
4075       if (AssignLeft != AssignRight) {
4076         return AssignLeft? ImplicitConversionSequence::Better
4077                          : ImplicitConversionSequence::Worse;
4078       }
4079     }
4080   }
4081 
4082   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4083     // Check for a better reference binding based on the kind of bindings.
4084     if (isBetterReferenceBindingKind(SCS1, SCS2))
4085       return ImplicitConversionSequence::Better;
4086     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4087       return ImplicitConversionSequence::Worse;
4088   }
4089 
4090   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4091   // bullet 3).
4092   if (ImplicitConversionSequence::CompareKind QualCK
4093         = CompareQualificationConversions(S, SCS1, SCS2))
4094     return QualCK;
4095 
4096   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4097     // C++ [over.ics.rank]p3b4:
4098     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4099     //      which the references refer are the same type except for
4100     //      top-level cv-qualifiers, and the type to which the reference
4101     //      initialized by S2 refers is more cv-qualified than the type
4102     //      to which the reference initialized by S1 refers.
4103     QualType T1 = SCS1.getToType(2);
4104     QualType T2 = SCS2.getToType(2);
4105     T1 = S.Context.getCanonicalType(T1);
4106     T2 = S.Context.getCanonicalType(T2);
4107     Qualifiers T1Quals, T2Quals;
4108     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4109     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4110     if (UnqualT1 == UnqualT2) {
4111       // Objective-C++ ARC: If the references refer to objects with different
4112       // lifetimes, prefer bindings that don't change lifetime.
4113       if (SCS1.ObjCLifetimeConversionBinding !=
4114                                           SCS2.ObjCLifetimeConversionBinding) {
4115         return SCS1.ObjCLifetimeConversionBinding
4116                                            ? ImplicitConversionSequence::Worse
4117                                            : ImplicitConversionSequence::Better;
4118       }
4119 
4120       // If the type is an array type, promote the element qualifiers to the
4121       // type for comparison.
4122       if (isa<ArrayType>(T1) && T1Quals)
4123         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4124       if (isa<ArrayType>(T2) && T2Quals)
4125         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4126       if (T2.isMoreQualifiedThan(T1))
4127         return ImplicitConversionSequence::Better;
4128       if (T1.isMoreQualifiedThan(T2))
4129         return ImplicitConversionSequence::Worse;
4130     }
4131   }
4132 
4133   // In Microsoft mode (below 19.28), prefer an integral conversion to a
4134   // floating-to-integral conversion if the integral conversion
4135   // is between types of the same size.
4136   // For example:
4137   // void f(float);
4138   // void f(int);
4139   // int main {
4140   //    long a;
4141   //    f(a);
4142   // }
4143   // Here, MSVC will call f(int) instead of generating a compile error
4144   // as clang will do in standard mode.
4145   if (S.getLangOpts().MSVCCompat &&
4146       !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4147       SCS1.Second == ICK_Integral_Conversion &&
4148       SCS2.Second == ICK_Floating_Integral &&
4149       S.Context.getTypeSize(SCS1.getFromType()) ==
4150           S.Context.getTypeSize(SCS1.getToType(2)))
4151     return ImplicitConversionSequence::Better;
4152 
4153   // Prefer a compatible vector conversion over a lax vector conversion
4154   // For example:
4155   //
4156   // typedef float __v4sf __attribute__((__vector_size__(16)));
4157   // void f(vector float);
4158   // void f(vector signed int);
4159   // int main() {
4160   //   __v4sf a;
4161   //   f(a);
4162   // }
4163   // Here, we'd like to choose f(vector float) and not
4164   // report an ambiguous call error
4165   if (SCS1.Second == ICK_Vector_Conversion &&
4166       SCS2.Second == ICK_Vector_Conversion) {
4167     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4168         SCS1.getFromType(), SCS1.getToType(2));
4169     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4170         SCS2.getFromType(), SCS2.getToType(2));
4171 
4172     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4173       return SCS1IsCompatibleVectorConversion
4174                  ? ImplicitConversionSequence::Better
4175                  : ImplicitConversionSequence::Worse;
4176   }
4177 
4178   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4179       SCS2.Second == ICK_SVE_Vector_Conversion) {
4180     bool SCS1IsCompatibleSVEVectorConversion =
4181         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4182     bool SCS2IsCompatibleSVEVectorConversion =
4183         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4184 
4185     if (SCS1IsCompatibleSVEVectorConversion !=
4186         SCS2IsCompatibleSVEVectorConversion)
4187       return SCS1IsCompatibleSVEVectorConversion
4188                  ? ImplicitConversionSequence::Better
4189                  : ImplicitConversionSequence::Worse;
4190   }
4191 
4192   return ImplicitConversionSequence::Indistinguishable;
4193 }
4194 
4195 /// CompareQualificationConversions - Compares two standard conversion
4196 /// sequences to determine whether they can be ranked based on their
4197 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4198 static ImplicitConversionSequence::CompareKind
4199 CompareQualificationConversions(Sema &S,
4200                                 const StandardConversionSequence& SCS1,
4201                                 const StandardConversionSequence& SCS2) {
4202   // C++ 13.3.3.2p3:
4203   //  -- S1 and S2 differ only in their qualification conversion and
4204   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4205   //     cv-qualification signature of type T1 is a proper subset of
4206   //     the cv-qualification signature of type T2, and S1 is not the
4207   //     deprecated string literal array-to-pointer conversion (4.2).
4208   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4209       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4210     return ImplicitConversionSequence::Indistinguishable;
4211 
4212   // FIXME: the example in the standard doesn't use a qualification
4213   // conversion (!)
4214   QualType T1 = SCS1.getToType(2);
4215   QualType T2 = SCS2.getToType(2);
4216   T1 = S.Context.getCanonicalType(T1);
4217   T2 = S.Context.getCanonicalType(T2);
4218   assert(!T1->isReferenceType() && !T2->isReferenceType());
4219   Qualifiers T1Quals, T2Quals;
4220   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4221   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4222 
4223   // If the types are the same, we won't learn anything by unwrapping
4224   // them.
4225   if (UnqualT1 == UnqualT2)
4226     return ImplicitConversionSequence::Indistinguishable;
4227 
4228   ImplicitConversionSequence::CompareKind Result
4229     = ImplicitConversionSequence::Indistinguishable;
4230 
4231   // Objective-C++ ARC:
4232   //   Prefer qualification conversions not involving a change in lifetime
4233   //   to qualification conversions that do not change lifetime.
4234   if (SCS1.QualificationIncludesObjCLifetime !=
4235                                       SCS2.QualificationIncludesObjCLifetime) {
4236     Result = SCS1.QualificationIncludesObjCLifetime
4237                ? ImplicitConversionSequence::Worse
4238                : ImplicitConversionSequence::Better;
4239   }
4240 
4241   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4242     // Within each iteration of the loop, we check the qualifiers to
4243     // determine if this still looks like a qualification
4244     // conversion. Then, if all is well, we unwrap one more level of
4245     // pointers or pointers-to-members and do it all again
4246     // until there are no more pointers or pointers-to-members left
4247     // to unwrap. This essentially mimics what
4248     // IsQualificationConversion does, but here we're checking for a
4249     // strict subset of qualifiers.
4250     if (T1.getQualifiers().withoutObjCLifetime() ==
4251         T2.getQualifiers().withoutObjCLifetime())
4252       // The qualifiers are the same, so this doesn't tell us anything
4253       // about how the sequences rank.
4254       // ObjC ownership quals are omitted above as they interfere with
4255       // the ARC overload rule.
4256       ;
4257     else if (T2.isMoreQualifiedThan(T1)) {
4258       // T1 has fewer qualifiers, so it could be the better sequence.
4259       if (Result == ImplicitConversionSequence::Worse)
4260         // Neither has qualifiers that are a subset of the other's
4261         // qualifiers.
4262         return ImplicitConversionSequence::Indistinguishable;
4263 
4264       Result = ImplicitConversionSequence::Better;
4265     } else if (T1.isMoreQualifiedThan(T2)) {
4266       // T2 has fewer qualifiers, so it could be the better sequence.
4267       if (Result == ImplicitConversionSequence::Better)
4268         // Neither has qualifiers that are a subset of the other's
4269         // qualifiers.
4270         return ImplicitConversionSequence::Indistinguishable;
4271 
4272       Result = ImplicitConversionSequence::Worse;
4273     } else {
4274       // Qualifiers are disjoint.
4275       return ImplicitConversionSequence::Indistinguishable;
4276     }
4277 
4278     // If the types after this point are equivalent, we're done.
4279     if (S.Context.hasSameUnqualifiedType(T1, T2))
4280       break;
4281   }
4282 
4283   // Check that the winning standard conversion sequence isn't using
4284   // the deprecated string literal array to pointer conversion.
4285   switch (Result) {
4286   case ImplicitConversionSequence::Better:
4287     if (SCS1.DeprecatedStringLiteralToCharPtr)
4288       Result = ImplicitConversionSequence::Indistinguishable;
4289     break;
4290 
4291   case ImplicitConversionSequence::Indistinguishable:
4292     break;
4293 
4294   case ImplicitConversionSequence::Worse:
4295     if (SCS2.DeprecatedStringLiteralToCharPtr)
4296       Result = ImplicitConversionSequence::Indistinguishable;
4297     break;
4298   }
4299 
4300   return Result;
4301 }
4302 
4303 /// CompareDerivedToBaseConversions - Compares two standard conversion
4304 /// sequences to determine whether they can be ranked based on their
4305 /// various kinds of derived-to-base conversions (C++
4306 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4307 /// conversions between Objective-C interface types.
4308 static ImplicitConversionSequence::CompareKind
4309 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4310                                 const StandardConversionSequence& SCS1,
4311                                 const StandardConversionSequence& SCS2) {
4312   QualType FromType1 = SCS1.getFromType();
4313   QualType ToType1 = SCS1.getToType(1);
4314   QualType FromType2 = SCS2.getFromType();
4315   QualType ToType2 = SCS2.getToType(1);
4316 
4317   // Adjust the types we're converting from via the array-to-pointer
4318   // conversion, if we need to.
4319   if (SCS1.First == ICK_Array_To_Pointer)
4320     FromType1 = S.Context.getArrayDecayedType(FromType1);
4321   if (SCS2.First == ICK_Array_To_Pointer)
4322     FromType2 = S.Context.getArrayDecayedType(FromType2);
4323 
4324   // Canonicalize all of the types.
4325   FromType1 = S.Context.getCanonicalType(FromType1);
4326   ToType1 = S.Context.getCanonicalType(ToType1);
4327   FromType2 = S.Context.getCanonicalType(FromType2);
4328   ToType2 = S.Context.getCanonicalType(ToType2);
4329 
4330   // C++ [over.ics.rank]p4b3:
4331   //
4332   //   If class B is derived directly or indirectly from class A and
4333   //   class C is derived directly or indirectly from B,
4334   //
4335   // Compare based on pointer conversions.
4336   if (SCS1.Second == ICK_Pointer_Conversion &&
4337       SCS2.Second == ICK_Pointer_Conversion &&
4338       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4339       FromType1->isPointerType() && FromType2->isPointerType() &&
4340       ToType1->isPointerType() && ToType2->isPointerType()) {
4341     QualType FromPointee1 =
4342         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4343     QualType ToPointee1 =
4344         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4345     QualType FromPointee2 =
4346         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4347     QualType ToPointee2 =
4348         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4349 
4350     //   -- conversion of C* to B* is better than conversion of C* to A*,
4351     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4352       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4353         return ImplicitConversionSequence::Better;
4354       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4355         return ImplicitConversionSequence::Worse;
4356     }
4357 
4358     //   -- conversion of B* to A* is better than conversion of C* to A*,
4359     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4360       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4361         return ImplicitConversionSequence::Better;
4362       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4363         return ImplicitConversionSequence::Worse;
4364     }
4365   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4366              SCS2.Second == ICK_Pointer_Conversion) {
4367     const ObjCObjectPointerType *FromPtr1
4368       = FromType1->getAs<ObjCObjectPointerType>();
4369     const ObjCObjectPointerType *FromPtr2
4370       = FromType2->getAs<ObjCObjectPointerType>();
4371     const ObjCObjectPointerType *ToPtr1
4372       = ToType1->getAs<ObjCObjectPointerType>();
4373     const ObjCObjectPointerType *ToPtr2
4374       = ToType2->getAs<ObjCObjectPointerType>();
4375 
4376     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4377       // Apply the same conversion ranking rules for Objective-C pointer types
4378       // that we do for C++ pointers to class types. However, we employ the
4379       // Objective-C pseudo-subtyping relationship used for assignment of
4380       // Objective-C pointer types.
4381       bool FromAssignLeft
4382         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4383       bool FromAssignRight
4384         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4385       bool ToAssignLeft
4386         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4387       bool ToAssignRight
4388         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4389 
4390       // A conversion to an a non-id object pointer type or qualified 'id'
4391       // type is better than a conversion to 'id'.
4392       if (ToPtr1->isObjCIdType() &&
4393           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4394         return ImplicitConversionSequence::Worse;
4395       if (ToPtr2->isObjCIdType() &&
4396           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4397         return ImplicitConversionSequence::Better;
4398 
4399       // A conversion to a non-id object pointer type is better than a
4400       // conversion to a qualified 'id' type
4401       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4402         return ImplicitConversionSequence::Worse;
4403       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4404         return ImplicitConversionSequence::Better;
4405 
4406       // A conversion to an a non-Class object pointer type or qualified 'Class'
4407       // type is better than a conversion to 'Class'.
4408       if (ToPtr1->isObjCClassType() &&
4409           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4410         return ImplicitConversionSequence::Worse;
4411       if (ToPtr2->isObjCClassType() &&
4412           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4413         return ImplicitConversionSequence::Better;
4414 
4415       // A conversion to a non-Class object pointer type is better than a
4416       // conversion to a qualified 'Class' type.
4417       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4418         return ImplicitConversionSequence::Worse;
4419       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4420         return ImplicitConversionSequence::Better;
4421 
4422       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4423       if (S.Context.hasSameType(FromType1, FromType2) &&
4424           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4425           (ToAssignLeft != ToAssignRight)) {
4426         if (FromPtr1->isSpecialized()) {
4427           // "conversion of B<A> * to B * is better than conversion of B * to
4428           // C *.
4429           bool IsFirstSame =
4430               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4431           bool IsSecondSame =
4432               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4433           if (IsFirstSame) {
4434             if (!IsSecondSame)
4435               return ImplicitConversionSequence::Better;
4436           } else if (IsSecondSame)
4437             return ImplicitConversionSequence::Worse;
4438         }
4439         return ToAssignLeft? ImplicitConversionSequence::Worse
4440                            : ImplicitConversionSequence::Better;
4441       }
4442 
4443       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4444       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4445           (FromAssignLeft != FromAssignRight))
4446         return FromAssignLeft? ImplicitConversionSequence::Better
4447         : ImplicitConversionSequence::Worse;
4448     }
4449   }
4450 
4451   // Ranking of member-pointer types.
4452   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4453       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4454       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4455     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4456     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4457     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4458     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4459     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4460     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4461     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4462     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4463     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4464     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4465     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4466     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4467     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4468     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4469       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4470         return ImplicitConversionSequence::Worse;
4471       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4472         return ImplicitConversionSequence::Better;
4473     }
4474     // conversion of B::* to C::* is better than conversion of A::* to C::*
4475     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4476       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4477         return ImplicitConversionSequence::Better;
4478       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4479         return ImplicitConversionSequence::Worse;
4480     }
4481   }
4482 
4483   if (SCS1.Second == ICK_Derived_To_Base) {
4484     //   -- conversion of C to B is better than conversion of C to A,
4485     //   -- binding of an expression of type C to a reference of type
4486     //      B& is better than binding an expression of type C to a
4487     //      reference of type A&,
4488     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4489         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4490       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4491         return ImplicitConversionSequence::Better;
4492       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4493         return ImplicitConversionSequence::Worse;
4494     }
4495 
4496     //   -- conversion of B to A is better than conversion of C to A.
4497     //   -- binding of an expression of type B to a reference of type
4498     //      A& is better than binding an expression of type C to a
4499     //      reference of type A&,
4500     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4501         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4502       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4503         return ImplicitConversionSequence::Better;
4504       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4505         return ImplicitConversionSequence::Worse;
4506     }
4507   }
4508 
4509   return ImplicitConversionSequence::Indistinguishable;
4510 }
4511 
4512 /// Determine whether the given type is valid, e.g., it is not an invalid
4513 /// C++ class.
4514 static bool isTypeValid(QualType T) {
4515   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4516     return !Record->isInvalidDecl();
4517 
4518   return true;
4519 }
4520 
4521 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4522   if (!T.getQualifiers().hasUnaligned())
4523     return T;
4524 
4525   Qualifiers Q;
4526   T = Ctx.getUnqualifiedArrayType(T, Q);
4527   Q.removeUnaligned();
4528   return Ctx.getQualifiedType(T, Q);
4529 }
4530 
4531 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4532 /// determine whether they are reference-compatible,
4533 /// reference-related, or incompatible, for use in C++ initialization by
4534 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4535 /// type, and the first type (T1) is the pointee type of the reference
4536 /// type being initialized.
4537 Sema::ReferenceCompareResult
4538 Sema::CompareReferenceRelationship(SourceLocation Loc,
4539                                    QualType OrigT1, QualType OrigT2,
4540                                    ReferenceConversions *ConvOut) {
4541   assert(!OrigT1->isReferenceType() &&
4542     "T1 must be the pointee type of the reference type");
4543   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4544 
4545   QualType T1 = Context.getCanonicalType(OrigT1);
4546   QualType T2 = Context.getCanonicalType(OrigT2);
4547   Qualifiers T1Quals, T2Quals;
4548   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4549   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4550 
4551   ReferenceConversions ConvTmp;
4552   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4553   Conv = ReferenceConversions();
4554 
4555   // C++2a [dcl.init.ref]p4:
4556   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4557   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4558   //   T1 is a base class of T2.
4559   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4560   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4561   //   "pointer to cv1 T1" via a standard conversion sequence.
4562 
4563   // Check for standard conversions we can apply to pointers: derived-to-base
4564   // conversions, ObjC pointer conversions, and function pointer conversions.
4565   // (Qualification conversions are checked last.)
4566   QualType ConvertedT2;
4567   if (UnqualT1 == UnqualT2) {
4568     // Nothing to do.
4569   } else if (isCompleteType(Loc, OrigT2) &&
4570              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4571              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4572     Conv |= ReferenceConversions::DerivedToBase;
4573   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4574            UnqualT2->isObjCObjectOrInterfaceType() &&
4575            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4576     Conv |= ReferenceConversions::ObjC;
4577   else if (UnqualT2->isFunctionType() &&
4578            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4579     Conv |= ReferenceConversions::Function;
4580     // No need to check qualifiers; function types don't have them.
4581     return Ref_Compatible;
4582   }
4583   bool ConvertedReferent = Conv != 0;
4584 
4585   // We can have a qualification conversion. Compute whether the types are
4586   // similar at the same time.
4587   bool PreviousToQualsIncludeConst = true;
4588   bool TopLevel = true;
4589   do {
4590     if (T1 == T2)
4591       break;
4592 
4593     // We will need a qualification conversion.
4594     Conv |= ReferenceConversions::Qualification;
4595 
4596     // Track whether we performed a qualification conversion anywhere other
4597     // than the top level. This matters for ranking reference bindings in
4598     // overload resolution.
4599     if (!TopLevel)
4600       Conv |= ReferenceConversions::NestedQualification;
4601 
4602     // MS compiler ignores __unaligned qualifier for references; do the same.
4603     T1 = withoutUnaligned(Context, T1);
4604     T2 = withoutUnaligned(Context, T2);
4605 
4606     // If we find a qualifier mismatch, the types are not reference-compatible,
4607     // but are still be reference-related if they're similar.
4608     bool ObjCLifetimeConversion = false;
4609     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4610                                        PreviousToQualsIncludeConst,
4611                                        ObjCLifetimeConversion))
4612       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4613                  ? Ref_Related
4614                  : Ref_Incompatible;
4615 
4616     // FIXME: Should we track this for any level other than the first?
4617     if (ObjCLifetimeConversion)
4618       Conv |= ReferenceConversions::ObjCLifetime;
4619 
4620     TopLevel = false;
4621   } while (Context.UnwrapSimilarTypes(T1, T2));
4622 
4623   // At this point, if the types are reference-related, we must either have the
4624   // same inner type (ignoring qualifiers), or must have already worked out how
4625   // to convert the referent.
4626   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4627              ? Ref_Compatible
4628              : Ref_Incompatible;
4629 }
4630 
4631 /// Look for a user-defined conversion to a value reference-compatible
4632 ///        with DeclType. Return true if something definite is found.
4633 static bool
4634 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4635                          QualType DeclType, SourceLocation DeclLoc,
4636                          Expr *Init, QualType T2, bool AllowRvalues,
4637                          bool AllowExplicit) {
4638   assert(T2->isRecordType() && "Can only find conversions of record types.");
4639   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4640 
4641   OverloadCandidateSet CandidateSet(
4642       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4643   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4644   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4645     NamedDecl *D = *I;
4646     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4647     if (isa<UsingShadowDecl>(D))
4648       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4649 
4650     FunctionTemplateDecl *ConvTemplate
4651       = dyn_cast<FunctionTemplateDecl>(D);
4652     CXXConversionDecl *Conv;
4653     if (ConvTemplate)
4654       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4655     else
4656       Conv = cast<CXXConversionDecl>(D);
4657 
4658     if (AllowRvalues) {
4659       // If we are initializing an rvalue reference, don't permit conversion
4660       // functions that return lvalues.
4661       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4662         const ReferenceType *RefType
4663           = Conv->getConversionType()->getAs<LValueReferenceType>();
4664         if (RefType && !RefType->getPointeeType()->isFunctionType())
4665           continue;
4666       }
4667 
4668       if (!ConvTemplate &&
4669           S.CompareReferenceRelationship(
4670               DeclLoc,
4671               Conv->getConversionType()
4672                   .getNonReferenceType()
4673                   .getUnqualifiedType(),
4674               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4675               Sema::Ref_Incompatible)
4676         continue;
4677     } else {
4678       // If the conversion function doesn't return a reference type,
4679       // it can't be considered for this conversion. An rvalue reference
4680       // is only acceptable if its referencee is a function type.
4681 
4682       const ReferenceType *RefType =
4683         Conv->getConversionType()->getAs<ReferenceType>();
4684       if (!RefType ||
4685           (!RefType->isLValueReferenceType() &&
4686            !RefType->getPointeeType()->isFunctionType()))
4687         continue;
4688     }
4689 
4690     if (ConvTemplate)
4691       S.AddTemplateConversionCandidate(
4692           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4693           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4694     else
4695       S.AddConversionCandidate(
4696           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4697           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4698   }
4699 
4700   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4701 
4702   OverloadCandidateSet::iterator Best;
4703   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4704   case OR_Success:
4705     // C++ [over.ics.ref]p1:
4706     //
4707     //   [...] If the parameter binds directly to the result of
4708     //   applying a conversion function to the argument
4709     //   expression, the implicit conversion sequence is a
4710     //   user-defined conversion sequence (13.3.3.1.2), with the
4711     //   second standard conversion sequence either an identity
4712     //   conversion or, if the conversion function returns an
4713     //   entity of a type that is a derived class of the parameter
4714     //   type, a derived-to-base Conversion.
4715     if (!Best->FinalConversion.DirectBinding)
4716       return false;
4717 
4718     ICS.setUserDefined();
4719     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4720     ICS.UserDefined.After = Best->FinalConversion;
4721     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4722     ICS.UserDefined.ConversionFunction = Best->Function;
4723     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4724     ICS.UserDefined.EllipsisConversion = false;
4725     assert(ICS.UserDefined.After.ReferenceBinding &&
4726            ICS.UserDefined.After.DirectBinding &&
4727            "Expected a direct reference binding!");
4728     return true;
4729 
4730   case OR_Ambiguous:
4731     ICS.setAmbiguous();
4732     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4733          Cand != CandidateSet.end(); ++Cand)
4734       if (Cand->Best)
4735         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4736     return true;
4737 
4738   case OR_No_Viable_Function:
4739   case OR_Deleted:
4740     // There was no suitable conversion, or we found a deleted
4741     // conversion; continue with other checks.
4742     return false;
4743   }
4744 
4745   llvm_unreachable("Invalid OverloadResult!");
4746 }
4747 
4748 /// Compute an implicit conversion sequence for reference
4749 /// initialization.
4750 static ImplicitConversionSequence
4751 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4752                  SourceLocation DeclLoc,
4753                  bool SuppressUserConversions,
4754                  bool AllowExplicit) {
4755   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4756 
4757   // Most paths end in a failed conversion.
4758   ImplicitConversionSequence ICS;
4759   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4760 
4761   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4762   QualType T2 = Init->getType();
4763 
4764   // If the initializer is the address of an overloaded function, try
4765   // to resolve the overloaded function. If all goes well, T2 is the
4766   // type of the resulting function.
4767   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4768     DeclAccessPair Found;
4769     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4770                                                                 false, Found))
4771       T2 = Fn->getType();
4772   }
4773 
4774   // Compute some basic properties of the types and the initializer.
4775   bool isRValRef = DeclType->isRValueReferenceType();
4776   Expr::Classification InitCategory = Init->Classify(S.Context);
4777 
4778   Sema::ReferenceConversions RefConv;
4779   Sema::ReferenceCompareResult RefRelationship =
4780       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4781 
4782   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4783     ICS.setStandard();
4784     ICS.Standard.First = ICK_Identity;
4785     // FIXME: A reference binding can be a function conversion too. We should
4786     // consider that when ordering reference-to-function bindings.
4787     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4788                               ? ICK_Derived_To_Base
4789                               : (RefConv & Sema::ReferenceConversions::ObjC)
4790                                     ? ICK_Compatible_Conversion
4791                                     : ICK_Identity;
4792     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4793     // a reference binding that performs a non-top-level qualification
4794     // conversion as a qualification conversion, not as an identity conversion.
4795     ICS.Standard.Third = (RefConv &
4796                               Sema::ReferenceConversions::NestedQualification)
4797                              ? ICK_Qualification
4798                              : ICK_Identity;
4799     ICS.Standard.setFromType(T2);
4800     ICS.Standard.setToType(0, T2);
4801     ICS.Standard.setToType(1, T1);
4802     ICS.Standard.setToType(2, T1);
4803     ICS.Standard.ReferenceBinding = true;
4804     ICS.Standard.DirectBinding = BindsDirectly;
4805     ICS.Standard.IsLvalueReference = !isRValRef;
4806     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4807     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4808     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4809     ICS.Standard.ObjCLifetimeConversionBinding =
4810         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4811     ICS.Standard.CopyConstructor = nullptr;
4812     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4813   };
4814 
4815   // C++0x [dcl.init.ref]p5:
4816   //   A reference to type "cv1 T1" is initialized by an expression
4817   //   of type "cv2 T2" as follows:
4818 
4819   //     -- If reference is an lvalue reference and the initializer expression
4820   if (!isRValRef) {
4821     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4822     //        reference-compatible with "cv2 T2," or
4823     //
4824     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4825     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4826       // C++ [over.ics.ref]p1:
4827       //   When a parameter of reference type binds directly (8.5.3)
4828       //   to an argument expression, the implicit conversion sequence
4829       //   is the identity conversion, unless the argument expression
4830       //   has a type that is a derived class of the parameter type,
4831       //   in which case the implicit conversion sequence is a
4832       //   derived-to-base Conversion (13.3.3.1).
4833       SetAsReferenceBinding(/*BindsDirectly=*/true);
4834 
4835       // Nothing more to do: the inaccessibility/ambiguity check for
4836       // derived-to-base conversions is suppressed when we're
4837       // computing the implicit conversion sequence (C++
4838       // [over.best.ics]p2).
4839       return ICS;
4840     }
4841 
4842     //       -- has a class type (i.e., T2 is a class type), where T1 is
4843     //          not reference-related to T2, and can be implicitly
4844     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4845     //          is reference-compatible with "cv3 T3" 92) (this
4846     //          conversion is selected by enumerating the applicable
4847     //          conversion functions (13.3.1.6) and choosing the best
4848     //          one through overload resolution (13.3)),
4849     if (!SuppressUserConversions && T2->isRecordType() &&
4850         S.isCompleteType(DeclLoc, T2) &&
4851         RefRelationship == Sema::Ref_Incompatible) {
4852       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4853                                    Init, T2, /*AllowRvalues=*/false,
4854                                    AllowExplicit))
4855         return ICS;
4856     }
4857   }
4858 
4859   //     -- Otherwise, the reference shall be an lvalue reference to a
4860   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4861   //        shall be an rvalue reference.
4862   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
4863     if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
4864       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4865     return ICS;
4866   }
4867 
4868   //       -- If the initializer expression
4869   //
4870   //            -- is an xvalue, class prvalue, array prvalue or function
4871   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4872   if (RefRelationship == Sema::Ref_Compatible &&
4873       (InitCategory.isXValue() ||
4874        (InitCategory.isPRValue() &&
4875           (T2->isRecordType() || T2->isArrayType())) ||
4876        (InitCategory.isLValue() && T2->isFunctionType()))) {
4877     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4878     // binding unless we're binding to a class prvalue.
4879     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4880     // allow the use of rvalue references in C++98/03 for the benefit of
4881     // standard library implementors; therefore, we need the xvalue check here.
4882     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4883                           !(InitCategory.isPRValue() || T2->isRecordType()));
4884     return ICS;
4885   }
4886 
4887   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4888   //               reference-related to T2, and can be implicitly converted to
4889   //               an xvalue, class prvalue, or function lvalue of type
4890   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4891   //               "cv3 T3",
4892   //
4893   //          then the reference is bound to the value of the initializer
4894   //          expression in the first case and to the result of the conversion
4895   //          in the second case (or, in either case, to an appropriate base
4896   //          class subobject).
4897   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4898       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4899       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4900                                Init, T2, /*AllowRvalues=*/true,
4901                                AllowExplicit)) {
4902     // In the second case, if the reference is an rvalue reference
4903     // and the second standard conversion sequence of the
4904     // user-defined conversion sequence includes an lvalue-to-rvalue
4905     // conversion, the program is ill-formed.
4906     if (ICS.isUserDefined() && isRValRef &&
4907         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4908       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4909 
4910     return ICS;
4911   }
4912 
4913   // A temporary of function type cannot be created; don't even try.
4914   if (T1->isFunctionType())
4915     return ICS;
4916 
4917   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4918   //          initialized from the initializer expression using the
4919   //          rules for a non-reference copy initialization (8.5). The
4920   //          reference is then bound to the temporary. If T1 is
4921   //          reference-related to T2, cv1 must be the same
4922   //          cv-qualification as, or greater cv-qualification than,
4923   //          cv2; otherwise, the program is ill-formed.
4924   if (RefRelationship == Sema::Ref_Related) {
4925     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4926     // we would be reference-compatible or reference-compatible with
4927     // added qualification. But that wasn't the case, so the reference
4928     // initialization fails.
4929     //
4930     // Note that we only want to check address spaces and cvr-qualifiers here.
4931     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4932     Qualifiers T1Quals = T1.getQualifiers();
4933     Qualifiers T2Quals = T2.getQualifiers();
4934     T1Quals.removeObjCGCAttr();
4935     T1Quals.removeObjCLifetime();
4936     T2Quals.removeObjCGCAttr();
4937     T2Quals.removeObjCLifetime();
4938     // MS compiler ignores __unaligned qualifier for references; do the same.
4939     T1Quals.removeUnaligned();
4940     T2Quals.removeUnaligned();
4941     if (!T1Quals.compatiblyIncludes(T2Quals))
4942       return ICS;
4943   }
4944 
4945   // If at least one of the types is a class type, the types are not
4946   // related, and we aren't allowed any user conversions, the
4947   // reference binding fails. This case is important for breaking
4948   // recursion, since TryImplicitConversion below will attempt to
4949   // create a temporary through the use of a copy constructor.
4950   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4951       (T1->isRecordType() || T2->isRecordType()))
4952     return ICS;
4953 
4954   // If T1 is reference-related to T2 and the reference is an rvalue
4955   // reference, the initializer expression shall not be an lvalue.
4956   if (RefRelationship >= Sema::Ref_Related && isRValRef &&
4957       Init->Classify(S.Context).isLValue()) {
4958     ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
4959     return ICS;
4960   }
4961 
4962   // C++ [over.ics.ref]p2:
4963   //   When a parameter of reference type is not bound directly to
4964   //   an argument expression, the conversion sequence is the one
4965   //   required to convert the argument expression to the
4966   //   underlying type of the reference according to
4967   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4968   //   to copy-initializing a temporary of the underlying type with
4969   //   the argument expression. Any difference in top-level
4970   //   cv-qualification is subsumed by the initialization itself
4971   //   and does not constitute a conversion.
4972   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4973                               AllowedExplicit::None,
4974                               /*InOverloadResolution=*/false,
4975                               /*CStyle=*/false,
4976                               /*AllowObjCWritebackConversion=*/false,
4977                               /*AllowObjCConversionOnExplicit=*/false);
4978 
4979   // Of course, that's still a reference binding.
4980   if (ICS.isStandard()) {
4981     ICS.Standard.ReferenceBinding = true;
4982     ICS.Standard.IsLvalueReference = !isRValRef;
4983     ICS.Standard.BindsToFunctionLvalue = false;
4984     ICS.Standard.BindsToRvalue = true;
4985     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4986     ICS.Standard.ObjCLifetimeConversionBinding = false;
4987   } else if (ICS.isUserDefined()) {
4988     const ReferenceType *LValRefType =
4989         ICS.UserDefined.ConversionFunction->getReturnType()
4990             ->getAs<LValueReferenceType>();
4991 
4992     // C++ [over.ics.ref]p3:
4993     //   Except for an implicit object parameter, for which see 13.3.1, a
4994     //   standard conversion sequence cannot be formed if it requires [...]
4995     //   binding an rvalue reference to an lvalue other than a function
4996     //   lvalue.
4997     // Note that the function case is not possible here.
4998     if (isRValRef && LValRefType) {
4999       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5000       return ICS;
5001     }
5002 
5003     ICS.UserDefined.After.ReferenceBinding = true;
5004     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5005     ICS.UserDefined.After.BindsToFunctionLvalue = false;
5006     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5007     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5008     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5009   }
5010 
5011   return ICS;
5012 }
5013 
5014 static ImplicitConversionSequence
5015 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5016                       bool SuppressUserConversions,
5017                       bool InOverloadResolution,
5018                       bool AllowObjCWritebackConversion,
5019                       bool AllowExplicit = false);
5020 
5021 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5022 /// initializer list From.
5023 static ImplicitConversionSequence
5024 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5025                   bool SuppressUserConversions,
5026                   bool InOverloadResolution,
5027                   bool AllowObjCWritebackConversion) {
5028   // C++11 [over.ics.list]p1:
5029   //   When an argument is an initializer list, it is not an expression and
5030   //   special rules apply for converting it to a parameter type.
5031 
5032   ImplicitConversionSequence Result;
5033   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5034 
5035   // We need a complete type for what follows. Incomplete types can never be
5036   // initialized from init lists.
5037   if (!S.isCompleteType(From->getBeginLoc(), ToType))
5038     return Result;
5039 
5040   // Per DR1467:
5041   //   If the parameter type is a class X and the initializer list has a single
5042   //   element of type cv U, where U is X or a class derived from X, the
5043   //   implicit conversion sequence is the one required to convert the element
5044   //   to the parameter type.
5045   //
5046   //   Otherwise, if the parameter type is a character array [... ]
5047   //   and the initializer list has a single element that is an
5048   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5049   //   implicit conversion sequence is the identity conversion.
5050   if (From->getNumInits() == 1) {
5051     if (ToType->isRecordType()) {
5052       QualType InitType = From->getInit(0)->getType();
5053       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5054           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5055         return TryCopyInitialization(S, From->getInit(0), ToType,
5056                                      SuppressUserConversions,
5057                                      InOverloadResolution,
5058                                      AllowObjCWritebackConversion);
5059     }
5060 
5061     if (const auto *AT = S.Context.getAsArrayType(ToType)) {
5062       if (S.IsStringInit(From->getInit(0), AT)) {
5063         InitializedEntity Entity =
5064           InitializedEntity::InitializeParameter(S.Context, ToType,
5065                                                  /*Consumed=*/false);
5066         if (S.CanPerformCopyInitialization(Entity, From)) {
5067           Result.setStandard();
5068           Result.Standard.setAsIdentityConversion();
5069           Result.Standard.setFromType(ToType);
5070           Result.Standard.setAllToTypes(ToType);
5071           return Result;
5072         }
5073       }
5074     }
5075   }
5076 
5077   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5078   // C++11 [over.ics.list]p2:
5079   //   If the parameter type is std::initializer_list<X> or "array of X" and
5080   //   all the elements can be implicitly converted to X, the implicit
5081   //   conversion sequence is the worst conversion necessary to convert an
5082   //   element of the list to X.
5083   //
5084   // C++14 [over.ics.list]p3:
5085   //   Otherwise, if the parameter type is "array of N X", if the initializer
5086   //   list has exactly N elements or if it has fewer than N elements and X is
5087   //   default-constructible, and if all the elements of the initializer list
5088   //   can be implicitly converted to X, the implicit conversion sequence is
5089   //   the worst conversion necessary to convert an element of the list to X.
5090   QualType InitTy = ToType;
5091   ArrayType const *AT = S.Context.getAsArrayType(ToType);
5092   if (AT || S.isStdInitializerList(ToType, &InitTy)) {
5093     unsigned e = From->getNumInits();
5094     ImplicitConversionSequence DfltElt;
5095     DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5096                    QualType());
5097     if (AT) {
5098       // Result has been initialized above as a BadConversionSequence
5099       InitTy = AT->getElementType();
5100       if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5101         if (CT->getSize().ult(e)) {
5102           // Too many inits, fatally bad
5103           Result.setBad(BadConversionSequence::too_many_initializers, From,
5104                         ToType);
5105           Result.setInitializerListContainerType(ToType);
5106           return Result;
5107         }
5108         if (CT->getSize().ugt(e)) {
5109           // Need an init from empty {}, is there one?
5110           InitListExpr EmptyList(S.Context, From->getEndLoc(), None,
5111                                  From->getEndLoc());
5112           EmptyList.setType(S.Context.VoidTy);
5113           DfltElt = TryListConversion(
5114               S, &EmptyList, InitTy, SuppressUserConversions,
5115               InOverloadResolution, AllowObjCWritebackConversion);
5116           if (DfltElt.isBad()) {
5117             // No {} init, fatally bad
5118             Result.setBad(BadConversionSequence::too_few_initializers, From,
5119                           ToType);
5120             Result.setInitializerListContainerType(ToType);
5121             return Result;
5122           }
5123         }
5124       }
5125     }
5126 
5127     Result.setStandard();
5128     Result.Standard.setAsIdentityConversion();
5129     Result.Standard.setFromType(InitTy);
5130     Result.Standard.setAllToTypes(InitTy);
5131     for (unsigned i = 0; i < e; ++i) {
5132       Expr *Init = From->getInit(i);
5133       ImplicitConversionSequence ICS = TryCopyInitialization(
5134           S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5135           AllowObjCWritebackConversion);
5136 
5137       // Keep the worse conversion seen so far.
5138       // FIXME: Sequences are not totally ordered, so 'worse' can be
5139       // ambiguous. CWG has been informed.
5140       if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5141                                              Result) ==
5142           ImplicitConversionSequence::Worse) {
5143         Result = ICS;
5144         // Bail as soon as we find something unconvertible.
5145         if (Result.isBad()) {
5146           Result.setInitializerListContainerType(ToType);
5147           return Result;
5148         }
5149       }
5150     }
5151 
5152     // If we needed any implicit {} initialization, compare that now.
5153     // over.ics.list/6 indicates we should compare that conversion.  Again CWG
5154     // has been informed that this might not be the best thing.
5155     if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5156                                 S, From->getEndLoc(), DfltElt, Result) ==
5157                                 ImplicitConversionSequence::Worse)
5158       Result = DfltElt;
5159 
5160     Result.setInitializerListContainerType(ToType);
5161     return Result;
5162   }
5163 
5164   // C++14 [over.ics.list]p4:
5165   // C++11 [over.ics.list]p3:
5166   //   Otherwise, if the parameter is a non-aggregate class X and overload
5167   //   resolution chooses a single best constructor [...] the implicit
5168   //   conversion sequence is a user-defined conversion sequence. If multiple
5169   //   constructors are viable but none is better than the others, the
5170   //   implicit conversion sequence is a user-defined conversion sequence.
5171   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5172     // This function can deal with initializer lists.
5173     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5174                                     AllowedExplicit::None,
5175                                     InOverloadResolution, /*CStyle=*/false,
5176                                     AllowObjCWritebackConversion,
5177                                     /*AllowObjCConversionOnExplicit=*/false);
5178   }
5179 
5180   // C++14 [over.ics.list]p5:
5181   // C++11 [over.ics.list]p4:
5182   //   Otherwise, if the parameter has an aggregate type which can be
5183   //   initialized from the initializer list [...] the implicit conversion
5184   //   sequence is a user-defined conversion sequence.
5185   if (ToType->isAggregateType()) {
5186     // Type is an aggregate, argument is an init list. At this point it comes
5187     // down to checking whether the initialization works.
5188     // FIXME: Find out whether this parameter is consumed or not.
5189     InitializedEntity Entity =
5190         InitializedEntity::InitializeParameter(S.Context, ToType,
5191                                                /*Consumed=*/false);
5192     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5193                                                                  From)) {
5194       Result.setUserDefined();
5195       Result.UserDefined.Before.setAsIdentityConversion();
5196       // Initializer lists don't have a type.
5197       Result.UserDefined.Before.setFromType(QualType());
5198       Result.UserDefined.Before.setAllToTypes(QualType());
5199 
5200       Result.UserDefined.After.setAsIdentityConversion();
5201       Result.UserDefined.After.setFromType(ToType);
5202       Result.UserDefined.After.setAllToTypes(ToType);
5203       Result.UserDefined.ConversionFunction = nullptr;
5204     }
5205     return Result;
5206   }
5207 
5208   // C++14 [over.ics.list]p6:
5209   // C++11 [over.ics.list]p5:
5210   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5211   if (ToType->isReferenceType()) {
5212     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5213     // mention initializer lists in any way. So we go by what list-
5214     // initialization would do and try to extrapolate from that.
5215 
5216     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5217 
5218     // If the initializer list has a single element that is reference-related
5219     // to the parameter type, we initialize the reference from that.
5220     if (From->getNumInits() == 1) {
5221       Expr *Init = From->getInit(0);
5222 
5223       QualType T2 = Init->getType();
5224 
5225       // If the initializer is the address of an overloaded function, try
5226       // to resolve the overloaded function. If all goes well, T2 is the
5227       // type of the resulting function.
5228       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5229         DeclAccessPair Found;
5230         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5231                                    Init, ToType, false, Found))
5232           T2 = Fn->getType();
5233       }
5234 
5235       // Compute some basic properties of the types and the initializer.
5236       Sema::ReferenceCompareResult RefRelationship =
5237           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5238 
5239       if (RefRelationship >= Sema::Ref_Related) {
5240         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5241                                 SuppressUserConversions,
5242                                 /*AllowExplicit=*/false);
5243       }
5244     }
5245 
5246     // Otherwise, we bind the reference to a temporary created from the
5247     // initializer list.
5248     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5249                                InOverloadResolution,
5250                                AllowObjCWritebackConversion);
5251     if (Result.isFailure())
5252       return Result;
5253     assert(!Result.isEllipsis() &&
5254            "Sub-initialization cannot result in ellipsis conversion.");
5255 
5256     // Can we even bind to a temporary?
5257     if (ToType->isRValueReferenceType() ||
5258         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5259       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5260                                             Result.UserDefined.After;
5261       SCS.ReferenceBinding = true;
5262       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5263       SCS.BindsToRvalue = true;
5264       SCS.BindsToFunctionLvalue = false;
5265       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5266       SCS.ObjCLifetimeConversionBinding = false;
5267     } else
5268       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5269                     From, ToType);
5270     return Result;
5271   }
5272 
5273   // C++14 [over.ics.list]p7:
5274   // C++11 [over.ics.list]p6:
5275   //   Otherwise, if the parameter type is not a class:
5276   if (!ToType->isRecordType()) {
5277     //    - if the initializer list has one element that is not itself an
5278     //      initializer list, the implicit conversion sequence is the one
5279     //      required to convert the element to the parameter type.
5280     unsigned NumInits = From->getNumInits();
5281     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5282       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5283                                      SuppressUserConversions,
5284                                      InOverloadResolution,
5285                                      AllowObjCWritebackConversion);
5286     //    - if the initializer list has no elements, the implicit conversion
5287     //      sequence is the identity conversion.
5288     else if (NumInits == 0) {
5289       Result.setStandard();
5290       Result.Standard.setAsIdentityConversion();
5291       Result.Standard.setFromType(ToType);
5292       Result.Standard.setAllToTypes(ToType);
5293     }
5294     return Result;
5295   }
5296 
5297   // C++14 [over.ics.list]p8:
5298   // C++11 [over.ics.list]p7:
5299   //   In all cases other than those enumerated above, no conversion is possible
5300   return Result;
5301 }
5302 
5303 /// TryCopyInitialization - Try to copy-initialize a value of type
5304 /// ToType from the expression From. Return the implicit conversion
5305 /// sequence required to pass this argument, which may be a bad
5306 /// conversion sequence (meaning that the argument cannot be passed to
5307 /// a parameter of this type). If @p SuppressUserConversions, then we
5308 /// do not permit any user-defined conversion sequences.
5309 static ImplicitConversionSequence
5310 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5311                       bool SuppressUserConversions,
5312                       bool InOverloadResolution,
5313                       bool AllowObjCWritebackConversion,
5314                       bool AllowExplicit) {
5315   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5316     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5317                              InOverloadResolution,AllowObjCWritebackConversion);
5318 
5319   if (ToType->isReferenceType())
5320     return TryReferenceInit(S, From, ToType,
5321                             /*FIXME:*/ From->getBeginLoc(),
5322                             SuppressUserConversions, AllowExplicit);
5323 
5324   return TryImplicitConversion(S, From, ToType,
5325                                SuppressUserConversions,
5326                                AllowedExplicit::None,
5327                                InOverloadResolution,
5328                                /*CStyle=*/false,
5329                                AllowObjCWritebackConversion,
5330                                /*AllowObjCConversionOnExplicit=*/false);
5331 }
5332 
5333 static bool TryCopyInitialization(const CanQualType FromQTy,
5334                                   const CanQualType ToQTy,
5335                                   Sema &S,
5336                                   SourceLocation Loc,
5337                                   ExprValueKind FromVK) {
5338   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5339   ImplicitConversionSequence ICS =
5340     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5341 
5342   return !ICS.isBad();
5343 }
5344 
5345 /// TryObjectArgumentInitialization - Try to initialize the object
5346 /// parameter of the given member function (@c Method) from the
5347 /// expression @p From.
5348 static ImplicitConversionSequence
5349 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5350                                 Expr::Classification FromClassification,
5351                                 CXXMethodDecl *Method,
5352                                 CXXRecordDecl *ActingContext) {
5353   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5354   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5355   //                 const volatile object.
5356   Qualifiers Quals = Method->getMethodQualifiers();
5357   if (isa<CXXDestructorDecl>(Method)) {
5358     Quals.addConst();
5359     Quals.addVolatile();
5360   }
5361 
5362   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5363 
5364   // Set up the conversion sequence as a "bad" conversion, to allow us
5365   // to exit early.
5366   ImplicitConversionSequence ICS;
5367 
5368   // We need to have an object of class type.
5369   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5370     FromType = PT->getPointeeType();
5371 
5372     // When we had a pointer, it's implicitly dereferenced, so we
5373     // better have an lvalue.
5374     assert(FromClassification.isLValue());
5375   }
5376 
5377   assert(FromType->isRecordType());
5378 
5379   // C++0x [over.match.funcs]p4:
5380   //   For non-static member functions, the type of the implicit object
5381   //   parameter is
5382   //
5383   //     - "lvalue reference to cv X" for functions declared without a
5384   //        ref-qualifier or with the & ref-qualifier
5385   //     - "rvalue reference to cv X" for functions declared with the &&
5386   //        ref-qualifier
5387   //
5388   // where X is the class of which the function is a member and cv is the
5389   // cv-qualification on the member function declaration.
5390   //
5391   // However, when finding an implicit conversion sequence for the argument, we
5392   // are not allowed to perform user-defined conversions
5393   // (C++ [over.match.funcs]p5). We perform a simplified version of
5394   // reference binding here, that allows class rvalues to bind to
5395   // non-constant references.
5396 
5397   // First check the qualifiers.
5398   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5399   if (ImplicitParamType.getCVRQualifiers()
5400                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5401       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5402     ICS.setBad(BadConversionSequence::bad_qualifiers,
5403                FromType, ImplicitParamType);
5404     return ICS;
5405   }
5406 
5407   if (FromTypeCanon.hasAddressSpace()) {
5408     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5409     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5410     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5411       ICS.setBad(BadConversionSequence::bad_qualifiers,
5412                  FromType, ImplicitParamType);
5413       return ICS;
5414     }
5415   }
5416 
5417   // Check that we have either the same type or a derived type. It
5418   // affects the conversion rank.
5419   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5420   ImplicitConversionKind SecondKind;
5421   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5422     SecondKind = ICK_Identity;
5423   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5424     SecondKind = ICK_Derived_To_Base;
5425   else {
5426     ICS.setBad(BadConversionSequence::unrelated_class,
5427                FromType, ImplicitParamType);
5428     return ICS;
5429   }
5430 
5431   // Check the ref-qualifier.
5432   switch (Method->getRefQualifier()) {
5433   case RQ_None:
5434     // Do nothing; we don't care about lvalueness or rvalueness.
5435     break;
5436 
5437   case RQ_LValue:
5438     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5439       // non-const lvalue reference cannot bind to an rvalue
5440       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5441                  ImplicitParamType);
5442       return ICS;
5443     }
5444     break;
5445 
5446   case RQ_RValue:
5447     if (!FromClassification.isRValue()) {
5448       // rvalue reference cannot bind to an lvalue
5449       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5450                  ImplicitParamType);
5451       return ICS;
5452     }
5453     break;
5454   }
5455 
5456   // Success. Mark this as a reference binding.
5457   ICS.setStandard();
5458   ICS.Standard.setAsIdentityConversion();
5459   ICS.Standard.Second = SecondKind;
5460   ICS.Standard.setFromType(FromType);
5461   ICS.Standard.setAllToTypes(ImplicitParamType);
5462   ICS.Standard.ReferenceBinding = true;
5463   ICS.Standard.DirectBinding = true;
5464   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5465   ICS.Standard.BindsToFunctionLvalue = false;
5466   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5467   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5468     = (Method->getRefQualifier() == RQ_None);
5469   return ICS;
5470 }
5471 
5472 /// PerformObjectArgumentInitialization - Perform initialization of
5473 /// the implicit object parameter for the given Method with the given
5474 /// expression.
5475 ExprResult
5476 Sema::PerformObjectArgumentInitialization(Expr *From,
5477                                           NestedNameSpecifier *Qualifier,
5478                                           NamedDecl *FoundDecl,
5479                                           CXXMethodDecl *Method) {
5480   QualType FromRecordType, DestType;
5481   QualType ImplicitParamRecordType  =
5482     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5483 
5484   Expr::Classification FromClassification;
5485   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5486     FromRecordType = PT->getPointeeType();
5487     DestType = Method->getThisType();
5488     FromClassification = Expr::Classification::makeSimpleLValue();
5489   } else {
5490     FromRecordType = From->getType();
5491     DestType = ImplicitParamRecordType;
5492     FromClassification = From->Classify(Context);
5493 
5494     // When performing member access on a prvalue, materialize a temporary.
5495     if (From->isPRValue()) {
5496       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5497                                             Method->getRefQualifier() !=
5498                                                 RefQualifierKind::RQ_RValue);
5499     }
5500   }
5501 
5502   // Note that we always use the true parent context when performing
5503   // the actual argument initialization.
5504   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5505       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5506       Method->getParent());
5507   if (ICS.isBad()) {
5508     switch (ICS.Bad.Kind) {
5509     case BadConversionSequence::bad_qualifiers: {
5510       Qualifiers FromQs = FromRecordType.getQualifiers();
5511       Qualifiers ToQs = DestType.getQualifiers();
5512       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5513       if (CVR) {
5514         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5515             << Method->getDeclName() << FromRecordType << (CVR - 1)
5516             << From->getSourceRange();
5517         Diag(Method->getLocation(), diag::note_previous_decl)
5518           << Method->getDeclName();
5519         return ExprError();
5520       }
5521       break;
5522     }
5523 
5524     case BadConversionSequence::lvalue_ref_to_rvalue:
5525     case BadConversionSequence::rvalue_ref_to_lvalue: {
5526       bool IsRValueQualified =
5527         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5528       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5529           << Method->getDeclName() << FromClassification.isRValue()
5530           << IsRValueQualified;
5531       Diag(Method->getLocation(), diag::note_previous_decl)
5532         << Method->getDeclName();
5533       return ExprError();
5534     }
5535 
5536     case BadConversionSequence::no_conversion:
5537     case BadConversionSequence::unrelated_class:
5538       break;
5539 
5540     case BadConversionSequence::too_few_initializers:
5541     case BadConversionSequence::too_many_initializers:
5542       llvm_unreachable("Lists are not objects");
5543     }
5544 
5545     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5546            << ImplicitParamRecordType << FromRecordType
5547            << From->getSourceRange();
5548   }
5549 
5550   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5551     ExprResult FromRes =
5552       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5553     if (FromRes.isInvalid())
5554       return ExprError();
5555     From = FromRes.get();
5556   }
5557 
5558   if (!Context.hasSameType(From->getType(), DestType)) {
5559     CastKind CK;
5560     QualType PteeTy = DestType->getPointeeType();
5561     LangAS DestAS =
5562         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5563     if (FromRecordType.getAddressSpace() != DestAS)
5564       CK = CK_AddressSpaceConversion;
5565     else
5566       CK = CK_NoOp;
5567     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5568   }
5569   return From;
5570 }
5571 
5572 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5573 /// expression From to bool (C++0x [conv]p3).
5574 static ImplicitConversionSequence
5575 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5576   // C++ [dcl.init]/17.8:
5577   //   - Otherwise, if the initialization is direct-initialization, the source
5578   //     type is std::nullptr_t, and the destination type is bool, the initial
5579   //     value of the object being initialized is false.
5580   if (From->getType()->isNullPtrType())
5581     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5582                                                         S.Context.BoolTy,
5583                                                         From->isGLValue());
5584 
5585   // All other direct-initialization of bool is equivalent to an implicit
5586   // conversion to bool in which explicit conversions are permitted.
5587   return TryImplicitConversion(S, From, S.Context.BoolTy,
5588                                /*SuppressUserConversions=*/false,
5589                                AllowedExplicit::Conversions,
5590                                /*InOverloadResolution=*/false,
5591                                /*CStyle=*/false,
5592                                /*AllowObjCWritebackConversion=*/false,
5593                                /*AllowObjCConversionOnExplicit=*/false);
5594 }
5595 
5596 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5597 /// of the expression From to bool (C++0x [conv]p3).
5598 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5599   if (checkPlaceholderForOverload(*this, From))
5600     return ExprError();
5601 
5602   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5603   if (!ICS.isBad())
5604     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5605 
5606   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5607     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5608            << From->getType() << From->getSourceRange();
5609   return ExprError();
5610 }
5611 
5612 /// Check that the specified conversion is permitted in a converted constant
5613 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5614 /// is acceptable.
5615 static bool CheckConvertedConstantConversions(Sema &S,
5616                                               StandardConversionSequence &SCS) {
5617   // Since we know that the target type is an integral or unscoped enumeration
5618   // type, most conversion kinds are impossible. All possible First and Third
5619   // conversions are fine.
5620   switch (SCS.Second) {
5621   case ICK_Identity:
5622   case ICK_Integral_Promotion:
5623   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5624   case ICK_Zero_Queue_Conversion:
5625     return true;
5626 
5627   case ICK_Boolean_Conversion:
5628     // Conversion from an integral or unscoped enumeration type to bool is
5629     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5630     // conversion, so we allow it in a converted constant expression.
5631     //
5632     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5633     // a lot of popular code. We should at least add a warning for this
5634     // (non-conforming) extension.
5635     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5636            SCS.getToType(2)->isBooleanType();
5637 
5638   case ICK_Pointer_Conversion:
5639   case ICK_Pointer_Member:
5640     // C++1z: null pointer conversions and null member pointer conversions are
5641     // only permitted if the source type is std::nullptr_t.
5642     return SCS.getFromType()->isNullPtrType();
5643 
5644   case ICK_Floating_Promotion:
5645   case ICK_Complex_Promotion:
5646   case ICK_Floating_Conversion:
5647   case ICK_Complex_Conversion:
5648   case ICK_Floating_Integral:
5649   case ICK_Compatible_Conversion:
5650   case ICK_Derived_To_Base:
5651   case ICK_Vector_Conversion:
5652   case ICK_SVE_Vector_Conversion:
5653   case ICK_Vector_Splat:
5654   case ICK_Complex_Real:
5655   case ICK_Block_Pointer_Conversion:
5656   case ICK_TransparentUnionConversion:
5657   case ICK_Writeback_Conversion:
5658   case ICK_Zero_Event_Conversion:
5659   case ICK_C_Only_Conversion:
5660   case ICK_Incompatible_Pointer_Conversion:
5661     return false;
5662 
5663   case ICK_Lvalue_To_Rvalue:
5664   case ICK_Array_To_Pointer:
5665   case ICK_Function_To_Pointer:
5666     llvm_unreachable("found a first conversion kind in Second");
5667 
5668   case ICK_Function_Conversion:
5669   case ICK_Qualification:
5670     llvm_unreachable("found a third conversion kind in Second");
5671 
5672   case ICK_Num_Conversion_Kinds:
5673     break;
5674   }
5675 
5676   llvm_unreachable("unknown conversion kind");
5677 }
5678 
5679 /// CheckConvertedConstantExpression - Check that the expression From is a
5680 /// converted constant expression of type T, perform the conversion and produce
5681 /// the converted expression, per C++11 [expr.const]p3.
5682 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5683                                                    QualType T, APValue &Value,
5684                                                    Sema::CCEKind CCE,
5685                                                    bool RequireInt,
5686                                                    NamedDecl *Dest) {
5687   assert(S.getLangOpts().CPlusPlus11 &&
5688          "converted constant expression outside C++11");
5689 
5690   if (checkPlaceholderForOverload(S, From))
5691     return ExprError();
5692 
5693   // C++1z [expr.const]p3:
5694   //  A converted constant expression of type T is an expression,
5695   //  implicitly converted to type T, where the converted
5696   //  expression is a constant expression and the implicit conversion
5697   //  sequence contains only [... list of conversions ...].
5698   ImplicitConversionSequence ICS =
5699       (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
5700           ? TryContextuallyConvertToBool(S, From)
5701           : TryCopyInitialization(S, From, T,
5702                                   /*SuppressUserConversions=*/false,
5703                                   /*InOverloadResolution=*/false,
5704                                   /*AllowObjCWritebackConversion=*/false,
5705                                   /*AllowExplicit=*/false);
5706   StandardConversionSequence *SCS = nullptr;
5707   switch (ICS.getKind()) {
5708   case ImplicitConversionSequence::StandardConversion:
5709     SCS = &ICS.Standard;
5710     break;
5711   case ImplicitConversionSequence::UserDefinedConversion:
5712     if (T->isRecordType())
5713       SCS = &ICS.UserDefined.Before;
5714     else
5715       SCS = &ICS.UserDefined.After;
5716     break;
5717   case ImplicitConversionSequence::AmbiguousConversion:
5718   case ImplicitConversionSequence::BadConversion:
5719     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5720       return S.Diag(From->getBeginLoc(),
5721                     diag::err_typecheck_converted_constant_expression)
5722              << From->getType() << From->getSourceRange() << T;
5723     return ExprError();
5724 
5725   case ImplicitConversionSequence::EllipsisConversion:
5726     llvm_unreachable("ellipsis conversion in converted constant expression");
5727   }
5728 
5729   // Check that we would only use permitted conversions.
5730   if (!CheckConvertedConstantConversions(S, *SCS)) {
5731     return S.Diag(From->getBeginLoc(),
5732                   diag::err_typecheck_converted_constant_expression_disallowed)
5733            << From->getType() << From->getSourceRange() << T;
5734   }
5735   // [...] and where the reference binding (if any) binds directly.
5736   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5737     return S.Diag(From->getBeginLoc(),
5738                   diag::err_typecheck_converted_constant_expression_indirect)
5739            << From->getType() << From->getSourceRange() << T;
5740   }
5741 
5742   // Usually we can simply apply the ImplicitConversionSequence we formed
5743   // earlier, but that's not guaranteed to work when initializing an object of
5744   // class type.
5745   ExprResult Result;
5746   if (T->isRecordType()) {
5747     assert(CCE == Sema::CCEK_TemplateArg &&
5748            "unexpected class type converted constant expr");
5749     Result = S.PerformCopyInitialization(
5750         InitializedEntity::InitializeTemplateParameter(
5751             T, cast<NonTypeTemplateParmDecl>(Dest)),
5752         SourceLocation(), From);
5753   } else {
5754     Result = S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5755   }
5756   if (Result.isInvalid())
5757     return Result;
5758 
5759   // C++2a [intro.execution]p5:
5760   //   A full-expression is [...] a constant-expression [...]
5761   Result =
5762       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5763                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5764   if (Result.isInvalid())
5765     return Result;
5766 
5767   // Check for a narrowing implicit conversion.
5768   bool ReturnPreNarrowingValue = false;
5769   APValue PreNarrowingValue;
5770   QualType PreNarrowingType;
5771   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5772                                 PreNarrowingType)) {
5773   case NK_Dependent_Narrowing:
5774     // Implicit conversion to a narrower type, but the expression is
5775     // value-dependent so we can't tell whether it's actually narrowing.
5776   case NK_Variable_Narrowing:
5777     // Implicit conversion to a narrower type, and the value is not a constant
5778     // expression. We'll diagnose this in a moment.
5779   case NK_Not_Narrowing:
5780     break;
5781 
5782   case NK_Constant_Narrowing:
5783     if (CCE == Sema::CCEK_ArrayBound &&
5784         PreNarrowingType->isIntegralOrEnumerationType() &&
5785         PreNarrowingValue.isInt()) {
5786       // Don't diagnose array bound narrowing here; we produce more precise
5787       // errors by allowing the un-narrowed value through.
5788       ReturnPreNarrowingValue = true;
5789       break;
5790     }
5791     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5792         << CCE << /*Constant*/ 1
5793         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5794     break;
5795 
5796   case NK_Type_Narrowing:
5797     // FIXME: It would be better to diagnose that the expression is not a
5798     // constant expression.
5799     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5800         << CCE << /*Constant*/ 0 << From->getType() << T;
5801     break;
5802   }
5803 
5804   if (Result.get()->isValueDependent()) {
5805     Value = APValue();
5806     return Result;
5807   }
5808 
5809   // Check the expression is a constant expression.
5810   SmallVector<PartialDiagnosticAt, 8> Notes;
5811   Expr::EvalResult Eval;
5812   Eval.Diag = &Notes;
5813 
5814   ConstantExprKind Kind;
5815   if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
5816     Kind = ConstantExprKind::ClassTemplateArgument;
5817   else if (CCE == Sema::CCEK_TemplateArg)
5818     Kind = ConstantExprKind::NonClassTemplateArgument;
5819   else
5820     Kind = ConstantExprKind::Normal;
5821 
5822   if (!Result.get()->EvaluateAsConstantExpr(Eval, S.Context, Kind) ||
5823       (RequireInt && !Eval.Val.isInt())) {
5824     // The expression can't be folded, so we can't keep it at this position in
5825     // the AST.
5826     Result = ExprError();
5827   } else {
5828     Value = Eval.Val;
5829 
5830     if (Notes.empty()) {
5831       // It's a constant expression.
5832       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5833       if (ReturnPreNarrowingValue)
5834         Value = std::move(PreNarrowingValue);
5835       return E;
5836     }
5837   }
5838 
5839   // It's not a constant expression. Produce an appropriate diagnostic.
5840   if (Notes.size() == 1 &&
5841       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
5842     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5843   } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
5844                                    diag::note_constexpr_invalid_template_arg) {
5845     Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
5846     for (unsigned I = 0; I < Notes.size(); ++I)
5847       S.Diag(Notes[I].first, Notes[I].second);
5848   } else {
5849     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5850         << CCE << From->getSourceRange();
5851     for (unsigned I = 0; I < Notes.size(); ++I)
5852       S.Diag(Notes[I].first, Notes[I].second);
5853   }
5854   return ExprError();
5855 }
5856 
5857 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5858                                                   APValue &Value, CCEKind CCE,
5859                                                   NamedDecl *Dest) {
5860   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
5861                                             Dest);
5862 }
5863 
5864 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5865                                                   llvm::APSInt &Value,
5866                                                   CCEKind CCE) {
5867   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5868 
5869   APValue V;
5870   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
5871                                               /*Dest=*/nullptr);
5872   if (!R.isInvalid() && !R.get()->isValueDependent())
5873     Value = V.getInt();
5874   return R;
5875 }
5876 
5877 
5878 /// dropPointerConversions - If the given standard conversion sequence
5879 /// involves any pointer conversions, remove them.  This may change
5880 /// the result type of the conversion sequence.
5881 static void dropPointerConversion(StandardConversionSequence &SCS) {
5882   if (SCS.Second == ICK_Pointer_Conversion) {
5883     SCS.Second = ICK_Identity;
5884     SCS.Third = ICK_Identity;
5885     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5886   }
5887 }
5888 
5889 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5890 /// convert the expression From to an Objective-C pointer type.
5891 static ImplicitConversionSequence
5892 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5893   // Do an implicit conversion to 'id'.
5894   QualType Ty = S.Context.getObjCIdType();
5895   ImplicitConversionSequence ICS
5896     = TryImplicitConversion(S, From, Ty,
5897                             // FIXME: Are these flags correct?
5898                             /*SuppressUserConversions=*/false,
5899                             AllowedExplicit::Conversions,
5900                             /*InOverloadResolution=*/false,
5901                             /*CStyle=*/false,
5902                             /*AllowObjCWritebackConversion=*/false,
5903                             /*AllowObjCConversionOnExplicit=*/true);
5904 
5905   // Strip off any final conversions to 'id'.
5906   switch (ICS.getKind()) {
5907   case ImplicitConversionSequence::BadConversion:
5908   case ImplicitConversionSequence::AmbiguousConversion:
5909   case ImplicitConversionSequence::EllipsisConversion:
5910     break;
5911 
5912   case ImplicitConversionSequence::UserDefinedConversion:
5913     dropPointerConversion(ICS.UserDefined.After);
5914     break;
5915 
5916   case ImplicitConversionSequence::StandardConversion:
5917     dropPointerConversion(ICS.Standard);
5918     break;
5919   }
5920 
5921   return ICS;
5922 }
5923 
5924 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5925 /// conversion of the expression From to an Objective-C pointer type.
5926 /// Returns a valid but null ExprResult if no conversion sequence exists.
5927 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5928   if (checkPlaceholderForOverload(*this, From))
5929     return ExprError();
5930 
5931   QualType Ty = Context.getObjCIdType();
5932   ImplicitConversionSequence ICS =
5933     TryContextuallyConvertToObjCPointer(*this, From);
5934   if (!ICS.isBad())
5935     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5936   return ExprResult();
5937 }
5938 
5939 /// Determine whether the provided type is an integral type, or an enumeration
5940 /// type of a permitted flavor.
5941 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5942   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5943                                  : T->isIntegralOrUnscopedEnumerationType();
5944 }
5945 
5946 static ExprResult
5947 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5948                             Sema::ContextualImplicitConverter &Converter,
5949                             QualType T, UnresolvedSetImpl &ViableConversions) {
5950 
5951   if (Converter.Suppress)
5952     return ExprError();
5953 
5954   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5955   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5956     CXXConversionDecl *Conv =
5957         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5958     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5959     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5960   }
5961   return From;
5962 }
5963 
5964 static bool
5965 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5966                            Sema::ContextualImplicitConverter &Converter,
5967                            QualType T, bool HadMultipleCandidates,
5968                            UnresolvedSetImpl &ExplicitConversions) {
5969   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5970     DeclAccessPair Found = ExplicitConversions[0];
5971     CXXConversionDecl *Conversion =
5972         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5973 
5974     // The user probably meant to invoke the given explicit
5975     // conversion; use it.
5976     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5977     std::string TypeStr;
5978     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5979 
5980     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5981         << FixItHint::CreateInsertion(From->getBeginLoc(),
5982                                       "static_cast<" + TypeStr + ">(")
5983         << FixItHint::CreateInsertion(
5984                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5985     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5986 
5987     // If we aren't in a SFINAE context, build a call to the
5988     // explicit conversion function.
5989     if (SemaRef.isSFINAEContext())
5990       return true;
5991 
5992     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5993     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5994                                                        HadMultipleCandidates);
5995     if (Result.isInvalid())
5996       return true;
5997     // Record usage of conversion in an implicit cast.
5998     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5999                                     CK_UserDefinedConversion, Result.get(),
6000                                     nullptr, Result.get()->getValueKind(),
6001                                     SemaRef.CurFPFeatureOverrides());
6002   }
6003   return false;
6004 }
6005 
6006 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6007                              Sema::ContextualImplicitConverter &Converter,
6008                              QualType T, bool HadMultipleCandidates,
6009                              DeclAccessPair &Found) {
6010   CXXConversionDecl *Conversion =
6011       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6012   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6013 
6014   QualType ToType = Conversion->getConversionType().getNonReferenceType();
6015   if (!Converter.SuppressConversion) {
6016     if (SemaRef.isSFINAEContext())
6017       return true;
6018 
6019     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6020         << From->getSourceRange();
6021   }
6022 
6023   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6024                                                      HadMultipleCandidates);
6025   if (Result.isInvalid())
6026     return true;
6027   // Record usage of conversion in an implicit cast.
6028   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6029                                   CK_UserDefinedConversion, Result.get(),
6030                                   nullptr, Result.get()->getValueKind(),
6031                                   SemaRef.CurFPFeatureOverrides());
6032   return false;
6033 }
6034 
6035 static ExprResult finishContextualImplicitConversion(
6036     Sema &SemaRef, SourceLocation Loc, Expr *From,
6037     Sema::ContextualImplicitConverter &Converter) {
6038   if (!Converter.match(From->getType()) && !Converter.Suppress)
6039     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6040         << From->getSourceRange();
6041 
6042   return SemaRef.DefaultLvalueConversion(From);
6043 }
6044 
6045 static void
6046 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6047                                   UnresolvedSetImpl &ViableConversions,
6048                                   OverloadCandidateSet &CandidateSet) {
6049   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6050     DeclAccessPair FoundDecl = ViableConversions[I];
6051     NamedDecl *D = FoundDecl.getDecl();
6052     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6053     if (isa<UsingShadowDecl>(D))
6054       D = cast<UsingShadowDecl>(D)->getTargetDecl();
6055 
6056     CXXConversionDecl *Conv;
6057     FunctionTemplateDecl *ConvTemplate;
6058     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
6059       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6060     else
6061       Conv = cast<CXXConversionDecl>(D);
6062 
6063     if (ConvTemplate)
6064       SemaRef.AddTemplateConversionCandidate(
6065           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6066           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6067     else
6068       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
6069                                      ToType, CandidateSet,
6070                                      /*AllowObjCConversionOnExplicit=*/false,
6071                                      /*AllowExplicit*/ true);
6072   }
6073 }
6074 
6075 /// Attempt to convert the given expression to a type which is accepted
6076 /// by the given converter.
6077 ///
6078 /// This routine will attempt to convert an expression of class type to a
6079 /// type accepted by the specified converter. In C++11 and before, the class
6080 /// must have a single non-explicit conversion function converting to a matching
6081 /// type. In C++1y, there can be multiple such conversion functions, but only
6082 /// one target type.
6083 ///
6084 /// \param Loc The source location of the construct that requires the
6085 /// conversion.
6086 ///
6087 /// \param From The expression we're converting from.
6088 ///
6089 /// \param Converter Used to control and diagnose the conversion process.
6090 ///
6091 /// \returns The expression, converted to an integral or enumeration type if
6092 /// successful.
6093 ExprResult Sema::PerformContextualImplicitConversion(
6094     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6095   // We can't perform any more checking for type-dependent expressions.
6096   if (From->isTypeDependent())
6097     return From;
6098 
6099   // Process placeholders immediately.
6100   if (From->hasPlaceholderType()) {
6101     ExprResult result = CheckPlaceholderExpr(From);
6102     if (result.isInvalid())
6103       return result;
6104     From = result.get();
6105   }
6106 
6107   // If the expression already has a matching type, we're golden.
6108   QualType T = From->getType();
6109   if (Converter.match(T))
6110     return DefaultLvalueConversion(From);
6111 
6112   // FIXME: Check for missing '()' if T is a function type?
6113 
6114   // We can only perform contextual implicit conversions on objects of class
6115   // type.
6116   const RecordType *RecordTy = T->getAs<RecordType>();
6117   if (!RecordTy || !getLangOpts().CPlusPlus) {
6118     if (!Converter.Suppress)
6119       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6120     return From;
6121   }
6122 
6123   // We must have a complete class type.
6124   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6125     ContextualImplicitConverter &Converter;
6126     Expr *From;
6127 
6128     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6129         : Converter(Converter), From(From) {}
6130 
6131     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6132       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6133     }
6134   } IncompleteDiagnoser(Converter, From);
6135 
6136   if (Converter.Suppress ? !isCompleteType(Loc, T)
6137                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6138     return From;
6139 
6140   // Look for a conversion to an integral or enumeration type.
6141   UnresolvedSet<4>
6142       ViableConversions; // These are *potentially* viable in C++1y.
6143   UnresolvedSet<4> ExplicitConversions;
6144   const auto &Conversions =
6145       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6146 
6147   bool HadMultipleCandidates =
6148       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6149 
6150   // To check that there is only one target type, in C++1y:
6151   QualType ToType;
6152   bool HasUniqueTargetType = true;
6153 
6154   // Collect explicit or viable (potentially in C++1y) conversions.
6155   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6156     NamedDecl *D = (*I)->getUnderlyingDecl();
6157     CXXConversionDecl *Conversion;
6158     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6159     if (ConvTemplate) {
6160       if (getLangOpts().CPlusPlus14)
6161         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6162       else
6163         continue; // C++11 does not consider conversion operator templates(?).
6164     } else
6165       Conversion = cast<CXXConversionDecl>(D);
6166 
6167     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6168            "Conversion operator templates are considered potentially "
6169            "viable in C++1y");
6170 
6171     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6172     if (Converter.match(CurToType) || ConvTemplate) {
6173 
6174       if (Conversion->isExplicit()) {
6175         // FIXME: For C++1y, do we need this restriction?
6176         // cf. diagnoseNoViableConversion()
6177         if (!ConvTemplate)
6178           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6179       } else {
6180         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6181           if (ToType.isNull())
6182             ToType = CurToType.getUnqualifiedType();
6183           else if (HasUniqueTargetType &&
6184                    (CurToType.getUnqualifiedType() != ToType))
6185             HasUniqueTargetType = false;
6186         }
6187         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6188       }
6189     }
6190   }
6191 
6192   if (getLangOpts().CPlusPlus14) {
6193     // C++1y [conv]p6:
6194     // ... An expression e of class type E appearing in such a context
6195     // is said to be contextually implicitly converted to a specified
6196     // type T and is well-formed if and only if e can be implicitly
6197     // converted to a type T that is determined as follows: E is searched
6198     // for conversion functions whose return type is cv T or reference to
6199     // cv T such that T is allowed by the context. There shall be
6200     // exactly one such T.
6201 
6202     // If no unique T is found:
6203     if (ToType.isNull()) {
6204       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6205                                      HadMultipleCandidates,
6206                                      ExplicitConversions))
6207         return ExprError();
6208       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6209     }
6210 
6211     // If more than one unique Ts are found:
6212     if (!HasUniqueTargetType)
6213       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6214                                          ViableConversions);
6215 
6216     // If one unique T is found:
6217     // First, build a candidate set from the previously recorded
6218     // potentially viable conversions.
6219     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6220     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6221                                       CandidateSet);
6222 
6223     // Then, perform overload resolution over the candidate set.
6224     OverloadCandidateSet::iterator Best;
6225     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6226     case OR_Success: {
6227       // Apply this conversion.
6228       DeclAccessPair Found =
6229           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6230       if (recordConversion(*this, Loc, From, Converter, T,
6231                            HadMultipleCandidates, Found))
6232         return ExprError();
6233       break;
6234     }
6235     case OR_Ambiguous:
6236       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6237                                          ViableConversions);
6238     case OR_No_Viable_Function:
6239       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6240                                      HadMultipleCandidates,
6241                                      ExplicitConversions))
6242         return ExprError();
6243       LLVM_FALLTHROUGH;
6244     case OR_Deleted:
6245       // We'll complain below about a non-integral condition type.
6246       break;
6247     }
6248   } else {
6249     switch (ViableConversions.size()) {
6250     case 0: {
6251       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6252                                      HadMultipleCandidates,
6253                                      ExplicitConversions))
6254         return ExprError();
6255 
6256       // We'll complain below about a non-integral condition type.
6257       break;
6258     }
6259     case 1: {
6260       // Apply this conversion.
6261       DeclAccessPair Found = ViableConversions[0];
6262       if (recordConversion(*this, Loc, From, Converter, T,
6263                            HadMultipleCandidates, Found))
6264         return ExprError();
6265       break;
6266     }
6267     default:
6268       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6269                                          ViableConversions);
6270     }
6271   }
6272 
6273   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6274 }
6275 
6276 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6277 /// an acceptable non-member overloaded operator for a call whose
6278 /// arguments have types T1 (and, if non-empty, T2). This routine
6279 /// implements the check in C++ [over.match.oper]p3b2 concerning
6280 /// enumeration types.
6281 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6282                                                    FunctionDecl *Fn,
6283                                                    ArrayRef<Expr *> Args) {
6284   QualType T1 = Args[0]->getType();
6285   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6286 
6287   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6288     return true;
6289 
6290   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6291     return true;
6292 
6293   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6294   if (Proto->getNumParams() < 1)
6295     return false;
6296 
6297   if (T1->isEnumeralType()) {
6298     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6299     if (Context.hasSameUnqualifiedType(T1, ArgType))
6300       return true;
6301   }
6302 
6303   if (Proto->getNumParams() < 2)
6304     return false;
6305 
6306   if (!T2.isNull() && T2->isEnumeralType()) {
6307     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6308     if (Context.hasSameUnqualifiedType(T2, ArgType))
6309       return true;
6310   }
6311 
6312   return false;
6313 }
6314 
6315 /// AddOverloadCandidate - Adds the given function to the set of
6316 /// candidate functions, using the given function call arguments.  If
6317 /// @p SuppressUserConversions, then don't allow user-defined
6318 /// conversions via constructors or conversion operators.
6319 ///
6320 /// \param PartialOverloading true if we are performing "partial" overloading
6321 /// based on an incomplete set of function arguments. This feature is used by
6322 /// code completion.
6323 void Sema::AddOverloadCandidate(
6324     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6325     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6326     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6327     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6328     OverloadCandidateParamOrder PO) {
6329   const FunctionProtoType *Proto
6330     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6331   assert(Proto && "Functions without a prototype cannot be overloaded");
6332   assert(!Function->getDescribedFunctionTemplate() &&
6333          "Use AddTemplateOverloadCandidate for function templates");
6334 
6335   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6336     if (!isa<CXXConstructorDecl>(Method)) {
6337       // If we get here, it's because we're calling a member function
6338       // that is named without a member access expression (e.g.,
6339       // "this->f") that was either written explicitly or created
6340       // implicitly. This can happen with a qualified call to a member
6341       // function, e.g., X::f(). We use an empty type for the implied
6342       // object argument (C++ [over.call.func]p3), and the acting context
6343       // is irrelevant.
6344       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6345                          Expr::Classification::makeSimpleLValue(), Args,
6346                          CandidateSet, SuppressUserConversions,
6347                          PartialOverloading, EarlyConversions, PO);
6348       return;
6349     }
6350     // We treat a constructor like a non-member function, since its object
6351     // argument doesn't participate in overload resolution.
6352   }
6353 
6354   if (!CandidateSet.isNewCandidate(Function, PO))
6355     return;
6356 
6357   // C++11 [class.copy]p11: [DR1402]
6358   //   A defaulted move constructor that is defined as deleted is ignored by
6359   //   overload resolution.
6360   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6361   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6362       Constructor->isMoveConstructor())
6363     return;
6364 
6365   // Overload resolution is always an unevaluated context.
6366   EnterExpressionEvaluationContext Unevaluated(
6367       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6368 
6369   // C++ [over.match.oper]p3:
6370   //   if no operand has a class type, only those non-member functions in the
6371   //   lookup set that have a first parameter of type T1 or "reference to
6372   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6373   //   is a right operand) a second parameter of type T2 or "reference to
6374   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6375   //   candidate functions.
6376   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6377       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6378     return;
6379 
6380   // Add this candidate
6381   OverloadCandidate &Candidate =
6382       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6383   Candidate.FoundDecl = FoundDecl;
6384   Candidate.Function = Function;
6385   Candidate.Viable = true;
6386   Candidate.RewriteKind =
6387       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6388   Candidate.IsSurrogate = false;
6389   Candidate.IsADLCandidate = IsADLCandidate;
6390   Candidate.IgnoreObjectArgument = false;
6391   Candidate.ExplicitCallArguments = Args.size();
6392 
6393   // Explicit functions are not actually candidates at all if we're not
6394   // allowing them in this context, but keep them around so we can point
6395   // to them in diagnostics.
6396   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6397     Candidate.Viable = false;
6398     Candidate.FailureKind = ovl_fail_explicit;
6399     return;
6400   }
6401 
6402   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6403       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6404     Candidate.Viable = false;
6405     Candidate.FailureKind = ovl_non_default_multiversion_function;
6406     return;
6407   }
6408 
6409   if (Constructor) {
6410     // C++ [class.copy]p3:
6411     //   A member function template is never instantiated to perform the copy
6412     //   of a class object to an object of its class type.
6413     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6414     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6415         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6416          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6417                        ClassType))) {
6418       Candidate.Viable = false;
6419       Candidate.FailureKind = ovl_fail_illegal_constructor;
6420       return;
6421     }
6422 
6423     // C++ [over.match.funcs]p8: (proposed DR resolution)
6424     //   A constructor inherited from class type C that has a first parameter
6425     //   of type "reference to P" (including such a constructor instantiated
6426     //   from a template) is excluded from the set of candidate functions when
6427     //   constructing an object of type cv D if the argument list has exactly
6428     //   one argument and D is reference-related to P and P is reference-related
6429     //   to C.
6430     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6431     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6432         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6433       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6434       QualType C = Context.getRecordType(Constructor->getParent());
6435       QualType D = Context.getRecordType(Shadow->getParent());
6436       SourceLocation Loc = Args.front()->getExprLoc();
6437       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6438           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6439         Candidate.Viable = false;
6440         Candidate.FailureKind = ovl_fail_inhctor_slice;
6441         return;
6442       }
6443     }
6444 
6445     // Check that the constructor is capable of constructing an object in the
6446     // destination address space.
6447     if (!Qualifiers::isAddressSpaceSupersetOf(
6448             Constructor->getMethodQualifiers().getAddressSpace(),
6449             CandidateSet.getDestAS())) {
6450       Candidate.Viable = false;
6451       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6452     }
6453   }
6454 
6455   unsigned NumParams = Proto->getNumParams();
6456 
6457   // (C++ 13.3.2p2): A candidate function having fewer than m
6458   // parameters is viable only if it has an ellipsis in its parameter
6459   // list (8.3.5).
6460   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6461       !Proto->isVariadic()) {
6462     Candidate.Viable = false;
6463     Candidate.FailureKind = ovl_fail_too_many_arguments;
6464     return;
6465   }
6466 
6467   // (C++ 13.3.2p2): A candidate function having more than m parameters
6468   // is viable only if the (m+1)st parameter has a default argument
6469   // (8.3.6). For the purposes of overload resolution, the
6470   // parameter list is truncated on the right, so that there are
6471   // exactly m parameters.
6472   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6473   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6474     // Not enough arguments.
6475     Candidate.Viable = false;
6476     Candidate.FailureKind = ovl_fail_too_few_arguments;
6477     return;
6478   }
6479 
6480   // (CUDA B.1): Check for invalid calls between targets.
6481   if (getLangOpts().CUDA)
6482     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6483       // Skip the check for callers that are implicit members, because in this
6484       // case we may not yet know what the member's target is; the target is
6485       // inferred for the member automatically, based on the bases and fields of
6486       // the class.
6487       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6488         Candidate.Viable = false;
6489         Candidate.FailureKind = ovl_fail_bad_target;
6490         return;
6491       }
6492 
6493   if (Function->getTrailingRequiresClause()) {
6494     ConstraintSatisfaction Satisfaction;
6495     if (CheckFunctionConstraints(Function, Satisfaction) ||
6496         !Satisfaction.IsSatisfied) {
6497       Candidate.Viable = false;
6498       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6499       return;
6500     }
6501   }
6502 
6503   // Determine the implicit conversion sequences for each of the
6504   // arguments.
6505   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6506     unsigned ConvIdx =
6507         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6508     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6509       // We already formed a conversion sequence for this parameter during
6510       // template argument deduction.
6511     } else if (ArgIdx < NumParams) {
6512       // (C++ 13.3.2p3): for F to be a viable function, there shall
6513       // exist for each argument an implicit conversion sequence
6514       // (13.3.3.1) that converts that argument to the corresponding
6515       // parameter of F.
6516       QualType ParamType = Proto->getParamType(ArgIdx);
6517       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6518           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6519           /*InOverloadResolution=*/true,
6520           /*AllowObjCWritebackConversion=*/
6521           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6522       if (Candidate.Conversions[ConvIdx].isBad()) {
6523         Candidate.Viable = false;
6524         Candidate.FailureKind = ovl_fail_bad_conversion;
6525         return;
6526       }
6527     } else {
6528       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6529       // argument for which there is no corresponding parameter is
6530       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6531       Candidate.Conversions[ConvIdx].setEllipsis();
6532     }
6533   }
6534 
6535   if (EnableIfAttr *FailedAttr =
6536           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6537     Candidate.Viable = false;
6538     Candidate.FailureKind = ovl_fail_enable_if;
6539     Candidate.DeductionFailure.Data = FailedAttr;
6540     return;
6541   }
6542 }
6543 
6544 ObjCMethodDecl *
6545 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6546                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6547   if (Methods.size() <= 1)
6548     return nullptr;
6549 
6550   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6551     bool Match = true;
6552     ObjCMethodDecl *Method = Methods[b];
6553     unsigned NumNamedArgs = Sel.getNumArgs();
6554     // Method might have more arguments than selector indicates. This is due
6555     // to addition of c-style arguments in method.
6556     if (Method->param_size() > NumNamedArgs)
6557       NumNamedArgs = Method->param_size();
6558     if (Args.size() < NumNamedArgs)
6559       continue;
6560 
6561     for (unsigned i = 0; i < NumNamedArgs; i++) {
6562       // We can't do any type-checking on a type-dependent argument.
6563       if (Args[i]->isTypeDependent()) {
6564         Match = false;
6565         break;
6566       }
6567 
6568       ParmVarDecl *param = Method->parameters()[i];
6569       Expr *argExpr = Args[i];
6570       assert(argExpr && "SelectBestMethod(): missing expression");
6571 
6572       // Strip the unbridged-cast placeholder expression off unless it's
6573       // a consumed argument.
6574       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6575           !param->hasAttr<CFConsumedAttr>())
6576         argExpr = stripARCUnbridgedCast(argExpr);
6577 
6578       // If the parameter is __unknown_anytype, move on to the next method.
6579       if (param->getType() == Context.UnknownAnyTy) {
6580         Match = false;
6581         break;
6582       }
6583 
6584       ImplicitConversionSequence ConversionState
6585         = TryCopyInitialization(*this, argExpr, param->getType(),
6586                                 /*SuppressUserConversions*/false,
6587                                 /*InOverloadResolution=*/true,
6588                                 /*AllowObjCWritebackConversion=*/
6589                                 getLangOpts().ObjCAutoRefCount,
6590                                 /*AllowExplicit*/false);
6591       // This function looks for a reasonably-exact match, so we consider
6592       // incompatible pointer conversions to be a failure here.
6593       if (ConversionState.isBad() ||
6594           (ConversionState.isStandard() &&
6595            ConversionState.Standard.Second ==
6596                ICK_Incompatible_Pointer_Conversion)) {
6597         Match = false;
6598         break;
6599       }
6600     }
6601     // Promote additional arguments to variadic methods.
6602     if (Match && Method->isVariadic()) {
6603       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6604         if (Args[i]->isTypeDependent()) {
6605           Match = false;
6606           break;
6607         }
6608         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6609                                                           nullptr);
6610         if (Arg.isInvalid()) {
6611           Match = false;
6612           break;
6613         }
6614       }
6615     } else {
6616       // Check for extra arguments to non-variadic methods.
6617       if (Args.size() != NumNamedArgs)
6618         Match = false;
6619       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6620         // Special case when selectors have no argument. In this case, select
6621         // one with the most general result type of 'id'.
6622         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6623           QualType ReturnT = Methods[b]->getReturnType();
6624           if (ReturnT->isObjCIdType())
6625             return Methods[b];
6626         }
6627       }
6628     }
6629 
6630     if (Match)
6631       return Method;
6632   }
6633   return nullptr;
6634 }
6635 
6636 static bool convertArgsForAvailabilityChecks(
6637     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6638     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6639     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6640   if (ThisArg) {
6641     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6642     assert(!isa<CXXConstructorDecl>(Method) &&
6643            "Shouldn't have `this` for ctors!");
6644     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6645     ExprResult R = S.PerformObjectArgumentInitialization(
6646         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6647     if (R.isInvalid())
6648       return false;
6649     ConvertedThis = R.get();
6650   } else {
6651     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6652       (void)MD;
6653       assert((MissingImplicitThis || MD->isStatic() ||
6654               isa<CXXConstructorDecl>(MD)) &&
6655              "Expected `this` for non-ctor instance methods");
6656     }
6657     ConvertedThis = nullptr;
6658   }
6659 
6660   // Ignore any variadic arguments. Converting them is pointless, since the
6661   // user can't refer to them in the function condition.
6662   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6663 
6664   // Convert the arguments.
6665   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6666     ExprResult R;
6667     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6668                                         S.Context, Function->getParamDecl(I)),
6669                                     SourceLocation(), Args[I]);
6670 
6671     if (R.isInvalid())
6672       return false;
6673 
6674     ConvertedArgs.push_back(R.get());
6675   }
6676 
6677   if (Trap.hasErrorOccurred())
6678     return false;
6679 
6680   // Push default arguments if needed.
6681   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6682     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6683       ParmVarDecl *P = Function->getParamDecl(i);
6684       if (!P->hasDefaultArg())
6685         return false;
6686       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6687       if (R.isInvalid())
6688         return false;
6689       ConvertedArgs.push_back(R.get());
6690     }
6691 
6692     if (Trap.hasErrorOccurred())
6693       return false;
6694   }
6695   return true;
6696 }
6697 
6698 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6699                                   SourceLocation CallLoc,
6700                                   ArrayRef<Expr *> Args,
6701                                   bool MissingImplicitThis) {
6702   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6703   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6704     return nullptr;
6705 
6706   SFINAETrap Trap(*this);
6707   SmallVector<Expr *, 16> ConvertedArgs;
6708   // FIXME: We should look into making enable_if late-parsed.
6709   Expr *DiscardedThis;
6710   if (!convertArgsForAvailabilityChecks(
6711           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6712           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6713     return *EnableIfAttrs.begin();
6714 
6715   for (auto *EIA : EnableIfAttrs) {
6716     APValue Result;
6717     // FIXME: This doesn't consider value-dependent cases, because doing so is
6718     // very difficult. Ideally, we should handle them more gracefully.
6719     if (EIA->getCond()->isValueDependent() ||
6720         !EIA->getCond()->EvaluateWithSubstitution(
6721             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6722       return EIA;
6723 
6724     if (!Result.isInt() || !Result.getInt().getBoolValue())
6725       return EIA;
6726   }
6727   return nullptr;
6728 }
6729 
6730 template <typename CheckFn>
6731 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6732                                         bool ArgDependent, SourceLocation Loc,
6733                                         CheckFn &&IsSuccessful) {
6734   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6735   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6736     if (ArgDependent == DIA->getArgDependent())
6737       Attrs.push_back(DIA);
6738   }
6739 
6740   // Common case: No diagnose_if attributes, so we can quit early.
6741   if (Attrs.empty())
6742     return false;
6743 
6744   auto WarningBegin = std::stable_partition(
6745       Attrs.begin(), Attrs.end(),
6746       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6747 
6748   // Note that diagnose_if attributes are late-parsed, so they appear in the
6749   // correct order (unlike enable_if attributes).
6750   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6751                                IsSuccessful);
6752   if (ErrAttr != WarningBegin) {
6753     const DiagnoseIfAttr *DIA = *ErrAttr;
6754     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6755     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6756         << DIA->getParent() << DIA->getCond()->getSourceRange();
6757     return true;
6758   }
6759 
6760   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6761     if (IsSuccessful(DIA)) {
6762       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6763       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6764           << DIA->getParent() << DIA->getCond()->getSourceRange();
6765     }
6766 
6767   return false;
6768 }
6769 
6770 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6771                                                const Expr *ThisArg,
6772                                                ArrayRef<const Expr *> Args,
6773                                                SourceLocation Loc) {
6774   return diagnoseDiagnoseIfAttrsWith(
6775       *this, Function, /*ArgDependent=*/true, Loc,
6776       [&](const DiagnoseIfAttr *DIA) {
6777         APValue Result;
6778         // It's sane to use the same Args for any redecl of this function, since
6779         // EvaluateWithSubstitution only cares about the position of each
6780         // argument in the arg list, not the ParmVarDecl* it maps to.
6781         if (!DIA->getCond()->EvaluateWithSubstitution(
6782                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6783           return false;
6784         return Result.isInt() && Result.getInt().getBoolValue();
6785       });
6786 }
6787 
6788 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6789                                                  SourceLocation Loc) {
6790   return diagnoseDiagnoseIfAttrsWith(
6791       *this, ND, /*ArgDependent=*/false, Loc,
6792       [&](const DiagnoseIfAttr *DIA) {
6793         bool Result;
6794         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6795                Result;
6796       });
6797 }
6798 
6799 /// Add all of the function declarations in the given function set to
6800 /// the overload candidate set.
6801 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6802                                  ArrayRef<Expr *> Args,
6803                                  OverloadCandidateSet &CandidateSet,
6804                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6805                                  bool SuppressUserConversions,
6806                                  bool PartialOverloading,
6807                                  bool FirstArgumentIsBase) {
6808   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6809     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6810     ArrayRef<Expr *> FunctionArgs = Args;
6811 
6812     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6813     FunctionDecl *FD =
6814         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6815 
6816     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6817       QualType ObjectType;
6818       Expr::Classification ObjectClassification;
6819       if (Args.size() > 0) {
6820         if (Expr *E = Args[0]) {
6821           // Use the explicit base to restrict the lookup:
6822           ObjectType = E->getType();
6823           // Pointers in the object arguments are implicitly dereferenced, so we
6824           // always classify them as l-values.
6825           if (!ObjectType.isNull() && ObjectType->isPointerType())
6826             ObjectClassification = Expr::Classification::makeSimpleLValue();
6827           else
6828             ObjectClassification = E->Classify(Context);
6829         } // .. else there is an implicit base.
6830         FunctionArgs = Args.slice(1);
6831       }
6832       if (FunTmpl) {
6833         AddMethodTemplateCandidate(
6834             FunTmpl, F.getPair(),
6835             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6836             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6837             FunctionArgs, CandidateSet, SuppressUserConversions,
6838             PartialOverloading);
6839       } else {
6840         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6841                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6842                            ObjectClassification, FunctionArgs, CandidateSet,
6843                            SuppressUserConversions, PartialOverloading);
6844       }
6845     } else {
6846       // This branch handles both standalone functions and static methods.
6847 
6848       // Slice the first argument (which is the base) when we access
6849       // static method as non-static.
6850       if (Args.size() > 0 &&
6851           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6852                         !isa<CXXConstructorDecl>(FD)))) {
6853         assert(cast<CXXMethodDecl>(FD)->isStatic());
6854         FunctionArgs = Args.slice(1);
6855       }
6856       if (FunTmpl) {
6857         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6858                                      ExplicitTemplateArgs, FunctionArgs,
6859                                      CandidateSet, SuppressUserConversions,
6860                                      PartialOverloading);
6861       } else {
6862         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6863                              SuppressUserConversions, PartialOverloading);
6864       }
6865     }
6866   }
6867 }
6868 
6869 /// AddMethodCandidate - Adds a named decl (which is some kind of
6870 /// method) as a method candidate to the given overload set.
6871 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6872                               Expr::Classification ObjectClassification,
6873                               ArrayRef<Expr *> Args,
6874                               OverloadCandidateSet &CandidateSet,
6875                               bool SuppressUserConversions,
6876                               OverloadCandidateParamOrder PO) {
6877   NamedDecl *Decl = FoundDecl.getDecl();
6878   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6879 
6880   if (isa<UsingShadowDecl>(Decl))
6881     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6882 
6883   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6884     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6885            "Expected a member function template");
6886     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6887                                /*ExplicitArgs*/ nullptr, ObjectType,
6888                                ObjectClassification, Args, CandidateSet,
6889                                SuppressUserConversions, false, PO);
6890   } else {
6891     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6892                        ObjectType, ObjectClassification, Args, CandidateSet,
6893                        SuppressUserConversions, false, None, PO);
6894   }
6895 }
6896 
6897 /// AddMethodCandidate - Adds the given C++ member function to the set
6898 /// of candidate functions, using the given function call arguments
6899 /// and the object argument (@c Object). For example, in a call
6900 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6901 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6902 /// allow user-defined conversions via constructors or conversion
6903 /// operators.
6904 void
6905 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6906                          CXXRecordDecl *ActingContext, QualType ObjectType,
6907                          Expr::Classification ObjectClassification,
6908                          ArrayRef<Expr *> Args,
6909                          OverloadCandidateSet &CandidateSet,
6910                          bool SuppressUserConversions,
6911                          bool PartialOverloading,
6912                          ConversionSequenceList EarlyConversions,
6913                          OverloadCandidateParamOrder PO) {
6914   const FunctionProtoType *Proto
6915     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6916   assert(Proto && "Methods without a prototype cannot be overloaded");
6917   assert(!isa<CXXConstructorDecl>(Method) &&
6918          "Use AddOverloadCandidate for constructors");
6919 
6920   if (!CandidateSet.isNewCandidate(Method, PO))
6921     return;
6922 
6923   // C++11 [class.copy]p23: [DR1402]
6924   //   A defaulted move assignment operator that is defined as deleted is
6925   //   ignored by overload resolution.
6926   if (Method->isDefaulted() && Method->isDeleted() &&
6927       Method->isMoveAssignmentOperator())
6928     return;
6929 
6930   // Overload resolution is always an unevaluated context.
6931   EnterExpressionEvaluationContext Unevaluated(
6932       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6933 
6934   // Add this candidate
6935   OverloadCandidate &Candidate =
6936       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6937   Candidate.FoundDecl = FoundDecl;
6938   Candidate.Function = Method;
6939   Candidate.RewriteKind =
6940       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6941   Candidate.IsSurrogate = false;
6942   Candidate.IgnoreObjectArgument = false;
6943   Candidate.ExplicitCallArguments = Args.size();
6944 
6945   unsigned NumParams = Proto->getNumParams();
6946 
6947   // (C++ 13.3.2p2): A candidate function having fewer than m
6948   // parameters is viable only if it has an ellipsis in its parameter
6949   // list (8.3.5).
6950   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6951       !Proto->isVariadic()) {
6952     Candidate.Viable = false;
6953     Candidate.FailureKind = ovl_fail_too_many_arguments;
6954     return;
6955   }
6956 
6957   // (C++ 13.3.2p2): A candidate function having more than m parameters
6958   // is viable only if the (m+1)st parameter has a default argument
6959   // (8.3.6). For the purposes of overload resolution, the
6960   // parameter list is truncated on the right, so that there are
6961   // exactly m parameters.
6962   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6963   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6964     // Not enough arguments.
6965     Candidate.Viable = false;
6966     Candidate.FailureKind = ovl_fail_too_few_arguments;
6967     return;
6968   }
6969 
6970   Candidate.Viable = true;
6971 
6972   if (Method->isStatic() || ObjectType.isNull())
6973     // The implicit object argument is ignored.
6974     Candidate.IgnoreObjectArgument = true;
6975   else {
6976     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6977     // Determine the implicit conversion sequence for the object
6978     // parameter.
6979     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6980         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6981         Method, ActingContext);
6982     if (Candidate.Conversions[ConvIdx].isBad()) {
6983       Candidate.Viable = false;
6984       Candidate.FailureKind = ovl_fail_bad_conversion;
6985       return;
6986     }
6987   }
6988 
6989   // (CUDA B.1): Check for invalid calls between targets.
6990   if (getLangOpts().CUDA)
6991     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6992       if (!IsAllowedCUDACall(Caller, Method)) {
6993         Candidate.Viable = false;
6994         Candidate.FailureKind = ovl_fail_bad_target;
6995         return;
6996       }
6997 
6998   if (Method->getTrailingRequiresClause()) {
6999     ConstraintSatisfaction Satisfaction;
7000     if (CheckFunctionConstraints(Method, Satisfaction) ||
7001         !Satisfaction.IsSatisfied) {
7002       Candidate.Viable = false;
7003       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7004       return;
7005     }
7006   }
7007 
7008   // Determine the implicit conversion sequences for each of the
7009   // arguments.
7010   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7011     unsigned ConvIdx =
7012         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7013     if (Candidate.Conversions[ConvIdx].isInitialized()) {
7014       // We already formed a conversion sequence for this parameter during
7015       // template argument deduction.
7016     } else if (ArgIdx < NumParams) {
7017       // (C++ 13.3.2p3): for F to be a viable function, there shall
7018       // exist for each argument an implicit conversion sequence
7019       // (13.3.3.1) that converts that argument to the corresponding
7020       // parameter of F.
7021       QualType ParamType = Proto->getParamType(ArgIdx);
7022       Candidate.Conversions[ConvIdx]
7023         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7024                                 SuppressUserConversions,
7025                                 /*InOverloadResolution=*/true,
7026                                 /*AllowObjCWritebackConversion=*/
7027                                   getLangOpts().ObjCAutoRefCount);
7028       if (Candidate.Conversions[ConvIdx].isBad()) {
7029         Candidate.Viable = false;
7030         Candidate.FailureKind = ovl_fail_bad_conversion;
7031         return;
7032       }
7033     } else {
7034       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7035       // argument for which there is no corresponding parameter is
7036       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7037       Candidate.Conversions[ConvIdx].setEllipsis();
7038     }
7039   }
7040 
7041   if (EnableIfAttr *FailedAttr =
7042           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7043     Candidate.Viable = false;
7044     Candidate.FailureKind = ovl_fail_enable_if;
7045     Candidate.DeductionFailure.Data = FailedAttr;
7046     return;
7047   }
7048 
7049   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
7050       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
7051     Candidate.Viable = false;
7052     Candidate.FailureKind = ovl_non_default_multiversion_function;
7053   }
7054 }
7055 
7056 /// Add a C++ member function template as a candidate to the candidate
7057 /// set, using template argument deduction to produce an appropriate member
7058 /// function template specialization.
7059 void Sema::AddMethodTemplateCandidate(
7060     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7061     CXXRecordDecl *ActingContext,
7062     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7063     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7064     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7065     bool PartialOverloading, OverloadCandidateParamOrder PO) {
7066   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7067     return;
7068 
7069   // C++ [over.match.funcs]p7:
7070   //   In each case where a candidate is a function template, candidate
7071   //   function template specializations are generated using template argument
7072   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7073   //   candidate functions in the usual way.113) A given name can refer to one
7074   //   or more function templates and also to a set of overloaded non-template
7075   //   functions. In such a case, the candidate functions generated from each
7076   //   function template are combined with the set of non-template candidate
7077   //   functions.
7078   TemplateDeductionInfo Info(CandidateSet.getLocation());
7079   FunctionDecl *Specialization = nullptr;
7080   ConversionSequenceList Conversions;
7081   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7082           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7083           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7084             return CheckNonDependentConversions(
7085                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7086                 SuppressUserConversions, ActingContext, ObjectType,
7087                 ObjectClassification, PO);
7088           })) {
7089     OverloadCandidate &Candidate =
7090         CandidateSet.addCandidate(Conversions.size(), Conversions);
7091     Candidate.FoundDecl = FoundDecl;
7092     Candidate.Function = MethodTmpl->getTemplatedDecl();
7093     Candidate.Viable = false;
7094     Candidate.RewriteKind =
7095       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7096     Candidate.IsSurrogate = false;
7097     Candidate.IgnoreObjectArgument =
7098         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7099         ObjectType.isNull();
7100     Candidate.ExplicitCallArguments = Args.size();
7101     if (Result == TDK_NonDependentConversionFailure)
7102       Candidate.FailureKind = ovl_fail_bad_conversion;
7103     else {
7104       Candidate.FailureKind = ovl_fail_bad_deduction;
7105       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7106                                                             Info);
7107     }
7108     return;
7109   }
7110 
7111   // Add the function template specialization produced by template argument
7112   // deduction as a candidate.
7113   assert(Specialization && "Missing member function template specialization?");
7114   assert(isa<CXXMethodDecl>(Specialization) &&
7115          "Specialization is not a member function?");
7116   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7117                      ActingContext, ObjectType, ObjectClassification, Args,
7118                      CandidateSet, SuppressUserConversions, PartialOverloading,
7119                      Conversions, PO);
7120 }
7121 
7122 /// Determine whether a given function template has a simple explicit specifier
7123 /// or a non-value-dependent explicit-specification that evaluates to true.
7124 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7125   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7126 }
7127 
7128 /// Add a C++ function template specialization as a candidate
7129 /// in the candidate set, using template argument deduction to produce
7130 /// an appropriate function template specialization.
7131 void Sema::AddTemplateOverloadCandidate(
7132     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7133     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7134     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7135     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7136     OverloadCandidateParamOrder PO) {
7137   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7138     return;
7139 
7140   // If the function template has a non-dependent explicit specification,
7141   // exclude it now if appropriate; we are not permitted to perform deduction
7142   // and substitution in this case.
7143   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7144     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7145     Candidate.FoundDecl = FoundDecl;
7146     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7147     Candidate.Viable = false;
7148     Candidate.FailureKind = ovl_fail_explicit;
7149     return;
7150   }
7151 
7152   // C++ [over.match.funcs]p7:
7153   //   In each case where a candidate is a function template, candidate
7154   //   function template specializations are generated using template argument
7155   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7156   //   candidate functions in the usual way.113) A given name can refer to one
7157   //   or more function templates and also to a set of overloaded non-template
7158   //   functions. In such a case, the candidate functions generated from each
7159   //   function template are combined with the set of non-template candidate
7160   //   functions.
7161   TemplateDeductionInfo Info(CandidateSet.getLocation());
7162   FunctionDecl *Specialization = nullptr;
7163   ConversionSequenceList Conversions;
7164   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7165           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7166           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7167             return CheckNonDependentConversions(
7168                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7169                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7170           })) {
7171     OverloadCandidate &Candidate =
7172         CandidateSet.addCandidate(Conversions.size(), Conversions);
7173     Candidate.FoundDecl = FoundDecl;
7174     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7175     Candidate.Viable = false;
7176     Candidate.RewriteKind =
7177       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7178     Candidate.IsSurrogate = false;
7179     Candidate.IsADLCandidate = IsADLCandidate;
7180     // Ignore the object argument if there is one, since we don't have an object
7181     // type.
7182     Candidate.IgnoreObjectArgument =
7183         isa<CXXMethodDecl>(Candidate.Function) &&
7184         !isa<CXXConstructorDecl>(Candidate.Function);
7185     Candidate.ExplicitCallArguments = Args.size();
7186     if (Result == TDK_NonDependentConversionFailure)
7187       Candidate.FailureKind = ovl_fail_bad_conversion;
7188     else {
7189       Candidate.FailureKind = ovl_fail_bad_deduction;
7190       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7191                                                             Info);
7192     }
7193     return;
7194   }
7195 
7196   // Add the function template specialization produced by template argument
7197   // deduction as a candidate.
7198   assert(Specialization && "Missing function template specialization?");
7199   AddOverloadCandidate(
7200       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7201       PartialOverloading, AllowExplicit,
7202       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7203 }
7204 
7205 /// Check that implicit conversion sequences can be formed for each argument
7206 /// whose corresponding parameter has a non-dependent type, per DR1391's
7207 /// [temp.deduct.call]p10.
7208 bool Sema::CheckNonDependentConversions(
7209     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7210     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7211     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7212     CXXRecordDecl *ActingContext, QualType ObjectType,
7213     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7214   // FIXME: The cases in which we allow explicit conversions for constructor
7215   // arguments never consider calling a constructor template. It's not clear
7216   // that is correct.
7217   const bool AllowExplicit = false;
7218 
7219   auto *FD = FunctionTemplate->getTemplatedDecl();
7220   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7221   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7222   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7223 
7224   Conversions =
7225       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7226 
7227   // Overload resolution is always an unevaluated context.
7228   EnterExpressionEvaluationContext Unevaluated(
7229       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7230 
7231   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7232   // require that, but this check should never result in a hard error, and
7233   // overload resolution is permitted to sidestep instantiations.
7234   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7235       !ObjectType.isNull()) {
7236     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7237     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7238         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7239         Method, ActingContext);
7240     if (Conversions[ConvIdx].isBad())
7241       return true;
7242   }
7243 
7244   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7245        ++I) {
7246     QualType ParamType = ParamTypes[I];
7247     if (!ParamType->isDependentType()) {
7248       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7249                              ? 0
7250                              : (ThisConversions + I);
7251       Conversions[ConvIdx]
7252         = TryCopyInitialization(*this, Args[I], ParamType,
7253                                 SuppressUserConversions,
7254                                 /*InOverloadResolution=*/true,
7255                                 /*AllowObjCWritebackConversion=*/
7256                                   getLangOpts().ObjCAutoRefCount,
7257                                 AllowExplicit);
7258       if (Conversions[ConvIdx].isBad())
7259         return true;
7260     }
7261   }
7262 
7263   return false;
7264 }
7265 
7266 /// Determine whether this is an allowable conversion from the result
7267 /// of an explicit conversion operator to the expected type, per C++
7268 /// [over.match.conv]p1 and [over.match.ref]p1.
7269 ///
7270 /// \param ConvType The return type of the conversion function.
7271 ///
7272 /// \param ToType The type we are converting to.
7273 ///
7274 /// \param AllowObjCPointerConversion Allow a conversion from one
7275 /// Objective-C pointer to another.
7276 ///
7277 /// \returns true if the conversion is allowable, false otherwise.
7278 static bool isAllowableExplicitConversion(Sema &S,
7279                                           QualType ConvType, QualType ToType,
7280                                           bool AllowObjCPointerConversion) {
7281   QualType ToNonRefType = ToType.getNonReferenceType();
7282 
7283   // Easy case: the types are the same.
7284   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7285     return true;
7286 
7287   // Allow qualification conversions.
7288   bool ObjCLifetimeConversion;
7289   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7290                                   ObjCLifetimeConversion))
7291     return true;
7292 
7293   // If we're not allowed to consider Objective-C pointer conversions,
7294   // we're done.
7295   if (!AllowObjCPointerConversion)
7296     return false;
7297 
7298   // Is this an Objective-C pointer conversion?
7299   bool IncompatibleObjC = false;
7300   QualType ConvertedType;
7301   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7302                                    IncompatibleObjC);
7303 }
7304 
7305 /// AddConversionCandidate - Add a C++ conversion function as a
7306 /// candidate in the candidate set (C++ [over.match.conv],
7307 /// C++ [over.match.copy]). From is the expression we're converting from,
7308 /// and ToType is the type that we're eventually trying to convert to
7309 /// (which may or may not be the same type as the type that the
7310 /// conversion function produces).
7311 void Sema::AddConversionCandidate(
7312     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7313     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7314     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7315     bool AllowExplicit, bool AllowResultConversion) {
7316   assert(!Conversion->getDescribedFunctionTemplate() &&
7317          "Conversion function templates use AddTemplateConversionCandidate");
7318   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7319   if (!CandidateSet.isNewCandidate(Conversion))
7320     return;
7321 
7322   // If the conversion function has an undeduced return type, trigger its
7323   // deduction now.
7324   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7325     if (DeduceReturnType(Conversion, From->getExprLoc()))
7326       return;
7327     ConvType = Conversion->getConversionType().getNonReferenceType();
7328   }
7329 
7330   // If we don't allow any conversion of the result type, ignore conversion
7331   // functions that don't convert to exactly (possibly cv-qualified) T.
7332   if (!AllowResultConversion &&
7333       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7334     return;
7335 
7336   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7337   // operator is only a candidate if its return type is the target type or
7338   // can be converted to the target type with a qualification conversion.
7339   //
7340   // FIXME: Include such functions in the candidate list and explain why we
7341   // can't select them.
7342   if (Conversion->isExplicit() &&
7343       !isAllowableExplicitConversion(*this, ConvType, ToType,
7344                                      AllowObjCConversionOnExplicit))
7345     return;
7346 
7347   // Overload resolution is always an unevaluated context.
7348   EnterExpressionEvaluationContext Unevaluated(
7349       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7350 
7351   // Add this candidate
7352   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7353   Candidate.FoundDecl = FoundDecl;
7354   Candidate.Function = Conversion;
7355   Candidate.IsSurrogate = false;
7356   Candidate.IgnoreObjectArgument = false;
7357   Candidate.FinalConversion.setAsIdentityConversion();
7358   Candidate.FinalConversion.setFromType(ConvType);
7359   Candidate.FinalConversion.setAllToTypes(ToType);
7360   Candidate.Viable = true;
7361   Candidate.ExplicitCallArguments = 1;
7362 
7363   // Explicit functions are not actually candidates at all if we're not
7364   // allowing them in this context, but keep them around so we can point
7365   // to them in diagnostics.
7366   if (!AllowExplicit && Conversion->isExplicit()) {
7367     Candidate.Viable = false;
7368     Candidate.FailureKind = ovl_fail_explicit;
7369     return;
7370   }
7371 
7372   // C++ [over.match.funcs]p4:
7373   //   For conversion functions, the function is considered to be a member of
7374   //   the class of the implicit implied object argument for the purpose of
7375   //   defining the type of the implicit object parameter.
7376   //
7377   // Determine the implicit conversion sequence for the implicit
7378   // object parameter.
7379   QualType ImplicitParamType = From->getType();
7380   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7381     ImplicitParamType = FromPtrType->getPointeeType();
7382   CXXRecordDecl *ConversionContext
7383     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7384 
7385   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7386       *this, CandidateSet.getLocation(), From->getType(),
7387       From->Classify(Context), Conversion, ConversionContext);
7388 
7389   if (Candidate.Conversions[0].isBad()) {
7390     Candidate.Viable = false;
7391     Candidate.FailureKind = ovl_fail_bad_conversion;
7392     return;
7393   }
7394 
7395   if (Conversion->getTrailingRequiresClause()) {
7396     ConstraintSatisfaction Satisfaction;
7397     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7398         !Satisfaction.IsSatisfied) {
7399       Candidate.Viable = false;
7400       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7401       return;
7402     }
7403   }
7404 
7405   // We won't go through a user-defined type conversion function to convert a
7406   // derived to base as such conversions are given Conversion Rank. They only
7407   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7408   QualType FromCanon
7409     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7410   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7411   if (FromCanon == ToCanon ||
7412       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7413     Candidate.Viable = false;
7414     Candidate.FailureKind = ovl_fail_trivial_conversion;
7415     return;
7416   }
7417 
7418   // To determine what the conversion from the result of calling the
7419   // conversion function to the type we're eventually trying to
7420   // convert to (ToType), we need to synthesize a call to the
7421   // conversion function and attempt copy initialization from it. This
7422   // makes sure that we get the right semantics with respect to
7423   // lvalues/rvalues and the type. Fortunately, we can allocate this
7424   // call on the stack and we don't need its arguments to be
7425   // well-formed.
7426   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7427                             VK_LValue, From->getBeginLoc());
7428   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7429                                 Context.getPointerType(Conversion->getType()),
7430                                 CK_FunctionToPointerDecay, &ConversionRef,
7431                                 VK_PRValue, FPOptionsOverride());
7432 
7433   QualType ConversionType = Conversion->getConversionType();
7434   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7435     Candidate.Viable = false;
7436     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7437     return;
7438   }
7439 
7440   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7441 
7442   // Note that it is safe to allocate CallExpr on the stack here because
7443   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7444   // allocator).
7445   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7446 
7447   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7448   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7449       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7450 
7451   ImplicitConversionSequence ICS =
7452       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7453                             /*SuppressUserConversions=*/true,
7454                             /*InOverloadResolution=*/false,
7455                             /*AllowObjCWritebackConversion=*/false);
7456 
7457   switch (ICS.getKind()) {
7458   case ImplicitConversionSequence::StandardConversion:
7459     Candidate.FinalConversion = ICS.Standard;
7460 
7461     // C++ [over.ics.user]p3:
7462     //   If the user-defined conversion is specified by a specialization of a
7463     //   conversion function template, the second standard conversion sequence
7464     //   shall have exact match rank.
7465     if (Conversion->getPrimaryTemplate() &&
7466         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7467       Candidate.Viable = false;
7468       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7469       return;
7470     }
7471 
7472     // C++0x [dcl.init.ref]p5:
7473     //    In the second case, if the reference is an rvalue reference and
7474     //    the second standard conversion sequence of the user-defined
7475     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7476     //    program is ill-formed.
7477     if (ToType->isRValueReferenceType() &&
7478         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7479       Candidate.Viable = false;
7480       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7481       return;
7482     }
7483     break;
7484 
7485   case ImplicitConversionSequence::BadConversion:
7486     Candidate.Viable = false;
7487     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7488     return;
7489 
7490   default:
7491     llvm_unreachable(
7492            "Can only end up with a standard conversion sequence or failure");
7493   }
7494 
7495   if (EnableIfAttr *FailedAttr =
7496           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7497     Candidate.Viable = false;
7498     Candidate.FailureKind = ovl_fail_enable_if;
7499     Candidate.DeductionFailure.Data = FailedAttr;
7500     return;
7501   }
7502 
7503   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7504       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7505     Candidate.Viable = false;
7506     Candidate.FailureKind = ovl_non_default_multiversion_function;
7507   }
7508 }
7509 
7510 /// Adds a conversion function template specialization
7511 /// candidate to the overload set, using template argument deduction
7512 /// to deduce the template arguments of the conversion function
7513 /// template from the type that we are converting to (C++
7514 /// [temp.deduct.conv]).
7515 void Sema::AddTemplateConversionCandidate(
7516     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7517     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7518     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7519     bool AllowExplicit, bool AllowResultConversion) {
7520   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7521          "Only conversion function templates permitted here");
7522 
7523   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7524     return;
7525 
7526   // If the function template has a non-dependent explicit specification,
7527   // exclude it now if appropriate; we are not permitted to perform deduction
7528   // and substitution in this case.
7529   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7530     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7531     Candidate.FoundDecl = FoundDecl;
7532     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7533     Candidate.Viable = false;
7534     Candidate.FailureKind = ovl_fail_explicit;
7535     return;
7536   }
7537 
7538   TemplateDeductionInfo Info(CandidateSet.getLocation());
7539   CXXConversionDecl *Specialization = nullptr;
7540   if (TemplateDeductionResult Result
7541         = DeduceTemplateArguments(FunctionTemplate, ToType,
7542                                   Specialization, Info)) {
7543     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7544     Candidate.FoundDecl = FoundDecl;
7545     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7546     Candidate.Viable = false;
7547     Candidate.FailureKind = ovl_fail_bad_deduction;
7548     Candidate.IsSurrogate = false;
7549     Candidate.IgnoreObjectArgument = false;
7550     Candidate.ExplicitCallArguments = 1;
7551     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7552                                                           Info);
7553     return;
7554   }
7555 
7556   // Add the conversion function template specialization produced by
7557   // template argument deduction as a candidate.
7558   assert(Specialization && "Missing function template specialization?");
7559   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7560                          CandidateSet, AllowObjCConversionOnExplicit,
7561                          AllowExplicit, AllowResultConversion);
7562 }
7563 
7564 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7565 /// converts the given @c Object to a function pointer via the
7566 /// conversion function @c Conversion, and then attempts to call it
7567 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7568 /// the type of function that we'll eventually be calling.
7569 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7570                                  DeclAccessPair FoundDecl,
7571                                  CXXRecordDecl *ActingContext,
7572                                  const FunctionProtoType *Proto,
7573                                  Expr *Object,
7574                                  ArrayRef<Expr *> Args,
7575                                  OverloadCandidateSet& CandidateSet) {
7576   if (!CandidateSet.isNewCandidate(Conversion))
7577     return;
7578 
7579   // Overload resolution is always an unevaluated context.
7580   EnterExpressionEvaluationContext Unevaluated(
7581       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7582 
7583   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7584   Candidate.FoundDecl = FoundDecl;
7585   Candidate.Function = nullptr;
7586   Candidate.Surrogate = Conversion;
7587   Candidate.Viable = true;
7588   Candidate.IsSurrogate = true;
7589   Candidate.IgnoreObjectArgument = false;
7590   Candidate.ExplicitCallArguments = Args.size();
7591 
7592   // Determine the implicit conversion sequence for the implicit
7593   // object parameter.
7594   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7595       *this, CandidateSet.getLocation(), Object->getType(),
7596       Object->Classify(Context), Conversion, ActingContext);
7597   if (ObjectInit.isBad()) {
7598     Candidate.Viable = false;
7599     Candidate.FailureKind = ovl_fail_bad_conversion;
7600     Candidate.Conversions[0] = ObjectInit;
7601     return;
7602   }
7603 
7604   // The first conversion is actually a user-defined conversion whose
7605   // first conversion is ObjectInit's standard conversion (which is
7606   // effectively a reference binding). Record it as such.
7607   Candidate.Conversions[0].setUserDefined();
7608   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7609   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7610   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7611   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7612   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7613   Candidate.Conversions[0].UserDefined.After
7614     = Candidate.Conversions[0].UserDefined.Before;
7615   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7616 
7617   // Find the
7618   unsigned NumParams = Proto->getNumParams();
7619 
7620   // (C++ 13.3.2p2): A candidate function having fewer than m
7621   // parameters is viable only if it has an ellipsis in its parameter
7622   // list (8.3.5).
7623   if (Args.size() > NumParams && !Proto->isVariadic()) {
7624     Candidate.Viable = false;
7625     Candidate.FailureKind = ovl_fail_too_many_arguments;
7626     return;
7627   }
7628 
7629   // Function types don't have any default arguments, so just check if
7630   // we have enough arguments.
7631   if (Args.size() < NumParams) {
7632     // Not enough arguments.
7633     Candidate.Viable = false;
7634     Candidate.FailureKind = ovl_fail_too_few_arguments;
7635     return;
7636   }
7637 
7638   // Determine the implicit conversion sequences for each of the
7639   // arguments.
7640   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7641     if (ArgIdx < NumParams) {
7642       // (C++ 13.3.2p3): for F to be a viable function, there shall
7643       // exist for each argument an implicit conversion sequence
7644       // (13.3.3.1) that converts that argument to the corresponding
7645       // parameter of F.
7646       QualType ParamType = Proto->getParamType(ArgIdx);
7647       Candidate.Conversions[ArgIdx + 1]
7648         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7649                                 /*SuppressUserConversions=*/false,
7650                                 /*InOverloadResolution=*/false,
7651                                 /*AllowObjCWritebackConversion=*/
7652                                   getLangOpts().ObjCAutoRefCount);
7653       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7654         Candidate.Viable = false;
7655         Candidate.FailureKind = ovl_fail_bad_conversion;
7656         return;
7657       }
7658     } else {
7659       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7660       // argument for which there is no corresponding parameter is
7661       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7662       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7663     }
7664   }
7665 
7666   if (EnableIfAttr *FailedAttr =
7667           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7668     Candidate.Viable = false;
7669     Candidate.FailureKind = ovl_fail_enable_if;
7670     Candidate.DeductionFailure.Data = FailedAttr;
7671     return;
7672   }
7673 }
7674 
7675 /// Add all of the non-member operator function declarations in the given
7676 /// function set to the overload candidate set.
7677 void Sema::AddNonMemberOperatorCandidates(
7678     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7679     OverloadCandidateSet &CandidateSet,
7680     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7681   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7682     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7683     ArrayRef<Expr *> FunctionArgs = Args;
7684 
7685     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7686     FunctionDecl *FD =
7687         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7688 
7689     // Don't consider rewritten functions if we're not rewriting.
7690     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7691       continue;
7692 
7693     assert(!isa<CXXMethodDecl>(FD) &&
7694            "unqualified operator lookup found a member function");
7695 
7696     if (FunTmpl) {
7697       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7698                                    FunctionArgs, CandidateSet);
7699       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7700         AddTemplateOverloadCandidate(
7701             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7702             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7703             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7704     } else {
7705       if (ExplicitTemplateArgs)
7706         continue;
7707       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7708       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7709         AddOverloadCandidate(FD, F.getPair(),
7710                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7711                              false, false, true, false, ADLCallKind::NotADL,
7712                              None, OverloadCandidateParamOrder::Reversed);
7713     }
7714   }
7715 }
7716 
7717 /// Add overload candidates for overloaded operators that are
7718 /// member functions.
7719 ///
7720 /// Add the overloaded operator candidates that are member functions
7721 /// for the operator Op that was used in an operator expression such
7722 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7723 /// CandidateSet will store the added overload candidates. (C++
7724 /// [over.match.oper]).
7725 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7726                                        SourceLocation OpLoc,
7727                                        ArrayRef<Expr *> Args,
7728                                        OverloadCandidateSet &CandidateSet,
7729                                        OverloadCandidateParamOrder PO) {
7730   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7731 
7732   // C++ [over.match.oper]p3:
7733   //   For a unary operator @ with an operand of a type whose
7734   //   cv-unqualified version is T1, and for a binary operator @ with
7735   //   a left operand of a type whose cv-unqualified version is T1 and
7736   //   a right operand of a type whose cv-unqualified version is T2,
7737   //   three sets of candidate functions, designated member
7738   //   candidates, non-member candidates and built-in candidates, are
7739   //   constructed as follows:
7740   QualType T1 = Args[0]->getType();
7741 
7742   //     -- If T1 is a complete class type or a class currently being
7743   //        defined, the set of member candidates is the result of the
7744   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7745   //        the set of member candidates is empty.
7746   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7747     // Complete the type if it can be completed.
7748     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7749       return;
7750     // If the type is neither complete nor being defined, bail out now.
7751     if (!T1Rec->getDecl()->getDefinition())
7752       return;
7753 
7754     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7755     LookupQualifiedName(Operators, T1Rec->getDecl());
7756     Operators.suppressDiagnostics();
7757 
7758     for (LookupResult::iterator Oper = Operators.begin(),
7759                              OperEnd = Operators.end();
7760          Oper != OperEnd;
7761          ++Oper)
7762       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7763                          Args[0]->Classify(Context), Args.slice(1),
7764                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7765   }
7766 }
7767 
7768 /// AddBuiltinCandidate - Add a candidate for a built-in
7769 /// operator. ResultTy and ParamTys are the result and parameter types
7770 /// of the built-in candidate, respectively. Args and NumArgs are the
7771 /// arguments being passed to the candidate. IsAssignmentOperator
7772 /// should be true when this built-in candidate is an assignment
7773 /// operator. NumContextualBoolArguments is the number of arguments
7774 /// (at the beginning of the argument list) that will be contextually
7775 /// converted to bool.
7776 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7777                                OverloadCandidateSet& CandidateSet,
7778                                bool IsAssignmentOperator,
7779                                unsigned NumContextualBoolArguments) {
7780   // Overload resolution is always an unevaluated context.
7781   EnterExpressionEvaluationContext Unevaluated(
7782       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7783 
7784   // Add this candidate
7785   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7786   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7787   Candidate.Function = nullptr;
7788   Candidate.IsSurrogate = false;
7789   Candidate.IgnoreObjectArgument = false;
7790   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7791 
7792   // Determine the implicit conversion sequences for each of the
7793   // arguments.
7794   Candidate.Viable = true;
7795   Candidate.ExplicitCallArguments = Args.size();
7796   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7797     // C++ [over.match.oper]p4:
7798     //   For the built-in assignment operators, conversions of the
7799     //   left operand are restricted as follows:
7800     //     -- no temporaries are introduced to hold the left operand, and
7801     //     -- no user-defined conversions are applied to the left
7802     //        operand to achieve a type match with the left-most
7803     //        parameter of a built-in candidate.
7804     //
7805     // We block these conversions by turning off user-defined
7806     // conversions, since that is the only way that initialization of
7807     // a reference to a non-class type can occur from something that
7808     // is not of the same type.
7809     if (ArgIdx < NumContextualBoolArguments) {
7810       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7811              "Contextual conversion to bool requires bool type");
7812       Candidate.Conversions[ArgIdx]
7813         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7814     } else {
7815       Candidate.Conversions[ArgIdx]
7816         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7817                                 ArgIdx == 0 && IsAssignmentOperator,
7818                                 /*InOverloadResolution=*/false,
7819                                 /*AllowObjCWritebackConversion=*/
7820                                   getLangOpts().ObjCAutoRefCount);
7821     }
7822     if (Candidate.Conversions[ArgIdx].isBad()) {
7823       Candidate.Viable = false;
7824       Candidate.FailureKind = ovl_fail_bad_conversion;
7825       break;
7826     }
7827   }
7828 }
7829 
7830 namespace {
7831 
7832 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7833 /// candidate operator functions for built-in operators (C++
7834 /// [over.built]). The types are separated into pointer types and
7835 /// enumeration types.
7836 class BuiltinCandidateTypeSet  {
7837   /// TypeSet - A set of types.
7838   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7839                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7840 
7841   /// PointerTypes - The set of pointer types that will be used in the
7842   /// built-in candidates.
7843   TypeSet PointerTypes;
7844 
7845   /// MemberPointerTypes - The set of member pointer types that will be
7846   /// used in the built-in candidates.
7847   TypeSet MemberPointerTypes;
7848 
7849   /// EnumerationTypes - The set of enumeration types that will be
7850   /// used in the built-in candidates.
7851   TypeSet EnumerationTypes;
7852 
7853   /// The set of vector types that will be used in the built-in
7854   /// candidates.
7855   TypeSet VectorTypes;
7856 
7857   /// The set of matrix types that will be used in the built-in
7858   /// candidates.
7859   TypeSet MatrixTypes;
7860 
7861   /// A flag indicating non-record types are viable candidates
7862   bool HasNonRecordTypes;
7863 
7864   /// A flag indicating whether either arithmetic or enumeration types
7865   /// were present in the candidate set.
7866   bool HasArithmeticOrEnumeralTypes;
7867 
7868   /// A flag indicating whether the nullptr type was present in the
7869   /// candidate set.
7870   bool HasNullPtrType;
7871 
7872   /// Sema - The semantic analysis instance where we are building the
7873   /// candidate type set.
7874   Sema &SemaRef;
7875 
7876   /// Context - The AST context in which we will build the type sets.
7877   ASTContext &Context;
7878 
7879   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7880                                                const Qualifiers &VisibleQuals);
7881   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7882 
7883 public:
7884   /// iterator - Iterates through the types that are part of the set.
7885   typedef TypeSet::iterator iterator;
7886 
7887   BuiltinCandidateTypeSet(Sema &SemaRef)
7888     : HasNonRecordTypes(false),
7889       HasArithmeticOrEnumeralTypes(false),
7890       HasNullPtrType(false),
7891       SemaRef(SemaRef),
7892       Context(SemaRef.Context) { }
7893 
7894   void AddTypesConvertedFrom(QualType Ty,
7895                              SourceLocation Loc,
7896                              bool AllowUserConversions,
7897                              bool AllowExplicitConversions,
7898                              const Qualifiers &VisibleTypeConversionsQuals);
7899 
7900   llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
7901   llvm::iterator_range<iterator> member_pointer_types() {
7902     return MemberPointerTypes;
7903   }
7904   llvm::iterator_range<iterator> enumeration_types() {
7905     return EnumerationTypes;
7906   }
7907   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7908   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7909 
7910   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7911   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7912   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7913   bool hasNullPtrType() const { return HasNullPtrType; }
7914 };
7915 
7916 } // end anonymous namespace
7917 
7918 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7919 /// the set of pointer types along with any more-qualified variants of
7920 /// that type. For example, if @p Ty is "int const *", this routine
7921 /// will add "int const *", "int const volatile *", "int const
7922 /// restrict *", and "int const volatile restrict *" to the set of
7923 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7924 /// false otherwise.
7925 ///
7926 /// FIXME: what to do about extended qualifiers?
7927 bool
7928 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7929                                              const Qualifiers &VisibleQuals) {
7930 
7931   // Insert this type.
7932   if (!PointerTypes.insert(Ty))
7933     return false;
7934 
7935   QualType PointeeTy;
7936   const PointerType *PointerTy = Ty->getAs<PointerType>();
7937   bool buildObjCPtr = false;
7938   if (!PointerTy) {
7939     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7940     PointeeTy = PTy->getPointeeType();
7941     buildObjCPtr = true;
7942   } else {
7943     PointeeTy = PointerTy->getPointeeType();
7944   }
7945 
7946   // Don't add qualified variants of arrays. For one, they're not allowed
7947   // (the qualifier would sink to the element type), and for another, the
7948   // only overload situation where it matters is subscript or pointer +- int,
7949   // and those shouldn't have qualifier variants anyway.
7950   if (PointeeTy->isArrayType())
7951     return true;
7952 
7953   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7954   bool hasVolatile = VisibleQuals.hasVolatile();
7955   bool hasRestrict = VisibleQuals.hasRestrict();
7956 
7957   // Iterate through all strict supersets of BaseCVR.
7958   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7959     if ((CVR | BaseCVR) != CVR) continue;
7960     // Skip over volatile if no volatile found anywhere in the types.
7961     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7962 
7963     // Skip over restrict if no restrict found anywhere in the types, or if
7964     // the type cannot be restrict-qualified.
7965     if ((CVR & Qualifiers::Restrict) &&
7966         (!hasRestrict ||
7967          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7968       continue;
7969 
7970     // Build qualified pointee type.
7971     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7972 
7973     // Build qualified pointer type.
7974     QualType QPointerTy;
7975     if (!buildObjCPtr)
7976       QPointerTy = Context.getPointerType(QPointeeTy);
7977     else
7978       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7979 
7980     // Insert qualified pointer type.
7981     PointerTypes.insert(QPointerTy);
7982   }
7983 
7984   return true;
7985 }
7986 
7987 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7988 /// to the set of pointer types along with any more-qualified variants of
7989 /// that type. For example, if @p Ty is "int const *", this routine
7990 /// will add "int const *", "int const volatile *", "int const
7991 /// restrict *", and "int const volatile restrict *" to the set of
7992 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7993 /// false otherwise.
7994 ///
7995 /// FIXME: what to do about extended qualifiers?
7996 bool
7997 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7998     QualType Ty) {
7999   // Insert this type.
8000   if (!MemberPointerTypes.insert(Ty))
8001     return false;
8002 
8003   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8004   assert(PointerTy && "type was not a member pointer type!");
8005 
8006   QualType PointeeTy = PointerTy->getPointeeType();
8007   // Don't add qualified variants of arrays. For one, they're not allowed
8008   // (the qualifier would sink to the element type), and for another, the
8009   // only overload situation where it matters is subscript or pointer +- int,
8010   // and those shouldn't have qualifier variants anyway.
8011   if (PointeeTy->isArrayType())
8012     return true;
8013   const Type *ClassTy = PointerTy->getClass();
8014 
8015   // Iterate through all strict supersets of the pointee type's CVR
8016   // qualifiers.
8017   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8018   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8019     if ((CVR | BaseCVR) != CVR) continue;
8020 
8021     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8022     MemberPointerTypes.insert(
8023       Context.getMemberPointerType(QPointeeTy, ClassTy));
8024   }
8025 
8026   return true;
8027 }
8028 
8029 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8030 /// Ty can be implicit converted to the given set of @p Types. We're
8031 /// primarily interested in pointer types and enumeration types. We also
8032 /// take member pointer types, for the conditional operator.
8033 /// AllowUserConversions is true if we should look at the conversion
8034 /// functions of a class type, and AllowExplicitConversions if we
8035 /// should also include the explicit conversion functions of a class
8036 /// type.
8037 void
8038 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8039                                                SourceLocation Loc,
8040                                                bool AllowUserConversions,
8041                                                bool AllowExplicitConversions,
8042                                                const Qualifiers &VisibleQuals) {
8043   // Only deal with canonical types.
8044   Ty = Context.getCanonicalType(Ty);
8045 
8046   // Look through reference types; they aren't part of the type of an
8047   // expression for the purposes of conversions.
8048   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8049     Ty = RefTy->getPointeeType();
8050 
8051   // If we're dealing with an array type, decay to the pointer.
8052   if (Ty->isArrayType())
8053     Ty = SemaRef.Context.getArrayDecayedType(Ty);
8054 
8055   // Otherwise, we don't care about qualifiers on the type.
8056   Ty = Ty.getLocalUnqualifiedType();
8057 
8058   // Flag if we ever add a non-record type.
8059   const RecordType *TyRec = Ty->getAs<RecordType>();
8060   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8061 
8062   // Flag if we encounter an arithmetic type.
8063   HasArithmeticOrEnumeralTypes =
8064     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8065 
8066   if (Ty->isObjCIdType() || Ty->isObjCClassType())
8067     PointerTypes.insert(Ty);
8068   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8069     // Insert our type, and its more-qualified variants, into the set
8070     // of types.
8071     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8072       return;
8073   } else if (Ty->isMemberPointerType()) {
8074     // Member pointers are far easier, since the pointee can't be converted.
8075     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8076       return;
8077   } else if (Ty->isEnumeralType()) {
8078     HasArithmeticOrEnumeralTypes = true;
8079     EnumerationTypes.insert(Ty);
8080   } else if (Ty->isVectorType()) {
8081     // We treat vector types as arithmetic types in many contexts as an
8082     // extension.
8083     HasArithmeticOrEnumeralTypes = true;
8084     VectorTypes.insert(Ty);
8085   } else if (Ty->isMatrixType()) {
8086     // Similar to vector types, we treat vector types as arithmetic types in
8087     // many contexts as an extension.
8088     HasArithmeticOrEnumeralTypes = true;
8089     MatrixTypes.insert(Ty);
8090   } else if (Ty->isNullPtrType()) {
8091     HasNullPtrType = true;
8092   } else if (AllowUserConversions && TyRec) {
8093     // No conversion functions in incomplete types.
8094     if (!SemaRef.isCompleteType(Loc, Ty))
8095       return;
8096 
8097     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8098     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8099       if (isa<UsingShadowDecl>(D))
8100         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8101 
8102       // Skip conversion function templates; they don't tell us anything
8103       // about which builtin types we can convert to.
8104       if (isa<FunctionTemplateDecl>(D))
8105         continue;
8106 
8107       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8108       if (AllowExplicitConversions || !Conv->isExplicit()) {
8109         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8110                               VisibleQuals);
8111       }
8112     }
8113   }
8114 }
8115 /// Helper function for adjusting address spaces for the pointer or reference
8116 /// operands of builtin operators depending on the argument.
8117 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8118                                                         Expr *Arg) {
8119   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8120 }
8121 
8122 /// Helper function for AddBuiltinOperatorCandidates() that adds
8123 /// the volatile- and non-volatile-qualified assignment operators for the
8124 /// given type to the candidate set.
8125 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8126                                                    QualType T,
8127                                                    ArrayRef<Expr *> Args,
8128                                     OverloadCandidateSet &CandidateSet) {
8129   QualType ParamTypes[2];
8130 
8131   // T& operator=(T&, T)
8132   ParamTypes[0] = S.Context.getLValueReferenceType(
8133       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8134   ParamTypes[1] = T;
8135   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8136                         /*IsAssignmentOperator=*/true);
8137 
8138   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8139     // volatile T& operator=(volatile T&, T)
8140     ParamTypes[0] = S.Context.getLValueReferenceType(
8141         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8142                                                 Args[0]));
8143     ParamTypes[1] = T;
8144     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8145                           /*IsAssignmentOperator=*/true);
8146   }
8147 }
8148 
8149 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8150 /// if any, found in visible type conversion functions found in ArgExpr's type.
8151 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8152     Qualifiers VRQuals;
8153     const RecordType *TyRec;
8154     if (const MemberPointerType *RHSMPType =
8155         ArgExpr->getType()->getAs<MemberPointerType>())
8156       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8157     else
8158       TyRec = ArgExpr->getType()->getAs<RecordType>();
8159     if (!TyRec) {
8160       // Just to be safe, assume the worst case.
8161       VRQuals.addVolatile();
8162       VRQuals.addRestrict();
8163       return VRQuals;
8164     }
8165 
8166     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8167     if (!ClassDecl->hasDefinition())
8168       return VRQuals;
8169 
8170     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8171       if (isa<UsingShadowDecl>(D))
8172         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8173       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8174         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8175         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8176           CanTy = ResTypeRef->getPointeeType();
8177         // Need to go down the pointer/mempointer chain and add qualifiers
8178         // as see them.
8179         bool done = false;
8180         while (!done) {
8181           if (CanTy.isRestrictQualified())
8182             VRQuals.addRestrict();
8183           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8184             CanTy = ResTypePtr->getPointeeType();
8185           else if (const MemberPointerType *ResTypeMPtr =
8186                 CanTy->getAs<MemberPointerType>())
8187             CanTy = ResTypeMPtr->getPointeeType();
8188           else
8189             done = true;
8190           if (CanTy.isVolatileQualified())
8191             VRQuals.addVolatile();
8192           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8193             return VRQuals;
8194         }
8195       }
8196     }
8197     return VRQuals;
8198 }
8199 
8200 namespace {
8201 
8202 /// Helper class to manage the addition of builtin operator overload
8203 /// candidates. It provides shared state and utility methods used throughout
8204 /// the process, as well as a helper method to add each group of builtin
8205 /// operator overloads from the standard to a candidate set.
8206 class BuiltinOperatorOverloadBuilder {
8207   // Common instance state available to all overload candidate addition methods.
8208   Sema &S;
8209   ArrayRef<Expr *> Args;
8210   Qualifiers VisibleTypeConversionsQuals;
8211   bool HasArithmeticOrEnumeralCandidateType;
8212   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8213   OverloadCandidateSet &CandidateSet;
8214 
8215   static constexpr int ArithmeticTypesCap = 24;
8216   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8217 
8218   // Define some indices used to iterate over the arithmetic types in
8219   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8220   // types are that preserved by promotion (C++ [over.built]p2).
8221   unsigned FirstIntegralType,
8222            LastIntegralType;
8223   unsigned FirstPromotedIntegralType,
8224            LastPromotedIntegralType;
8225   unsigned FirstPromotedArithmeticType,
8226            LastPromotedArithmeticType;
8227   unsigned NumArithmeticTypes;
8228 
8229   void InitArithmeticTypes() {
8230     // Start of promoted types.
8231     FirstPromotedArithmeticType = 0;
8232     ArithmeticTypes.push_back(S.Context.FloatTy);
8233     ArithmeticTypes.push_back(S.Context.DoubleTy);
8234     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8235     if (S.Context.getTargetInfo().hasFloat128Type())
8236       ArithmeticTypes.push_back(S.Context.Float128Ty);
8237     if (S.Context.getTargetInfo().hasIbm128Type())
8238       ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8239 
8240     // Start of integral types.
8241     FirstIntegralType = ArithmeticTypes.size();
8242     FirstPromotedIntegralType = ArithmeticTypes.size();
8243     ArithmeticTypes.push_back(S.Context.IntTy);
8244     ArithmeticTypes.push_back(S.Context.LongTy);
8245     ArithmeticTypes.push_back(S.Context.LongLongTy);
8246     if (S.Context.getTargetInfo().hasInt128Type() ||
8247         (S.Context.getAuxTargetInfo() &&
8248          S.Context.getAuxTargetInfo()->hasInt128Type()))
8249       ArithmeticTypes.push_back(S.Context.Int128Ty);
8250     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8251     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8252     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8253     if (S.Context.getTargetInfo().hasInt128Type() ||
8254         (S.Context.getAuxTargetInfo() &&
8255          S.Context.getAuxTargetInfo()->hasInt128Type()))
8256       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8257     LastPromotedIntegralType = ArithmeticTypes.size();
8258     LastPromotedArithmeticType = ArithmeticTypes.size();
8259     // End of promoted types.
8260 
8261     ArithmeticTypes.push_back(S.Context.BoolTy);
8262     ArithmeticTypes.push_back(S.Context.CharTy);
8263     ArithmeticTypes.push_back(S.Context.WCharTy);
8264     if (S.Context.getLangOpts().Char8)
8265       ArithmeticTypes.push_back(S.Context.Char8Ty);
8266     ArithmeticTypes.push_back(S.Context.Char16Ty);
8267     ArithmeticTypes.push_back(S.Context.Char32Ty);
8268     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8269     ArithmeticTypes.push_back(S.Context.ShortTy);
8270     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8271     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8272     LastIntegralType = ArithmeticTypes.size();
8273     NumArithmeticTypes = ArithmeticTypes.size();
8274     // End of integral types.
8275     // FIXME: What about complex? What about half?
8276 
8277     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8278            "Enough inline storage for all arithmetic types.");
8279   }
8280 
8281   /// Helper method to factor out the common pattern of adding overloads
8282   /// for '++' and '--' builtin operators.
8283   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8284                                            bool HasVolatile,
8285                                            bool HasRestrict) {
8286     QualType ParamTypes[2] = {
8287       S.Context.getLValueReferenceType(CandidateTy),
8288       S.Context.IntTy
8289     };
8290 
8291     // Non-volatile version.
8292     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8293 
8294     // Use a heuristic to reduce number of builtin candidates in the set:
8295     // add volatile version only if there are conversions to a volatile type.
8296     if (HasVolatile) {
8297       ParamTypes[0] =
8298         S.Context.getLValueReferenceType(
8299           S.Context.getVolatileType(CandidateTy));
8300       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8301     }
8302 
8303     // Add restrict version only if there are conversions to a restrict type
8304     // and our candidate type is a non-restrict-qualified pointer.
8305     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8306         !CandidateTy.isRestrictQualified()) {
8307       ParamTypes[0]
8308         = S.Context.getLValueReferenceType(
8309             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8310       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8311 
8312       if (HasVolatile) {
8313         ParamTypes[0]
8314           = S.Context.getLValueReferenceType(
8315               S.Context.getCVRQualifiedType(CandidateTy,
8316                                             (Qualifiers::Volatile |
8317                                              Qualifiers::Restrict)));
8318         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8319       }
8320     }
8321 
8322   }
8323 
8324   /// Helper to add an overload candidate for a binary builtin with types \p L
8325   /// and \p R.
8326   void AddCandidate(QualType L, QualType R) {
8327     QualType LandR[2] = {L, R};
8328     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8329   }
8330 
8331 public:
8332   BuiltinOperatorOverloadBuilder(
8333     Sema &S, ArrayRef<Expr *> Args,
8334     Qualifiers VisibleTypeConversionsQuals,
8335     bool HasArithmeticOrEnumeralCandidateType,
8336     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8337     OverloadCandidateSet &CandidateSet)
8338     : S(S), Args(Args),
8339       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8340       HasArithmeticOrEnumeralCandidateType(
8341         HasArithmeticOrEnumeralCandidateType),
8342       CandidateTypes(CandidateTypes),
8343       CandidateSet(CandidateSet) {
8344 
8345     InitArithmeticTypes();
8346   }
8347 
8348   // Increment is deprecated for bool since C++17.
8349   //
8350   // C++ [over.built]p3:
8351   //
8352   //   For every pair (T, VQ), where T is an arithmetic type other
8353   //   than bool, and VQ is either volatile or empty, there exist
8354   //   candidate operator functions of the form
8355   //
8356   //       VQ T&      operator++(VQ T&);
8357   //       T          operator++(VQ T&, int);
8358   //
8359   // C++ [over.built]p4:
8360   //
8361   //   For every pair (T, VQ), where T is an arithmetic type other
8362   //   than bool, and VQ is either volatile or empty, there exist
8363   //   candidate operator functions of the form
8364   //
8365   //       VQ T&      operator--(VQ T&);
8366   //       T          operator--(VQ T&, int);
8367   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8368     if (!HasArithmeticOrEnumeralCandidateType)
8369       return;
8370 
8371     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8372       const auto TypeOfT = ArithmeticTypes[Arith];
8373       if (TypeOfT == S.Context.BoolTy) {
8374         if (Op == OO_MinusMinus)
8375           continue;
8376         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8377           continue;
8378       }
8379       addPlusPlusMinusMinusStyleOverloads(
8380         TypeOfT,
8381         VisibleTypeConversionsQuals.hasVolatile(),
8382         VisibleTypeConversionsQuals.hasRestrict());
8383     }
8384   }
8385 
8386   // C++ [over.built]p5:
8387   //
8388   //   For every pair (T, VQ), where T is a cv-qualified or
8389   //   cv-unqualified object type, and VQ is either volatile or
8390   //   empty, there exist candidate operator functions of the form
8391   //
8392   //       T*VQ&      operator++(T*VQ&);
8393   //       T*VQ&      operator--(T*VQ&);
8394   //       T*         operator++(T*VQ&, int);
8395   //       T*         operator--(T*VQ&, int);
8396   void addPlusPlusMinusMinusPointerOverloads() {
8397     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8398       // Skip pointer types that aren't pointers to object types.
8399       if (!PtrTy->getPointeeType()->isObjectType())
8400         continue;
8401 
8402       addPlusPlusMinusMinusStyleOverloads(
8403           PtrTy,
8404           (!PtrTy.isVolatileQualified() &&
8405            VisibleTypeConversionsQuals.hasVolatile()),
8406           (!PtrTy.isRestrictQualified() &&
8407            VisibleTypeConversionsQuals.hasRestrict()));
8408     }
8409   }
8410 
8411   // C++ [over.built]p6:
8412   //   For every cv-qualified or cv-unqualified object type T, there
8413   //   exist candidate operator functions of the form
8414   //
8415   //       T&         operator*(T*);
8416   //
8417   // C++ [over.built]p7:
8418   //   For every function type T that does not have cv-qualifiers or a
8419   //   ref-qualifier, there exist candidate operator functions of the form
8420   //       T&         operator*(T*);
8421   void addUnaryStarPointerOverloads() {
8422     for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
8423       QualType PointeeTy = ParamTy->getPointeeType();
8424       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8425         continue;
8426 
8427       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8428         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8429           continue;
8430 
8431       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8432     }
8433   }
8434 
8435   // C++ [over.built]p9:
8436   //  For every promoted arithmetic type T, there exist candidate
8437   //  operator functions of the form
8438   //
8439   //       T         operator+(T);
8440   //       T         operator-(T);
8441   void addUnaryPlusOrMinusArithmeticOverloads() {
8442     if (!HasArithmeticOrEnumeralCandidateType)
8443       return;
8444 
8445     for (unsigned Arith = FirstPromotedArithmeticType;
8446          Arith < LastPromotedArithmeticType; ++Arith) {
8447       QualType ArithTy = ArithmeticTypes[Arith];
8448       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8449     }
8450 
8451     // Extension: We also add these operators for vector types.
8452     for (QualType VecTy : CandidateTypes[0].vector_types())
8453       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8454   }
8455 
8456   // C++ [over.built]p8:
8457   //   For every type T, there exist candidate operator functions of
8458   //   the form
8459   //
8460   //       T*         operator+(T*);
8461   void addUnaryPlusPointerOverloads() {
8462     for (QualType ParamTy : CandidateTypes[0].pointer_types())
8463       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8464   }
8465 
8466   // C++ [over.built]p10:
8467   //   For every promoted integral type T, there exist candidate
8468   //   operator functions of the form
8469   //
8470   //        T         operator~(T);
8471   void addUnaryTildePromotedIntegralOverloads() {
8472     if (!HasArithmeticOrEnumeralCandidateType)
8473       return;
8474 
8475     for (unsigned Int = FirstPromotedIntegralType;
8476          Int < LastPromotedIntegralType; ++Int) {
8477       QualType IntTy = ArithmeticTypes[Int];
8478       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8479     }
8480 
8481     // Extension: We also add this operator for vector types.
8482     for (QualType VecTy : CandidateTypes[0].vector_types())
8483       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8484   }
8485 
8486   // C++ [over.match.oper]p16:
8487   //   For every pointer to member type T or type std::nullptr_t, there
8488   //   exist candidate operator functions of the form
8489   //
8490   //        bool operator==(T,T);
8491   //        bool operator!=(T,T);
8492   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8493     /// Set of (canonical) types that we've already handled.
8494     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8495 
8496     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8497       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8498         // Don't add the same builtin candidate twice.
8499         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8500           continue;
8501 
8502         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
8503         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8504       }
8505 
8506       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8507         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8508         if (AddedTypes.insert(NullPtrTy).second) {
8509           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8510           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8511         }
8512       }
8513     }
8514   }
8515 
8516   // C++ [over.built]p15:
8517   //
8518   //   For every T, where T is an enumeration type or a pointer type,
8519   //   there exist candidate operator functions of the form
8520   //
8521   //        bool       operator<(T, T);
8522   //        bool       operator>(T, T);
8523   //        bool       operator<=(T, T);
8524   //        bool       operator>=(T, T);
8525   //        bool       operator==(T, T);
8526   //        bool       operator!=(T, T);
8527   //           R       operator<=>(T, T)
8528   void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
8529     // C++ [over.match.oper]p3:
8530     //   [...]the built-in candidates include all of the candidate operator
8531     //   functions defined in 13.6 that, compared to the given operator, [...]
8532     //   do not have the same parameter-type-list as any non-template non-member
8533     //   candidate.
8534     //
8535     // Note that in practice, this only affects enumeration types because there
8536     // aren't any built-in candidates of record type, and a user-defined operator
8537     // must have an operand of record or enumeration type. Also, the only other
8538     // overloaded operator with enumeration arguments, operator=,
8539     // cannot be overloaded for enumeration types, so this is the only place
8540     // where we must suppress candidates like this.
8541     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8542       UserDefinedBinaryOperators;
8543 
8544     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8545       if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
8546         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8547                                          CEnd = CandidateSet.end();
8548              C != CEnd; ++C) {
8549           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8550             continue;
8551 
8552           if (C->Function->isFunctionTemplateSpecialization())
8553             continue;
8554 
8555           // We interpret "same parameter-type-list" as applying to the
8556           // "synthesized candidate, with the order of the two parameters
8557           // reversed", not to the original function.
8558           bool Reversed = C->isReversed();
8559           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8560                                         ->getType()
8561                                         .getUnqualifiedType();
8562           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8563                                          ->getType()
8564                                          .getUnqualifiedType();
8565 
8566           // Skip if either parameter isn't of enumeral type.
8567           if (!FirstParamType->isEnumeralType() ||
8568               !SecondParamType->isEnumeralType())
8569             continue;
8570 
8571           // Add this operator to the set of known user-defined operators.
8572           UserDefinedBinaryOperators.insert(
8573             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8574                            S.Context.getCanonicalType(SecondParamType)));
8575         }
8576       }
8577     }
8578 
8579     /// Set of (canonical) types that we've already handled.
8580     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8581 
8582     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8583       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
8584         // Don't add the same builtin candidate twice.
8585         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8586           continue;
8587         if (IsSpaceship && PtrTy->isFunctionPointerType())
8588           continue;
8589 
8590         QualType ParamTypes[2] = {PtrTy, PtrTy};
8591         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8592       }
8593       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8594         CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
8595 
8596         // Don't add the same builtin candidate twice, or if a user defined
8597         // candidate exists.
8598         if (!AddedTypes.insert(CanonType).second ||
8599             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8600                                                             CanonType)))
8601           continue;
8602         QualType ParamTypes[2] = {EnumTy, EnumTy};
8603         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8604       }
8605     }
8606   }
8607 
8608   // C++ [over.built]p13:
8609   //
8610   //   For every cv-qualified or cv-unqualified object type T
8611   //   there exist candidate operator functions of the form
8612   //
8613   //      T*         operator+(T*, ptrdiff_t);
8614   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8615   //      T*         operator-(T*, ptrdiff_t);
8616   //      T*         operator+(ptrdiff_t, T*);
8617   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8618   //
8619   // C++ [over.built]p14:
8620   //
8621   //   For every T, where T is a pointer to object type, there
8622   //   exist candidate operator functions of the form
8623   //
8624   //      ptrdiff_t  operator-(T, T);
8625   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8626     /// Set of (canonical) types that we've already handled.
8627     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8628 
8629     for (int Arg = 0; Arg < 2; ++Arg) {
8630       QualType AsymmetricParamTypes[2] = {
8631         S.Context.getPointerDiffType(),
8632         S.Context.getPointerDiffType(),
8633       };
8634       for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
8635         QualType PointeeTy = PtrTy->getPointeeType();
8636         if (!PointeeTy->isObjectType())
8637           continue;
8638 
8639         AsymmetricParamTypes[Arg] = PtrTy;
8640         if (Arg == 0 || Op == OO_Plus) {
8641           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8642           // T* operator+(ptrdiff_t, T*);
8643           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8644         }
8645         if (Op == OO_Minus) {
8646           // ptrdiff_t operator-(T, T);
8647           if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8648             continue;
8649 
8650           QualType ParamTypes[2] = {PtrTy, PtrTy};
8651           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8652         }
8653       }
8654     }
8655   }
8656 
8657   // C++ [over.built]p12:
8658   //
8659   //   For every pair of promoted arithmetic types L and R, there
8660   //   exist candidate operator functions of the form
8661   //
8662   //        LR         operator*(L, R);
8663   //        LR         operator/(L, R);
8664   //        LR         operator+(L, R);
8665   //        LR         operator-(L, R);
8666   //        bool       operator<(L, R);
8667   //        bool       operator>(L, R);
8668   //        bool       operator<=(L, R);
8669   //        bool       operator>=(L, R);
8670   //        bool       operator==(L, R);
8671   //        bool       operator!=(L, R);
8672   //
8673   //   where LR is the result of the usual arithmetic conversions
8674   //   between types L and R.
8675   //
8676   // C++ [over.built]p24:
8677   //
8678   //   For every pair of promoted arithmetic types L and R, there exist
8679   //   candidate operator functions of the form
8680   //
8681   //        LR       operator?(bool, L, R);
8682   //
8683   //   where LR is the result of the usual arithmetic conversions
8684   //   between types L and R.
8685   // Our candidates ignore the first parameter.
8686   void addGenericBinaryArithmeticOverloads() {
8687     if (!HasArithmeticOrEnumeralCandidateType)
8688       return;
8689 
8690     for (unsigned Left = FirstPromotedArithmeticType;
8691          Left < LastPromotedArithmeticType; ++Left) {
8692       for (unsigned Right = FirstPromotedArithmeticType;
8693            Right < LastPromotedArithmeticType; ++Right) {
8694         QualType LandR[2] = { ArithmeticTypes[Left],
8695                               ArithmeticTypes[Right] };
8696         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8697       }
8698     }
8699 
8700     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8701     // conditional operator for vector types.
8702     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8703       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8704         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8705         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8706       }
8707   }
8708 
8709   /// Add binary operator overloads for each candidate matrix type M1, M2:
8710   ///  * (M1, M1) -> M1
8711   ///  * (M1, M1.getElementType()) -> M1
8712   ///  * (M2.getElementType(), M2) -> M2
8713   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8714   void addMatrixBinaryArithmeticOverloads() {
8715     if (!HasArithmeticOrEnumeralCandidateType)
8716       return;
8717 
8718     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8719       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8720       AddCandidate(M1, M1);
8721     }
8722 
8723     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8724       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8725       if (!CandidateTypes[0].containsMatrixType(M2))
8726         AddCandidate(M2, M2);
8727     }
8728   }
8729 
8730   // C++2a [over.built]p14:
8731   //
8732   //   For every integral type T there exists a candidate operator function
8733   //   of the form
8734   //
8735   //        std::strong_ordering operator<=>(T, T)
8736   //
8737   // C++2a [over.built]p15:
8738   //
8739   //   For every pair of floating-point types L and R, there exists a candidate
8740   //   operator function of the form
8741   //
8742   //       std::partial_ordering operator<=>(L, R);
8743   //
8744   // FIXME: The current specification for integral types doesn't play nice with
8745   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8746   // comparisons. Under the current spec this can lead to ambiguity during
8747   // overload resolution. For example:
8748   //
8749   //   enum A : int {a};
8750   //   auto x = (a <=> (long)42);
8751   //
8752   //   error: call is ambiguous for arguments 'A' and 'long'.
8753   //   note: candidate operator<=>(int, int)
8754   //   note: candidate operator<=>(long, long)
8755   //
8756   // To avoid this error, this function deviates from the specification and adds
8757   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8758   // arithmetic types (the same as the generic relational overloads).
8759   //
8760   // For now this function acts as a placeholder.
8761   void addThreeWayArithmeticOverloads() {
8762     addGenericBinaryArithmeticOverloads();
8763   }
8764 
8765   // C++ [over.built]p17:
8766   //
8767   //   For every pair of promoted integral types L and R, there
8768   //   exist candidate operator functions of the form
8769   //
8770   //      LR         operator%(L, R);
8771   //      LR         operator&(L, R);
8772   //      LR         operator^(L, R);
8773   //      LR         operator|(L, R);
8774   //      L          operator<<(L, R);
8775   //      L          operator>>(L, R);
8776   //
8777   //   where LR is the result of the usual arithmetic conversions
8778   //   between types L and R.
8779   void addBinaryBitwiseArithmeticOverloads() {
8780     if (!HasArithmeticOrEnumeralCandidateType)
8781       return;
8782 
8783     for (unsigned Left = FirstPromotedIntegralType;
8784          Left < LastPromotedIntegralType; ++Left) {
8785       for (unsigned Right = FirstPromotedIntegralType;
8786            Right < LastPromotedIntegralType; ++Right) {
8787         QualType LandR[2] = { ArithmeticTypes[Left],
8788                               ArithmeticTypes[Right] };
8789         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8790       }
8791     }
8792   }
8793 
8794   // C++ [over.built]p20:
8795   //
8796   //   For every pair (T, VQ), where T is an enumeration or
8797   //   pointer to member type and VQ is either volatile or
8798   //   empty, there exist candidate operator functions of the form
8799   //
8800   //        VQ T&      operator=(VQ T&, T);
8801   void addAssignmentMemberPointerOrEnumeralOverloads() {
8802     /// Set of (canonical) types that we've already handled.
8803     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8804 
8805     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8806       for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
8807         if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
8808           continue;
8809 
8810         AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
8811       }
8812 
8813       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
8814         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
8815           continue;
8816 
8817         AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
8818       }
8819     }
8820   }
8821 
8822   // C++ [over.built]p19:
8823   //
8824   //   For every pair (T, VQ), where T is any type and VQ is either
8825   //   volatile or empty, there exist candidate operator functions
8826   //   of the form
8827   //
8828   //        T*VQ&      operator=(T*VQ&, T*);
8829   //
8830   // C++ [over.built]p21:
8831   //
8832   //   For every pair (T, VQ), where T is a cv-qualified or
8833   //   cv-unqualified object type and VQ is either volatile or
8834   //   empty, there exist candidate operator functions of the form
8835   //
8836   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8837   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8838   void addAssignmentPointerOverloads(bool isEqualOp) {
8839     /// Set of (canonical) types that we've already handled.
8840     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8841 
8842     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
8843       // If this is operator=, keep track of the builtin candidates we added.
8844       if (isEqualOp)
8845         AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
8846       else if (!PtrTy->getPointeeType()->isObjectType())
8847         continue;
8848 
8849       // non-volatile version
8850       QualType ParamTypes[2] = {
8851           S.Context.getLValueReferenceType(PtrTy),
8852           isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
8853       };
8854       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8855                             /*IsAssignmentOperator=*/ isEqualOp);
8856 
8857       bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8858                           VisibleTypeConversionsQuals.hasVolatile();
8859       if (NeedVolatile) {
8860         // volatile version
8861         ParamTypes[0] =
8862             S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
8863         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8864                               /*IsAssignmentOperator=*/isEqualOp);
8865       }
8866 
8867       if (!PtrTy.isRestrictQualified() &&
8868           VisibleTypeConversionsQuals.hasRestrict()) {
8869         // restrict version
8870         ParamTypes[0] =
8871             S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
8872         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8873                               /*IsAssignmentOperator=*/isEqualOp);
8874 
8875         if (NeedVolatile) {
8876           // volatile restrict version
8877           ParamTypes[0] =
8878               S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8879                   PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8880           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8881                                 /*IsAssignmentOperator=*/isEqualOp);
8882         }
8883       }
8884     }
8885 
8886     if (isEqualOp) {
8887       for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
8888         // Make sure we don't add the same candidate twice.
8889         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
8890           continue;
8891 
8892         QualType ParamTypes[2] = {
8893             S.Context.getLValueReferenceType(PtrTy),
8894             PtrTy,
8895         };
8896 
8897         // non-volatile version
8898         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8899                               /*IsAssignmentOperator=*/true);
8900 
8901         bool NeedVolatile = !PtrTy.isVolatileQualified() &&
8902                             VisibleTypeConversionsQuals.hasVolatile();
8903         if (NeedVolatile) {
8904           // volatile version
8905           ParamTypes[0] = S.Context.getLValueReferenceType(
8906               S.Context.getVolatileType(PtrTy));
8907           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8908                                 /*IsAssignmentOperator=*/true);
8909         }
8910 
8911         if (!PtrTy.isRestrictQualified() &&
8912             VisibleTypeConversionsQuals.hasRestrict()) {
8913           // restrict version
8914           ParamTypes[0] = S.Context.getLValueReferenceType(
8915               S.Context.getRestrictType(PtrTy));
8916           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8917                                 /*IsAssignmentOperator=*/true);
8918 
8919           if (NeedVolatile) {
8920             // volatile restrict version
8921             ParamTypes[0] =
8922                 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
8923                     PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
8924             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8925                                   /*IsAssignmentOperator=*/true);
8926           }
8927         }
8928       }
8929     }
8930   }
8931 
8932   // C++ [over.built]p18:
8933   //
8934   //   For every triple (L, VQ, R), where L is an arithmetic type,
8935   //   VQ is either volatile or empty, and R is a promoted
8936   //   arithmetic type, there exist candidate operator functions of
8937   //   the form
8938   //
8939   //        VQ L&      operator=(VQ L&, R);
8940   //        VQ L&      operator*=(VQ L&, R);
8941   //        VQ L&      operator/=(VQ L&, R);
8942   //        VQ L&      operator+=(VQ L&, R);
8943   //        VQ L&      operator-=(VQ L&, R);
8944   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8945     if (!HasArithmeticOrEnumeralCandidateType)
8946       return;
8947 
8948     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8949       for (unsigned Right = FirstPromotedArithmeticType;
8950            Right < LastPromotedArithmeticType; ++Right) {
8951         QualType ParamTypes[2];
8952         ParamTypes[1] = ArithmeticTypes[Right];
8953         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8954             S, ArithmeticTypes[Left], Args[0]);
8955         // Add this built-in operator as a candidate (VQ is empty).
8956         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8957         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8958                               /*IsAssignmentOperator=*/isEqualOp);
8959 
8960         // Add this built-in operator as a candidate (VQ is 'volatile').
8961         if (VisibleTypeConversionsQuals.hasVolatile()) {
8962           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8963           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8964           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8965                                 /*IsAssignmentOperator=*/isEqualOp);
8966         }
8967       }
8968     }
8969 
8970     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8971     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8972       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8973         QualType ParamTypes[2];
8974         ParamTypes[1] = Vec2Ty;
8975         // Add this built-in operator as a candidate (VQ is empty).
8976         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8977         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8978                               /*IsAssignmentOperator=*/isEqualOp);
8979 
8980         // Add this built-in operator as a candidate (VQ is 'volatile').
8981         if (VisibleTypeConversionsQuals.hasVolatile()) {
8982           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8983           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8984           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8985                                 /*IsAssignmentOperator=*/isEqualOp);
8986         }
8987       }
8988   }
8989 
8990   // C++ [over.built]p22:
8991   //
8992   //   For every triple (L, VQ, R), where L is an integral type, VQ
8993   //   is either volatile or empty, and R is a promoted integral
8994   //   type, there exist candidate operator functions of the form
8995   //
8996   //        VQ L&       operator%=(VQ L&, R);
8997   //        VQ L&       operator<<=(VQ L&, R);
8998   //        VQ L&       operator>>=(VQ L&, R);
8999   //        VQ L&       operator&=(VQ L&, R);
9000   //        VQ L&       operator^=(VQ L&, R);
9001   //        VQ L&       operator|=(VQ L&, R);
9002   void addAssignmentIntegralOverloads() {
9003     if (!HasArithmeticOrEnumeralCandidateType)
9004       return;
9005 
9006     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9007       for (unsigned Right = FirstPromotedIntegralType;
9008            Right < LastPromotedIntegralType; ++Right) {
9009         QualType ParamTypes[2];
9010         ParamTypes[1] = ArithmeticTypes[Right];
9011         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9012             S, ArithmeticTypes[Left], Args[0]);
9013         // Add this built-in operator as a candidate (VQ is empty).
9014         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
9015         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9016         if (VisibleTypeConversionsQuals.hasVolatile()) {
9017           // Add this built-in operator as a candidate (VQ is 'volatile').
9018           ParamTypes[0] = LeftBaseTy;
9019           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
9020           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9021           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9022         }
9023       }
9024     }
9025   }
9026 
9027   // C++ [over.operator]p23:
9028   //
9029   //   There also exist candidate operator functions of the form
9030   //
9031   //        bool        operator!(bool);
9032   //        bool        operator&&(bool, bool);
9033   //        bool        operator||(bool, bool);
9034   void addExclaimOverload() {
9035     QualType ParamTy = S.Context.BoolTy;
9036     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9037                           /*IsAssignmentOperator=*/false,
9038                           /*NumContextualBoolArguments=*/1);
9039   }
9040   void addAmpAmpOrPipePipeOverload() {
9041     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9042     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9043                           /*IsAssignmentOperator=*/false,
9044                           /*NumContextualBoolArguments=*/2);
9045   }
9046 
9047   // C++ [over.built]p13:
9048   //
9049   //   For every cv-qualified or cv-unqualified object type T there
9050   //   exist candidate operator functions of the form
9051   //
9052   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
9053   //        T&         operator[](T*, ptrdiff_t);
9054   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
9055   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
9056   //        T&         operator[](ptrdiff_t, T*);
9057   void addSubscriptOverloads() {
9058     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9059       QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9060       QualType PointeeType = PtrTy->getPointeeType();
9061       if (!PointeeType->isObjectType())
9062         continue;
9063 
9064       // T& operator[](T*, ptrdiff_t)
9065       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9066     }
9067 
9068     for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9069       QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9070       QualType PointeeType = PtrTy->getPointeeType();
9071       if (!PointeeType->isObjectType())
9072         continue;
9073 
9074       // T& operator[](ptrdiff_t, T*)
9075       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9076     }
9077   }
9078 
9079   // C++ [over.built]p11:
9080   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9081   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9082   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9083   //    there exist candidate operator functions of the form
9084   //
9085   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9086   //
9087   //    where CV12 is the union of CV1 and CV2.
9088   void addArrowStarOverloads() {
9089     for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9090       QualType C1Ty = PtrTy;
9091       QualType C1;
9092       QualifierCollector Q1;
9093       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9094       if (!isa<RecordType>(C1))
9095         continue;
9096       // heuristic to reduce number of builtin candidates in the set.
9097       // Add volatile/restrict version only if there are conversions to a
9098       // volatile/restrict type.
9099       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9100         continue;
9101       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9102         continue;
9103       for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9104         const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9105         QualType C2 = QualType(mptr->getClass(), 0);
9106         C2 = C2.getUnqualifiedType();
9107         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9108           break;
9109         QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9110         // build CV12 T&
9111         QualType T = mptr->getPointeeType();
9112         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9113             T.isVolatileQualified())
9114           continue;
9115         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9116             T.isRestrictQualified())
9117           continue;
9118         T = Q1.apply(S.Context, T);
9119         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9120       }
9121     }
9122   }
9123 
9124   // Note that we don't consider the first argument, since it has been
9125   // contextually converted to bool long ago. The candidates below are
9126   // therefore added as binary.
9127   //
9128   // C++ [over.built]p25:
9129   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9130   //   enumeration type, there exist candidate operator functions of the form
9131   //
9132   //        T        operator?(bool, T, T);
9133   //
9134   void addConditionalOperatorOverloads() {
9135     /// Set of (canonical) types that we've already handled.
9136     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9137 
9138     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9139       for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9140         if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9141           continue;
9142 
9143         QualType ParamTypes[2] = {PtrTy, PtrTy};
9144         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9145       }
9146 
9147       for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9148         if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9149           continue;
9150 
9151         QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9152         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9153       }
9154 
9155       if (S.getLangOpts().CPlusPlus11) {
9156         for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9157           if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9158             continue;
9159 
9160           if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9161             continue;
9162 
9163           QualType ParamTypes[2] = {EnumTy, EnumTy};
9164           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9165         }
9166       }
9167     }
9168   }
9169 };
9170 
9171 } // end anonymous namespace
9172 
9173 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9174 /// operator overloads to the candidate set (C++ [over.built]), based
9175 /// on the operator @p Op and the arguments given. For example, if the
9176 /// operator is a binary '+', this routine might add "int
9177 /// operator+(int, int)" to cover integer addition.
9178 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9179                                         SourceLocation OpLoc,
9180                                         ArrayRef<Expr *> Args,
9181                                         OverloadCandidateSet &CandidateSet) {
9182   // Find all of the types that the arguments can convert to, but only
9183   // if the operator we're looking at has built-in operator candidates
9184   // that make use of these types. Also record whether we encounter non-record
9185   // candidate types or either arithmetic or enumeral candidate types.
9186   Qualifiers VisibleTypeConversionsQuals;
9187   VisibleTypeConversionsQuals.addConst();
9188   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9189     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9190 
9191   bool HasNonRecordCandidateType = false;
9192   bool HasArithmeticOrEnumeralCandidateType = false;
9193   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9194   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9195     CandidateTypes.emplace_back(*this);
9196     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9197                                                  OpLoc,
9198                                                  true,
9199                                                  (Op == OO_Exclaim ||
9200                                                   Op == OO_AmpAmp ||
9201                                                   Op == OO_PipePipe),
9202                                                  VisibleTypeConversionsQuals);
9203     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9204         CandidateTypes[ArgIdx].hasNonRecordTypes();
9205     HasArithmeticOrEnumeralCandidateType =
9206         HasArithmeticOrEnumeralCandidateType ||
9207         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9208   }
9209 
9210   // Exit early when no non-record types have been added to the candidate set
9211   // for any of the arguments to the operator.
9212   //
9213   // We can't exit early for !, ||, or &&, since there we have always have
9214   // 'bool' overloads.
9215   if (!HasNonRecordCandidateType &&
9216       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9217     return;
9218 
9219   // Setup an object to manage the common state for building overloads.
9220   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9221                                            VisibleTypeConversionsQuals,
9222                                            HasArithmeticOrEnumeralCandidateType,
9223                                            CandidateTypes, CandidateSet);
9224 
9225   // Dispatch over the operation to add in only those overloads which apply.
9226   switch (Op) {
9227   case OO_None:
9228   case NUM_OVERLOADED_OPERATORS:
9229     llvm_unreachable("Expected an overloaded operator");
9230 
9231   case OO_New:
9232   case OO_Delete:
9233   case OO_Array_New:
9234   case OO_Array_Delete:
9235   case OO_Call:
9236     llvm_unreachable(
9237                     "Special operators don't use AddBuiltinOperatorCandidates");
9238 
9239   case OO_Comma:
9240   case OO_Arrow:
9241   case OO_Coawait:
9242     // C++ [over.match.oper]p3:
9243     //   -- For the operator ',', the unary operator '&', the
9244     //      operator '->', or the operator 'co_await', the
9245     //      built-in candidates set is empty.
9246     break;
9247 
9248   case OO_Plus: // '+' is either unary or binary
9249     if (Args.size() == 1)
9250       OpBuilder.addUnaryPlusPointerOverloads();
9251     LLVM_FALLTHROUGH;
9252 
9253   case OO_Minus: // '-' is either unary or binary
9254     if (Args.size() == 1) {
9255       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9256     } else {
9257       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9258       OpBuilder.addGenericBinaryArithmeticOverloads();
9259       OpBuilder.addMatrixBinaryArithmeticOverloads();
9260     }
9261     break;
9262 
9263   case OO_Star: // '*' is either unary or binary
9264     if (Args.size() == 1)
9265       OpBuilder.addUnaryStarPointerOverloads();
9266     else {
9267       OpBuilder.addGenericBinaryArithmeticOverloads();
9268       OpBuilder.addMatrixBinaryArithmeticOverloads();
9269     }
9270     break;
9271 
9272   case OO_Slash:
9273     OpBuilder.addGenericBinaryArithmeticOverloads();
9274     break;
9275 
9276   case OO_PlusPlus:
9277   case OO_MinusMinus:
9278     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9279     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9280     break;
9281 
9282   case OO_EqualEqual:
9283   case OO_ExclaimEqual:
9284     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9285     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9286     OpBuilder.addGenericBinaryArithmeticOverloads();
9287     break;
9288 
9289   case OO_Less:
9290   case OO_Greater:
9291   case OO_LessEqual:
9292   case OO_GreaterEqual:
9293     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9294     OpBuilder.addGenericBinaryArithmeticOverloads();
9295     break;
9296 
9297   case OO_Spaceship:
9298     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9299     OpBuilder.addThreeWayArithmeticOverloads();
9300     break;
9301 
9302   case OO_Percent:
9303   case OO_Caret:
9304   case OO_Pipe:
9305   case OO_LessLess:
9306   case OO_GreaterGreater:
9307     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9308     break;
9309 
9310   case OO_Amp: // '&' is either unary or binary
9311     if (Args.size() == 1)
9312       // C++ [over.match.oper]p3:
9313       //   -- For the operator ',', the unary operator '&', or the
9314       //      operator '->', the built-in candidates set is empty.
9315       break;
9316 
9317     OpBuilder.addBinaryBitwiseArithmeticOverloads();
9318     break;
9319 
9320   case OO_Tilde:
9321     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9322     break;
9323 
9324   case OO_Equal:
9325     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9326     LLVM_FALLTHROUGH;
9327 
9328   case OO_PlusEqual:
9329   case OO_MinusEqual:
9330     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9331     LLVM_FALLTHROUGH;
9332 
9333   case OO_StarEqual:
9334   case OO_SlashEqual:
9335     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9336     break;
9337 
9338   case OO_PercentEqual:
9339   case OO_LessLessEqual:
9340   case OO_GreaterGreaterEqual:
9341   case OO_AmpEqual:
9342   case OO_CaretEqual:
9343   case OO_PipeEqual:
9344     OpBuilder.addAssignmentIntegralOverloads();
9345     break;
9346 
9347   case OO_Exclaim:
9348     OpBuilder.addExclaimOverload();
9349     break;
9350 
9351   case OO_AmpAmp:
9352   case OO_PipePipe:
9353     OpBuilder.addAmpAmpOrPipePipeOverload();
9354     break;
9355 
9356   case OO_Subscript:
9357     OpBuilder.addSubscriptOverloads();
9358     break;
9359 
9360   case OO_ArrowStar:
9361     OpBuilder.addArrowStarOverloads();
9362     break;
9363 
9364   case OO_Conditional:
9365     OpBuilder.addConditionalOperatorOverloads();
9366     OpBuilder.addGenericBinaryArithmeticOverloads();
9367     break;
9368   }
9369 }
9370 
9371 /// Add function candidates found via argument-dependent lookup
9372 /// to the set of overloading candidates.
9373 ///
9374 /// This routine performs argument-dependent name lookup based on the
9375 /// given function name (which may also be an operator name) and adds
9376 /// all of the overload candidates found by ADL to the overload
9377 /// candidate set (C++ [basic.lookup.argdep]).
9378 void
9379 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9380                                            SourceLocation Loc,
9381                                            ArrayRef<Expr *> Args,
9382                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9383                                            OverloadCandidateSet& CandidateSet,
9384                                            bool PartialOverloading) {
9385   ADLResult Fns;
9386 
9387   // FIXME: This approach for uniquing ADL results (and removing
9388   // redundant candidates from the set) relies on pointer-equality,
9389   // which means we need to key off the canonical decl.  However,
9390   // always going back to the canonical decl might not get us the
9391   // right set of default arguments.  What default arguments are
9392   // we supposed to consider on ADL candidates, anyway?
9393 
9394   // FIXME: Pass in the explicit template arguments?
9395   ArgumentDependentLookup(Name, Loc, Args, Fns);
9396 
9397   // Erase all of the candidates we already knew about.
9398   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9399                                    CandEnd = CandidateSet.end();
9400        Cand != CandEnd; ++Cand)
9401     if (Cand->Function) {
9402       Fns.erase(Cand->Function);
9403       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9404         Fns.erase(FunTmpl);
9405     }
9406 
9407   // For each of the ADL candidates we found, add it to the overload
9408   // set.
9409   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9410     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9411 
9412     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9413       if (ExplicitTemplateArgs)
9414         continue;
9415 
9416       AddOverloadCandidate(
9417           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9418           PartialOverloading, /*AllowExplicit=*/true,
9419           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9420       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9421         AddOverloadCandidate(
9422             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9423             /*SuppressUserConversions=*/false, PartialOverloading,
9424             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9425             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9426       }
9427     } else {
9428       auto *FTD = cast<FunctionTemplateDecl>(*I);
9429       AddTemplateOverloadCandidate(
9430           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9431           /*SuppressUserConversions=*/false, PartialOverloading,
9432           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9433       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9434               Context, FTD->getTemplatedDecl())) {
9435         AddTemplateOverloadCandidate(
9436             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9437             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9438             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9439             OverloadCandidateParamOrder::Reversed);
9440       }
9441     }
9442   }
9443 }
9444 
9445 namespace {
9446 enum class Comparison { Equal, Better, Worse };
9447 }
9448 
9449 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9450 /// overload resolution.
9451 ///
9452 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9453 /// Cand1's first N enable_if attributes have precisely the same conditions as
9454 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9455 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9456 ///
9457 /// Note that you can have a pair of candidates such that Cand1's enable_if
9458 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9459 /// worse than Cand1's.
9460 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9461                                        const FunctionDecl *Cand2) {
9462   // Common case: One (or both) decls don't have enable_if attrs.
9463   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9464   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9465   if (!Cand1Attr || !Cand2Attr) {
9466     if (Cand1Attr == Cand2Attr)
9467       return Comparison::Equal;
9468     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9469   }
9470 
9471   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9472   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9473 
9474   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9475   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9476     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9477     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9478 
9479     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9480     // has fewer enable_if attributes than Cand2, and vice versa.
9481     if (!Cand1A)
9482       return Comparison::Worse;
9483     if (!Cand2A)
9484       return Comparison::Better;
9485 
9486     Cand1ID.clear();
9487     Cand2ID.clear();
9488 
9489     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9490     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9491     if (Cand1ID != Cand2ID)
9492       return Comparison::Worse;
9493   }
9494 
9495   return Comparison::Equal;
9496 }
9497 
9498 static Comparison
9499 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9500                               const OverloadCandidate &Cand2) {
9501   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9502       !Cand2.Function->isMultiVersion())
9503     return Comparison::Equal;
9504 
9505   // If both are invalid, they are equal. If one of them is invalid, the other
9506   // is better.
9507   if (Cand1.Function->isInvalidDecl()) {
9508     if (Cand2.Function->isInvalidDecl())
9509       return Comparison::Equal;
9510     return Comparison::Worse;
9511   }
9512   if (Cand2.Function->isInvalidDecl())
9513     return Comparison::Better;
9514 
9515   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9516   // cpu_dispatch, else arbitrarily based on the identifiers.
9517   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9518   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9519   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9520   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9521 
9522   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9523     return Comparison::Equal;
9524 
9525   if (Cand1CPUDisp && !Cand2CPUDisp)
9526     return Comparison::Better;
9527   if (Cand2CPUDisp && !Cand1CPUDisp)
9528     return Comparison::Worse;
9529 
9530   if (Cand1CPUSpec && Cand2CPUSpec) {
9531     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9532       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9533                  ? Comparison::Better
9534                  : Comparison::Worse;
9535 
9536     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9537         FirstDiff = std::mismatch(
9538             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9539             Cand2CPUSpec->cpus_begin(),
9540             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9541               return LHS->getName() == RHS->getName();
9542             });
9543 
9544     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9545            "Two different cpu-specific versions should not have the same "
9546            "identifier list, otherwise they'd be the same decl!");
9547     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9548                ? Comparison::Better
9549                : Comparison::Worse;
9550   }
9551   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9552 }
9553 
9554 /// Compute the type of the implicit object parameter for the given function,
9555 /// if any. Returns None if there is no implicit object parameter, and a null
9556 /// QualType if there is a 'matches anything' implicit object parameter.
9557 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9558                                                      const FunctionDecl *F) {
9559   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9560     return llvm::None;
9561 
9562   auto *M = cast<CXXMethodDecl>(F);
9563   // Static member functions' object parameters match all types.
9564   if (M->isStatic())
9565     return QualType();
9566 
9567   QualType T = M->getThisObjectType();
9568   if (M->getRefQualifier() == RQ_RValue)
9569     return Context.getRValueReferenceType(T);
9570   return Context.getLValueReferenceType(T);
9571 }
9572 
9573 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9574                                    const FunctionDecl *F2, unsigned NumParams) {
9575   if (declaresSameEntity(F1, F2))
9576     return true;
9577 
9578   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9579     if (First) {
9580       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9581         return *T;
9582     }
9583     assert(I < F->getNumParams());
9584     return F->getParamDecl(I++)->getType();
9585   };
9586 
9587   unsigned I1 = 0, I2 = 0;
9588   for (unsigned I = 0; I != NumParams; ++I) {
9589     QualType T1 = NextParam(F1, I1, I == 0);
9590     QualType T2 = NextParam(F2, I2, I == 0);
9591     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9592       return false;
9593   }
9594   return true;
9595 }
9596 
9597 /// isBetterOverloadCandidate - Determines whether the first overload
9598 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9599 bool clang::isBetterOverloadCandidate(
9600     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9601     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9602   // Define viable functions to be better candidates than non-viable
9603   // functions.
9604   if (!Cand2.Viable)
9605     return Cand1.Viable;
9606   else if (!Cand1.Viable)
9607     return false;
9608 
9609   // [CUDA] A function with 'never' preference is marked not viable, therefore
9610   // is never shown up here. The worst preference shown up here is 'wrong side',
9611   // e.g. an H function called by a HD function in device compilation. This is
9612   // valid AST as long as the HD function is not emitted, e.g. it is an inline
9613   // function which is called only by an H function. A deferred diagnostic will
9614   // be triggered if it is emitted. However a wrong-sided function is still
9615   // a viable candidate here.
9616   //
9617   // If Cand1 can be emitted and Cand2 cannot be emitted in the current
9618   // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
9619   // can be emitted, Cand1 is not better than Cand2. This rule should have
9620   // precedence over other rules.
9621   //
9622   // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
9623   // other rules should be used to determine which is better. This is because
9624   // host/device based overloading resolution is mostly for determining
9625   // viability of a function. If two functions are both viable, other factors
9626   // should take precedence in preference, e.g. the standard-defined preferences
9627   // like argument conversion ranks or enable_if partial-ordering. The
9628   // preference for pass-object-size parameters is probably most similar to a
9629   // type-based-overloading decision and so should take priority.
9630   //
9631   // If other rules cannot determine which is better, CUDA preference will be
9632   // used again to determine which is better.
9633   //
9634   // TODO: Currently IdentifyCUDAPreference does not return correct values
9635   // for functions called in global variable initializers due to missing
9636   // correct context about device/host. Therefore we can only enforce this
9637   // rule when there is a caller. We should enforce this rule for functions
9638   // in global variable initializers once proper context is added.
9639   //
9640   // TODO: We can only enable the hostness based overloading resolution when
9641   // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
9642   // overloading resolution diagnostics.
9643   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
9644       S.getLangOpts().GPUExcludeWrongSideOverloads) {
9645     if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) {
9646       bool IsCallerImplicitHD = Sema::isCUDAImplicitHostDeviceFunction(Caller);
9647       bool IsCand1ImplicitHD =
9648           Sema::isCUDAImplicitHostDeviceFunction(Cand1.Function);
9649       bool IsCand2ImplicitHD =
9650           Sema::isCUDAImplicitHostDeviceFunction(Cand2.Function);
9651       auto P1 = S.IdentifyCUDAPreference(Caller, Cand1.Function);
9652       auto P2 = S.IdentifyCUDAPreference(Caller, Cand2.Function);
9653       assert(P1 != Sema::CFP_Never && P2 != Sema::CFP_Never);
9654       // The implicit HD function may be a function in a system header which
9655       // is forced by pragma. In device compilation, if we prefer HD candidates
9656       // over wrong-sided candidates, overloading resolution may change, which
9657       // may result in non-deferrable diagnostics. As a workaround, we let
9658       // implicit HD candidates take equal preference as wrong-sided candidates.
9659       // This will preserve the overloading resolution.
9660       // TODO: We still need special handling of implicit HD functions since
9661       // they may incur other diagnostics to be deferred. We should make all
9662       // host/device related diagnostics deferrable and remove special handling
9663       // of implicit HD functions.
9664       auto EmitThreshold =
9665           (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
9666            (IsCand1ImplicitHD || IsCand2ImplicitHD))
9667               ? Sema::CFP_Never
9668               : Sema::CFP_WrongSide;
9669       auto Cand1Emittable = P1 > EmitThreshold;
9670       auto Cand2Emittable = P2 > EmitThreshold;
9671       if (Cand1Emittable && !Cand2Emittable)
9672         return true;
9673       if (!Cand1Emittable && Cand2Emittable)
9674         return false;
9675     }
9676   }
9677 
9678   // C++ [over.match.best]p1:
9679   //
9680   //   -- if F is a static member function, ICS1(F) is defined such
9681   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9682   //      any function G, and, symmetrically, ICS1(G) is neither
9683   //      better nor worse than ICS1(F).
9684   unsigned StartArg = 0;
9685   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9686     StartArg = 1;
9687 
9688   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9689     // We don't allow incompatible pointer conversions in C++.
9690     if (!S.getLangOpts().CPlusPlus)
9691       return ICS.isStandard() &&
9692              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9693 
9694     // The only ill-formed conversion we allow in C++ is the string literal to
9695     // char* conversion, which is only considered ill-formed after C++11.
9696     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9697            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9698   };
9699 
9700   // Define functions that don't require ill-formed conversions for a given
9701   // argument to be better candidates than functions that do.
9702   unsigned NumArgs = Cand1.Conversions.size();
9703   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9704   bool HasBetterConversion = false;
9705   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9706     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9707     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9708     if (Cand1Bad != Cand2Bad) {
9709       if (Cand1Bad)
9710         return false;
9711       HasBetterConversion = true;
9712     }
9713   }
9714 
9715   if (HasBetterConversion)
9716     return true;
9717 
9718   // C++ [over.match.best]p1:
9719   //   A viable function F1 is defined to be a better function than another
9720   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9721   //   conversion sequence than ICSi(F2), and then...
9722   bool HasWorseConversion = false;
9723   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9724     switch (CompareImplicitConversionSequences(S, Loc,
9725                                                Cand1.Conversions[ArgIdx],
9726                                                Cand2.Conversions[ArgIdx])) {
9727     case ImplicitConversionSequence::Better:
9728       // Cand1 has a better conversion sequence.
9729       HasBetterConversion = true;
9730       break;
9731 
9732     case ImplicitConversionSequence::Worse:
9733       if (Cand1.Function && Cand2.Function &&
9734           Cand1.isReversed() != Cand2.isReversed() &&
9735           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9736                                  NumArgs)) {
9737         // Work around large-scale breakage caused by considering reversed
9738         // forms of operator== in C++20:
9739         //
9740         // When comparing a function against a reversed function with the same
9741         // parameter types, if we have a better conversion for one argument and
9742         // a worse conversion for the other, the implicit conversion sequences
9743         // are treated as being equally good.
9744         //
9745         // This prevents a comparison function from being considered ambiguous
9746         // with a reversed form that is written in the same way.
9747         //
9748         // We diagnose this as an extension from CreateOverloadedBinOp.
9749         HasWorseConversion = true;
9750         break;
9751       }
9752 
9753       // Cand1 can't be better than Cand2.
9754       return false;
9755 
9756     case ImplicitConversionSequence::Indistinguishable:
9757       // Do nothing.
9758       break;
9759     }
9760   }
9761 
9762   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9763   //       ICSj(F2), or, if not that,
9764   if (HasBetterConversion && !HasWorseConversion)
9765     return true;
9766 
9767   //   -- the context is an initialization by user-defined conversion
9768   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9769   //      from the return type of F1 to the destination type (i.e.,
9770   //      the type of the entity being initialized) is a better
9771   //      conversion sequence than the standard conversion sequence
9772   //      from the return type of F2 to the destination type.
9773   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9774       Cand1.Function && Cand2.Function &&
9775       isa<CXXConversionDecl>(Cand1.Function) &&
9776       isa<CXXConversionDecl>(Cand2.Function)) {
9777     // First check whether we prefer one of the conversion functions over the
9778     // other. This only distinguishes the results in non-standard, extension
9779     // cases such as the conversion from a lambda closure type to a function
9780     // pointer or block.
9781     ImplicitConversionSequence::CompareKind Result =
9782         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9783     if (Result == ImplicitConversionSequence::Indistinguishable)
9784       Result = CompareStandardConversionSequences(S, Loc,
9785                                                   Cand1.FinalConversion,
9786                                                   Cand2.FinalConversion);
9787 
9788     if (Result != ImplicitConversionSequence::Indistinguishable)
9789       return Result == ImplicitConversionSequence::Better;
9790 
9791     // FIXME: Compare kind of reference binding if conversion functions
9792     // convert to a reference type used in direct reference binding, per
9793     // C++14 [over.match.best]p1 section 2 bullet 3.
9794   }
9795 
9796   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9797   // as combined with the resolution to CWG issue 243.
9798   //
9799   // When the context is initialization by constructor ([over.match.ctor] or
9800   // either phase of [over.match.list]), a constructor is preferred over
9801   // a conversion function.
9802   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9803       Cand1.Function && Cand2.Function &&
9804       isa<CXXConstructorDecl>(Cand1.Function) !=
9805           isa<CXXConstructorDecl>(Cand2.Function))
9806     return isa<CXXConstructorDecl>(Cand1.Function);
9807 
9808   //    -- F1 is a non-template function and F2 is a function template
9809   //       specialization, or, if not that,
9810   bool Cand1IsSpecialization = Cand1.Function &&
9811                                Cand1.Function->getPrimaryTemplate();
9812   bool Cand2IsSpecialization = Cand2.Function &&
9813                                Cand2.Function->getPrimaryTemplate();
9814   if (Cand1IsSpecialization != Cand2IsSpecialization)
9815     return Cand2IsSpecialization;
9816 
9817   //   -- F1 and F2 are function template specializations, and the function
9818   //      template for F1 is more specialized than the template for F2
9819   //      according to the partial ordering rules described in 14.5.5.2, or,
9820   //      if not that,
9821   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9822     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9823             Cand1.Function->getPrimaryTemplate(),
9824             Cand2.Function->getPrimaryTemplate(), Loc,
9825             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9826                                                    : TPOC_Call,
9827             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9828             Cand1.isReversed() ^ Cand2.isReversed()))
9829       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9830   }
9831 
9832   //   -— F1 and F2 are non-template functions with the same
9833   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9834   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9835       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9836       Cand2.Function->hasPrototype()) {
9837     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9838     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9839     if (PT1->getNumParams() == PT2->getNumParams() &&
9840         PT1->isVariadic() == PT2->isVariadic() &&
9841         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9842       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9843       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9844       if (RC1 && RC2) {
9845         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9846         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9847                                      {RC2}, AtLeastAsConstrained1) ||
9848             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9849                                      {RC1}, AtLeastAsConstrained2))
9850           return false;
9851         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9852           return AtLeastAsConstrained1;
9853       } else if (RC1 || RC2) {
9854         return RC1 != nullptr;
9855       }
9856     }
9857   }
9858 
9859   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9860   //      class B of D, and for all arguments the corresponding parameters of
9861   //      F1 and F2 have the same type.
9862   // FIXME: Implement the "all parameters have the same type" check.
9863   bool Cand1IsInherited =
9864       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9865   bool Cand2IsInherited =
9866       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9867   if (Cand1IsInherited != Cand2IsInherited)
9868     return Cand2IsInherited;
9869   else if (Cand1IsInherited) {
9870     assert(Cand2IsInherited);
9871     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9872     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9873     if (Cand1Class->isDerivedFrom(Cand2Class))
9874       return true;
9875     if (Cand2Class->isDerivedFrom(Cand1Class))
9876       return false;
9877     // Inherited from sibling base classes: still ambiguous.
9878   }
9879 
9880   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9881   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9882   //      with reversed order of parameters and F1 is not
9883   //
9884   // We rank reversed + different operator as worse than just reversed, but
9885   // that comparison can never happen, because we only consider reversing for
9886   // the maximally-rewritten operator (== or <=>).
9887   if (Cand1.RewriteKind != Cand2.RewriteKind)
9888     return Cand1.RewriteKind < Cand2.RewriteKind;
9889 
9890   // Check C++17 tie-breakers for deduction guides.
9891   {
9892     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9893     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9894     if (Guide1 && Guide2) {
9895       //  -- F1 is generated from a deduction-guide and F2 is not
9896       if (Guide1->isImplicit() != Guide2->isImplicit())
9897         return Guide2->isImplicit();
9898 
9899       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9900       if (Guide1->isCopyDeductionCandidate())
9901         return true;
9902     }
9903   }
9904 
9905   // Check for enable_if value-based overload resolution.
9906   if (Cand1.Function && Cand2.Function) {
9907     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9908     if (Cmp != Comparison::Equal)
9909       return Cmp == Comparison::Better;
9910   }
9911 
9912   bool HasPS1 = Cand1.Function != nullptr &&
9913                 functionHasPassObjectSizeParams(Cand1.Function);
9914   bool HasPS2 = Cand2.Function != nullptr &&
9915                 functionHasPassObjectSizeParams(Cand2.Function);
9916   if (HasPS1 != HasPS2 && HasPS1)
9917     return true;
9918 
9919   auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
9920   if (MV == Comparison::Better)
9921     return true;
9922   if (MV == Comparison::Worse)
9923     return false;
9924 
9925   // If other rules cannot determine which is better, CUDA preference is used
9926   // to determine which is better.
9927   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9928     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9929     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9930            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9931   }
9932 
9933   // General member function overloading is handled above, so this only handles
9934   // constructors with address spaces.
9935   // This only handles address spaces since C++ has no other
9936   // qualifier that can be used with constructors.
9937   const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
9938   const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
9939   if (CD1 && CD2) {
9940     LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
9941     LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
9942     if (AS1 != AS2) {
9943       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9944         return true;
9945       if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1))
9946         return false;
9947     }
9948   }
9949 
9950   return false;
9951 }
9952 
9953 /// Determine whether two declarations are "equivalent" for the purposes of
9954 /// name lookup and overload resolution. This applies when the same internal/no
9955 /// linkage entity is defined by two modules (probably by textually including
9956 /// the same header). In such a case, we don't consider the declarations to
9957 /// declare the same entity, but we also don't want lookups with both
9958 /// declarations visible to be ambiguous in some cases (this happens when using
9959 /// a modularized libstdc++).
9960 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9961                                                   const NamedDecl *B) {
9962   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9963   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9964   if (!VA || !VB)
9965     return false;
9966 
9967   // The declarations must be declaring the same name as an internal linkage
9968   // entity in different modules.
9969   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9970           VB->getDeclContext()->getRedeclContext()) ||
9971       getOwningModule(VA) == getOwningModule(VB) ||
9972       VA->isExternallyVisible() || VB->isExternallyVisible())
9973     return false;
9974 
9975   // Check that the declarations appear to be equivalent.
9976   //
9977   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9978   // For constants and functions, we should check the initializer or body is
9979   // the same. For non-constant variables, we shouldn't allow it at all.
9980   if (Context.hasSameType(VA->getType(), VB->getType()))
9981     return true;
9982 
9983   // Enum constants within unnamed enumerations will have different types, but
9984   // may still be similar enough to be interchangeable for our purposes.
9985   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9986     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9987       // Only handle anonymous enums. If the enumerations were named and
9988       // equivalent, they would have been merged to the same type.
9989       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9990       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9991       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9992           !Context.hasSameType(EnumA->getIntegerType(),
9993                                EnumB->getIntegerType()))
9994         return false;
9995       // Allow this only if the value is the same for both enumerators.
9996       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9997     }
9998   }
9999 
10000   // Nothing else is sufficiently similar.
10001   return false;
10002 }
10003 
10004 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10005     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10006   assert(D && "Unknown declaration");
10007   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10008 
10009   Module *M = getOwningModule(D);
10010   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10011       << !M << (M ? M->getFullModuleName() : "");
10012 
10013   for (auto *E : Equiv) {
10014     Module *M = getOwningModule(E);
10015     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10016         << !M << (M ? M->getFullModuleName() : "");
10017   }
10018 }
10019 
10020 /// Computes the best viable function (C++ 13.3.3)
10021 /// within an overload candidate set.
10022 ///
10023 /// \param Loc The location of the function name (or operator symbol) for
10024 /// which overload resolution occurs.
10025 ///
10026 /// \param Best If overload resolution was successful or found a deleted
10027 /// function, \p Best points to the candidate function found.
10028 ///
10029 /// \returns The result of overload resolution.
10030 OverloadingResult
10031 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10032                                          iterator &Best) {
10033   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10034   std::transform(begin(), end(), std::back_inserter(Candidates),
10035                  [](OverloadCandidate &Cand) { return &Cand; });
10036 
10037   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10038   // are accepted by both clang and NVCC. However, during a particular
10039   // compilation mode only one call variant is viable. We need to
10040   // exclude non-viable overload candidates from consideration based
10041   // only on their host/device attributes. Specifically, if one
10042   // candidate call is WrongSide and the other is SameSide, we ignore
10043   // the WrongSide candidate.
10044   // We only need to remove wrong-sided candidates here if
10045   // -fgpu-exclude-wrong-side-overloads is off. When
10046   // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10047   // uniformly in isBetterOverloadCandidate.
10048   if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10049     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
10050     bool ContainsSameSideCandidate =
10051         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10052           // Check viable function only.
10053           return Cand->Viable && Cand->Function &&
10054                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10055                      Sema::CFP_SameSide;
10056         });
10057     if (ContainsSameSideCandidate) {
10058       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10059         // Check viable function only to avoid unnecessary data copying/moving.
10060         return Cand->Viable && Cand->Function &&
10061                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
10062                    Sema::CFP_WrongSide;
10063       };
10064       llvm::erase_if(Candidates, IsWrongSideCandidate);
10065     }
10066   }
10067 
10068   // Find the best viable function.
10069   Best = end();
10070   for (auto *Cand : Candidates) {
10071     Cand->Best = false;
10072     if (Cand->Viable)
10073       if (Best == end() ||
10074           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10075         Best = Cand;
10076   }
10077 
10078   // If we didn't find any viable functions, abort.
10079   if (Best == end())
10080     return OR_No_Viable_Function;
10081 
10082   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10083 
10084   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10085   PendingBest.push_back(&*Best);
10086   Best->Best = true;
10087 
10088   // Make sure that this function is better than every other viable
10089   // function. If not, we have an ambiguity.
10090   while (!PendingBest.empty()) {
10091     auto *Curr = PendingBest.pop_back_val();
10092     for (auto *Cand : Candidates) {
10093       if (Cand->Viable && !Cand->Best &&
10094           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10095         PendingBest.push_back(Cand);
10096         Cand->Best = true;
10097 
10098         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10099                                                      Curr->Function))
10100           EquivalentCands.push_back(Cand->Function);
10101         else
10102           Best = end();
10103       }
10104     }
10105   }
10106 
10107   // If we found more than one best candidate, this is ambiguous.
10108   if (Best == end())
10109     return OR_Ambiguous;
10110 
10111   // Best is the best viable function.
10112   if (Best->Function && Best->Function->isDeleted())
10113     return OR_Deleted;
10114 
10115   if (!EquivalentCands.empty())
10116     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10117                                                     EquivalentCands);
10118 
10119   return OR_Success;
10120 }
10121 
10122 namespace {
10123 
10124 enum OverloadCandidateKind {
10125   oc_function,
10126   oc_method,
10127   oc_reversed_binary_operator,
10128   oc_constructor,
10129   oc_implicit_default_constructor,
10130   oc_implicit_copy_constructor,
10131   oc_implicit_move_constructor,
10132   oc_implicit_copy_assignment,
10133   oc_implicit_move_assignment,
10134   oc_implicit_equality_comparison,
10135   oc_inherited_constructor
10136 };
10137 
10138 enum OverloadCandidateSelect {
10139   ocs_non_template,
10140   ocs_template,
10141   ocs_described_template,
10142 };
10143 
10144 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10145 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
10146                           OverloadCandidateRewriteKind CRK,
10147                           std::string &Description) {
10148 
10149   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10150   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10151     isTemplate = true;
10152     Description = S.getTemplateArgumentBindingsText(
10153         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10154   }
10155 
10156   OverloadCandidateSelect Select = [&]() {
10157     if (!Description.empty())
10158       return ocs_described_template;
10159     return isTemplate ? ocs_template : ocs_non_template;
10160   }();
10161 
10162   OverloadCandidateKind Kind = [&]() {
10163     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10164       return oc_implicit_equality_comparison;
10165 
10166     if (CRK & CRK_Reversed)
10167       return oc_reversed_binary_operator;
10168 
10169     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10170       if (!Ctor->isImplicit()) {
10171         if (isa<ConstructorUsingShadowDecl>(Found))
10172           return oc_inherited_constructor;
10173         else
10174           return oc_constructor;
10175       }
10176 
10177       if (Ctor->isDefaultConstructor())
10178         return oc_implicit_default_constructor;
10179 
10180       if (Ctor->isMoveConstructor())
10181         return oc_implicit_move_constructor;
10182 
10183       assert(Ctor->isCopyConstructor() &&
10184              "unexpected sort of implicit constructor");
10185       return oc_implicit_copy_constructor;
10186     }
10187 
10188     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10189       // This actually gets spelled 'candidate function' for now, but
10190       // it doesn't hurt to split it out.
10191       if (!Meth->isImplicit())
10192         return oc_method;
10193 
10194       if (Meth->isMoveAssignmentOperator())
10195         return oc_implicit_move_assignment;
10196 
10197       if (Meth->isCopyAssignmentOperator())
10198         return oc_implicit_copy_assignment;
10199 
10200       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10201       return oc_method;
10202     }
10203 
10204     return oc_function;
10205   }();
10206 
10207   return std::make_pair(Kind, Select);
10208 }
10209 
10210 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10211   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10212   // set.
10213   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10214     S.Diag(FoundDecl->getLocation(),
10215            diag::note_ovl_candidate_inherited_constructor)
10216       << Shadow->getNominatedBaseClass();
10217 }
10218 
10219 } // end anonymous namespace
10220 
10221 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10222                                     const FunctionDecl *FD) {
10223   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10224     bool AlwaysTrue;
10225     if (EnableIf->getCond()->isValueDependent() ||
10226         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10227       return false;
10228     if (!AlwaysTrue)
10229       return false;
10230   }
10231   return true;
10232 }
10233 
10234 /// Returns true if we can take the address of the function.
10235 ///
10236 /// \param Complain - If true, we'll emit a diagnostic
10237 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10238 ///   we in overload resolution?
10239 /// \param Loc - The location of the statement we're complaining about. Ignored
10240 ///   if we're not complaining, or if we're in overload resolution.
10241 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10242                                               bool Complain,
10243                                               bool InOverloadResolution,
10244                                               SourceLocation Loc) {
10245   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10246     if (Complain) {
10247       if (InOverloadResolution)
10248         S.Diag(FD->getBeginLoc(),
10249                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10250       else
10251         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10252     }
10253     return false;
10254   }
10255 
10256   if (FD->getTrailingRequiresClause()) {
10257     ConstraintSatisfaction Satisfaction;
10258     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10259       return false;
10260     if (!Satisfaction.IsSatisfied) {
10261       if (Complain) {
10262         if (InOverloadResolution)
10263           S.Diag(FD->getBeginLoc(),
10264                  diag::note_ovl_candidate_unsatisfied_constraints);
10265         else
10266           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10267               << FD;
10268         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10269       }
10270       return false;
10271     }
10272   }
10273 
10274   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10275     return P->hasAttr<PassObjectSizeAttr>();
10276   });
10277   if (I == FD->param_end())
10278     return true;
10279 
10280   if (Complain) {
10281     // Add one to ParamNo because it's user-facing
10282     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10283     if (InOverloadResolution)
10284       S.Diag(FD->getLocation(),
10285              diag::note_ovl_candidate_has_pass_object_size_params)
10286           << ParamNo;
10287     else
10288       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10289           << FD << ParamNo;
10290   }
10291   return false;
10292 }
10293 
10294 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10295                                                const FunctionDecl *FD) {
10296   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10297                                            /*InOverloadResolution=*/true,
10298                                            /*Loc=*/SourceLocation());
10299 }
10300 
10301 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10302                                              bool Complain,
10303                                              SourceLocation Loc) {
10304   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10305                                              /*InOverloadResolution=*/false,
10306                                              Loc);
10307 }
10308 
10309 // Don't print candidates other than the one that matches the calling
10310 // convention of the call operator, since that is guaranteed to exist.
10311 static bool shouldSkipNotingLambdaConversionDecl(FunctionDecl *Fn) {
10312   const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
10313 
10314   if (!ConvD)
10315     return false;
10316   const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
10317   if (!RD->isLambda())
10318     return false;
10319 
10320   CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
10321   CallingConv CallOpCC =
10322       CallOp->getType()->castAs<FunctionType>()->getCallConv();
10323   QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
10324   CallingConv ConvToCC =
10325       ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
10326 
10327   return ConvToCC != CallOpCC;
10328 }
10329 
10330 // Notes the location of an overload candidate.
10331 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10332                                  OverloadCandidateRewriteKind RewriteKind,
10333                                  QualType DestType, bool TakingAddress) {
10334   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10335     return;
10336   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10337       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10338     return;
10339   if (shouldSkipNotingLambdaConversionDecl(Fn))
10340     return;
10341 
10342   std::string FnDesc;
10343   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10344       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10345   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10346                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10347                          << Fn << FnDesc;
10348 
10349   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10350   Diag(Fn->getLocation(), PD);
10351   MaybeEmitInheritedConstructorNote(*this, Found);
10352 }
10353 
10354 static void
10355 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10356   // Perhaps the ambiguity was caused by two atomic constraints that are
10357   // 'identical' but not equivalent:
10358   //
10359   // void foo() requires (sizeof(T) > 4) { } // #1
10360   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10361   //
10362   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10363   // #2 to subsume #1, but these constraint are not considered equivalent
10364   // according to the subsumption rules because they are not the same
10365   // source-level construct. This behavior is quite confusing and we should try
10366   // to help the user figure out what happened.
10367 
10368   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10369   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10370   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10371     if (!I->Function)
10372       continue;
10373     SmallVector<const Expr *, 3> AC;
10374     if (auto *Template = I->Function->getPrimaryTemplate())
10375       Template->getAssociatedConstraints(AC);
10376     else
10377       I->Function->getAssociatedConstraints(AC);
10378     if (AC.empty())
10379       continue;
10380     if (FirstCand == nullptr) {
10381       FirstCand = I->Function;
10382       FirstAC = AC;
10383     } else if (SecondCand == nullptr) {
10384       SecondCand = I->Function;
10385       SecondAC = AC;
10386     } else {
10387       // We have more than one pair of constrained functions - this check is
10388       // expensive and we'd rather not try to diagnose it.
10389       return;
10390     }
10391   }
10392   if (!SecondCand)
10393     return;
10394   // The diagnostic can only happen if there are associated constraints on
10395   // both sides (there needs to be some identical atomic constraint).
10396   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10397                                                       SecondCand, SecondAC))
10398     // Just show the user one diagnostic, they'll probably figure it out
10399     // from here.
10400     return;
10401 }
10402 
10403 // Notes the location of all overload candidates designated through
10404 // OverloadedExpr
10405 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10406                                      bool TakingAddress) {
10407   assert(OverloadedExpr->getType() == Context.OverloadTy);
10408 
10409   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10410   OverloadExpr *OvlExpr = Ovl.Expression;
10411 
10412   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10413                             IEnd = OvlExpr->decls_end();
10414        I != IEnd; ++I) {
10415     if (FunctionTemplateDecl *FunTmpl =
10416                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10417       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10418                             TakingAddress);
10419     } else if (FunctionDecl *Fun
10420                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10421       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10422     }
10423   }
10424 }
10425 
10426 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10427 /// "lead" diagnostic; it will be given two arguments, the source and
10428 /// target types of the conversion.
10429 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10430                                  Sema &S,
10431                                  SourceLocation CaretLoc,
10432                                  const PartialDiagnostic &PDiag) const {
10433   S.Diag(CaretLoc, PDiag)
10434     << Ambiguous.getFromType() << Ambiguous.getToType();
10435   unsigned CandsShown = 0;
10436   AmbiguousConversionSequence::const_iterator I, E;
10437   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10438     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
10439       break;
10440     ++CandsShown;
10441     S.NoteOverloadCandidate(I->first, I->second);
10442   }
10443   S.Diags.overloadCandidatesShown(CandsShown);
10444   if (I != E)
10445     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10446 }
10447 
10448 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10449                                   unsigned I, bool TakingCandidateAddress) {
10450   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10451   assert(Conv.isBad());
10452   assert(Cand->Function && "for now, candidate must be a function");
10453   FunctionDecl *Fn = Cand->Function;
10454 
10455   // There's a conversion slot for the object argument if this is a
10456   // non-constructor method.  Note that 'I' corresponds the
10457   // conversion-slot index.
10458   bool isObjectArgument = false;
10459   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10460     if (I == 0)
10461       isObjectArgument = true;
10462     else
10463       I--;
10464   }
10465 
10466   std::string FnDesc;
10467   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10468       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10469                                 FnDesc);
10470 
10471   Expr *FromExpr = Conv.Bad.FromExpr;
10472   QualType FromTy = Conv.Bad.getFromType();
10473   QualType ToTy = Conv.Bad.getToType();
10474 
10475   if (FromTy == S.Context.OverloadTy) {
10476     assert(FromExpr && "overload set argument came from implicit argument?");
10477     Expr *E = FromExpr->IgnoreParens();
10478     if (isa<UnaryOperator>(E))
10479       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10480     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10481 
10482     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10483         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10484         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10485         << Name << I + 1;
10486     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10487     return;
10488   }
10489 
10490   // Do some hand-waving analysis to see if the non-viability is due
10491   // to a qualifier mismatch.
10492   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10493   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10494   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10495     CToTy = RT->getPointeeType();
10496   else {
10497     // TODO: detect and diagnose the full richness of const mismatches.
10498     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10499       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10500         CFromTy = FromPT->getPointeeType();
10501         CToTy = ToPT->getPointeeType();
10502       }
10503   }
10504 
10505   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10506       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10507     Qualifiers FromQs = CFromTy.getQualifiers();
10508     Qualifiers ToQs = CToTy.getQualifiers();
10509 
10510     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10511       if (isObjectArgument)
10512         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10513             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10514             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10515             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10516       else
10517         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10518             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10519             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10520             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10521             << ToTy->isReferenceType() << I + 1;
10522       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10523       return;
10524     }
10525 
10526     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10527       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10528           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10529           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10530           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10531           << (unsigned)isObjectArgument << I + 1;
10532       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10533       return;
10534     }
10535 
10536     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10537       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10538           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10539           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10540           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10541           << (unsigned)isObjectArgument << I + 1;
10542       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10543       return;
10544     }
10545 
10546     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10547       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10548           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10549           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10550           << FromQs.hasUnaligned() << I + 1;
10551       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10552       return;
10553     }
10554 
10555     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10556     assert(CVR && "expected qualifiers mismatch");
10557 
10558     if (isObjectArgument) {
10559       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10560           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10561           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10562           << (CVR - 1);
10563     } else {
10564       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10565           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10566           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10567           << (CVR - 1) << I + 1;
10568     }
10569     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10570     return;
10571   }
10572 
10573   if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
10574       Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
10575     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
10576         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10577         << (unsigned)isObjectArgument << I + 1
10578         << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
10579         << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10580     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10581     return;
10582   }
10583 
10584   // Special diagnostic for failure to convert an initializer list, since
10585   // telling the user that it has type void is not useful.
10586   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10587     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10588         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10589         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10590         << ToTy << (unsigned)isObjectArgument << I + 1
10591         << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
10592             : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
10593                 ? 2
10594                 : 0);
10595     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10596     return;
10597   }
10598 
10599   // Diagnose references or pointers to incomplete types differently,
10600   // since it's far from impossible that the incompleteness triggered
10601   // the failure.
10602   QualType TempFromTy = FromTy.getNonReferenceType();
10603   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10604     TempFromTy = PTy->getPointeeType();
10605   if (TempFromTy->isIncompleteType()) {
10606     // Emit the generic diagnostic and, optionally, add the hints to it.
10607     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10608         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10609         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10610         << ToTy << (unsigned)isObjectArgument << I + 1
10611         << (unsigned)(Cand->Fix.Kind);
10612 
10613     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10614     return;
10615   }
10616 
10617   // Diagnose base -> derived pointer conversions.
10618   unsigned BaseToDerivedConversion = 0;
10619   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10620     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10621       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10622                                                FromPtrTy->getPointeeType()) &&
10623           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10624           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10625           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10626                           FromPtrTy->getPointeeType()))
10627         BaseToDerivedConversion = 1;
10628     }
10629   } else if (const ObjCObjectPointerType *FromPtrTy
10630                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10631     if (const ObjCObjectPointerType *ToPtrTy
10632                                         = ToTy->getAs<ObjCObjectPointerType>())
10633       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10634         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10635           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10636                                                 FromPtrTy->getPointeeType()) &&
10637               FromIface->isSuperClassOf(ToIface))
10638             BaseToDerivedConversion = 2;
10639   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10640     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10641         !FromTy->isIncompleteType() &&
10642         !ToRefTy->getPointeeType()->isIncompleteType() &&
10643         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10644       BaseToDerivedConversion = 3;
10645     }
10646   }
10647 
10648   if (BaseToDerivedConversion) {
10649     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10650         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10651         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10652         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10653     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10654     return;
10655   }
10656 
10657   if (isa<ObjCObjectPointerType>(CFromTy) &&
10658       isa<PointerType>(CToTy)) {
10659       Qualifiers FromQs = CFromTy.getQualifiers();
10660       Qualifiers ToQs = CToTy.getQualifiers();
10661       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10662         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10663             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10664             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10665             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10666         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10667         return;
10668       }
10669   }
10670 
10671   if (TakingCandidateAddress &&
10672       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10673     return;
10674 
10675   // Emit the generic diagnostic and, optionally, add the hints to it.
10676   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10677   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10678         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10679         << ToTy << (unsigned)isObjectArgument << I + 1
10680         << (unsigned)(Cand->Fix.Kind);
10681 
10682   // If we can fix the conversion, suggest the FixIts.
10683   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10684        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10685     FDiag << *HI;
10686   S.Diag(Fn->getLocation(), FDiag);
10687 
10688   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10689 }
10690 
10691 /// Additional arity mismatch diagnosis specific to a function overload
10692 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10693 /// over a candidate in any candidate set.
10694 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10695                                unsigned NumArgs) {
10696   FunctionDecl *Fn = Cand->Function;
10697   unsigned MinParams = Fn->getMinRequiredArguments();
10698 
10699   // With invalid overloaded operators, it's possible that we think we
10700   // have an arity mismatch when in fact it looks like we have the
10701   // right number of arguments, because only overloaded operators have
10702   // the weird behavior of overloading member and non-member functions.
10703   // Just don't report anything.
10704   if (Fn->isInvalidDecl() &&
10705       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10706     return true;
10707 
10708   if (NumArgs < MinParams) {
10709     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10710            (Cand->FailureKind == ovl_fail_bad_deduction &&
10711             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10712   } else {
10713     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10714            (Cand->FailureKind == ovl_fail_bad_deduction &&
10715             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10716   }
10717 
10718   return false;
10719 }
10720 
10721 /// General arity mismatch diagnosis over a candidate in a candidate set.
10722 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10723                                   unsigned NumFormalArgs) {
10724   assert(isa<FunctionDecl>(D) &&
10725       "The templated declaration should at least be a function"
10726       " when diagnosing bad template argument deduction due to too many"
10727       " or too few arguments");
10728 
10729   FunctionDecl *Fn = cast<FunctionDecl>(D);
10730 
10731   // TODO: treat calls to a missing default constructor as a special case
10732   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10733   unsigned MinParams = Fn->getMinRequiredArguments();
10734 
10735   // at least / at most / exactly
10736   unsigned mode, modeCount;
10737   if (NumFormalArgs < MinParams) {
10738     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10739         FnTy->isTemplateVariadic())
10740       mode = 0; // "at least"
10741     else
10742       mode = 2; // "exactly"
10743     modeCount = MinParams;
10744   } else {
10745     if (MinParams != FnTy->getNumParams())
10746       mode = 1; // "at most"
10747     else
10748       mode = 2; // "exactly"
10749     modeCount = FnTy->getNumParams();
10750   }
10751 
10752   std::string Description;
10753   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10754       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10755 
10756   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10757     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10758         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10759         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10760   else
10761     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10762         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10763         << Description << mode << modeCount << NumFormalArgs;
10764 
10765   MaybeEmitInheritedConstructorNote(S, Found);
10766 }
10767 
10768 /// Arity mismatch diagnosis specific to a function overload candidate.
10769 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10770                                   unsigned NumFormalArgs) {
10771   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10772     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10773 }
10774 
10775 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10776   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10777     return TD;
10778   llvm_unreachable("Unsupported: Getting the described template declaration"
10779                    " for bad deduction diagnosis");
10780 }
10781 
10782 /// Diagnose a failed template-argument deduction.
10783 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10784                                  DeductionFailureInfo &DeductionFailure,
10785                                  unsigned NumArgs,
10786                                  bool TakingCandidateAddress) {
10787   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10788   NamedDecl *ParamD;
10789   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10790   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10791   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10792   switch (DeductionFailure.Result) {
10793   case Sema::TDK_Success:
10794     llvm_unreachable("TDK_success while diagnosing bad deduction");
10795 
10796   case Sema::TDK_Incomplete: {
10797     assert(ParamD && "no parameter found for incomplete deduction result");
10798     S.Diag(Templated->getLocation(),
10799            diag::note_ovl_candidate_incomplete_deduction)
10800         << ParamD->getDeclName();
10801     MaybeEmitInheritedConstructorNote(S, Found);
10802     return;
10803   }
10804 
10805   case Sema::TDK_IncompletePack: {
10806     assert(ParamD && "no parameter found for incomplete deduction result");
10807     S.Diag(Templated->getLocation(),
10808            diag::note_ovl_candidate_incomplete_deduction_pack)
10809         << ParamD->getDeclName()
10810         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10811         << *DeductionFailure.getFirstArg();
10812     MaybeEmitInheritedConstructorNote(S, Found);
10813     return;
10814   }
10815 
10816   case Sema::TDK_Underqualified: {
10817     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10818     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10819 
10820     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10821 
10822     // Param will have been canonicalized, but it should just be a
10823     // qualified version of ParamD, so move the qualifiers to that.
10824     QualifierCollector Qs;
10825     Qs.strip(Param);
10826     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10827     assert(S.Context.hasSameType(Param, NonCanonParam));
10828 
10829     // Arg has also been canonicalized, but there's nothing we can do
10830     // about that.  It also doesn't matter as much, because it won't
10831     // have any template parameters in it (because deduction isn't
10832     // done on dependent types).
10833     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10834 
10835     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10836         << ParamD->getDeclName() << Arg << NonCanonParam;
10837     MaybeEmitInheritedConstructorNote(S, Found);
10838     return;
10839   }
10840 
10841   case Sema::TDK_Inconsistent: {
10842     assert(ParamD && "no parameter found for inconsistent deduction result");
10843     int which = 0;
10844     if (isa<TemplateTypeParmDecl>(ParamD))
10845       which = 0;
10846     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10847       // Deduction might have failed because we deduced arguments of two
10848       // different types for a non-type template parameter.
10849       // FIXME: Use a different TDK value for this.
10850       QualType T1 =
10851           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10852       QualType T2 =
10853           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10854       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10855         S.Diag(Templated->getLocation(),
10856                diag::note_ovl_candidate_inconsistent_deduction_types)
10857           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10858           << *DeductionFailure.getSecondArg() << T2;
10859         MaybeEmitInheritedConstructorNote(S, Found);
10860         return;
10861       }
10862 
10863       which = 1;
10864     } else {
10865       which = 2;
10866     }
10867 
10868     // Tweak the diagnostic if the problem is that we deduced packs of
10869     // different arities. We'll print the actual packs anyway in case that
10870     // includes additional useful information.
10871     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10872         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10873         DeductionFailure.getFirstArg()->pack_size() !=
10874             DeductionFailure.getSecondArg()->pack_size()) {
10875       which = 3;
10876     }
10877 
10878     S.Diag(Templated->getLocation(),
10879            diag::note_ovl_candidate_inconsistent_deduction)
10880         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10881         << *DeductionFailure.getSecondArg();
10882     MaybeEmitInheritedConstructorNote(S, Found);
10883     return;
10884   }
10885 
10886   case Sema::TDK_InvalidExplicitArguments:
10887     assert(ParamD && "no parameter found for invalid explicit arguments");
10888     if (ParamD->getDeclName())
10889       S.Diag(Templated->getLocation(),
10890              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10891           << ParamD->getDeclName();
10892     else {
10893       int index = 0;
10894       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10895         index = TTP->getIndex();
10896       else if (NonTypeTemplateParmDecl *NTTP
10897                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10898         index = NTTP->getIndex();
10899       else
10900         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10901       S.Diag(Templated->getLocation(),
10902              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10903           << (index + 1);
10904     }
10905     MaybeEmitInheritedConstructorNote(S, Found);
10906     return;
10907 
10908   case Sema::TDK_ConstraintsNotSatisfied: {
10909     // Format the template argument list into the argument string.
10910     SmallString<128> TemplateArgString;
10911     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10912     TemplateArgString = " ";
10913     TemplateArgString += S.getTemplateArgumentBindingsText(
10914         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10915     if (TemplateArgString.size() == 1)
10916       TemplateArgString.clear();
10917     S.Diag(Templated->getLocation(),
10918            diag::note_ovl_candidate_unsatisfied_constraints)
10919         << TemplateArgString;
10920 
10921     S.DiagnoseUnsatisfiedConstraint(
10922         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10923     return;
10924   }
10925   case Sema::TDK_TooManyArguments:
10926   case Sema::TDK_TooFewArguments:
10927     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10928     return;
10929 
10930   case Sema::TDK_InstantiationDepth:
10931     S.Diag(Templated->getLocation(),
10932            diag::note_ovl_candidate_instantiation_depth);
10933     MaybeEmitInheritedConstructorNote(S, Found);
10934     return;
10935 
10936   case Sema::TDK_SubstitutionFailure: {
10937     // Format the template argument list into the argument string.
10938     SmallString<128> TemplateArgString;
10939     if (TemplateArgumentList *Args =
10940             DeductionFailure.getTemplateArgumentList()) {
10941       TemplateArgString = " ";
10942       TemplateArgString += S.getTemplateArgumentBindingsText(
10943           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10944       if (TemplateArgString.size() == 1)
10945         TemplateArgString.clear();
10946     }
10947 
10948     // If this candidate was disabled by enable_if, say so.
10949     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10950     if (PDiag && PDiag->second.getDiagID() ==
10951           diag::err_typename_nested_not_found_enable_if) {
10952       // FIXME: Use the source range of the condition, and the fully-qualified
10953       //        name of the enable_if template. These are both present in PDiag.
10954       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10955         << "'enable_if'" << TemplateArgString;
10956       return;
10957     }
10958 
10959     // We found a specific requirement that disabled the enable_if.
10960     if (PDiag && PDiag->second.getDiagID() ==
10961         diag::err_typename_nested_not_found_requirement) {
10962       S.Diag(Templated->getLocation(),
10963              diag::note_ovl_candidate_disabled_by_requirement)
10964         << PDiag->second.getStringArg(0) << TemplateArgString;
10965       return;
10966     }
10967 
10968     // Format the SFINAE diagnostic into the argument string.
10969     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10970     //        formatted message in another diagnostic.
10971     SmallString<128> SFINAEArgString;
10972     SourceRange R;
10973     if (PDiag) {
10974       SFINAEArgString = ": ";
10975       R = SourceRange(PDiag->first, PDiag->first);
10976       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10977     }
10978 
10979     S.Diag(Templated->getLocation(),
10980            diag::note_ovl_candidate_substitution_failure)
10981         << TemplateArgString << SFINAEArgString << R;
10982     MaybeEmitInheritedConstructorNote(S, Found);
10983     return;
10984   }
10985 
10986   case Sema::TDK_DeducedMismatch:
10987   case Sema::TDK_DeducedMismatchNested: {
10988     // Format the template argument list into the argument string.
10989     SmallString<128> TemplateArgString;
10990     if (TemplateArgumentList *Args =
10991             DeductionFailure.getTemplateArgumentList()) {
10992       TemplateArgString = " ";
10993       TemplateArgString += S.getTemplateArgumentBindingsText(
10994           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10995       if (TemplateArgString.size() == 1)
10996         TemplateArgString.clear();
10997     }
10998 
10999     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11000         << (*DeductionFailure.getCallArgIndex() + 1)
11001         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11002         << TemplateArgString
11003         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
11004     break;
11005   }
11006 
11007   case Sema::TDK_NonDeducedMismatch: {
11008     // FIXME: Provide a source location to indicate what we couldn't match.
11009     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11010     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11011     if (FirstTA.getKind() == TemplateArgument::Template &&
11012         SecondTA.getKind() == TemplateArgument::Template) {
11013       TemplateName FirstTN = FirstTA.getAsTemplate();
11014       TemplateName SecondTN = SecondTA.getAsTemplate();
11015       if (FirstTN.getKind() == TemplateName::Template &&
11016           SecondTN.getKind() == TemplateName::Template) {
11017         if (FirstTN.getAsTemplateDecl()->getName() ==
11018             SecondTN.getAsTemplateDecl()->getName()) {
11019           // FIXME: This fixes a bad diagnostic where both templates are named
11020           // the same.  This particular case is a bit difficult since:
11021           // 1) It is passed as a string to the diagnostic printer.
11022           // 2) The diagnostic printer only attempts to find a better
11023           //    name for types, not decls.
11024           // Ideally, this should folded into the diagnostic printer.
11025           S.Diag(Templated->getLocation(),
11026                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11027               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11028           return;
11029         }
11030       }
11031     }
11032 
11033     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11034         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11035       return;
11036 
11037     // FIXME: For generic lambda parameters, check if the function is a lambda
11038     // call operator, and if so, emit a prettier and more informative
11039     // diagnostic that mentions 'auto' and lambda in addition to
11040     // (or instead of?) the canonical template type parameters.
11041     S.Diag(Templated->getLocation(),
11042            diag::note_ovl_candidate_non_deduced_mismatch)
11043         << FirstTA << SecondTA;
11044     return;
11045   }
11046   // TODO: diagnose these individually, then kill off
11047   // note_ovl_candidate_bad_deduction, which is uselessly vague.
11048   case Sema::TDK_MiscellaneousDeductionFailure:
11049     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11050     MaybeEmitInheritedConstructorNote(S, Found);
11051     return;
11052   case Sema::TDK_CUDATargetMismatch:
11053     S.Diag(Templated->getLocation(),
11054            diag::note_cuda_ovl_candidate_target_mismatch);
11055     return;
11056   }
11057 }
11058 
11059 /// Diagnose a failed template-argument deduction, for function calls.
11060 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11061                                  unsigned NumArgs,
11062                                  bool TakingCandidateAddress) {
11063   unsigned TDK = Cand->DeductionFailure.Result;
11064   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
11065     if (CheckArityMismatch(S, Cand, NumArgs))
11066       return;
11067   }
11068   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
11069                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11070 }
11071 
11072 /// CUDA: diagnose an invalid call across targets.
11073 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11074   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
11075   FunctionDecl *Callee = Cand->Function;
11076 
11077   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
11078                            CalleeTarget = S.IdentifyCUDATarget(Callee);
11079 
11080   std::string FnDesc;
11081   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11082       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11083                                 Cand->getRewriteKind(), FnDesc);
11084 
11085   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11086       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11087       << FnDesc /* Ignored */
11088       << CalleeTarget << CallerTarget;
11089 
11090   // This could be an implicit constructor for which we could not infer the
11091   // target due to a collsion. Diagnose that case.
11092   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11093   if (Meth != nullptr && Meth->isImplicit()) {
11094     CXXRecordDecl *ParentClass = Meth->getParent();
11095     Sema::CXXSpecialMember CSM;
11096 
11097     switch (FnKindPair.first) {
11098     default:
11099       return;
11100     case oc_implicit_default_constructor:
11101       CSM = Sema::CXXDefaultConstructor;
11102       break;
11103     case oc_implicit_copy_constructor:
11104       CSM = Sema::CXXCopyConstructor;
11105       break;
11106     case oc_implicit_move_constructor:
11107       CSM = Sema::CXXMoveConstructor;
11108       break;
11109     case oc_implicit_copy_assignment:
11110       CSM = Sema::CXXCopyAssignment;
11111       break;
11112     case oc_implicit_move_assignment:
11113       CSM = Sema::CXXMoveAssignment;
11114       break;
11115     };
11116 
11117     bool ConstRHS = false;
11118     if (Meth->getNumParams()) {
11119       if (const ReferenceType *RT =
11120               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11121         ConstRHS = RT->getPointeeType().isConstQualified();
11122       }
11123     }
11124 
11125     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11126                                               /* ConstRHS */ ConstRHS,
11127                                               /* Diagnose */ true);
11128   }
11129 }
11130 
11131 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11132   FunctionDecl *Callee = Cand->Function;
11133   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11134 
11135   S.Diag(Callee->getLocation(),
11136          diag::note_ovl_candidate_disabled_by_function_cond_attr)
11137       << Attr->getCond()->getSourceRange() << Attr->getMessage();
11138 }
11139 
11140 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11141   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
11142   assert(ES.isExplicit() && "not an explicit candidate");
11143 
11144   unsigned Kind;
11145   switch (Cand->Function->getDeclKind()) {
11146   case Decl::Kind::CXXConstructor:
11147     Kind = 0;
11148     break;
11149   case Decl::Kind::CXXConversion:
11150     Kind = 1;
11151     break;
11152   case Decl::Kind::CXXDeductionGuide:
11153     Kind = Cand->Function->isImplicit() ? 0 : 2;
11154     break;
11155   default:
11156     llvm_unreachable("invalid Decl");
11157   }
11158 
11159   // Note the location of the first (in-class) declaration; a redeclaration
11160   // (particularly an out-of-class definition) will typically lack the
11161   // 'explicit' specifier.
11162   // FIXME: This is probably a good thing to do for all 'candidate' notes.
11163   FunctionDecl *First = Cand->Function->getFirstDecl();
11164   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11165     First = Pattern->getFirstDecl();
11166 
11167   S.Diag(First->getLocation(),
11168          diag::note_ovl_candidate_explicit)
11169       << Kind << (ES.getExpr() ? 1 : 0)
11170       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11171 }
11172 
11173 /// Generates a 'note' diagnostic for an overload candidate.  We've
11174 /// already generated a primary error at the call site.
11175 ///
11176 /// It really does need to be a single diagnostic with its caret
11177 /// pointed at the candidate declaration.  Yes, this creates some
11178 /// major challenges of technical writing.  Yes, this makes pointing
11179 /// out problems with specific arguments quite awkward.  It's still
11180 /// better than generating twenty screens of text for every failed
11181 /// overload.
11182 ///
11183 /// It would be great to be able to express per-candidate problems
11184 /// more richly for those diagnostic clients that cared, but we'd
11185 /// still have to be just as careful with the default diagnostics.
11186 /// \param CtorDestAS Addr space of object being constructed (for ctor
11187 /// candidates only).
11188 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11189                                   unsigned NumArgs,
11190                                   bool TakingCandidateAddress,
11191                                   LangAS CtorDestAS = LangAS::Default) {
11192   FunctionDecl *Fn = Cand->Function;
11193   if (shouldSkipNotingLambdaConversionDecl(Fn))
11194     return;
11195 
11196   // Note deleted candidates, but only if they're viable.
11197   if (Cand->Viable) {
11198     if (Fn->isDeleted()) {
11199       std::string FnDesc;
11200       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11201           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11202                                     Cand->getRewriteKind(), FnDesc);
11203 
11204       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11205           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11206           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11207       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11208       return;
11209     }
11210 
11211     // We don't really have anything else to say about viable candidates.
11212     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11213     return;
11214   }
11215 
11216   switch (Cand->FailureKind) {
11217   case ovl_fail_too_many_arguments:
11218   case ovl_fail_too_few_arguments:
11219     return DiagnoseArityMismatch(S, Cand, NumArgs);
11220 
11221   case ovl_fail_bad_deduction:
11222     return DiagnoseBadDeduction(S, Cand, NumArgs,
11223                                 TakingCandidateAddress);
11224 
11225   case ovl_fail_illegal_constructor: {
11226     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11227       << (Fn->getPrimaryTemplate() ? 1 : 0);
11228     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11229     return;
11230   }
11231 
11232   case ovl_fail_object_addrspace_mismatch: {
11233     Qualifiers QualsForPrinting;
11234     QualsForPrinting.setAddressSpace(CtorDestAS);
11235     S.Diag(Fn->getLocation(),
11236            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11237         << QualsForPrinting;
11238     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11239     return;
11240   }
11241 
11242   case ovl_fail_trivial_conversion:
11243   case ovl_fail_bad_final_conversion:
11244   case ovl_fail_final_conversion_not_exact:
11245     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11246 
11247   case ovl_fail_bad_conversion: {
11248     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11249     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11250       if (Cand->Conversions[I].isBad())
11251         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11252 
11253     // FIXME: this currently happens when we're called from SemaInit
11254     // when user-conversion overload fails.  Figure out how to handle
11255     // those conditions and diagnose them well.
11256     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11257   }
11258 
11259   case ovl_fail_bad_target:
11260     return DiagnoseBadTarget(S, Cand);
11261 
11262   case ovl_fail_enable_if:
11263     return DiagnoseFailedEnableIfAttr(S, Cand);
11264 
11265   case ovl_fail_explicit:
11266     return DiagnoseFailedExplicitSpec(S, Cand);
11267 
11268   case ovl_fail_inhctor_slice:
11269     // It's generally not interesting to note copy/move constructors here.
11270     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11271       return;
11272     S.Diag(Fn->getLocation(),
11273            diag::note_ovl_candidate_inherited_constructor_slice)
11274       << (Fn->getPrimaryTemplate() ? 1 : 0)
11275       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11276     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11277     return;
11278 
11279   case ovl_fail_addr_not_available: {
11280     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11281     (void)Available;
11282     assert(!Available);
11283     break;
11284   }
11285   case ovl_non_default_multiversion_function:
11286     // Do nothing, these should simply be ignored.
11287     break;
11288 
11289   case ovl_fail_constraints_not_satisfied: {
11290     std::string FnDesc;
11291     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11292         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11293                                   Cand->getRewriteKind(), FnDesc);
11294 
11295     S.Diag(Fn->getLocation(),
11296            diag::note_ovl_candidate_constraints_not_satisfied)
11297         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11298         << FnDesc /* Ignored */;
11299     ConstraintSatisfaction Satisfaction;
11300     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11301       break;
11302     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11303   }
11304   }
11305 }
11306 
11307 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11308   if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
11309     return;
11310 
11311   // Desugar the type of the surrogate down to a function type,
11312   // retaining as many typedefs as possible while still showing
11313   // the function type (and, therefore, its parameter types).
11314   QualType FnType = Cand->Surrogate->getConversionType();
11315   bool isLValueReference = false;
11316   bool isRValueReference = false;
11317   bool isPointer = false;
11318   if (const LValueReferenceType *FnTypeRef =
11319         FnType->getAs<LValueReferenceType>()) {
11320     FnType = FnTypeRef->getPointeeType();
11321     isLValueReference = true;
11322   } else if (const RValueReferenceType *FnTypeRef =
11323                FnType->getAs<RValueReferenceType>()) {
11324     FnType = FnTypeRef->getPointeeType();
11325     isRValueReference = true;
11326   }
11327   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11328     FnType = FnTypePtr->getPointeeType();
11329     isPointer = true;
11330   }
11331   // Desugar down to a function type.
11332   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11333   // Reconstruct the pointer/reference as appropriate.
11334   if (isPointer) FnType = S.Context.getPointerType(FnType);
11335   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11336   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11337 
11338   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11339     << FnType;
11340 }
11341 
11342 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11343                                          SourceLocation OpLoc,
11344                                          OverloadCandidate *Cand) {
11345   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11346   std::string TypeStr("operator");
11347   TypeStr += Opc;
11348   TypeStr += "(";
11349   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11350   if (Cand->Conversions.size() == 1) {
11351     TypeStr += ")";
11352     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11353   } else {
11354     TypeStr += ", ";
11355     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11356     TypeStr += ")";
11357     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11358   }
11359 }
11360 
11361 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11362                                          OverloadCandidate *Cand) {
11363   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11364     if (ICS.isBad()) break; // all meaningless after first invalid
11365     if (!ICS.isAmbiguous()) continue;
11366 
11367     ICS.DiagnoseAmbiguousConversion(
11368         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11369   }
11370 }
11371 
11372 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11373   if (Cand->Function)
11374     return Cand->Function->getLocation();
11375   if (Cand->IsSurrogate)
11376     return Cand->Surrogate->getLocation();
11377   return SourceLocation();
11378 }
11379 
11380 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11381   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11382   case Sema::TDK_Success:
11383   case Sema::TDK_NonDependentConversionFailure:
11384     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11385 
11386   case Sema::TDK_Invalid:
11387   case Sema::TDK_Incomplete:
11388   case Sema::TDK_IncompletePack:
11389     return 1;
11390 
11391   case Sema::TDK_Underqualified:
11392   case Sema::TDK_Inconsistent:
11393     return 2;
11394 
11395   case Sema::TDK_SubstitutionFailure:
11396   case Sema::TDK_DeducedMismatch:
11397   case Sema::TDK_ConstraintsNotSatisfied:
11398   case Sema::TDK_DeducedMismatchNested:
11399   case Sema::TDK_NonDeducedMismatch:
11400   case Sema::TDK_MiscellaneousDeductionFailure:
11401   case Sema::TDK_CUDATargetMismatch:
11402     return 3;
11403 
11404   case Sema::TDK_InstantiationDepth:
11405     return 4;
11406 
11407   case Sema::TDK_InvalidExplicitArguments:
11408     return 5;
11409 
11410   case Sema::TDK_TooManyArguments:
11411   case Sema::TDK_TooFewArguments:
11412     return 6;
11413   }
11414   llvm_unreachable("Unhandled deduction result");
11415 }
11416 
11417 namespace {
11418 struct CompareOverloadCandidatesForDisplay {
11419   Sema &S;
11420   SourceLocation Loc;
11421   size_t NumArgs;
11422   OverloadCandidateSet::CandidateSetKind CSK;
11423 
11424   CompareOverloadCandidatesForDisplay(
11425       Sema &S, SourceLocation Loc, size_t NArgs,
11426       OverloadCandidateSet::CandidateSetKind CSK)
11427       : S(S), NumArgs(NArgs), CSK(CSK) {}
11428 
11429   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11430     // If there are too many or too few arguments, that's the high-order bit we
11431     // want to sort by, even if the immediate failure kind was something else.
11432     if (C->FailureKind == ovl_fail_too_many_arguments ||
11433         C->FailureKind == ovl_fail_too_few_arguments)
11434       return static_cast<OverloadFailureKind>(C->FailureKind);
11435 
11436     if (C->Function) {
11437       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11438         return ovl_fail_too_many_arguments;
11439       if (NumArgs < C->Function->getMinRequiredArguments())
11440         return ovl_fail_too_few_arguments;
11441     }
11442 
11443     return static_cast<OverloadFailureKind>(C->FailureKind);
11444   }
11445 
11446   bool operator()(const OverloadCandidate *L,
11447                   const OverloadCandidate *R) {
11448     // Fast-path this check.
11449     if (L == R) return false;
11450 
11451     // Order first by viability.
11452     if (L->Viable) {
11453       if (!R->Viable) return true;
11454 
11455       // TODO: introduce a tri-valued comparison for overload
11456       // candidates.  Would be more worthwhile if we had a sort
11457       // that could exploit it.
11458       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11459         return true;
11460       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11461         return false;
11462     } else if (R->Viable)
11463       return false;
11464 
11465     assert(L->Viable == R->Viable);
11466 
11467     // Criteria by which we can sort non-viable candidates:
11468     if (!L->Viable) {
11469       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11470       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11471 
11472       // 1. Arity mismatches come after other candidates.
11473       if (LFailureKind == ovl_fail_too_many_arguments ||
11474           LFailureKind == ovl_fail_too_few_arguments) {
11475         if (RFailureKind == ovl_fail_too_many_arguments ||
11476             RFailureKind == ovl_fail_too_few_arguments) {
11477           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11478           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11479           if (LDist == RDist) {
11480             if (LFailureKind == RFailureKind)
11481               // Sort non-surrogates before surrogates.
11482               return !L->IsSurrogate && R->IsSurrogate;
11483             // Sort candidates requiring fewer parameters than there were
11484             // arguments given after candidates requiring more parameters
11485             // than there were arguments given.
11486             return LFailureKind == ovl_fail_too_many_arguments;
11487           }
11488           return LDist < RDist;
11489         }
11490         return false;
11491       }
11492       if (RFailureKind == ovl_fail_too_many_arguments ||
11493           RFailureKind == ovl_fail_too_few_arguments)
11494         return true;
11495 
11496       // 2. Bad conversions come first and are ordered by the number
11497       // of bad conversions and quality of good conversions.
11498       if (LFailureKind == ovl_fail_bad_conversion) {
11499         if (RFailureKind != ovl_fail_bad_conversion)
11500           return true;
11501 
11502         // The conversion that can be fixed with a smaller number of changes,
11503         // comes first.
11504         unsigned numLFixes = L->Fix.NumConversionsFixed;
11505         unsigned numRFixes = R->Fix.NumConversionsFixed;
11506         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11507         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11508         if (numLFixes != numRFixes) {
11509           return numLFixes < numRFixes;
11510         }
11511 
11512         // If there's any ordering between the defined conversions...
11513         // FIXME: this might not be transitive.
11514         assert(L->Conversions.size() == R->Conversions.size());
11515 
11516         int leftBetter = 0;
11517         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11518         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11519           switch (CompareImplicitConversionSequences(S, Loc,
11520                                                      L->Conversions[I],
11521                                                      R->Conversions[I])) {
11522           case ImplicitConversionSequence::Better:
11523             leftBetter++;
11524             break;
11525 
11526           case ImplicitConversionSequence::Worse:
11527             leftBetter--;
11528             break;
11529 
11530           case ImplicitConversionSequence::Indistinguishable:
11531             break;
11532           }
11533         }
11534         if (leftBetter > 0) return true;
11535         if (leftBetter < 0) return false;
11536 
11537       } else if (RFailureKind == ovl_fail_bad_conversion)
11538         return false;
11539 
11540       if (LFailureKind == ovl_fail_bad_deduction) {
11541         if (RFailureKind != ovl_fail_bad_deduction)
11542           return true;
11543 
11544         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11545           return RankDeductionFailure(L->DeductionFailure)
11546                < RankDeductionFailure(R->DeductionFailure);
11547       } else if (RFailureKind == ovl_fail_bad_deduction)
11548         return false;
11549 
11550       // TODO: others?
11551     }
11552 
11553     // Sort everything else by location.
11554     SourceLocation LLoc = GetLocationForCandidate(L);
11555     SourceLocation RLoc = GetLocationForCandidate(R);
11556 
11557     // Put candidates without locations (e.g. builtins) at the end.
11558     if (LLoc.isInvalid()) return false;
11559     if (RLoc.isInvalid()) return true;
11560 
11561     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11562   }
11563 };
11564 }
11565 
11566 /// CompleteNonViableCandidate - Normally, overload resolution only
11567 /// computes up to the first bad conversion. Produces the FixIt set if
11568 /// possible.
11569 static void
11570 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11571                            ArrayRef<Expr *> Args,
11572                            OverloadCandidateSet::CandidateSetKind CSK) {
11573   assert(!Cand->Viable);
11574 
11575   // Don't do anything on failures other than bad conversion.
11576   if (Cand->FailureKind != ovl_fail_bad_conversion)
11577     return;
11578 
11579   // We only want the FixIts if all the arguments can be corrected.
11580   bool Unfixable = false;
11581   // Use a implicit copy initialization to check conversion fixes.
11582   Cand->Fix.setConversionChecker(TryCopyInitialization);
11583 
11584   // Attempt to fix the bad conversion.
11585   unsigned ConvCount = Cand->Conversions.size();
11586   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11587        ++ConvIdx) {
11588     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11589     if (Cand->Conversions[ConvIdx].isInitialized() &&
11590         Cand->Conversions[ConvIdx].isBad()) {
11591       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11592       break;
11593     }
11594   }
11595 
11596   // FIXME: this should probably be preserved from the overload
11597   // operation somehow.
11598   bool SuppressUserConversions = false;
11599 
11600   unsigned ConvIdx = 0;
11601   unsigned ArgIdx = 0;
11602   ArrayRef<QualType> ParamTypes;
11603   bool Reversed = Cand->isReversed();
11604 
11605   if (Cand->IsSurrogate) {
11606     QualType ConvType
11607       = Cand->Surrogate->getConversionType().getNonReferenceType();
11608     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11609       ConvType = ConvPtrType->getPointeeType();
11610     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11611     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11612     ConvIdx = 1;
11613   } else if (Cand->Function) {
11614     ParamTypes =
11615         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11616     if (isa<CXXMethodDecl>(Cand->Function) &&
11617         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11618       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11619       ConvIdx = 1;
11620       if (CSK == OverloadCandidateSet::CSK_Operator &&
11621           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11622         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11623         ArgIdx = 1;
11624     }
11625   } else {
11626     // Builtin operator.
11627     assert(ConvCount <= 3);
11628     ParamTypes = Cand->BuiltinParamTypes;
11629   }
11630 
11631   // Fill in the rest of the conversions.
11632   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11633        ConvIdx != ConvCount;
11634        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11635     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11636     if (Cand->Conversions[ConvIdx].isInitialized()) {
11637       // We've already checked this conversion.
11638     } else if (ParamIdx < ParamTypes.size()) {
11639       if (ParamTypes[ParamIdx]->isDependentType())
11640         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11641             Args[ArgIdx]->getType());
11642       else {
11643         Cand->Conversions[ConvIdx] =
11644             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11645                                   SuppressUserConversions,
11646                                   /*InOverloadResolution=*/true,
11647                                   /*AllowObjCWritebackConversion=*/
11648                                   S.getLangOpts().ObjCAutoRefCount);
11649         // Store the FixIt in the candidate if it exists.
11650         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11651           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11652       }
11653     } else
11654       Cand->Conversions[ConvIdx].setEllipsis();
11655   }
11656 }
11657 
11658 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11659     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11660     SourceLocation OpLoc,
11661     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11662   // Sort the candidates by viability and position.  Sorting directly would
11663   // be prohibitive, so we make a set of pointers and sort those.
11664   SmallVector<OverloadCandidate*, 32> Cands;
11665   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11666   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11667     if (!Filter(*Cand))
11668       continue;
11669     switch (OCD) {
11670     case OCD_AllCandidates:
11671       if (!Cand->Viable) {
11672         if (!Cand->Function && !Cand->IsSurrogate) {
11673           // This a non-viable builtin candidate.  We do not, in general,
11674           // want to list every possible builtin candidate.
11675           continue;
11676         }
11677         CompleteNonViableCandidate(S, Cand, Args, Kind);
11678       }
11679       break;
11680 
11681     case OCD_ViableCandidates:
11682       if (!Cand->Viable)
11683         continue;
11684       break;
11685 
11686     case OCD_AmbiguousCandidates:
11687       if (!Cand->Best)
11688         continue;
11689       break;
11690     }
11691 
11692     Cands.push_back(Cand);
11693   }
11694 
11695   llvm::stable_sort(
11696       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11697 
11698   return Cands;
11699 }
11700 
11701 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
11702                                             SourceLocation OpLoc) {
11703   bool DeferHint = false;
11704   if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
11705     // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
11706     // host device candidates.
11707     auto WrongSidedCands =
11708         CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
11709           return (Cand.Viable == false &&
11710                   Cand.FailureKind == ovl_fail_bad_target) ||
11711                  (Cand.Function &&
11712                   Cand.Function->template hasAttr<CUDAHostAttr>() &&
11713                   Cand.Function->template hasAttr<CUDADeviceAttr>());
11714         });
11715     DeferHint = !WrongSidedCands.empty();
11716   }
11717   return DeferHint;
11718 }
11719 
11720 /// When overload resolution fails, prints diagnostic messages containing the
11721 /// candidates in the candidate set.
11722 void OverloadCandidateSet::NoteCandidates(
11723     PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
11724     ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
11725     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11726 
11727   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11728 
11729   S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
11730 
11731   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11732 
11733   if (OCD == OCD_AmbiguousCandidates)
11734     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11735 }
11736 
11737 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11738                                           ArrayRef<OverloadCandidate *> Cands,
11739                                           StringRef Opc, SourceLocation OpLoc) {
11740   bool ReportedAmbiguousConversions = false;
11741 
11742   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11743   unsigned CandsShown = 0;
11744   auto I = Cands.begin(), E = Cands.end();
11745   for (; I != E; ++I) {
11746     OverloadCandidate *Cand = *I;
11747 
11748     if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
11749         ShowOverloads == Ovl_Best) {
11750       break;
11751     }
11752     ++CandsShown;
11753 
11754     if (Cand->Function)
11755       NoteFunctionCandidate(S, Cand, Args.size(),
11756                             /*TakingCandidateAddress=*/false, DestAS);
11757     else if (Cand->IsSurrogate)
11758       NoteSurrogateCandidate(S, Cand);
11759     else {
11760       assert(Cand->Viable &&
11761              "Non-viable built-in candidates are not added to Cands.");
11762       // Generally we only see ambiguities including viable builtin
11763       // operators if overload resolution got screwed up by an
11764       // ambiguous user-defined conversion.
11765       //
11766       // FIXME: It's quite possible for different conversions to see
11767       // different ambiguities, though.
11768       if (!ReportedAmbiguousConversions) {
11769         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11770         ReportedAmbiguousConversions = true;
11771       }
11772 
11773       // If this is a viable builtin, print it.
11774       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11775     }
11776   }
11777 
11778   // Inform S.Diags that we've shown an overload set with N elements.  This may
11779   // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
11780   S.Diags.overloadCandidatesShown(CandsShown);
11781 
11782   if (I != E)
11783     S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
11784            shouldDeferDiags(S, Args, OpLoc))
11785         << int(E - I);
11786 }
11787 
11788 static SourceLocation
11789 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11790   return Cand->Specialization ? Cand->Specialization->getLocation()
11791                               : SourceLocation();
11792 }
11793 
11794 namespace {
11795 struct CompareTemplateSpecCandidatesForDisplay {
11796   Sema &S;
11797   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11798 
11799   bool operator()(const TemplateSpecCandidate *L,
11800                   const TemplateSpecCandidate *R) {
11801     // Fast-path this check.
11802     if (L == R)
11803       return false;
11804 
11805     // Assuming that both candidates are not matches...
11806 
11807     // Sort by the ranking of deduction failures.
11808     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11809       return RankDeductionFailure(L->DeductionFailure) <
11810              RankDeductionFailure(R->DeductionFailure);
11811 
11812     // Sort everything else by location.
11813     SourceLocation LLoc = GetLocationForCandidate(L);
11814     SourceLocation RLoc = GetLocationForCandidate(R);
11815 
11816     // Put candidates without locations (e.g. builtins) at the end.
11817     if (LLoc.isInvalid())
11818       return false;
11819     if (RLoc.isInvalid())
11820       return true;
11821 
11822     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11823   }
11824 };
11825 }
11826 
11827 /// Diagnose a template argument deduction failure.
11828 /// We are treating these failures as overload failures due to bad
11829 /// deductions.
11830 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11831                                                  bool ForTakingAddress) {
11832   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11833                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11834 }
11835 
11836 void TemplateSpecCandidateSet::destroyCandidates() {
11837   for (iterator i = begin(), e = end(); i != e; ++i) {
11838     i->DeductionFailure.Destroy();
11839   }
11840 }
11841 
11842 void TemplateSpecCandidateSet::clear() {
11843   destroyCandidates();
11844   Candidates.clear();
11845 }
11846 
11847 /// NoteCandidates - When no template specialization match is found, prints
11848 /// diagnostic messages containing the non-matching specializations that form
11849 /// the candidate set.
11850 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11851 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11852 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11853   // Sort the candidates by position (assuming no candidate is a match).
11854   // Sorting directly would be prohibitive, so we make a set of pointers
11855   // and sort those.
11856   SmallVector<TemplateSpecCandidate *, 32> Cands;
11857   Cands.reserve(size());
11858   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11859     if (Cand->Specialization)
11860       Cands.push_back(Cand);
11861     // Otherwise, this is a non-matching builtin candidate.  We do not,
11862     // in general, want to list every possible builtin candidate.
11863   }
11864 
11865   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11866 
11867   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11868   // for generalization purposes (?).
11869   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11870 
11871   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11872   unsigned CandsShown = 0;
11873   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11874     TemplateSpecCandidate *Cand = *I;
11875 
11876     // Set an arbitrary limit on the number of candidates we'll spam
11877     // the user with.  FIXME: This limit should depend on details of the
11878     // candidate list.
11879     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11880       break;
11881     ++CandsShown;
11882 
11883     assert(Cand->Specialization &&
11884            "Non-matching built-in candidates are not added to Cands.");
11885     Cand->NoteDeductionFailure(S, ForTakingAddress);
11886   }
11887 
11888   if (I != E)
11889     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11890 }
11891 
11892 // [PossiblyAFunctionType]  -->   [Return]
11893 // NonFunctionType --> NonFunctionType
11894 // R (A) --> R(A)
11895 // R (*)(A) --> R (A)
11896 // R (&)(A) --> R (A)
11897 // R (S::*)(A) --> R (A)
11898 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11899   QualType Ret = PossiblyAFunctionType;
11900   if (const PointerType *ToTypePtr =
11901     PossiblyAFunctionType->getAs<PointerType>())
11902     Ret = ToTypePtr->getPointeeType();
11903   else if (const ReferenceType *ToTypeRef =
11904     PossiblyAFunctionType->getAs<ReferenceType>())
11905     Ret = ToTypeRef->getPointeeType();
11906   else if (const MemberPointerType *MemTypePtr =
11907     PossiblyAFunctionType->getAs<MemberPointerType>())
11908     Ret = MemTypePtr->getPointeeType();
11909   Ret =
11910     Context.getCanonicalType(Ret).getUnqualifiedType();
11911   return Ret;
11912 }
11913 
11914 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11915                                  bool Complain = true) {
11916   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11917       S.DeduceReturnType(FD, Loc, Complain))
11918     return true;
11919 
11920   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11921   if (S.getLangOpts().CPlusPlus17 &&
11922       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11923       !S.ResolveExceptionSpec(Loc, FPT))
11924     return true;
11925 
11926   return false;
11927 }
11928 
11929 namespace {
11930 // A helper class to help with address of function resolution
11931 // - allows us to avoid passing around all those ugly parameters
11932 class AddressOfFunctionResolver {
11933   Sema& S;
11934   Expr* SourceExpr;
11935   const QualType& TargetType;
11936   QualType TargetFunctionType; // Extracted function type from target type
11937 
11938   bool Complain;
11939   //DeclAccessPair& ResultFunctionAccessPair;
11940   ASTContext& Context;
11941 
11942   bool TargetTypeIsNonStaticMemberFunction;
11943   bool FoundNonTemplateFunction;
11944   bool StaticMemberFunctionFromBoundPointer;
11945   bool HasComplained;
11946 
11947   OverloadExpr::FindResult OvlExprInfo;
11948   OverloadExpr *OvlExpr;
11949   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11950   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11951   TemplateSpecCandidateSet FailedCandidates;
11952 
11953 public:
11954   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11955                             const QualType &TargetType, bool Complain)
11956       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11957         Complain(Complain), Context(S.getASTContext()),
11958         TargetTypeIsNonStaticMemberFunction(
11959             !!TargetType->getAs<MemberPointerType>()),
11960         FoundNonTemplateFunction(false),
11961         StaticMemberFunctionFromBoundPointer(false),
11962         HasComplained(false),
11963         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11964         OvlExpr(OvlExprInfo.Expression),
11965         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11966     ExtractUnqualifiedFunctionTypeFromTargetType();
11967 
11968     if (TargetFunctionType->isFunctionType()) {
11969       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11970         if (!UME->isImplicitAccess() &&
11971             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11972           StaticMemberFunctionFromBoundPointer = true;
11973     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11974       DeclAccessPair dap;
11975       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11976               OvlExpr, false, &dap)) {
11977         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11978           if (!Method->isStatic()) {
11979             // If the target type is a non-function type and the function found
11980             // is a non-static member function, pretend as if that was the
11981             // target, it's the only possible type to end up with.
11982             TargetTypeIsNonStaticMemberFunction = true;
11983 
11984             // And skip adding the function if its not in the proper form.
11985             // We'll diagnose this due to an empty set of functions.
11986             if (!OvlExprInfo.HasFormOfMemberPointer)
11987               return;
11988           }
11989 
11990         Matches.push_back(std::make_pair(dap, Fn));
11991       }
11992       return;
11993     }
11994 
11995     if (OvlExpr->hasExplicitTemplateArgs())
11996       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11997 
11998     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11999       // C++ [over.over]p4:
12000       //   If more than one function is selected, [...]
12001       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12002         if (FoundNonTemplateFunction)
12003           EliminateAllTemplateMatches();
12004         else
12005           EliminateAllExceptMostSpecializedTemplate();
12006       }
12007     }
12008 
12009     if (S.getLangOpts().CUDA && Matches.size() > 1)
12010       EliminateSuboptimalCudaMatches();
12011   }
12012 
12013   bool hasComplained() const { return HasComplained; }
12014 
12015 private:
12016   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12017     QualType Discard;
12018     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12019            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12020   }
12021 
12022   /// \return true if A is considered a better overload candidate for the
12023   /// desired type than B.
12024   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12025     // If A doesn't have exactly the correct type, we don't want to classify it
12026     // as "better" than anything else. This way, the user is required to
12027     // disambiguate for us if there are multiple candidates and no exact match.
12028     return candidateHasExactlyCorrectType(A) &&
12029            (!candidateHasExactlyCorrectType(B) ||
12030             compareEnableIfAttrs(S, A, B) == Comparison::Better);
12031   }
12032 
12033   /// \return true if we were able to eliminate all but one overload candidate,
12034   /// false otherwise.
12035   bool eliminiateSuboptimalOverloadCandidates() {
12036     // Same algorithm as overload resolution -- one pass to pick the "best",
12037     // another pass to be sure that nothing is better than the best.
12038     auto Best = Matches.begin();
12039     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12040       if (isBetterCandidate(I->second, Best->second))
12041         Best = I;
12042 
12043     const FunctionDecl *BestFn = Best->second;
12044     auto IsBestOrInferiorToBest = [this, BestFn](
12045         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12046       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12047     };
12048 
12049     // Note: We explicitly leave Matches unmodified if there isn't a clear best
12050     // option, so we can potentially give the user a better error
12051     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12052       return false;
12053     Matches[0] = *Best;
12054     Matches.resize(1);
12055     return true;
12056   }
12057 
12058   bool isTargetTypeAFunction() const {
12059     return TargetFunctionType->isFunctionType();
12060   }
12061 
12062   // [ToType]     [Return]
12063 
12064   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12065   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12066   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12067   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12068     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12069   }
12070 
12071   // return true if any matching specializations were found
12072   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12073                                    const DeclAccessPair& CurAccessFunPair) {
12074     if (CXXMethodDecl *Method
12075               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
12076       // Skip non-static function templates when converting to pointer, and
12077       // static when converting to member pointer.
12078       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12079         return false;
12080     }
12081     else if (TargetTypeIsNonStaticMemberFunction)
12082       return false;
12083 
12084     // C++ [over.over]p2:
12085     //   If the name is a function template, template argument deduction is
12086     //   done (14.8.2.2), and if the argument deduction succeeds, the
12087     //   resulting template argument list is used to generate a single
12088     //   function template specialization, which is added to the set of
12089     //   overloaded functions considered.
12090     FunctionDecl *Specialization = nullptr;
12091     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12092     if (Sema::TemplateDeductionResult Result
12093           = S.DeduceTemplateArguments(FunctionTemplate,
12094                                       &OvlExplicitTemplateArgs,
12095                                       TargetFunctionType, Specialization,
12096                                       Info, /*IsAddressOfFunction*/true)) {
12097       // Make a note of the failed deduction for diagnostics.
12098       FailedCandidates.addCandidate()
12099           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
12100                MakeDeductionFailureInfo(Context, Result, Info));
12101       return false;
12102     }
12103 
12104     // Template argument deduction ensures that we have an exact match or
12105     // compatible pointer-to-function arguments that would be adjusted by ICS.
12106     // This function template specicalization works.
12107     assert(S.isSameOrCompatibleFunctionType(
12108               Context.getCanonicalType(Specialization->getType()),
12109               Context.getCanonicalType(TargetFunctionType)));
12110 
12111     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
12112       return false;
12113 
12114     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
12115     return true;
12116   }
12117 
12118   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
12119                                       const DeclAccessPair& CurAccessFunPair) {
12120     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12121       // Skip non-static functions when converting to pointer, and static
12122       // when converting to member pointer.
12123       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
12124         return false;
12125     }
12126     else if (TargetTypeIsNonStaticMemberFunction)
12127       return false;
12128 
12129     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
12130       if (S.getLangOpts().CUDA)
12131         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
12132           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
12133             return false;
12134       if (FunDecl->isMultiVersion()) {
12135         const auto *TA = FunDecl->getAttr<TargetAttr>();
12136         if (TA && !TA->isDefaultVersion())
12137           return false;
12138       }
12139 
12140       // If any candidate has a placeholder return type, trigger its deduction
12141       // now.
12142       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
12143                                Complain)) {
12144         HasComplained |= Complain;
12145         return false;
12146       }
12147 
12148       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
12149         return false;
12150 
12151       // If we're in C, we need to support types that aren't exactly identical.
12152       if (!S.getLangOpts().CPlusPlus ||
12153           candidateHasExactlyCorrectType(FunDecl)) {
12154         Matches.push_back(std::make_pair(
12155             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
12156         FoundNonTemplateFunction = true;
12157         return true;
12158       }
12159     }
12160 
12161     return false;
12162   }
12163 
12164   bool FindAllFunctionsThatMatchTargetTypeExactly() {
12165     bool Ret = false;
12166 
12167     // If the overload expression doesn't have the form of a pointer to
12168     // member, don't try to convert it to a pointer-to-member type.
12169     if (IsInvalidFormOfPointerToMemberFunction())
12170       return false;
12171 
12172     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12173                                E = OvlExpr->decls_end();
12174          I != E; ++I) {
12175       // Look through any using declarations to find the underlying function.
12176       NamedDecl *Fn = (*I)->getUnderlyingDecl();
12177 
12178       // C++ [over.over]p3:
12179       //   Non-member functions and static member functions match
12180       //   targets of type "pointer-to-function" or "reference-to-function."
12181       //   Nonstatic member functions match targets of
12182       //   type "pointer-to-member-function."
12183       // Note that according to DR 247, the containing class does not matter.
12184       if (FunctionTemplateDecl *FunctionTemplate
12185                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
12186         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
12187           Ret = true;
12188       }
12189       // If we have explicit template arguments supplied, skip non-templates.
12190       else if (!OvlExpr->hasExplicitTemplateArgs() &&
12191                AddMatchingNonTemplateFunction(Fn, I.getPair()))
12192         Ret = true;
12193     }
12194     assert(Ret || Matches.empty());
12195     return Ret;
12196   }
12197 
12198   void EliminateAllExceptMostSpecializedTemplate() {
12199     //   [...] and any given function template specialization F1 is
12200     //   eliminated if the set contains a second function template
12201     //   specialization whose function template is more specialized
12202     //   than the function template of F1 according to the partial
12203     //   ordering rules of 14.5.5.2.
12204 
12205     // The algorithm specified above is quadratic. We instead use a
12206     // two-pass algorithm (similar to the one used to identify the
12207     // best viable function in an overload set) that identifies the
12208     // best function template (if it exists).
12209 
12210     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12211     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12212       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12213 
12214     // TODO: It looks like FailedCandidates does not serve much purpose
12215     // here, since the no_viable diagnostic has index 0.
12216     UnresolvedSetIterator Result = S.getMostSpecialized(
12217         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12218         SourceExpr->getBeginLoc(), S.PDiag(),
12219         S.PDiag(diag::err_addr_ovl_ambiguous)
12220             << Matches[0].second->getDeclName(),
12221         S.PDiag(diag::note_ovl_candidate)
12222             << (unsigned)oc_function << (unsigned)ocs_described_template,
12223         Complain, TargetFunctionType);
12224 
12225     if (Result != MatchesCopy.end()) {
12226       // Make it the first and only element
12227       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12228       Matches[0].second = cast<FunctionDecl>(*Result);
12229       Matches.resize(1);
12230     } else
12231       HasComplained |= Complain;
12232   }
12233 
12234   void EliminateAllTemplateMatches() {
12235     //   [...] any function template specializations in the set are
12236     //   eliminated if the set also contains a non-template function, [...]
12237     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12238       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12239         ++I;
12240       else {
12241         Matches[I] = Matches[--N];
12242         Matches.resize(N);
12243       }
12244     }
12245   }
12246 
12247   void EliminateSuboptimalCudaMatches() {
12248     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12249   }
12250 
12251 public:
12252   void ComplainNoMatchesFound() const {
12253     assert(Matches.empty());
12254     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12255         << OvlExpr->getName() << TargetFunctionType
12256         << OvlExpr->getSourceRange();
12257     if (FailedCandidates.empty())
12258       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12259                                   /*TakingAddress=*/true);
12260     else {
12261       // We have some deduction failure messages. Use them to diagnose
12262       // the function templates, and diagnose the non-template candidates
12263       // normally.
12264       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12265                                  IEnd = OvlExpr->decls_end();
12266            I != IEnd; ++I)
12267         if (FunctionDecl *Fun =
12268                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12269           if (!functionHasPassObjectSizeParams(Fun))
12270             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12271                                     /*TakingAddress=*/true);
12272       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12273     }
12274   }
12275 
12276   bool IsInvalidFormOfPointerToMemberFunction() const {
12277     return TargetTypeIsNonStaticMemberFunction &&
12278       !OvlExprInfo.HasFormOfMemberPointer;
12279   }
12280 
12281   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12282       // TODO: Should we condition this on whether any functions might
12283       // have matched, or is it more appropriate to do that in callers?
12284       // TODO: a fixit wouldn't hurt.
12285       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12286         << TargetType << OvlExpr->getSourceRange();
12287   }
12288 
12289   bool IsStaticMemberFunctionFromBoundPointer() const {
12290     return StaticMemberFunctionFromBoundPointer;
12291   }
12292 
12293   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12294     S.Diag(OvlExpr->getBeginLoc(),
12295            diag::err_invalid_form_pointer_member_function)
12296         << OvlExpr->getSourceRange();
12297   }
12298 
12299   void ComplainOfInvalidConversion() const {
12300     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12301         << OvlExpr->getName() << TargetType;
12302   }
12303 
12304   void ComplainMultipleMatchesFound() const {
12305     assert(Matches.size() > 1);
12306     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12307         << OvlExpr->getName() << OvlExpr->getSourceRange();
12308     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12309                                 /*TakingAddress=*/true);
12310   }
12311 
12312   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12313 
12314   int getNumMatches() const { return Matches.size(); }
12315 
12316   FunctionDecl* getMatchingFunctionDecl() const {
12317     if (Matches.size() != 1) return nullptr;
12318     return Matches[0].second;
12319   }
12320 
12321   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12322     if (Matches.size() != 1) return nullptr;
12323     return &Matches[0].first;
12324   }
12325 };
12326 }
12327 
12328 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12329 /// an overloaded function (C++ [over.over]), where @p From is an
12330 /// expression with overloaded function type and @p ToType is the type
12331 /// we're trying to resolve to. For example:
12332 ///
12333 /// @code
12334 /// int f(double);
12335 /// int f(int);
12336 ///
12337 /// int (*pfd)(double) = f; // selects f(double)
12338 /// @endcode
12339 ///
12340 /// This routine returns the resulting FunctionDecl if it could be
12341 /// resolved, and NULL otherwise. When @p Complain is true, this
12342 /// routine will emit diagnostics if there is an error.
12343 FunctionDecl *
12344 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12345                                          QualType TargetType,
12346                                          bool Complain,
12347                                          DeclAccessPair &FoundResult,
12348                                          bool *pHadMultipleCandidates) {
12349   assert(AddressOfExpr->getType() == Context.OverloadTy);
12350 
12351   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12352                                      Complain);
12353   int NumMatches = Resolver.getNumMatches();
12354   FunctionDecl *Fn = nullptr;
12355   bool ShouldComplain = Complain && !Resolver.hasComplained();
12356   if (NumMatches == 0 && ShouldComplain) {
12357     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12358       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12359     else
12360       Resolver.ComplainNoMatchesFound();
12361   }
12362   else if (NumMatches > 1 && ShouldComplain)
12363     Resolver.ComplainMultipleMatchesFound();
12364   else if (NumMatches == 1) {
12365     Fn = Resolver.getMatchingFunctionDecl();
12366     assert(Fn);
12367     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12368       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12369     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12370     if (Complain) {
12371       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12372         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12373       else
12374         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12375     }
12376   }
12377 
12378   if (pHadMultipleCandidates)
12379     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12380   return Fn;
12381 }
12382 
12383 /// Given an expression that refers to an overloaded function, try to
12384 /// resolve that function to a single function that can have its address taken.
12385 /// This will modify `Pair` iff it returns non-null.
12386 ///
12387 /// This routine can only succeed if from all of the candidates in the overload
12388 /// set for SrcExpr that can have their addresses taken, there is one candidate
12389 /// that is more constrained than the rest.
12390 FunctionDecl *
12391 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12392   OverloadExpr::FindResult R = OverloadExpr::find(E);
12393   OverloadExpr *Ovl = R.Expression;
12394   bool IsResultAmbiguous = false;
12395   FunctionDecl *Result = nullptr;
12396   DeclAccessPair DAP;
12397   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12398 
12399   auto CheckMoreConstrained =
12400       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12401         SmallVector<const Expr *, 1> AC1, AC2;
12402         FD1->getAssociatedConstraints(AC1);
12403         FD2->getAssociatedConstraints(AC2);
12404         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12405         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12406           return None;
12407         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12408           return None;
12409         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12410           return None;
12411         return AtLeastAsConstrained1;
12412       };
12413 
12414   // Don't use the AddressOfResolver because we're specifically looking for
12415   // cases where we have one overload candidate that lacks
12416   // enable_if/pass_object_size/...
12417   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12418     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12419     if (!FD)
12420       return nullptr;
12421 
12422     if (!checkAddressOfFunctionIsAvailable(FD))
12423       continue;
12424 
12425     // We have more than one result - see if it is more constrained than the
12426     // previous one.
12427     if (Result) {
12428       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12429                                                                         Result);
12430       if (!MoreConstrainedThanPrevious) {
12431         IsResultAmbiguous = true;
12432         AmbiguousDecls.push_back(FD);
12433         continue;
12434       }
12435       if (!*MoreConstrainedThanPrevious)
12436         continue;
12437       // FD is more constrained - replace Result with it.
12438     }
12439     IsResultAmbiguous = false;
12440     DAP = I.getPair();
12441     Result = FD;
12442   }
12443 
12444   if (IsResultAmbiguous)
12445     return nullptr;
12446 
12447   if (Result) {
12448     SmallVector<const Expr *, 1> ResultAC;
12449     // We skipped over some ambiguous declarations which might be ambiguous with
12450     // the selected result.
12451     for (FunctionDecl *Skipped : AmbiguousDecls)
12452       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12453         return nullptr;
12454     Pair = DAP;
12455   }
12456   return Result;
12457 }
12458 
12459 /// Given an overloaded function, tries to turn it into a non-overloaded
12460 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12461 /// will perform access checks, diagnose the use of the resultant decl, and, if
12462 /// requested, potentially perform a function-to-pointer decay.
12463 ///
12464 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12465 /// Otherwise, returns true. This may emit diagnostics and return true.
12466 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12467     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12468   Expr *E = SrcExpr.get();
12469   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12470 
12471   DeclAccessPair DAP;
12472   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12473   if (!Found || Found->isCPUDispatchMultiVersion() ||
12474       Found->isCPUSpecificMultiVersion())
12475     return false;
12476 
12477   // Emitting multiple diagnostics for a function that is both inaccessible and
12478   // unavailable is consistent with our behavior elsewhere. So, always check
12479   // for both.
12480   DiagnoseUseOfDecl(Found, E->getExprLoc());
12481   CheckAddressOfMemberAccess(E, DAP);
12482   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12483   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12484     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12485   else
12486     SrcExpr = Fixed;
12487   return true;
12488 }
12489 
12490 /// Given an expression that refers to an overloaded function, try to
12491 /// resolve that overloaded function expression down to a single function.
12492 ///
12493 /// This routine can only resolve template-ids that refer to a single function
12494 /// template, where that template-id refers to a single template whose template
12495 /// arguments are either provided by the template-id or have defaults,
12496 /// as described in C++0x [temp.arg.explicit]p3.
12497 ///
12498 /// If no template-ids are found, no diagnostics are emitted and NULL is
12499 /// returned.
12500 FunctionDecl *
12501 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12502                                                   bool Complain,
12503                                                   DeclAccessPair *FoundResult) {
12504   // C++ [over.over]p1:
12505   //   [...] [Note: any redundant set of parentheses surrounding the
12506   //   overloaded function name is ignored (5.1). ]
12507   // C++ [over.over]p1:
12508   //   [...] The overloaded function name can be preceded by the &
12509   //   operator.
12510 
12511   // If we didn't actually find any template-ids, we're done.
12512   if (!ovl->hasExplicitTemplateArgs())
12513     return nullptr;
12514 
12515   TemplateArgumentListInfo ExplicitTemplateArgs;
12516   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12517   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12518 
12519   // Look through all of the overloaded functions, searching for one
12520   // whose type matches exactly.
12521   FunctionDecl *Matched = nullptr;
12522   for (UnresolvedSetIterator I = ovl->decls_begin(),
12523          E = ovl->decls_end(); I != E; ++I) {
12524     // C++0x [temp.arg.explicit]p3:
12525     //   [...] In contexts where deduction is done and fails, or in contexts
12526     //   where deduction is not done, if a template argument list is
12527     //   specified and it, along with any default template arguments,
12528     //   identifies a single function template specialization, then the
12529     //   template-id is an lvalue for the function template specialization.
12530     FunctionTemplateDecl *FunctionTemplate
12531       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12532 
12533     // C++ [over.over]p2:
12534     //   If the name is a function template, template argument deduction is
12535     //   done (14.8.2.2), and if the argument deduction succeeds, the
12536     //   resulting template argument list is used to generate a single
12537     //   function template specialization, which is added to the set of
12538     //   overloaded functions considered.
12539     FunctionDecl *Specialization = nullptr;
12540     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12541     if (TemplateDeductionResult Result
12542           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12543                                     Specialization, Info,
12544                                     /*IsAddressOfFunction*/true)) {
12545       // Make a note of the failed deduction for diagnostics.
12546       // TODO: Actually use the failed-deduction info?
12547       FailedCandidates.addCandidate()
12548           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12549                MakeDeductionFailureInfo(Context, Result, Info));
12550       continue;
12551     }
12552 
12553     assert(Specialization && "no specialization and no error?");
12554 
12555     // Multiple matches; we can't resolve to a single declaration.
12556     if (Matched) {
12557       if (Complain) {
12558         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12559           << ovl->getName();
12560         NoteAllOverloadCandidates(ovl);
12561       }
12562       return nullptr;
12563     }
12564 
12565     Matched = Specialization;
12566     if (FoundResult) *FoundResult = I.getPair();
12567   }
12568 
12569   if (Matched &&
12570       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12571     return nullptr;
12572 
12573   return Matched;
12574 }
12575 
12576 // Resolve and fix an overloaded expression that can be resolved
12577 // because it identifies a single function template specialization.
12578 //
12579 // Last three arguments should only be supplied if Complain = true
12580 //
12581 // Return true if it was logically possible to so resolve the
12582 // expression, regardless of whether or not it succeeded.  Always
12583 // returns true if 'complain' is set.
12584 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12585                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12586                       bool complain, SourceRange OpRangeForComplaining,
12587                                            QualType DestTypeForComplaining,
12588                                             unsigned DiagIDForComplaining) {
12589   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12590 
12591   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12592 
12593   DeclAccessPair found;
12594   ExprResult SingleFunctionExpression;
12595   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12596                            ovl.Expression, /*complain*/ false, &found)) {
12597     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12598       SrcExpr = ExprError();
12599       return true;
12600     }
12601 
12602     // It is only correct to resolve to an instance method if we're
12603     // resolving a form that's permitted to be a pointer to member.
12604     // Otherwise we'll end up making a bound member expression, which
12605     // is illegal in all the contexts we resolve like this.
12606     if (!ovl.HasFormOfMemberPointer &&
12607         isa<CXXMethodDecl>(fn) &&
12608         cast<CXXMethodDecl>(fn)->isInstance()) {
12609       if (!complain) return false;
12610 
12611       Diag(ovl.Expression->getExprLoc(),
12612            diag::err_bound_member_function)
12613         << 0 << ovl.Expression->getSourceRange();
12614 
12615       // TODO: I believe we only end up here if there's a mix of
12616       // static and non-static candidates (otherwise the expression
12617       // would have 'bound member' type, not 'overload' type).
12618       // Ideally we would note which candidate was chosen and why
12619       // the static candidates were rejected.
12620       SrcExpr = ExprError();
12621       return true;
12622     }
12623 
12624     // Fix the expression to refer to 'fn'.
12625     SingleFunctionExpression =
12626         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12627 
12628     // If desired, do function-to-pointer decay.
12629     if (doFunctionPointerConverion) {
12630       SingleFunctionExpression =
12631         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12632       if (SingleFunctionExpression.isInvalid()) {
12633         SrcExpr = ExprError();
12634         return true;
12635       }
12636     }
12637   }
12638 
12639   if (!SingleFunctionExpression.isUsable()) {
12640     if (complain) {
12641       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12642         << ovl.Expression->getName()
12643         << DestTypeForComplaining
12644         << OpRangeForComplaining
12645         << ovl.Expression->getQualifierLoc().getSourceRange();
12646       NoteAllOverloadCandidates(SrcExpr.get());
12647 
12648       SrcExpr = ExprError();
12649       return true;
12650     }
12651 
12652     return false;
12653   }
12654 
12655   SrcExpr = SingleFunctionExpression;
12656   return true;
12657 }
12658 
12659 /// Add a single candidate to the overload set.
12660 static void AddOverloadedCallCandidate(Sema &S,
12661                                        DeclAccessPair FoundDecl,
12662                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12663                                        ArrayRef<Expr *> Args,
12664                                        OverloadCandidateSet &CandidateSet,
12665                                        bool PartialOverloading,
12666                                        bool KnownValid) {
12667   NamedDecl *Callee = FoundDecl.getDecl();
12668   if (isa<UsingShadowDecl>(Callee))
12669     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12670 
12671   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12672     if (ExplicitTemplateArgs) {
12673       assert(!KnownValid && "Explicit template arguments?");
12674       return;
12675     }
12676     // Prevent ill-formed function decls to be added as overload candidates.
12677     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12678       return;
12679 
12680     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12681                            /*SuppressUserConversions=*/false,
12682                            PartialOverloading);
12683     return;
12684   }
12685 
12686   if (FunctionTemplateDecl *FuncTemplate
12687       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12688     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12689                                    ExplicitTemplateArgs, Args, CandidateSet,
12690                                    /*SuppressUserConversions=*/false,
12691                                    PartialOverloading);
12692     return;
12693   }
12694 
12695   assert(!KnownValid && "unhandled case in overloaded call candidate");
12696 }
12697 
12698 /// Add the overload candidates named by callee and/or found by argument
12699 /// dependent lookup to the given overload set.
12700 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12701                                        ArrayRef<Expr *> Args,
12702                                        OverloadCandidateSet &CandidateSet,
12703                                        bool PartialOverloading) {
12704 
12705 #ifndef NDEBUG
12706   // Verify that ArgumentDependentLookup is consistent with the rules
12707   // in C++0x [basic.lookup.argdep]p3:
12708   //
12709   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12710   //   and let Y be the lookup set produced by argument dependent
12711   //   lookup (defined as follows). If X contains
12712   //
12713   //     -- a declaration of a class member, or
12714   //
12715   //     -- a block-scope function declaration that is not a
12716   //        using-declaration, or
12717   //
12718   //     -- a declaration that is neither a function or a function
12719   //        template
12720   //
12721   //   then Y is empty.
12722 
12723   if (ULE->requiresADL()) {
12724     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12725            E = ULE->decls_end(); I != E; ++I) {
12726       assert(!(*I)->getDeclContext()->isRecord());
12727       assert(isa<UsingShadowDecl>(*I) ||
12728              !(*I)->getDeclContext()->isFunctionOrMethod());
12729       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12730     }
12731   }
12732 #endif
12733 
12734   // It would be nice to avoid this copy.
12735   TemplateArgumentListInfo TABuffer;
12736   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12737   if (ULE->hasExplicitTemplateArgs()) {
12738     ULE->copyTemplateArgumentsInto(TABuffer);
12739     ExplicitTemplateArgs = &TABuffer;
12740   }
12741 
12742   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12743          E = ULE->decls_end(); I != E; ++I)
12744     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12745                                CandidateSet, PartialOverloading,
12746                                /*KnownValid*/ true);
12747 
12748   if (ULE->requiresADL())
12749     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12750                                          Args, ExplicitTemplateArgs,
12751                                          CandidateSet, PartialOverloading);
12752 }
12753 
12754 /// Add the call candidates from the given set of lookup results to the given
12755 /// overload set. Non-function lookup results are ignored.
12756 void Sema::AddOverloadedCallCandidates(
12757     LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
12758     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
12759   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12760     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12761                                CandidateSet, false, /*KnownValid*/ false);
12762 }
12763 
12764 /// Determine whether a declaration with the specified name could be moved into
12765 /// a different namespace.
12766 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12767   switch (Name.getCXXOverloadedOperator()) {
12768   case OO_New: case OO_Array_New:
12769   case OO_Delete: case OO_Array_Delete:
12770     return false;
12771 
12772   default:
12773     return true;
12774   }
12775 }
12776 
12777 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12778 /// template, where the non-dependent name was declared after the template
12779 /// was defined. This is common in code written for a compilers which do not
12780 /// correctly implement two-stage name lookup.
12781 ///
12782 /// Returns true if a viable candidate was found and a diagnostic was issued.
12783 static bool DiagnoseTwoPhaseLookup(
12784     Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
12785     LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
12786     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12787     CXXRecordDecl **FoundInClass = nullptr) {
12788   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12789     return false;
12790 
12791   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12792     if (DC->isTransparentContext())
12793       continue;
12794 
12795     SemaRef.LookupQualifiedName(R, DC);
12796 
12797     if (!R.empty()) {
12798       R.suppressDiagnostics();
12799 
12800       OverloadCandidateSet Candidates(FnLoc, CSK);
12801       SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
12802                                           Candidates);
12803 
12804       OverloadCandidateSet::iterator Best;
12805       OverloadingResult OR =
12806           Candidates.BestViableFunction(SemaRef, FnLoc, Best);
12807 
12808       if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
12809         // We either found non-function declarations or a best viable function
12810         // at class scope. A class-scope lookup result disables ADL. Don't
12811         // look past this, but let the caller know that we found something that
12812         // either is, or might be, usable in this class.
12813         if (FoundInClass) {
12814           *FoundInClass = RD;
12815           if (OR == OR_Success) {
12816             R.clear();
12817             R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
12818             R.resolveKind();
12819           }
12820         }
12821         return false;
12822       }
12823 
12824       if (OR != OR_Success) {
12825         // There wasn't a unique best function or function template.
12826         return false;
12827       }
12828 
12829       // Find the namespaces where ADL would have looked, and suggest
12830       // declaring the function there instead.
12831       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12832       Sema::AssociatedClassSet AssociatedClasses;
12833       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12834                                                  AssociatedNamespaces,
12835                                                  AssociatedClasses);
12836       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12837       if (canBeDeclaredInNamespace(R.getLookupName())) {
12838         DeclContext *Std = SemaRef.getStdNamespace();
12839         for (Sema::AssociatedNamespaceSet::iterator
12840                it = AssociatedNamespaces.begin(),
12841                end = AssociatedNamespaces.end(); it != end; ++it) {
12842           // Never suggest declaring a function within namespace 'std'.
12843           if (Std && Std->Encloses(*it))
12844             continue;
12845 
12846           // Never suggest declaring a function within a namespace with a
12847           // reserved name, like __gnu_cxx.
12848           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12849           if (NS &&
12850               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12851             continue;
12852 
12853           SuggestedNamespaces.insert(*it);
12854         }
12855       }
12856 
12857       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12858         << R.getLookupName();
12859       if (SuggestedNamespaces.empty()) {
12860         SemaRef.Diag(Best->Function->getLocation(),
12861                      diag::note_not_found_by_two_phase_lookup)
12862           << R.getLookupName() << 0;
12863       } else if (SuggestedNamespaces.size() == 1) {
12864         SemaRef.Diag(Best->Function->getLocation(),
12865                      diag::note_not_found_by_two_phase_lookup)
12866           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12867       } else {
12868         // FIXME: It would be useful to list the associated namespaces here,
12869         // but the diagnostics infrastructure doesn't provide a way to produce
12870         // a localized representation of a list of items.
12871         SemaRef.Diag(Best->Function->getLocation(),
12872                      diag::note_not_found_by_two_phase_lookup)
12873           << R.getLookupName() << 2;
12874       }
12875 
12876       // Try to recover by calling this function.
12877       return true;
12878     }
12879 
12880     R.clear();
12881   }
12882 
12883   return false;
12884 }
12885 
12886 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12887 /// template, where the non-dependent operator was declared after the template
12888 /// was defined.
12889 ///
12890 /// Returns true if a viable candidate was found and a diagnostic was issued.
12891 static bool
12892 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12893                                SourceLocation OpLoc,
12894                                ArrayRef<Expr *> Args) {
12895   DeclarationName OpName =
12896     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12897   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12898   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12899                                 OverloadCandidateSet::CSK_Operator,
12900                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12901 }
12902 
12903 namespace {
12904 class BuildRecoveryCallExprRAII {
12905   Sema &SemaRef;
12906 public:
12907   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12908     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12909     SemaRef.IsBuildingRecoveryCallExpr = true;
12910   }
12911 
12912   ~BuildRecoveryCallExprRAII() {
12913     SemaRef.IsBuildingRecoveryCallExpr = false;
12914   }
12915 };
12916 
12917 }
12918 
12919 /// Attempts to recover from a call where no functions were found.
12920 ///
12921 /// This function will do one of three things:
12922 ///  * Diagnose, recover, and return a recovery expression.
12923 ///  * Diagnose, fail to recover, and return ExprError().
12924 ///  * Do not diagnose, do not recover, and return ExprResult(). The caller is
12925 ///    expected to diagnose as appropriate.
12926 static ExprResult
12927 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12928                       UnresolvedLookupExpr *ULE,
12929                       SourceLocation LParenLoc,
12930                       MutableArrayRef<Expr *> Args,
12931                       SourceLocation RParenLoc,
12932                       bool EmptyLookup, bool AllowTypoCorrection) {
12933   // Do not try to recover if it is already building a recovery call.
12934   // This stops infinite loops for template instantiations like
12935   //
12936   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12937   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12938   if (SemaRef.IsBuildingRecoveryCallExpr)
12939     return ExprResult();
12940   BuildRecoveryCallExprRAII RCE(SemaRef);
12941 
12942   CXXScopeSpec SS;
12943   SS.Adopt(ULE->getQualifierLoc());
12944   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12945 
12946   TemplateArgumentListInfo TABuffer;
12947   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12948   if (ULE->hasExplicitTemplateArgs()) {
12949     ULE->copyTemplateArgumentsInto(TABuffer);
12950     ExplicitTemplateArgs = &TABuffer;
12951   }
12952 
12953   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12954                  Sema::LookupOrdinaryName);
12955   CXXRecordDecl *FoundInClass = nullptr;
12956   if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
12957                              OverloadCandidateSet::CSK_Normal,
12958                              ExplicitTemplateArgs, Args, &FoundInClass)) {
12959     // OK, diagnosed a two-phase lookup issue.
12960   } else if (EmptyLookup) {
12961     // Try to recover from an empty lookup with typo correction.
12962     R.clear();
12963     NoTypoCorrectionCCC NoTypoValidator{};
12964     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12965                                                 ExplicitTemplateArgs != nullptr,
12966                                                 dyn_cast<MemberExpr>(Fn));
12967     CorrectionCandidateCallback &Validator =
12968         AllowTypoCorrection
12969             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12970             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12971     if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12972                                     Args))
12973       return ExprError();
12974   } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
12975     // We found a usable declaration of the name in a dependent base of some
12976     // enclosing class.
12977     // FIXME: We should also explain why the candidates found by name lookup
12978     // were not viable.
12979     if (SemaRef.DiagnoseDependentMemberLookup(R))
12980       return ExprError();
12981   } else {
12982     // We had viable candidates and couldn't recover; let the caller diagnose
12983     // this.
12984     return ExprResult();
12985   }
12986 
12987   // If we get here, we should have issued a diagnostic and formed a recovery
12988   // lookup result.
12989   assert(!R.empty() && "lookup results empty despite recovery");
12990 
12991   // If recovery created an ambiguity, just bail out.
12992   if (R.isAmbiguous()) {
12993     R.suppressDiagnostics();
12994     return ExprError();
12995   }
12996 
12997   // Build an implicit member call if appropriate.  Just drop the
12998   // casts and such from the call, we don't really care.
12999   ExprResult NewFn = ExprError();
13000   if ((*R.begin())->isCXXClassMember())
13001     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13002                                                     ExplicitTemplateArgs, S);
13003   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13004     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13005                                         ExplicitTemplateArgs);
13006   else
13007     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13008 
13009   if (NewFn.isInvalid())
13010     return ExprError();
13011 
13012   // This shouldn't cause an infinite loop because we're giving it
13013   // an expression with viable lookup results, which should never
13014   // end up here.
13015   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13016                                MultiExprArg(Args.data(), Args.size()),
13017                                RParenLoc);
13018 }
13019 
13020 /// Constructs and populates an OverloadedCandidateSet from
13021 /// the given function.
13022 /// \returns true when an the ExprResult output parameter has been set.
13023 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13024                                   UnresolvedLookupExpr *ULE,
13025                                   MultiExprArg Args,
13026                                   SourceLocation RParenLoc,
13027                                   OverloadCandidateSet *CandidateSet,
13028                                   ExprResult *Result) {
13029 #ifndef NDEBUG
13030   if (ULE->requiresADL()) {
13031     // To do ADL, we must have found an unqualified name.
13032     assert(!ULE->getQualifier() && "qualified name with ADL");
13033 
13034     // We don't perform ADL for implicit declarations of builtins.
13035     // Verify that this was correctly set up.
13036     FunctionDecl *F;
13037     if (ULE->decls_begin() != ULE->decls_end() &&
13038         ULE->decls_begin() + 1 == ULE->decls_end() &&
13039         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13040         F->getBuiltinID() && F->isImplicit())
13041       llvm_unreachable("performing ADL for builtin");
13042 
13043     // We don't perform ADL in C.
13044     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13045   }
13046 #endif
13047 
13048   UnbridgedCastsSet UnbridgedCasts;
13049   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13050     *Result = ExprError();
13051     return true;
13052   }
13053 
13054   // Add the functions denoted by the callee to the set of candidate
13055   // functions, including those from argument-dependent lookup.
13056   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13057 
13058   if (getLangOpts().MSVCCompat &&
13059       CurContext->isDependentContext() && !isSFINAEContext() &&
13060       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13061 
13062     OverloadCandidateSet::iterator Best;
13063     if (CandidateSet->empty() ||
13064         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13065             OR_No_Viable_Function) {
13066       // In Microsoft mode, if we are inside a template class member function
13067       // then create a type dependent CallExpr. The goal is to postpone name
13068       // lookup to instantiation time to be able to search into type dependent
13069       // base classes.
13070       CallExpr *CE =
13071           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13072                            RParenLoc, CurFPFeatureOverrides());
13073       CE->markDependentForPostponedNameLookup();
13074       *Result = CE;
13075       return true;
13076     }
13077   }
13078 
13079   if (CandidateSet->empty())
13080     return false;
13081 
13082   UnbridgedCasts.restore();
13083   return false;
13084 }
13085 
13086 // Guess at what the return type for an unresolvable overload should be.
13087 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13088                                    OverloadCandidateSet::iterator *Best) {
13089   llvm::Optional<QualType> Result;
13090   // Adjust Type after seeing a candidate.
13091   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13092     if (!Candidate.Function)
13093       return;
13094     if (Candidate.Function->isInvalidDecl())
13095       return;
13096     QualType T = Candidate.Function->getReturnType();
13097     if (T.isNull())
13098       return;
13099     if (!Result)
13100       Result = T;
13101     else if (Result != T)
13102       Result = QualType();
13103   };
13104 
13105   // Look for an unambiguous type from a progressively larger subset.
13106   // e.g. if types disagree, but all *viable* overloads return int, choose int.
13107   //
13108   // First, consider only the best candidate.
13109   if (Best && *Best != CS.end())
13110     ConsiderCandidate(**Best);
13111   // Next, consider only viable candidates.
13112   if (!Result)
13113     for (const auto &C : CS)
13114       if (C.Viable)
13115         ConsiderCandidate(C);
13116   // Finally, consider all candidates.
13117   if (!Result)
13118     for (const auto &C : CS)
13119       ConsiderCandidate(C);
13120 
13121   if (!Result)
13122     return QualType();
13123   auto Value = Result.getValue();
13124   if (Value.isNull() || Value->isUndeducedType())
13125     return QualType();
13126   return Value;
13127 }
13128 
13129 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13130 /// the completed call expression. If overload resolution fails, emits
13131 /// diagnostics and returns ExprError()
13132 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13133                                            UnresolvedLookupExpr *ULE,
13134                                            SourceLocation LParenLoc,
13135                                            MultiExprArg Args,
13136                                            SourceLocation RParenLoc,
13137                                            Expr *ExecConfig,
13138                                            OverloadCandidateSet *CandidateSet,
13139                                            OverloadCandidateSet::iterator *Best,
13140                                            OverloadingResult OverloadResult,
13141                                            bool AllowTypoCorrection) {
13142   switch (OverloadResult) {
13143   case OR_Success: {
13144     FunctionDecl *FDecl = (*Best)->Function;
13145     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
13146     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
13147       return ExprError();
13148     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13149     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13150                                          ExecConfig, /*IsExecConfig=*/false,
13151                                          (*Best)->IsADLCandidate);
13152   }
13153 
13154   case OR_No_Viable_Function: {
13155     // Try to recover by looking for viable functions which the user might
13156     // have meant to call.
13157     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
13158                                                 Args, RParenLoc,
13159                                                 CandidateSet->empty(),
13160                                                 AllowTypoCorrection);
13161     if (Recovery.isInvalid() || Recovery.isUsable())
13162       return Recovery;
13163 
13164     // If the user passes in a function that we can't take the address of, we
13165     // generally end up emitting really bad error messages. Here, we attempt to
13166     // emit better ones.
13167     for (const Expr *Arg : Args) {
13168       if (!Arg->getType()->isFunctionType())
13169         continue;
13170       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
13171         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13172         if (FD &&
13173             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13174                                                        Arg->getExprLoc()))
13175           return ExprError();
13176       }
13177     }
13178 
13179     CandidateSet->NoteCandidates(
13180         PartialDiagnosticAt(
13181             Fn->getBeginLoc(),
13182             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
13183                 << ULE->getName() << Fn->getSourceRange()),
13184         SemaRef, OCD_AllCandidates, Args);
13185     break;
13186   }
13187 
13188   case OR_Ambiguous:
13189     CandidateSet->NoteCandidates(
13190         PartialDiagnosticAt(Fn->getBeginLoc(),
13191                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
13192                                 << ULE->getName() << Fn->getSourceRange()),
13193         SemaRef, OCD_AmbiguousCandidates, Args);
13194     break;
13195 
13196   case OR_Deleted: {
13197     CandidateSet->NoteCandidates(
13198         PartialDiagnosticAt(Fn->getBeginLoc(),
13199                             SemaRef.PDiag(diag::err_ovl_deleted_call)
13200                                 << ULE->getName() << Fn->getSourceRange()),
13201         SemaRef, OCD_AllCandidates, Args);
13202 
13203     // We emitted an error for the unavailable/deleted function call but keep
13204     // the call in the AST.
13205     FunctionDecl *FDecl = (*Best)->Function;
13206     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
13207     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
13208                                          ExecConfig, /*IsExecConfig=*/false,
13209                                          (*Best)->IsADLCandidate);
13210   }
13211   }
13212 
13213   // Overload resolution failed, try to recover.
13214   SmallVector<Expr *, 8> SubExprs = {Fn};
13215   SubExprs.append(Args.begin(), Args.end());
13216   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
13217                                     chooseRecoveryType(*CandidateSet, Best));
13218 }
13219 
13220 static void markUnaddressableCandidatesUnviable(Sema &S,
13221                                                 OverloadCandidateSet &CS) {
13222   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
13223     if (I->Viable &&
13224         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
13225       I->Viable = false;
13226       I->FailureKind = ovl_fail_addr_not_available;
13227     }
13228   }
13229 }
13230 
13231 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13232 /// (which eventually refers to the declaration Func) and the call
13233 /// arguments Args/NumArgs, attempt to resolve the function call down
13234 /// to a specific function. If overload resolution succeeds, returns
13235 /// the call expression produced by overload resolution.
13236 /// Otherwise, emits diagnostics and returns ExprError.
13237 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13238                                          UnresolvedLookupExpr *ULE,
13239                                          SourceLocation LParenLoc,
13240                                          MultiExprArg Args,
13241                                          SourceLocation RParenLoc,
13242                                          Expr *ExecConfig,
13243                                          bool AllowTypoCorrection,
13244                                          bool CalleesAddressIsTaken) {
13245   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13246                                     OverloadCandidateSet::CSK_Normal);
13247   ExprResult result;
13248 
13249   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13250                              &result))
13251     return result;
13252 
13253   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13254   // functions that aren't addressible are considered unviable.
13255   if (CalleesAddressIsTaken)
13256     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13257 
13258   OverloadCandidateSet::iterator Best;
13259   OverloadingResult OverloadResult =
13260       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13261 
13262   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13263                                   ExecConfig, &CandidateSet, &Best,
13264                                   OverloadResult, AllowTypoCorrection);
13265 }
13266 
13267 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13268   return Functions.size() > 1 ||
13269          (Functions.size() == 1 &&
13270           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13271 }
13272 
13273 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13274                                             NestedNameSpecifierLoc NNSLoc,
13275                                             DeclarationNameInfo DNI,
13276                                             const UnresolvedSetImpl &Fns,
13277                                             bool PerformADL) {
13278   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13279                                       PerformADL, IsOverloaded(Fns),
13280                                       Fns.begin(), Fns.end());
13281 }
13282 
13283 /// Create a unary operation that may resolve to an overloaded
13284 /// operator.
13285 ///
13286 /// \param OpLoc The location of the operator itself (e.g., '*').
13287 ///
13288 /// \param Opc The UnaryOperatorKind that describes this operator.
13289 ///
13290 /// \param Fns The set of non-member functions that will be
13291 /// considered by overload resolution. The caller needs to build this
13292 /// set based on the context using, e.g.,
13293 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13294 /// set should not contain any member functions; those will be added
13295 /// by CreateOverloadedUnaryOp().
13296 ///
13297 /// \param Input The input argument.
13298 ExprResult
13299 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13300                               const UnresolvedSetImpl &Fns,
13301                               Expr *Input, bool PerformADL) {
13302   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13303   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13304   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13305   // TODO: provide better source location info.
13306   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13307 
13308   if (checkPlaceholderForOverload(*this, Input))
13309     return ExprError();
13310 
13311   Expr *Args[2] = { Input, nullptr };
13312   unsigned NumArgs = 1;
13313 
13314   // For post-increment and post-decrement, add the implicit '0' as
13315   // the second argument, so that we know this is a post-increment or
13316   // post-decrement.
13317   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13318     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13319     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13320                                      SourceLocation());
13321     NumArgs = 2;
13322   }
13323 
13324   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13325 
13326   if (Input->isTypeDependent()) {
13327     if (Fns.empty())
13328       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13329                                    VK_PRValue, OK_Ordinary, OpLoc, false,
13330                                    CurFPFeatureOverrides());
13331 
13332     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13333     ExprResult Fn = CreateUnresolvedLookupExpr(
13334         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13335     if (Fn.isInvalid())
13336       return ExprError();
13337     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13338                                        Context.DependentTy, VK_PRValue, OpLoc,
13339                                        CurFPFeatureOverrides());
13340   }
13341 
13342   // Build an empty overload set.
13343   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13344 
13345   // Add the candidates from the given function set.
13346   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13347 
13348   // Add operator candidates that are member functions.
13349   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13350 
13351   // Add candidates from ADL.
13352   if (PerformADL) {
13353     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13354                                          /*ExplicitTemplateArgs*/nullptr,
13355                                          CandidateSet);
13356   }
13357 
13358   // Add builtin operator candidates.
13359   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13360 
13361   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13362 
13363   // Perform overload resolution.
13364   OverloadCandidateSet::iterator Best;
13365   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13366   case OR_Success: {
13367     // We found a built-in operator or an overloaded operator.
13368     FunctionDecl *FnDecl = Best->Function;
13369 
13370     if (FnDecl) {
13371       Expr *Base = nullptr;
13372       // We matched an overloaded operator. Build a call to that
13373       // operator.
13374 
13375       // Convert the arguments.
13376       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13377         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13378 
13379         ExprResult InputRes =
13380           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13381                                               Best->FoundDecl, Method);
13382         if (InputRes.isInvalid())
13383           return ExprError();
13384         Base = Input = InputRes.get();
13385       } else {
13386         // Convert the arguments.
13387         ExprResult InputInit
13388           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13389                                                       Context,
13390                                                       FnDecl->getParamDecl(0)),
13391                                       SourceLocation(),
13392                                       Input);
13393         if (InputInit.isInvalid())
13394           return ExprError();
13395         Input = InputInit.get();
13396       }
13397 
13398       // Build the actual expression node.
13399       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13400                                                 Base, HadMultipleCandidates,
13401                                                 OpLoc);
13402       if (FnExpr.isInvalid())
13403         return ExprError();
13404 
13405       // Determine the result type.
13406       QualType ResultTy = FnDecl->getReturnType();
13407       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13408       ResultTy = ResultTy.getNonLValueExprType(Context);
13409 
13410       Args[0] = Input;
13411       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13412           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13413           CurFPFeatureOverrides(), Best->IsADLCandidate);
13414 
13415       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13416         return ExprError();
13417 
13418       if (CheckFunctionCall(FnDecl, TheCall,
13419                             FnDecl->getType()->castAs<FunctionProtoType>()))
13420         return ExprError();
13421       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13422     } else {
13423       // We matched a built-in operator. Convert the arguments, then
13424       // break out so that we will build the appropriate built-in
13425       // operator node.
13426       ExprResult InputRes = PerformImplicitConversion(
13427           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13428           CCK_ForBuiltinOverloadedOp);
13429       if (InputRes.isInvalid())
13430         return ExprError();
13431       Input = InputRes.get();
13432       break;
13433     }
13434   }
13435 
13436   case OR_No_Viable_Function:
13437     // This is an erroneous use of an operator which can be overloaded by
13438     // a non-member function. Check for non-member operators which were
13439     // defined too late to be candidates.
13440     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13441       // FIXME: Recover by calling the found function.
13442       return ExprError();
13443 
13444     // No viable function; fall through to handling this as a
13445     // built-in operator, which will produce an error message for us.
13446     break;
13447 
13448   case OR_Ambiguous:
13449     CandidateSet.NoteCandidates(
13450         PartialDiagnosticAt(OpLoc,
13451                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13452                                 << UnaryOperator::getOpcodeStr(Opc)
13453                                 << Input->getType() << Input->getSourceRange()),
13454         *this, OCD_AmbiguousCandidates, ArgsArray,
13455         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13456     return ExprError();
13457 
13458   case OR_Deleted:
13459     CandidateSet.NoteCandidates(
13460         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13461                                        << UnaryOperator::getOpcodeStr(Opc)
13462                                        << Input->getSourceRange()),
13463         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13464         OpLoc);
13465     return ExprError();
13466   }
13467 
13468   // Either we found no viable overloaded operator or we matched a
13469   // built-in operator. In either case, fall through to trying to
13470   // build a built-in operation.
13471   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13472 }
13473 
13474 /// Perform lookup for an overloaded binary operator.
13475 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13476                                  OverloadedOperatorKind Op,
13477                                  const UnresolvedSetImpl &Fns,
13478                                  ArrayRef<Expr *> Args, bool PerformADL) {
13479   SourceLocation OpLoc = CandidateSet.getLocation();
13480 
13481   OverloadedOperatorKind ExtraOp =
13482       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13483           ? getRewrittenOverloadedOperator(Op)
13484           : OO_None;
13485 
13486   // Add the candidates from the given function set. This also adds the
13487   // rewritten candidates using these functions if necessary.
13488   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13489 
13490   // Add operator candidates that are member functions.
13491   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13492   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13493     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13494                                 OverloadCandidateParamOrder::Reversed);
13495 
13496   // In C++20, also add any rewritten member candidates.
13497   if (ExtraOp) {
13498     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13499     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13500       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13501                                   CandidateSet,
13502                                   OverloadCandidateParamOrder::Reversed);
13503   }
13504 
13505   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13506   // performed for an assignment operator (nor for operator[] nor operator->,
13507   // which don't get here).
13508   if (Op != OO_Equal && PerformADL) {
13509     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13510     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13511                                          /*ExplicitTemplateArgs*/ nullptr,
13512                                          CandidateSet);
13513     if (ExtraOp) {
13514       DeclarationName ExtraOpName =
13515           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13516       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13517                                            /*ExplicitTemplateArgs*/ nullptr,
13518                                            CandidateSet);
13519     }
13520   }
13521 
13522   // Add builtin operator candidates.
13523   //
13524   // FIXME: We don't add any rewritten candidates here. This is strictly
13525   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13526   // resulting in our selecting a rewritten builtin candidate. For example:
13527   //
13528   //   enum class E { e };
13529   //   bool operator!=(E, E) requires false;
13530   //   bool k = E::e != E::e;
13531   //
13532   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13533   // it seems unreasonable to consider rewritten builtin candidates. A core
13534   // issue has been filed proposing to removed this requirement.
13535   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13536 }
13537 
13538 /// Create a binary operation that may resolve to an overloaded
13539 /// operator.
13540 ///
13541 /// \param OpLoc The location of the operator itself (e.g., '+').
13542 ///
13543 /// \param Opc The BinaryOperatorKind that describes this operator.
13544 ///
13545 /// \param Fns The set of non-member functions that will be
13546 /// considered by overload resolution. The caller needs to build this
13547 /// set based on the context using, e.g.,
13548 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13549 /// set should not contain any member functions; those will be added
13550 /// by CreateOverloadedBinOp().
13551 ///
13552 /// \param LHS Left-hand argument.
13553 /// \param RHS Right-hand argument.
13554 /// \param PerformADL Whether to consider operator candidates found by ADL.
13555 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13556 ///        C++20 operator rewrites.
13557 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13558 ///        the function in question. Such a function is never a candidate in
13559 ///        our overload resolution. This also enables synthesizing a three-way
13560 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13561 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13562                                        BinaryOperatorKind Opc,
13563                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13564                                        Expr *RHS, bool PerformADL,
13565                                        bool AllowRewrittenCandidates,
13566                                        FunctionDecl *DefaultedFn) {
13567   Expr *Args[2] = { LHS, RHS };
13568   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13569 
13570   if (!getLangOpts().CPlusPlus20)
13571     AllowRewrittenCandidates = false;
13572 
13573   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13574 
13575   // If either side is type-dependent, create an appropriate dependent
13576   // expression.
13577   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13578     if (Fns.empty()) {
13579       // If there are no functions to store, just build a dependent
13580       // BinaryOperator or CompoundAssignment.
13581       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13582         return CompoundAssignOperator::Create(
13583             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13584             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13585             Context.DependentTy);
13586       return BinaryOperator::Create(
13587           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
13588           OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13589     }
13590 
13591     // FIXME: save results of ADL from here?
13592     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13593     // TODO: provide better source location info in DNLoc component.
13594     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13595     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13596     ExprResult Fn = CreateUnresolvedLookupExpr(
13597         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13598     if (Fn.isInvalid())
13599       return ExprError();
13600     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13601                                        Context.DependentTy, VK_PRValue, OpLoc,
13602                                        CurFPFeatureOverrides());
13603   }
13604 
13605   // Always do placeholder-like conversions on the RHS.
13606   if (checkPlaceholderForOverload(*this, Args[1]))
13607     return ExprError();
13608 
13609   // Do placeholder-like conversion on the LHS; note that we should
13610   // not get here with a PseudoObject LHS.
13611   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13612   if (checkPlaceholderForOverload(*this, Args[0]))
13613     return ExprError();
13614 
13615   // If this is the assignment operator, we only perform overload resolution
13616   // if the left-hand side is a class or enumeration type. This is actually
13617   // a hack. The standard requires that we do overload resolution between the
13618   // various built-in candidates, but as DR507 points out, this can lead to
13619   // problems. So we do it this way, which pretty much follows what GCC does.
13620   // Note that we go the traditional code path for compound assignment forms.
13621   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13622     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13623 
13624   // If this is the .* operator, which is not overloadable, just
13625   // create a built-in binary operator.
13626   if (Opc == BO_PtrMemD)
13627     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13628 
13629   // Build the overload set.
13630   OverloadCandidateSet CandidateSet(
13631       OpLoc, OverloadCandidateSet::CSK_Operator,
13632       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13633   if (DefaultedFn)
13634     CandidateSet.exclude(DefaultedFn);
13635   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13636 
13637   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13638 
13639   // Perform overload resolution.
13640   OverloadCandidateSet::iterator Best;
13641   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13642     case OR_Success: {
13643       // We found a built-in operator or an overloaded operator.
13644       FunctionDecl *FnDecl = Best->Function;
13645 
13646       bool IsReversed = Best->isReversed();
13647       if (IsReversed)
13648         std::swap(Args[0], Args[1]);
13649 
13650       if (FnDecl) {
13651         Expr *Base = nullptr;
13652         // We matched an overloaded operator. Build a call to that
13653         // operator.
13654 
13655         OverloadedOperatorKind ChosenOp =
13656             FnDecl->getDeclName().getCXXOverloadedOperator();
13657 
13658         // C++2a [over.match.oper]p9:
13659         //   If a rewritten operator== candidate is selected by overload
13660         //   resolution for an operator@, its return type shall be cv bool
13661         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13662             !FnDecl->getReturnType()->isBooleanType()) {
13663           bool IsExtension =
13664               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13665           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13666                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13667               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13668               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13669           Diag(FnDecl->getLocation(), diag::note_declared_at);
13670           if (!IsExtension)
13671             return ExprError();
13672         }
13673 
13674         if (AllowRewrittenCandidates && !IsReversed &&
13675             CandidateSet.getRewriteInfo().isReversible()) {
13676           // We could have reversed this operator, but didn't. Check if some
13677           // reversed form was a viable candidate, and if so, if it had a
13678           // better conversion for either parameter. If so, this call is
13679           // formally ambiguous, and allowing it is an extension.
13680           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13681           for (OverloadCandidate &Cand : CandidateSet) {
13682             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13683                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13684               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13685                 if (CompareImplicitConversionSequences(
13686                         *this, OpLoc, Cand.Conversions[ArgIdx],
13687                         Best->Conversions[ArgIdx]) ==
13688                     ImplicitConversionSequence::Better) {
13689                   AmbiguousWith.push_back(Cand.Function);
13690                   break;
13691                 }
13692               }
13693             }
13694           }
13695 
13696           if (!AmbiguousWith.empty()) {
13697             bool AmbiguousWithSelf =
13698                 AmbiguousWith.size() == 1 &&
13699                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13700             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13701                 << BinaryOperator::getOpcodeStr(Opc)
13702                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13703                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13704             if (AmbiguousWithSelf) {
13705               Diag(FnDecl->getLocation(),
13706                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13707             } else {
13708               Diag(FnDecl->getLocation(),
13709                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13710               for (auto *F : AmbiguousWith)
13711                 Diag(F->getLocation(),
13712                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13713             }
13714           }
13715         }
13716 
13717         // Convert the arguments.
13718         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13719           // Best->Access is only meaningful for class members.
13720           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13721 
13722           ExprResult Arg1 =
13723             PerformCopyInitialization(
13724               InitializedEntity::InitializeParameter(Context,
13725                                                      FnDecl->getParamDecl(0)),
13726               SourceLocation(), Args[1]);
13727           if (Arg1.isInvalid())
13728             return ExprError();
13729 
13730           ExprResult Arg0 =
13731             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13732                                                 Best->FoundDecl, Method);
13733           if (Arg0.isInvalid())
13734             return ExprError();
13735           Base = Args[0] = Arg0.getAs<Expr>();
13736           Args[1] = RHS = Arg1.getAs<Expr>();
13737         } else {
13738           // Convert the arguments.
13739           ExprResult Arg0 = PerformCopyInitialization(
13740             InitializedEntity::InitializeParameter(Context,
13741                                                    FnDecl->getParamDecl(0)),
13742             SourceLocation(), Args[0]);
13743           if (Arg0.isInvalid())
13744             return ExprError();
13745 
13746           ExprResult Arg1 =
13747             PerformCopyInitialization(
13748               InitializedEntity::InitializeParameter(Context,
13749                                                      FnDecl->getParamDecl(1)),
13750               SourceLocation(), Args[1]);
13751           if (Arg1.isInvalid())
13752             return ExprError();
13753           Args[0] = LHS = Arg0.getAs<Expr>();
13754           Args[1] = RHS = Arg1.getAs<Expr>();
13755         }
13756 
13757         // Build the actual expression node.
13758         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13759                                                   Best->FoundDecl, Base,
13760                                                   HadMultipleCandidates, OpLoc);
13761         if (FnExpr.isInvalid())
13762           return ExprError();
13763 
13764         // Determine the result type.
13765         QualType ResultTy = FnDecl->getReturnType();
13766         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13767         ResultTy = ResultTy.getNonLValueExprType(Context);
13768 
13769         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13770             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13771             CurFPFeatureOverrides(), Best->IsADLCandidate);
13772 
13773         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13774                                 FnDecl))
13775           return ExprError();
13776 
13777         ArrayRef<const Expr *> ArgsArray(Args, 2);
13778         const Expr *ImplicitThis = nullptr;
13779         // Cut off the implicit 'this'.
13780         if (isa<CXXMethodDecl>(FnDecl)) {
13781           ImplicitThis = ArgsArray[0];
13782           ArgsArray = ArgsArray.slice(1);
13783         }
13784 
13785         // Check for a self move.
13786         if (Op == OO_Equal)
13787           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13788 
13789         if (ImplicitThis) {
13790           QualType ThisType = Context.getPointerType(ImplicitThis->getType());
13791           QualType ThisTypeFromDecl = Context.getPointerType(
13792               cast<CXXMethodDecl>(FnDecl)->getThisObjectType());
13793 
13794           CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
13795                             ThisTypeFromDecl);
13796         }
13797 
13798         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13799                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13800                   VariadicDoesNotApply);
13801 
13802         ExprResult R = MaybeBindToTemporary(TheCall);
13803         if (R.isInvalid())
13804           return ExprError();
13805 
13806         R = CheckForImmediateInvocation(R, FnDecl);
13807         if (R.isInvalid())
13808           return ExprError();
13809 
13810         // For a rewritten candidate, we've already reversed the arguments
13811         // if needed. Perform the rest of the rewrite now.
13812         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13813             (Op == OO_Spaceship && IsReversed)) {
13814           if (Op == OO_ExclaimEqual) {
13815             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13816             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13817           } else {
13818             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13819             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13820             Expr *ZeroLiteral =
13821                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13822 
13823             Sema::CodeSynthesisContext Ctx;
13824             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13825             Ctx.Entity = FnDecl;
13826             pushCodeSynthesisContext(Ctx);
13827 
13828             R = CreateOverloadedBinOp(
13829                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13830                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13831                 /*AllowRewrittenCandidates=*/false);
13832 
13833             popCodeSynthesisContext();
13834           }
13835           if (R.isInvalid())
13836             return ExprError();
13837         } else {
13838           assert(ChosenOp == Op && "unexpected operator name");
13839         }
13840 
13841         // Make a note in the AST if we did any rewriting.
13842         if (Best->RewriteKind != CRK_None)
13843           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13844 
13845         return R;
13846       } else {
13847         // We matched a built-in operator. Convert the arguments, then
13848         // break out so that we will build the appropriate built-in
13849         // operator node.
13850         ExprResult ArgsRes0 = PerformImplicitConversion(
13851             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13852             AA_Passing, CCK_ForBuiltinOverloadedOp);
13853         if (ArgsRes0.isInvalid())
13854           return ExprError();
13855         Args[0] = ArgsRes0.get();
13856 
13857         ExprResult ArgsRes1 = PerformImplicitConversion(
13858             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13859             AA_Passing, CCK_ForBuiltinOverloadedOp);
13860         if (ArgsRes1.isInvalid())
13861           return ExprError();
13862         Args[1] = ArgsRes1.get();
13863         break;
13864       }
13865     }
13866 
13867     case OR_No_Viable_Function: {
13868       // C++ [over.match.oper]p9:
13869       //   If the operator is the operator , [...] and there are no
13870       //   viable functions, then the operator is assumed to be the
13871       //   built-in operator and interpreted according to clause 5.
13872       if (Opc == BO_Comma)
13873         break;
13874 
13875       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13876       // compare result using '==' and '<'.
13877       if (DefaultedFn && Opc == BO_Cmp) {
13878         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13879                                                           Args[1], DefaultedFn);
13880         if (E.isInvalid() || E.isUsable())
13881           return E;
13882       }
13883 
13884       // For class as left operand for assignment or compound assignment
13885       // operator do not fall through to handling in built-in, but report that
13886       // no overloaded assignment operator found
13887       ExprResult Result = ExprError();
13888       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13889       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13890                                                    Args, OpLoc);
13891       DeferDiagsRAII DDR(*this,
13892                          CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
13893       if (Args[0]->getType()->isRecordType() &&
13894           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13895         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13896              << BinaryOperator::getOpcodeStr(Opc)
13897              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13898         if (Args[0]->getType()->isIncompleteType()) {
13899           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13900             << Args[0]->getType()
13901             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13902         }
13903       } else {
13904         // This is an erroneous use of an operator which can be overloaded by
13905         // a non-member function. Check for non-member operators which were
13906         // defined too late to be candidates.
13907         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13908           // FIXME: Recover by calling the found function.
13909           return ExprError();
13910 
13911         // No viable function; try to create a built-in operation, which will
13912         // produce an error. Then, show the non-viable candidates.
13913         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13914       }
13915       assert(Result.isInvalid() &&
13916              "C++ binary operator overloading is missing candidates!");
13917       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13918       return Result;
13919     }
13920 
13921     case OR_Ambiguous:
13922       CandidateSet.NoteCandidates(
13923           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13924                                          << BinaryOperator::getOpcodeStr(Opc)
13925                                          << Args[0]->getType()
13926                                          << Args[1]->getType()
13927                                          << Args[0]->getSourceRange()
13928                                          << Args[1]->getSourceRange()),
13929           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13930           OpLoc);
13931       return ExprError();
13932 
13933     case OR_Deleted:
13934       if (isImplicitlyDeleted(Best->Function)) {
13935         FunctionDecl *DeletedFD = Best->Function;
13936         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13937         if (DFK.isSpecialMember()) {
13938           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13939             << Args[0]->getType() << DFK.asSpecialMember();
13940         } else {
13941           assert(DFK.isComparison());
13942           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13943             << Args[0]->getType() << DeletedFD;
13944         }
13945 
13946         // The user probably meant to call this special member. Just
13947         // explain why it's deleted.
13948         NoteDeletedFunction(DeletedFD);
13949         return ExprError();
13950       }
13951       CandidateSet.NoteCandidates(
13952           PartialDiagnosticAt(
13953               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13954                          << getOperatorSpelling(Best->Function->getDeclName()
13955                                                     .getCXXOverloadedOperator())
13956                          << Args[0]->getSourceRange()
13957                          << Args[1]->getSourceRange()),
13958           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13959           OpLoc);
13960       return ExprError();
13961   }
13962 
13963   // We matched a built-in operator; build it.
13964   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13965 }
13966 
13967 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13968     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13969     FunctionDecl *DefaultedFn) {
13970   const ComparisonCategoryInfo *Info =
13971       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13972   // If we're not producing a known comparison category type, we can't
13973   // synthesize a three-way comparison. Let the caller diagnose this.
13974   if (!Info)
13975     return ExprResult((Expr*)nullptr);
13976 
13977   // If we ever want to perform this synthesis more generally, we will need to
13978   // apply the temporary materialization conversion to the operands.
13979   assert(LHS->isGLValue() && RHS->isGLValue() &&
13980          "cannot use prvalue expressions more than once");
13981   Expr *OrigLHS = LHS;
13982   Expr *OrigRHS = RHS;
13983 
13984   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13985   // each of them multiple times below.
13986   LHS = new (Context)
13987       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13988                       LHS->getObjectKind(), LHS);
13989   RHS = new (Context)
13990       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13991                       RHS->getObjectKind(), RHS);
13992 
13993   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13994                                         DefaultedFn);
13995   if (Eq.isInvalid())
13996     return ExprError();
13997 
13998   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13999                                           true, DefaultedFn);
14000   if (Less.isInvalid())
14001     return ExprError();
14002 
14003   ExprResult Greater;
14004   if (Info->isPartial()) {
14005     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
14006                                     DefaultedFn);
14007     if (Greater.isInvalid())
14008       return ExprError();
14009   }
14010 
14011   // Form the list of comparisons we're going to perform.
14012   struct Comparison {
14013     ExprResult Cmp;
14014     ComparisonCategoryResult Result;
14015   } Comparisons[4] =
14016   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
14017                           : ComparisonCategoryResult::Equivalent},
14018     {Less, ComparisonCategoryResult::Less},
14019     {Greater, ComparisonCategoryResult::Greater},
14020     {ExprResult(), ComparisonCategoryResult::Unordered},
14021   };
14022 
14023   int I = Info->isPartial() ? 3 : 2;
14024 
14025   // Combine the comparisons with suitable conditional expressions.
14026   ExprResult Result;
14027   for (; I >= 0; --I) {
14028     // Build a reference to the comparison category constant.
14029     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
14030     // FIXME: Missing a constant for a comparison category. Diagnose this?
14031     if (!VI)
14032       return ExprResult((Expr*)nullptr);
14033     ExprResult ThisResult =
14034         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
14035     if (ThisResult.isInvalid())
14036       return ExprError();
14037 
14038     // Build a conditional unless this is the final case.
14039     if (Result.get()) {
14040       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
14041                                   ThisResult.get(), Result.get());
14042       if (Result.isInvalid())
14043         return ExprError();
14044     } else {
14045       Result = ThisResult;
14046     }
14047   }
14048 
14049   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14050   // bind the OpaqueValueExprs before they're (repeatedly) used.
14051   Expr *SyntacticForm = BinaryOperator::Create(
14052       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
14053       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
14054       CurFPFeatureOverrides());
14055   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
14056   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
14057 }
14058 
14059 ExprResult
14060 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
14061                                          SourceLocation RLoc,
14062                                          Expr *Base, Expr *Idx) {
14063   Expr *Args[2] = { Base, Idx };
14064   DeclarationName OpName =
14065       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
14066 
14067   // If either side is type-dependent, create an appropriate dependent
14068   // expression.
14069   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14070 
14071     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14072     // CHECKME: no 'operator' keyword?
14073     DeclarationNameInfo OpNameInfo(OpName, LLoc);
14074     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14075     ExprResult Fn = CreateUnresolvedLookupExpr(
14076         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
14077     if (Fn.isInvalid())
14078       return ExprError();
14079     // Can't add any actual overloads yet
14080 
14081     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
14082                                        Context.DependentTy, VK_PRValue, RLoc,
14083                                        CurFPFeatureOverrides());
14084   }
14085 
14086   // Handle placeholders on both operands.
14087   if (checkPlaceholderForOverload(*this, Args[0]))
14088     return ExprError();
14089   if (checkPlaceholderForOverload(*this, Args[1]))
14090     return ExprError();
14091 
14092   // Build an empty overload set.
14093   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
14094 
14095   // Subscript can only be overloaded as a member function.
14096 
14097   // Add operator candidates that are member functions.
14098   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14099 
14100   // Add builtin operator candidates.
14101   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
14102 
14103   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14104 
14105   // Perform overload resolution.
14106   OverloadCandidateSet::iterator Best;
14107   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
14108     case OR_Success: {
14109       // We found a built-in operator or an overloaded operator.
14110       FunctionDecl *FnDecl = Best->Function;
14111 
14112       if (FnDecl) {
14113         // We matched an overloaded operator. Build a call to that
14114         // operator.
14115 
14116         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
14117 
14118         // Convert the arguments.
14119         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
14120         ExprResult Arg0 =
14121           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
14122                                               Best->FoundDecl, Method);
14123         if (Arg0.isInvalid())
14124           return ExprError();
14125         Args[0] = Arg0.get();
14126 
14127         // Convert the arguments.
14128         ExprResult InputInit
14129           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14130                                                       Context,
14131                                                       FnDecl->getParamDecl(0)),
14132                                       SourceLocation(),
14133                                       Args[1]);
14134         if (InputInit.isInvalid())
14135           return ExprError();
14136 
14137         Args[1] = InputInit.getAs<Expr>();
14138 
14139         // Build the actual expression node.
14140         DeclarationNameInfo OpLocInfo(OpName, LLoc);
14141         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
14142         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14143                                                   Best->FoundDecl,
14144                                                   Base,
14145                                                   HadMultipleCandidates,
14146                                                   OpLocInfo.getLoc(),
14147                                                   OpLocInfo.getInfo());
14148         if (FnExpr.isInvalid())
14149           return ExprError();
14150 
14151         // Determine the result type
14152         QualType ResultTy = FnDecl->getReturnType();
14153         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14154         ResultTy = ResultTy.getNonLValueExprType(Context);
14155 
14156         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14157             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
14158             CurFPFeatureOverrides());
14159         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
14160           return ExprError();
14161 
14162         if (CheckFunctionCall(Method, TheCall,
14163                               Method->getType()->castAs<FunctionProtoType>()))
14164           return ExprError();
14165 
14166         return MaybeBindToTemporary(TheCall);
14167       } else {
14168         // We matched a built-in operator. Convert the arguments, then
14169         // break out so that we will build the appropriate built-in
14170         // operator node.
14171         ExprResult ArgsRes0 = PerformImplicitConversion(
14172             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14173             AA_Passing, CCK_ForBuiltinOverloadedOp);
14174         if (ArgsRes0.isInvalid())
14175           return ExprError();
14176         Args[0] = ArgsRes0.get();
14177 
14178         ExprResult ArgsRes1 = PerformImplicitConversion(
14179             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14180             AA_Passing, CCK_ForBuiltinOverloadedOp);
14181         if (ArgsRes1.isInvalid())
14182           return ExprError();
14183         Args[1] = ArgsRes1.get();
14184 
14185         break;
14186       }
14187     }
14188 
14189     case OR_No_Viable_Function: {
14190       PartialDiagnostic PD = CandidateSet.empty()
14191           ? (PDiag(diag::err_ovl_no_oper)
14192              << Args[0]->getType() << /*subscript*/ 0
14193              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
14194           : (PDiag(diag::err_ovl_no_viable_subscript)
14195              << Args[0]->getType() << Args[0]->getSourceRange()
14196              << Args[1]->getSourceRange());
14197       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
14198                                   OCD_AllCandidates, Args, "[]", LLoc);
14199       return ExprError();
14200     }
14201 
14202     case OR_Ambiguous:
14203       CandidateSet.NoteCandidates(
14204           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14205                                         << "[]" << Args[0]->getType()
14206                                         << Args[1]->getType()
14207                                         << Args[0]->getSourceRange()
14208                                         << Args[1]->getSourceRange()),
14209           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
14210       return ExprError();
14211 
14212     case OR_Deleted:
14213       CandidateSet.NoteCandidates(
14214           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
14215                                         << "[]" << Args[0]->getSourceRange()
14216                                         << Args[1]->getSourceRange()),
14217           *this, OCD_AllCandidates, Args, "[]", LLoc);
14218       return ExprError();
14219     }
14220 
14221   // We matched a built-in operator; build it.
14222   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
14223 }
14224 
14225 /// BuildCallToMemberFunction - Build a call to a member
14226 /// function. MemExpr is the expression that refers to the member
14227 /// function (and includes the object parameter), Args/NumArgs are the
14228 /// arguments to the function call (not including the object
14229 /// parameter). The caller needs to validate that the member
14230 /// expression refers to a non-static member function or an overloaded
14231 /// member function.
14232 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
14233                                            SourceLocation LParenLoc,
14234                                            MultiExprArg Args,
14235                                            SourceLocation RParenLoc,
14236                                            Expr *ExecConfig, bool IsExecConfig,
14237                                            bool AllowRecovery) {
14238   assert(MemExprE->getType() == Context.BoundMemberTy ||
14239          MemExprE->getType() == Context.OverloadTy);
14240 
14241   // Dig out the member expression. This holds both the object
14242   // argument and the member function we're referring to.
14243   Expr *NakedMemExpr = MemExprE->IgnoreParens();
14244 
14245   // Determine whether this is a call to a pointer-to-member function.
14246   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14247     assert(op->getType() == Context.BoundMemberTy);
14248     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14249 
14250     QualType fnType =
14251       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14252 
14253     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14254     QualType resultType = proto->getCallResultType(Context);
14255     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14256 
14257     // Check that the object type isn't more qualified than the
14258     // member function we're calling.
14259     Qualifiers funcQuals = proto->getMethodQuals();
14260 
14261     QualType objectType = op->getLHS()->getType();
14262     if (op->getOpcode() == BO_PtrMemI)
14263       objectType = objectType->castAs<PointerType>()->getPointeeType();
14264     Qualifiers objectQuals = objectType.getQualifiers();
14265 
14266     Qualifiers difference = objectQuals - funcQuals;
14267     difference.removeObjCGCAttr();
14268     difference.removeAddressSpace();
14269     if (difference) {
14270       std::string qualsString = difference.getAsString();
14271       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14272         << fnType.getUnqualifiedType()
14273         << qualsString
14274         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14275     }
14276 
14277     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14278         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14279         CurFPFeatureOverrides(), proto->getNumParams());
14280 
14281     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14282                             call, nullptr))
14283       return ExprError();
14284 
14285     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14286       return ExprError();
14287 
14288     if (CheckOtherCall(call, proto))
14289       return ExprError();
14290 
14291     return MaybeBindToTemporary(call);
14292   }
14293 
14294   // We only try to build a recovery expr at this level if we can preserve
14295   // the return type, otherwise we return ExprError() and let the caller
14296   // recover.
14297   auto BuildRecoveryExpr = [&](QualType Type) {
14298     if (!AllowRecovery)
14299       return ExprError();
14300     std::vector<Expr *> SubExprs = {MemExprE};
14301     llvm::for_each(Args, [&SubExprs](Expr *E) { SubExprs.push_back(E); });
14302     return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
14303                               Type);
14304   };
14305   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14306     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
14307                             RParenLoc, CurFPFeatureOverrides());
14308 
14309   UnbridgedCastsSet UnbridgedCasts;
14310   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14311     return ExprError();
14312 
14313   MemberExpr *MemExpr;
14314   CXXMethodDecl *Method = nullptr;
14315   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14316   NestedNameSpecifier *Qualifier = nullptr;
14317   if (isa<MemberExpr>(NakedMemExpr)) {
14318     MemExpr = cast<MemberExpr>(NakedMemExpr);
14319     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14320     FoundDecl = MemExpr->getFoundDecl();
14321     Qualifier = MemExpr->getQualifier();
14322     UnbridgedCasts.restore();
14323   } else {
14324     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14325     Qualifier = UnresExpr->getQualifier();
14326 
14327     QualType ObjectType = UnresExpr->getBaseType();
14328     Expr::Classification ObjectClassification
14329       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14330                             : UnresExpr->getBase()->Classify(Context);
14331 
14332     // Add overload candidates
14333     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14334                                       OverloadCandidateSet::CSK_Normal);
14335 
14336     // FIXME: avoid copy.
14337     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14338     if (UnresExpr->hasExplicitTemplateArgs()) {
14339       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14340       TemplateArgs = &TemplateArgsBuffer;
14341     }
14342 
14343     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14344            E = UnresExpr->decls_end(); I != E; ++I) {
14345 
14346       NamedDecl *Func = *I;
14347       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14348       if (isa<UsingShadowDecl>(Func))
14349         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14350 
14351 
14352       // Microsoft supports direct constructor calls.
14353       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14354         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14355                              CandidateSet,
14356                              /*SuppressUserConversions*/ false);
14357       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14358         // If explicit template arguments were provided, we can't call a
14359         // non-template member function.
14360         if (TemplateArgs)
14361           continue;
14362 
14363         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14364                            ObjectClassification, Args, CandidateSet,
14365                            /*SuppressUserConversions=*/false);
14366       } else {
14367         AddMethodTemplateCandidate(
14368             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14369             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14370             /*SuppressUserConversions=*/false);
14371       }
14372     }
14373 
14374     DeclarationName DeclName = UnresExpr->getMemberName();
14375 
14376     UnbridgedCasts.restore();
14377 
14378     OverloadCandidateSet::iterator Best;
14379     bool Succeeded = false;
14380     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14381                                             Best)) {
14382     case OR_Success:
14383       Method = cast<CXXMethodDecl>(Best->Function);
14384       FoundDecl = Best->FoundDecl;
14385       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14386       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14387         break;
14388       // If FoundDecl is different from Method (such as if one is a template
14389       // and the other a specialization), make sure DiagnoseUseOfDecl is
14390       // called on both.
14391       // FIXME: This would be more comprehensively addressed by modifying
14392       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14393       // being used.
14394       if (Method != FoundDecl.getDecl() &&
14395                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14396         break;
14397       Succeeded = true;
14398       break;
14399 
14400     case OR_No_Viable_Function:
14401       CandidateSet.NoteCandidates(
14402           PartialDiagnosticAt(
14403               UnresExpr->getMemberLoc(),
14404               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14405                   << DeclName << MemExprE->getSourceRange()),
14406           *this, OCD_AllCandidates, Args);
14407       break;
14408     case OR_Ambiguous:
14409       CandidateSet.NoteCandidates(
14410           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14411                               PDiag(diag::err_ovl_ambiguous_member_call)
14412                                   << DeclName << MemExprE->getSourceRange()),
14413           *this, OCD_AmbiguousCandidates, Args);
14414       break;
14415     case OR_Deleted:
14416       CandidateSet.NoteCandidates(
14417           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14418                               PDiag(diag::err_ovl_deleted_member_call)
14419                                   << DeclName << MemExprE->getSourceRange()),
14420           *this, OCD_AllCandidates, Args);
14421       break;
14422     }
14423     // Overload resolution fails, try to recover.
14424     if (!Succeeded)
14425       return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
14426 
14427     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14428 
14429     // If overload resolution picked a static member, build a
14430     // non-member call based on that function.
14431     if (Method->isStatic()) {
14432       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
14433                                    ExecConfig, IsExecConfig);
14434     }
14435 
14436     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14437   }
14438 
14439   QualType ResultType = Method->getReturnType();
14440   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14441   ResultType = ResultType.getNonLValueExprType(Context);
14442 
14443   assert(Method && "Member call to something that isn't a method?");
14444   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14445   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14446       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14447       CurFPFeatureOverrides(), Proto->getNumParams());
14448 
14449   // Check for a valid return type.
14450   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14451                           TheCall, Method))
14452     return BuildRecoveryExpr(ResultType);
14453 
14454   // Convert the object argument (for a non-static member function call).
14455   // We only need to do this if there was actually an overload; otherwise
14456   // it was done at lookup.
14457   if (!Method->isStatic()) {
14458     ExprResult ObjectArg =
14459       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14460                                           FoundDecl, Method);
14461     if (ObjectArg.isInvalid())
14462       return ExprError();
14463     MemExpr->setBase(ObjectArg.get());
14464   }
14465 
14466   // Convert the rest of the arguments
14467   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14468                               RParenLoc))
14469     return BuildRecoveryExpr(ResultType);
14470 
14471   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14472 
14473   if (CheckFunctionCall(Method, TheCall, Proto))
14474     return ExprError();
14475 
14476   // In the case the method to call was not selected by the overloading
14477   // resolution process, we still need to handle the enable_if attribute. Do
14478   // that here, so it will not hide previous -- and more relevant -- errors.
14479   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14480     if (const EnableIfAttr *Attr =
14481             CheckEnableIf(Method, LParenLoc, Args, true)) {
14482       Diag(MemE->getMemberLoc(),
14483            diag::err_ovl_no_viable_member_function_in_call)
14484           << Method << Method->getSourceRange();
14485       Diag(Method->getLocation(),
14486            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14487           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14488       return ExprError();
14489     }
14490   }
14491 
14492   if ((isa<CXXConstructorDecl>(CurContext) ||
14493        isa<CXXDestructorDecl>(CurContext)) &&
14494       TheCall->getMethodDecl()->isPure()) {
14495     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14496 
14497     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14498         MemExpr->performsVirtualDispatch(getLangOpts())) {
14499       Diag(MemExpr->getBeginLoc(),
14500            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14501           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14502           << MD->getParent();
14503 
14504       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14505       if (getLangOpts().AppleKext)
14506         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14507             << MD->getParent() << MD->getDeclName();
14508     }
14509   }
14510 
14511   if (CXXDestructorDecl *DD =
14512           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14513     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14514     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14515     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14516                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14517                          MemExpr->getMemberLoc());
14518   }
14519 
14520   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14521                                      TheCall->getMethodDecl());
14522 }
14523 
14524 /// BuildCallToObjectOfClassType - Build a call to an object of class
14525 /// type (C++ [over.call.object]), which can end up invoking an
14526 /// overloaded function call operator (@c operator()) or performing a
14527 /// user-defined conversion on the object argument.
14528 ExprResult
14529 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14530                                    SourceLocation LParenLoc,
14531                                    MultiExprArg Args,
14532                                    SourceLocation RParenLoc) {
14533   if (checkPlaceholderForOverload(*this, Obj))
14534     return ExprError();
14535   ExprResult Object = Obj;
14536 
14537   UnbridgedCastsSet UnbridgedCasts;
14538   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14539     return ExprError();
14540 
14541   assert(Object.get()->getType()->isRecordType() &&
14542          "Requires object type argument");
14543 
14544   // C++ [over.call.object]p1:
14545   //  If the primary-expression E in the function call syntax
14546   //  evaluates to a class object of type "cv T", then the set of
14547   //  candidate functions includes at least the function call
14548   //  operators of T. The function call operators of T are obtained by
14549   //  ordinary lookup of the name operator() in the context of
14550   //  (E).operator().
14551   OverloadCandidateSet CandidateSet(LParenLoc,
14552                                     OverloadCandidateSet::CSK_Operator);
14553   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14554 
14555   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14556                           diag::err_incomplete_object_call, Object.get()))
14557     return true;
14558 
14559   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14560   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14561   LookupQualifiedName(R, Record->getDecl());
14562   R.suppressDiagnostics();
14563 
14564   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14565        Oper != OperEnd; ++Oper) {
14566     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14567                        Object.get()->Classify(Context), Args, CandidateSet,
14568                        /*SuppressUserConversion=*/false);
14569   }
14570 
14571   // C++ [over.call.object]p2:
14572   //   In addition, for each (non-explicit in C++0x) conversion function
14573   //   declared in T of the form
14574   //
14575   //        operator conversion-type-id () cv-qualifier;
14576   //
14577   //   where cv-qualifier is the same cv-qualification as, or a
14578   //   greater cv-qualification than, cv, and where conversion-type-id
14579   //   denotes the type "pointer to function of (P1,...,Pn) returning
14580   //   R", or the type "reference to pointer to function of
14581   //   (P1,...,Pn) returning R", or the type "reference to function
14582   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14583   //   is also considered as a candidate function. Similarly,
14584   //   surrogate call functions are added to the set of candidate
14585   //   functions for each conversion function declared in an
14586   //   accessible base class provided the function is not hidden
14587   //   within T by another intervening declaration.
14588   const auto &Conversions =
14589       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14590   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14591     NamedDecl *D = *I;
14592     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14593     if (isa<UsingShadowDecl>(D))
14594       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14595 
14596     // Skip over templated conversion functions; they aren't
14597     // surrogates.
14598     if (isa<FunctionTemplateDecl>(D))
14599       continue;
14600 
14601     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14602     if (!Conv->isExplicit()) {
14603       // Strip the reference type (if any) and then the pointer type (if
14604       // any) to get down to what might be a function type.
14605       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14606       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14607         ConvType = ConvPtrType->getPointeeType();
14608 
14609       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14610       {
14611         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14612                               Object.get(), Args, CandidateSet);
14613       }
14614     }
14615   }
14616 
14617   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14618 
14619   // Perform overload resolution.
14620   OverloadCandidateSet::iterator Best;
14621   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14622                                           Best)) {
14623   case OR_Success:
14624     // Overload resolution succeeded; we'll build the appropriate call
14625     // below.
14626     break;
14627 
14628   case OR_No_Viable_Function: {
14629     PartialDiagnostic PD =
14630         CandidateSet.empty()
14631             ? (PDiag(diag::err_ovl_no_oper)
14632                << Object.get()->getType() << /*call*/ 1
14633                << Object.get()->getSourceRange())
14634             : (PDiag(diag::err_ovl_no_viable_object_call)
14635                << Object.get()->getType() << Object.get()->getSourceRange());
14636     CandidateSet.NoteCandidates(
14637         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14638         OCD_AllCandidates, Args);
14639     break;
14640   }
14641   case OR_Ambiguous:
14642     CandidateSet.NoteCandidates(
14643         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14644                             PDiag(diag::err_ovl_ambiguous_object_call)
14645                                 << Object.get()->getType()
14646                                 << Object.get()->getSourceRange()),
14647         *this, OCD_AmbiguousCandidates, Args);
14648     break;
14649 
14650   case OR_Deleted:
14651     CandidateSet.NoteCandidates(
14652         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14653                             PDiag(diag::err_ovl_deleted_object_call)
14654                                 << Object.get()->getType()
14655                                 << Object.get()->getSourceRange()),
14656         *this, OCD_AllCandidates, Args);
14657     break;
14658   }
14659 
14660   if (Best == CandidateSet.end())
14661     return true;
14662 
14663   UnbridgedCasts.restore();
14664 
14665   if (Best->Function == nullptr) {
14666     // Since there is no function declaration, this is one of the
14667     // surrogate candidates. Dig out the conversion function.
14668     CXXConversionDecl *Conv
14669       = cast<CXXConversionDecl>(
14670                          Best->Conversions[0].UserDefined.ConversionFunction);
14671 
14672     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14673                               Best->FoundDecl);
14674     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14675       return ExprError();
14676     assert(Conv == Best->FoundDecl.getDecl() &&
14677              "Found Decl & conversion-to-functionptr should be same, right?!");
14678     // We selected one of the surrogate functions that converts the
14679     // object parameter to a function pointer. Perform the conversion
14680     // on the object argument, then let BuildCallExpr finish the job.
14681 
14682     // Create an implicit member expr to refer to the conversion operator.
14683     // and then call it.
14684     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14685                                              Conv, HadMultipleCandidates);
14686     if (Call.isInvalid())
14687       return ExprError();
14688     // Record usage of conversion in an implicit cast.
14689     Call = ImplicitCastExpr::Create(
14690         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14691         nullptr, VK_PRValue, CurFPFeatureOverrides());
14692 
14693     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14694   }
14695 
14696   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14697 
14698   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14699   // that calls this method, using Object for the implicit object
14700   // parameter and passing along the remaining arguments.
14701   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14702 
14703   // An error diagnostic has already been printed when parsing the declaration.
14704   if (Method->isInvalidDecl())
14705     return ExprError();
14706 
14707   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14708   unsigned NumParams = Proto->getNumParams();
14709 
14710   DeclarationNameInfo OpLocInfo(
14711                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14712   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14713   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14714                                            Obj, HadMultipleCandidates,
14715                                            OpLocInfo.getLoc(),
14716                                            OpLocInfo.getInfo());
14717   if (NewFn.isInvalid())
14718     return true;
14719 
14720   // The number of argument slots to allocate in the call. If we have default
14721   // arguments we need to allocate space for them as well. We additionally
14722   // need one more slot for the object parameter.
14723   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14724 
14725   // Build the full argument list for the method call (the implicit object
14726   // parameter is placed at the beginning of the list).
14727   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14728 
14729   bool IsError = false;
14730 
14731   // Initialize the implicit object parameter.
14732   ExprResult ObjRes =
14733     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14734                                         Best->FoundDecl, Method);
14735   if (ObjRes.isInvalid())
14736     IsError = true;
14737   else
14738     Object = ObjRes;
14739   MethodArgs[0] = Object.get();
14740 
14741   // Check the argument types.
14742   for (unsigned i = 0; i != NumParams; i++) {
14743     Expr *Arg;
14744     if (i < Args.size()) {
14745       Arg = Args[i];
14746 
14747       // Pass the argument.
14748 
14749       ExprResult InputInit
14750         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14751                                                     Context,
14752                                                     Method->getParamDecl(i)),
14753                                     SourceLocation(), Arg);
14754 
14755       IsError |= InputInit.isInvalid();
14756       Arg = InputInit.getAs<Expr>();
14757     } else {
14758       ExprResult DefArg
14759         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14760       if (DefArg.isInvalid()) {
14761         IsError = true;
14762         break;
14763       }
14764 
14765       Arg = DefArg.getAs<Expr>();
14766     }
14767 
14768     MethodArgs[i + 1] = Arg;
14769   }
14770 
14771   // If this is a variadic call, handle args passed through "...".
14772   if (Proto->isVariadic()) {
14773     // Promote the arguments (C99 6.5.2.2p7).
14774     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14775       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14776                                                         nullptr);
14777       IsError |= Arg.isInvalid();
14778       MethodArgs[i + 1] = Arg.get();
14779     }
14780   }
14781 
14782   if (IsError)
14783     return true;
14784 
14785   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14786 
14787   // Once we've built TheCall, all of the expressions are properly owned.
14788   QualType ResultTy = Method->getReturnType();
14789   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14790   ResultTy = ResultTy.getNonLValueExprType(Context);
14791 
14792   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14793       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14794       CurFPFeatureOverrides());
14795 
14796   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14797     return true;
14798 
14799   if (CheckFunctionCall(Method, TheCall, Proto))
14800     return true;
14801 
14802   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14803 }
14804 
14805 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14806 ///  (if one exists), where @c Base is an expression of class type and
14807 /// @c Member is the name of the member we're trying to find.
14808 ExprResult
14809 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14810                                bool *NoArrowOperatorFound) {
14811   assert(Base->getType()->isRecordType() &&
14812          "left-hand side must have class type");
14813 
14814   if (checkPlaceholderForOverload(*this, Base))
14815     return ExprError();
14816 
14817   SourceLocation Loc = Base->getExprLoc();
14818 
14819   // C++ [over.ref]p1:
14820   //
14821   //   [...] An expression x->m is interpreted as (x.operator->())->m
14822   //   for a class object x of type T if T::operator->() exists and if
14823   //   the operator is selected as the best match function by the
14824   //   overload resolution mechanism (13.3).
14825   DeclarationName OpName =
14826     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14827   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14828 
14829   if (RequireCompleteType(Loc, Base->getType(),
14830                           diag::err_typecheck_incomplete_tag, Base))
14831     return ExprError();
14832 
14833   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14834   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14835   R.suppressDiagnostics();
14836 
14837   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14838        Oper != OperEnd; ++Oper) {
14839     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14840                        None, CandidateSet, /*SuppressUserConversion=*/false);
14841   }
14842 
14843   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14844 
14845   // Perform overload resolution.
14846   OverloadCandidateSet::iterator Best;
14847   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14848   case OR_Success:
14849     // Overload resolution succeeded; we'll build the call below.
14850     break;
14851 
14852   case OR_No_Viable_Function: {
14853     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14854     if (CandidateSet.empty()) {
14855       QualType BaseType = Base->getType();
14856       if (NoArrowOperatorFound) {
14857         // Report this specific error to the caller instead of emitting a
14858         // diagnostic, as requested.
14859         *NoArrowOperatorFound = true;
14860         return ExprError();
14861       }
14862       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14863         << BaseType << Base->getSourceRange();
14864       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14865         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14866           << FixItHint::CreateReplacement(OpLoc, ".");
14867       }
14868     } else
14869       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14870         << "operator->" << Base->getSourceRange();
14871     CandidateSet.NoteCandidates(*this, Base, Cands);
14872     return ExprError();
14873   }
14874   case OR_Ambiguous:
14875     CandidateSet.NoteCandidates(
14876         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14877                                        << "->" << Base->getType()
14878                                        << Base->getSourceRange()),
14879         *this, OCD_AmbiguousCandidates, Base);
14880     return ExprError();
14881 
14882   case OR_Deleted:
14883     CandidateSet.NoteCandidates(
14884         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14885                                        << "->" << Base->getSourceRange()),
14886         *this, OCD_AllCandidates, Base);
14887     return ExprError();
14888   }
14889 
14890   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14891 
14892   // Convert the object parameter.
14893   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14894   ExprResult BaseResult =
14895     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14896                                         Best->FoundDecl, Method);
14897   if (BaseResult.isInvalid())
14898     return ExprError();
14899   Base = BaseResult.get();
14900 
14901   // Build the operator call.
14902   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14903                                             Base, HadMultipleCandidates, OpLoc);
14904   if (FnExpr.isInvalid())
14905     return ExprError();
14906 
14907   QualType ResultTy = Method->getReturnType();
14908   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14909   ResultTy = ResultTy.getNonLValueExprType(Context);
14910   CXXOperatorCallExpr *TheCall =
14911       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14912                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14913 
14914   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14915     return ExprError();
14916 
14917   if (CheckFunctionCall(Method, TheCall,
14918                         Method->getType()->castAs<FunctionProtoType>()))
14919     return ExprError();
14920 
14921   return MaybeBindToTemporary(TheCall);
14922 }
14923 
14924 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14925 /// a literal operator described by the provided lookup results.
14926 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14927                                           DeclarationNameInfo &SuffixInfo,
14928                                           ArrayRef<Expr*> Args,
14929                                           SourceLocation LitEndLoc,
14930                                        TemplateArgumentListInfo *TemplateArgs) {
14931   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14932 
14933   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14934                                     OverloadCandidateSet::CSK_Normal);
14935   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14936                                  TemplateArgs);
14937 
14938   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14939 
14940   // Perform overload resolution. This will usually be trivial, but might need
14941   // to perform substitutions for a literal operator template.
14942   OverloadCandidateSet::iterator Best;
14943   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14944   case OR_Success:
14945   case OR_Deleted:
14946     break;
14947 
14948   case OR_No_Viable_Function:
14949     CandidateSet.NoteCandidates(
14950         PartialDiagnosticAt(UDSuffixLoc,
14951                             PDiag(diag::err_ovl_no_viable_function_in_call)
14952                                 << R.getLookupName()),
14953         *this, OCD_AllCandidates, Args);
14954     return ExprError();
14955 
14956   case OR_Ambiguous:
14957     CandidateSet.NoteCandidates(
14958         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14959                                                 << R.getLookupName()),
14960         *this, OCD_AmbiguousCandidates, Args);
14961     return ExprError();
14962   }
14963 
14964   FunctionDecl *FD = Best->Function;
14965   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14966                                         nullptr, HadMultipleCandidates,
14967                                         SuffixInfo.getLoc(),
14968                                         SuffixInfo.getInfo());
14969   if (Fn.isInvalid())
14970     return true;
14971 
14972   // Check the argument types. This should almost always be a no-op, except
14973   // that array-to-pointer decay is applied to string literals.
14974   Expr *ConvArgs[2];
14975   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14976     ExprResult InputInit = PerformCopyInitialization(
14977       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14978       SourceLocation(), Args[ArgIdx]);
14979     if (InputInit.isInvalid())
14980       return true;
14981     ConvArgs[ArgIdx] = InputInit.get();
14982   }
14983 
14984   QualType ResultTy = FD->getReturnType();
14985   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14986   ResultTy = ResultTy.getNonLValueExprType(Context);
14987 
14988   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14989       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14990       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14991 
14992   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14993     return ExprError();
14994 
14995   if (CheckFunctionCall(FD, UDL, nullptr))
14996     return ExprError();
14997 
14998   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14999 }
15000 
15001 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15002 /// given LookupResult is non-empty, it is assumed to describe a member which
15003 /// will be invoked. Otherwise, the function will be found via argument
15004 /// dependent lookup.
15005 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15006 /// otherwise CallExpr is set to ExprError() and some non-success value
15007 /// is returned.
15008 Sema::ForRangeStatus
15009 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
15010                                 SourceLocation RangeLoc,
15011                                 const DeclarationNameInfo &NameInfo,
15012                                 LookupResult &MemberLookup,
15013                                 OverloadCandidateSet *CandidateSet,
15014                                 Expr *Range, ExprResult *CallExpr) {
15015   Scope *S = nullptr;
15016 
15017   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
15018   if (!MemberLookup.empty()) {
15019     ExprResult MemberRef =
15020         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
15021                                  /*IsPtr=*/false, CXXScopeSpec(),
15022                                  /*TemplateKWLoc=*/SourceLocation(),
15023                                  /*FirstQualifierInScope=*/nullptr,
15024                                  MemberLookup,
15025                                  /*TemplateArgs=*/nullptr, S);
15026     if (MemberRef.isInvalid()) {
15027       *CallExpr = ExprError();
15028       return FRS_DiagnosticIssued;
15029     }
15030     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
15031     if (CallExpr->isInvalid()) {
15032       *CallExpr = ExprError();
15033       return FRS_DiagnosticIssued;
15034     }
15035   } else {
15036     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15037                                                 NestedNameSpecifierLoc(),
15038                                                 NameInfo, UnresolvedSet<0>());
15039     if (FnR.isInvalid())
15040       return FRS_DiagnosticIssued;
15041     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
15042 
15043     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
15044                                                     CandidateSet, CallExpr);
15045     if (CandidateSet->empty() || CandidateSetError) {
15046       *CallExpr = ExprError();
15047       return FRS_NoViableFunction;
15048     }
15049     OverloadCandidateSet::iterator Best;
15050     OverloadingResult OverloadResult =
15051         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
15052 
15053     if (OverloadResult == OR_No_Viable_Function) {
15054       *CallExpr = ExprError();
15055       return FRS_NoViableFunction;
15056     }
15057     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
15058                                          Loc, nullptr, CandidateSet, &Best,
15059                                          OverloadResult,
15060                                          /*AllowTypoCorrection=*/false);
15061     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
15062       *CallExpr = ExprError();
15063       return FRS_DiagnosticIssued;
15064     }
15065   }
15066   return FRS_Success;
15067 }
15068 
15069 
15070 /// FixOverloadedFunctionReference - E is an expression that refers to
15071 /// a C++ overloaded function (possibly with some parentheses and
15072 /// perhaps a '&' around it). We have resolved the overloaded function
15073 /// to the function declaration Fn, so patch up the expression E to
15074 /// refer (possibly indirectly) to Fn. Returns the new expr.
15075 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
15076                                            FunctionDecl *Fn) {
15077   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
15078     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
15079                                                    Found, Fn);
15080     if (SubExpr == PE->getSubExpr())
15081       return PE;
15082 
15083     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
15084   }
15085 
15086   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
15087     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
15088                                                    Found, Fn);
15089     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
15090                                SubExpr->getType()) &&
15091            "Implicit cast type cannot be determined from overload");
15092     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
15093     if (SubExpr == ICE->getSubExpr())
15094       return ICE;
15095 
15096     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
15097                                     SubExpr, nullptr, ICE->getValueKind(),
15098                                     CurFPFeatureOverrides());
15099   }
15100 
15101   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
15102     if (!GSE->isResultDependent()) {
15103       Expr *SubExpr =
15104           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
15105       if (SubExpr == GSE->getResultExpr())
15106         return GSE;
15107 
15108       // Replace the resulting type information before rebuilding the generic
15109       // selection expression.
15110       ArrayRef<Expr *> A = GSE->getAssocExprs();
15111       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
15112       unsigned ResultIdx = GSE->getResultIndex();
15113       AssocExprs[ResultIdx] = SubExpr;
15114 
15115       return GenericSelectionExpr::Create(
15116           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
15117           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
15118           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
15119           ResultIdx);
15120     }
15121     // Rather than fall through to the unreachable, return the original generic
15122     // selection expression.
15123     return GSE;
15124   }
15125 
15126   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
15127     assert(UnOp->getOpcode() == UO_AddrOf &&
15128            "Can only take the address of an overloaded function");
15129     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
15130       if (Method->isStatic()) {
15131         // Do nothing: static member functions aren't any different
15132         // from non-member functions.
15133       } else {
15134         // Fix the subexpression, which really has to be an
15135         // UnresolvedLookupExpr holding an overloaded member function
15136         // or template.
15137         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15138                                                        Found, Fn);
15139         if (SubExpr == UnOp->getSubExpr())
15140           return UnOp;
15141 
15142         assert(isa<DeclRefExpr>(SubExpr)
15143                && "fixed to something other than a decl ref");
15144         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
15145                && "fixed to a member ref with no nested name qualifier");
15146 
15147         // We have taken the address of a pointer to member
15148         // function. Perform the computation here so that we get the
15149         // appropriate pointer to member type.
15150         QualType ClassType
15151           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
15152         QualType MemPtrType
15153           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
15154         // Under the MS ABI, lock down the inheritance model now.
15155         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15156           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
15157 
15158         return UnaryOperator::Create(
15159             Context, SubExpr, UO_AddrOf, MemPtrType, VK_PRValue, OK_Ordinary,
15160             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
15161       }
15162     }
15163     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
15164                                                    Found, Fn);
15165     if (SubExpr == UnOp->getSubExpr())
15166       return UnOp;
15167 
15168     return UnaryOperator::Create(
15169         Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()),
15170         VK_PRValue, OK_Ordinary, UnOp->getOperatorLoc(), false,
15171         CurFPFeatureOverrides());
15172   }
15173 
15174   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15175     // FIXME: avoid copy.
15176     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15177     if (ULE->hasExplicitTemplateArgs()) {
15178       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
15179       TemplateArgs = &TemplateArgsBuffer;
15180     }
15181 
15182     DeclRefExpr *DRE =
15183         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
15184                          ULE->getQualifierLoc(), Found.getDecl(),
15185                          ULE->getTemplateKeywordLoc(), TemplateArgs);
15186     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
15187     return DRE;
15188   }
15189 
15190   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
15191     // FIXME: avoid copy.
15192     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15193     if (MemExpr->hasExplicitTemplateArgs()) {
15194       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15195       TemplateArgs = &TemplateArgsBuffer;
15196     }
15197 
15198     Expr *Base;
15199 
15200     // If we're filling in a static method where we used to have an
15201     // implicit member access, rewrite to a simple decl ref.
15202     if (MemExpr->isImplicitAccess()) {
15203       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15204         DeclRefExpr *DRE = BuildDeclRefExpr(
15205             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
15206             MemExpr->getQualifierLoc(), Found.getDecl(),
15207             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
15208         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
15209         return DRE;
15210       } else {
15211         SourceLocation Loc = MemExpr->getMemberLoc();
15212         if (MemExpr->getQualifier())
15213           Loc = MemExpr->getQualifierLoc().getBeginLoc();
15214         Base =
15215             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
15216       }
15217     } else
15218       Base = MemExpr->getBase();
15219 
15220     ExprValueKind valueKind;
15221     QualType type;
15222     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
15223       valueKind = VK_LValue;
15224       type = Fn->getType();
15225     } else {
15226       valueKind = VK_PRValue;
15227       type = Context.BoundMemberTy;
15228     }
15229 
15230     return BuildMemberExpr(
15231         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
15232         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
15233         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
15234         type, valueKind, OK_Ordinary, TemplateArgs);
15235   }
15236 
15237   llvm_unreachable("Invalid reference to overloaded function");
15238 }
15239 
15240 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
15241                                                 DeclAccessPair Found,
15242                                                 FunctionDecl *Fn) {
15243   return FixOverloadedFunctionReference(E.get(), Found, Fn);
15244 }
15245