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/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.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/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   DeclRefExpr *DRE = new (S.Context)
64       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65   if (HadMultipleCandidates)
66     DRE->setHadMultipleCandidates(true);
67 
68   S.MarkDeclRefReferenced(DRE, Base);
69   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71       S.ResolveExceptionSpec(Loc, FPT);
72       DRE->setType(Fn->getType());
73     }
74   }
75   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76                              CK_FunctionToPointerDecay);
77 }
78 
79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80                                  bool InOverloadResolution,
81                                  StandardConversionSequence &SCS,
82                                  bool CStyle,
83                                  bool AllowObjCWritebackConversion);
84 
85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86                                                  QualType &ToType,
87                                                  bool InOverloadResolution,
88                                                  StandardConversionSequence &SCS,
89                                                  bool CStyle);
90 static OverloadingResult
91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92                         UserDefinedConversionSequence& User,
93                         OverloadCandidateSet& Conversions,
94                         bool AllowExplicit,
95                         bool AllowObjCConversionOnExplicit);
96 
97 
98 static ImplicitConversionSequence::CompareKind
99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100                                    const StandardConversionSequence& SCS1,
101                                    const StandardConversionSequence& SCS2);
102 
103 static ImplicitConversionSequence::CompareKind
104 CompareQualificationConversions(Sema &S,
105                                 const StandardConversionSequence& SCS1,
106                                 const StandardConversionSequence& SCS2);
107 
108 static ImplicitConversionSequence::CompareKind
109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110                                 const StandardConversionSequence& SCS1,
111                                 const StandardConversionSequence& SCS2);
112 
113 /// GetConversionRank - Retrieve the implicit conversion rank
114 /// corresponding to the given implicit conversion kind.
115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116   static const ImplicitConversionRank
117     Rank[(int)ICK_Num_Conversion_Kinds] = {
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Promotion,
125     ICR_Promotion,
126     ICR_Promotion,
127     ICR_Conversion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_OCL_Scalar_Widening,
138     ICR_Complex_Real_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Writeback_Conversion,
142     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143                      // it was omitted by the patch that added
144                      // ICK_Zero_Event_Conversion
145     ICR_C_Conversion,
146     ICR_C_Conversion_Extension
147   };
148   return Rank[(int)Kind];
149 }
150 
151 /// GetImplicitConversionName - Return the name of this kind of
152 /// implicit conversion.
153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155     "No conversion",
156     "Lvalue-to-rvalue",
157     "Array-to-pointer",
158     "Function-to-pointer",
159     "Function pointer conversion",
160     "Qualification",
161     "Integral promotion",
162     "Floating point promotion",
163     "Complex promotion",
164     "Integral conversion",
165     "Floating conversion",
166     "Complex conversion",
167     "Floating-integral conversion",
168     "Pointer conversion",
169     "Pointer-to-member conversion",
170     "Boolean conversion",
171     "Compatible-types conversion",
172     "Derived-to-base conversion",
173     "Vector conversion",
174     "Vector splat",
175     "Complex-real conversion",
176     "Block Pointer conversion",
177     "Transparent Union Conversion",
178     "Writeback conversion",
179     "OpenCL Zero Event Conversion",
180     "C specific type conversion",
181     "Incompatible pointer conversion"
182   };
183   return Name[Kind];
184 }
185 
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
188 void StandardConversionSequence::setAsIdentityConversion() {
189   First = ICK_Identity;
190   Second = ICK_Identity;
191   Third = ICK_Identity;
192   DeprecatedStringLiteralToCharPtr = false;
193   QualificationIncludesObjCLifetime = false;
194   ReferenceBinding = false;
195   DirectBinding = false;
196   IsLvalueReference = true;
197   BindsToFunctionLvalue = false;
198   BindsToRvalue = false;
199   BindsImplicitObjectArgumentWithoutRefQualifier = false;
200   ObjCLifetimeConversionBinding = false;
201   CopyConstructor = nullptr;
202 }
203 
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208   ImplicitConversionRank Rank = ICR_Exact_Match;
209   if  (GetConversionRank(First) > Rank)
210     Rank = GetConversionRank(First);
211   if  (GetConversionRank(Second) > Rank)
212     Rank = GetConversionRank(Second);
213   if  (GetConversionRank(Third) > Rank)
214     Rank = GetConversionRank(Third);
215   return Rank;
216 }
217 
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
222 bool StandardConversionSequence::isPointerConversionToBool() const {
223   // Note that FromType has not necessarily been transformed by the
224   // array-to-pointer or function-to-pointer implicit conversions, so
225   // check for their presence as well as checking whether FromType is
226   // a pointer.
227   if (getToType(1)->isBooleanType() &&
228       (getFromType()->isPointerType() ||
229        getFromType()->isMemberPointerType() ||
230        getFromType()->isObjCObjectPointerType() ||
231        getFromType()->isBlockPointerType() ||
232        getFromType()->isNullPtrType() ||
233        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234     return true;
235 
236   return false;
237 }
238 
239 /// isPointerConversionToVoidPointer - Determines whether this
240 /// conversion is a conversion of a pointer to a void pointer. This is
241 /// used as part of the ranking of standard conversion sequences (C++
242 /// 13.3.3.2p4).
243 bool
244 StandardConversionSequence::
245 isPointerConversionToVoidPointer(ASTContext& Context) const {
246   QualType FromType = getFromType();
247   QualType ToType = getToType(1);
248 
249   // Note that FromType has not necessarily been transformed by the
250   // array-to-pointer implicit conversion, so check for its presence
251   // and redo the conversion to get a pointer.
252   if (First == ICK_Array_To_Pointer)
253     FromType = Context.getArrayDecayedType(FromType);
254 
255   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257       return ToPtrType->getPointeeType()->isVoidType();
258 
259   return false;
260 }
261 
262 /// Skip any implicit casts which could be either part of a narrowing conversion
263 /// or after one in an implicit conversion.
264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265                                              const Expr *Converted) {
266   // We can have cleanups wrapping the converted expression; these need to be
267   // preserved so that destructors run if necessary.
268   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269     Expr *Inner =
270         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272                                     EWC->getObjects());
273   }
274 
275   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276     switch (ICE->getCastKind()) {
277     case CK_NoOp:
278     case CK_IntegralCast:
279     case CK_IntegralToBoolean:
280     case CK_IntegralToFloating:
281     case CK_BooleanToSignedIntegral:
282     case CK_FloatingToIntegral:
283     case CK_FloatingToBoolean:
284     case CK_FloatingCast:
285       Converted = ICE->getSubExpr();
286       continue;
287 
288     default:
289       return Converted;
290     }
291   }
292 
293   return Converted;
294 }
295 
296 /// Check if this standard conversion sequence represents a narrowing
297 /// conversion, according to C++11 [dcl.init.list]p7.
298 ///
299 /// \param Ctx  The AST context.
300 /// \param Converted  The result of applying this standard conversion sequence.
301 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
302 ///        value of the expression prior to the narrowing conversion.
303 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
304 ///        type of the expression prior to the narrowing conversion.
305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306 ///        from floating point types to integral types should be ignored.
307 NarrowingKind StandardConversionSequence::getNarrowingKind(
308     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
311 
312   // C++11 [dcl.init.list]p7:
313   //   A narrowing conversion is an implicit conversion ...
314   QualType FromType = getToType(0);
315   QualType ToType = getToType(1);
316 
317   // A conversion to an enumeration type is narrowing if the conversion to
318   // the underlying type is narrowing. This only arises for expressions of
319   // the form 'Enum{init}'.
320   if (auto *ET = ToType->getAs<EnumType>())
321     ToType = ET->getDecl()->getIntegerType();
322 
323   switch (Second) {
324   // 'bool' is an integral type; dispatch to the right place to handle it.
325   case ICK_Boolean_Conversion:
326     if (FromType->isRealFloatingType())
327       goto FloatingIntegralConversion;
328     if (FromType->isIntegralOrUnscopedEnumerationType())
329       goto IntegralConversion;
330     // Boolean conversions can be from pointers and pointers to members
331     // [conv.bool], and those aren't considered narrowing conversions.
332     return NK_Not_Narrowing;
333 
334   // -- from a floating-point type to an integer type, or
335   //
336   // -- from an integer type or unscoped enumeration type to a floating-point
337   //    type, except where the source is a constant expression and the actual
338   //    value after conversion will fit into the target type and will produce
339   //    the original value when converted back to the original type, or
340   case ICK_Floating_Integral:
341   FloatingIntegralConversion:
342     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343       return NK_Type_Narrowing;
344     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345                ToType->isRealFloatingType()) {
346       if (IgnoreFloatToIntegralConversion)
347         return NK_Not_Narrowing;
348       llvm::APSInt IntConstantValue;
349       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350       assert(Initializer && "Unknown conversion expression");
351 
352       // If it's value-dependent, we can't tell whether it's narrowing.
353       if (Initializer->isValueDependent())
354         return NK_Dependent_Narrowing;
355 
356       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357         // Convert the integer to the floating type.
358         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360                                 llvm::APFloat::rmNearestTiesToEven);
361         // And back.
362         llvm::APSInt ConvertedValue = IntConstantValue;
363         bool ignored;
364         Result.convertToInteger(ConvertedValue,
365                                 llvm::APFloat::rmTowardZero, &ignored);
366         // If the resulting value is different, this was a narrowing conversion.
367         if (IntConstantValue != ConvertedValue) {
368           ConstantValue = APValue(IntConstantValue);
369           ConstantType = Initializer->getType();
370           return NK_Constant_Narrowing;
371         }
372       } else {
373         // Variables are always narrowings.
374         return NK_Variable_Narrowing;
375       }
376     }
377     return NK_Not_Narrowing;
378 
379   // -- from long double to double or float, or from double to float, except
380   //    where the source is a constant expression and the actual value after
381   //    conversion is within the range of values that can be represented (even
382   //    if it cannot be represented exactly), or
383   case ICK_Floating_Conversion:
384     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386       // FromType is larger than ToType.
387       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388 
389       // If it's value-dependent, we can't tell whether it's narrowing.
390       if (Initializer->isValueDependent())
391         return NK_Dependent_Narrowing;
392 
393       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394         // Constant!
395         assert(ConstantValue.isFloat());
396         llvm::APFloat FloatVal = ConstantValue.getFloat();
397         // Convert the source value into the target type.
398         bool ignored;
399         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400           Ctx.getFloatTypeSemantics(ToType),
401           llvm::APFloat::rmNearestTiesToEven, &ignored);
402         // If there was no overflow, the source value is within the range of
403         // values that can be represented.
404         if (ConvertStatus & llvm::APFloat::opOverflow) {
405           ConstantType = Initializer->getType();
406           return NK_Constant_Narrowing;
407         }
408       } else {
409         return NK_Variable_Narrowing;
410       }
411     }
412     return NK_Not_Narrowing;
413 
414   // -- from an integer type or unscoped enumeration type to an integer type
415   //    that cannot represent all the values of the original type, except where
416   //    the source is a constant expression and the actual value after
417   //    conversion will fit into the target type and will produce the original
418   //    value when converted back to the original type.
419   case ICK_Integral_Conversion:
420   IntegralConversion: {
421     assert(FromType->isIntegralOrUnscopedEnumerationType());
422     assert(ToType->isIntegralOrUnscopedEnumerationType());
423     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424     const unsigned FromWidth = Ctx.getIntWidth(FromType);
425     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426     const unsigned ToWidth = Ctx.getIntWidth(ToType);
427 
428     if (FromWidth > ToWidth ||
429         (FromWidth == ToWidth && FromSigned != ToSigned) ||
430         (FromSigned && !ToSigned)) {
431       // Not all values of FromType can be represented in ToType.
432       llvm::APSInt InitializerValue;
433       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434 
435       // If it's value-dependent, we can't tell whether it's narrowing.
436       if (Initializer->isValueDependent())
437         return NK_Dependent_Narrowing;
438 
439       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440         // Such conversions on variables are always narrowing.
441         return NK_Variable_Narrowing;
442       }
443       bool Narrowing = false;
444       if (FromWidth < ToWidth) {
445         // Negative -> unsigned is narrowing. Otherwise, more bits is never
446         // narrowing.
447         if (InitializerValue.isSigned() && InitializerValue.isNegative())
448           Narrowing = true;
449       } else {
450         // Add a bit to the InitializerValue so we don't have to worry about
451         // signed vs. unsigned comparisons.
452         InitializerValue = InitializerValue.extend(
453           InitializerValue.getBitWidth() + 1);
454         // Convert the initializer to and from the target width and signed-ness.
455         llvm::APSInt ConvertedValue = InitializerValue;
456         ConvertedValue = ConvertedValue.trunc(ToWidth);
457         ConvertedValue.setIsSigned(ToSigned);
458         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459         ConvertedValue.setIsSigned(InitializerValue.isSigned());
460         // If the result is different, this was a narrowing conversion.
461         if (ConvertedValue != InitializerValue)
462           Narrowing = true;
463       }
464       if (Narrowing) {
465         ConstantType = Initializer->getType();
466         ConstantValue = APValue(InitializerValue);
467         return NK_Constant_Narrowing;
468       }
469     }
470     return NK_Not_Narrowing;
471   }
472 
473   default:
474     // Other kinds of conversions are not narrowings.
475     return NK_Not_Narrowing;
476   }
477 }
478 
479 /// dump - Print this standard conversion sequence to standard
480 /// error. Useful for debugging overloading issues.
481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
482   raw_ostream &OS = llvm::errs();
483   bool PrintedSomething = false;
484   if (First != ICK_Identity) {
485     OS << GetImplicitConversionName(First);
486     PrintedSomething = true;
487   }
488 
489   if (Second != ICK_Identity) {
490     if (PrintedSomething) {
491       OS << " -> ";
492     }
493     OS << GetImplicitConversionName(Second);
494 
495     if (CopyConstructor) {
496       OS << " (by copy constructor)";
497     } else if (DirectBinding) {
498       OS << " (direct reference binding)";
499     } else if (ReferenceBinding) {
500       OS << " (reference binding)";
501     }
502     PrintedSomething = true;
503   }
504 
505   if (Third != ICK_Identity) {
506     if (PrintedSomething) {
507       OS << " -> ";
508     }
509     OS << GetImplicitConversionName(Third);
510     PrintedSomething = true;
511   }
512 
513   if (!PrintedSomething) {
514     OS << "No conversions required";
515   }
516 }
517 
518 /// dump - Print this user-defined conversion sequence to standard
519 /// error. Useful for debugging overloading issues.
520 void UserDefinedConversionSequence::dump() const {
521   raw_ostream &OS = llvm::errs();
522   if (Before.First || Before.Second || Before.Third) {
523     Before.dump();
524     OS << " -> ";
525   }
526   if (ConversionFunction)
527     OS << '\'' << *ConversionFunction << '\'';
528   else
529     OS << "aggregate initialization";
530   if (After.First || After.Second || After.Third) {
531     OS << " -> ";
532     After.dump();
533   }
534 }
535 
536 /// dump - Print this implicit conversion sequence to standard
537 /// error. Useful for debugging overloading issues.
538 void ImplicitConversionSequence::dump() const {
539   raw_ostream &OS = llvm::errs();
540   if (isStdInitializerListElement())
541     OS << "Worst std::initializer_list element conversion: ";
542   switch (ConversionKind) {
543   case StandardConversion:
544     OS << "Standard conversion: ";
545     Standard.dump();
546     break;
547   case UserDefinedConversion:
548     OS << "User-defined conversion: ";
549     UserDefined.dump();
550     break;
551   case EllipsisConversion:
552     OS << "Ellipsis conversion";
553     break;
554   case AmbiguousConversion:
555     OS << "Ambiguous conversion";
556     break;
557   case BadConversion:
558     OS << "Bad conversion";
559     break;
560   }
561 
562   OS << "\n";
563 }
564 
565 void AmbiguousConversionSequence::construct() {
566   new (&conversions()) ConversionSet();
567 }
568 
569 void AmbiguousConversionSequence::destruct() {
570   conversions().~ConversionSet();
571 }
572 
573 void
574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575   FromTypePtr = O.FromTypePtr;
576   ToTypePtr = O.ToTypePtr;
577   new (&conversions()) ConversionSet(O.conversions());
578 }
579 
580 namespace {
581   // Structure used by DeductionFailureInfo to store
582   // template argument information.
583   struct DFIArguments {
584     TemplateArgument FirstArg;
585     TemplateArgument SecondArg;
586   };
587   // Structure used by DeductionFailureInfo to store
588   // template parameter and template argument information.
589   struct DFIParamWithArguments : DFIArguments {
590     TemplateParameter Param;
591   };
592   // Structure used by DeductionFailureInfo to store template argument
593   // information and the index of the problematic call argument.
594   struct DFIDeducedMismatchArgs : DFIArguments {
595     TemplateArgumentList *TemplateArgs;
596     unsigned CallArgIndex;
597   };
598   // Structure used by DeductionFailureInfo to store information about
599   // unsatisfied constraints.
600   struct CNSInfo {
601     TemplateArgumentList *TemplateArgs;
602     ConstraintSatisfaction Satisfaction;
603   };
604 }
605 
606 /// Convert from Sema's representation of template deduction information
607 /// to the form used in overload-candidate information.
608 DeductionFailureInfo
609 clang::MakeDeductionFailureInfo(ASTContext &Context,
610                                 Sema::TemplateDeductionResult TDK,
611                                 TemplateDeductionInfo &Info) {
612   DeductionFailureInfo Result;
613   Result.Result = static_cast<unsigned>(TDK);
614   Result.HasDiagnostic = false;
615   switch (TDK) {
616   case Sema::TDK_Invalid:
617   case Sema::TDK_InstantiationDepth:
618   case Sema::TDK_TooManyArguments:
619   case Sema::TDK_TooFewArguments:
620   case Sema::TDK_MiscellaneousDeductionFailure:
621   case Sema::TDK_CUDATargetMismatch:
622     Result.Data = nullptr;
623     break;
624 
625   case Sema::TDK_Incomplete:
626   case Sema::TDK_InvalidExplicitArguments:
627     Result.Data = Info.Param.getOpaqueValue();
628     break;
629 
630   case Sema::TDK_DeducedMismatch:
631   case Sema::TDK_DeducedMismatchNested: {
632     // FIXME: Should allocate from normal heap so that we can free this later.
633     auto *Saved = new (Context) DFIDeducedMismatchArgs;
634     Saved->FirstArg = Info.FirstArg;
635     Saved->SecondArg = Info.SecondArg;
636     Saved->TemplateArgs = Info.take();
637     Saved->CallArgIndex = Info.CallArgIndex;
638     Result.Data = Saved;
639     break;
640   }
641 
642   case Sema::TDK_NonDeducedMismatch: {
643     // FIXME: Should allocate from normal heap so that we can free this later.
644     DFIArguments *Saved = new (Context) DFIArguments;
645     Saved->FirstArg = Info.FirstArg;
646     Saved->SecondArg = Info.SecondArg;
647     Result.Data = Saved;
648     break;
649   }
650 
651   case Sema::TDK_IncompletePack:
652     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653   case Sema::TDK_Inconsistent:
654   case Sema::TDK_Underqualified: {
655     // FIXME: Should allocate from normal heap so that we can free this later.
656     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657     Saved->Param = Info.Param;
658     Saved->FirstArg = Info.FirstArg;
659     Saved->SecondArg = Info.SecondArg;
660     Result.Data = Saved;
661     break;
662   }
663 
664   case Sema::TDK_SubstitutionFailure:
665     Result.Data = Info.take();
666     if (Info.hasSFINAEDiagnostic()) {
667       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668           SourceLocation(), PartialDiagnostic::NullDiagnostic());
669       Info.takeSFINAEDiagnostic(*Diag);
670       Result.HasDiagnostic = true;
671     }
672     break;
673 
674   case Sema::TDK_ConstraintsNotSatisfied: {
675     CNSInfo *Saved = new (Context) CNSInfo;
676     Saved->TemplateArgs = Info.take();
677     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678     Result.Data = Saved;
679     break;
680   }
681 
682   case Sema::TDK_Success:
683   case Sema::TDK_NonDependentConversionFailure:
684     llvm_unreachable("not a deduction failure");
685   }
686 
687   return Result;
688 }
689 
690 void DeductionFailureInfo::Destroy() {
691   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692   case Sema::TDK_Success:
693   case Sema::TDK_Invalid:
694   case Sema::TDK_InstantiationDepth:
695   case Sema::TDK_Incomplete:
696   case Sema::TDK_TooManyArguments:
697   case Sema::TDK_TooFewArguments:
698   case Sema::TDK_InvalidExplicitArguments:
699   case Sema::TDK_CUDATargetMismatch:
700   case Sema::TDK_NonDependentConversionFailure:
701     break;
702 
703   case Sema::TDK_IncompletePack:
704   case Sema::TDK_Inconsistent:
705   case Sema::TDK_Underqualified:
706   case Sema::TDK_DeducedMismatch:
707   case Sema::TDK_DeducedMismatchNested:
708   case Sema::TDK_NonDeducedMismatch:
709     // FIXME: Destroy the data?
710     Data = nullptr;
711     break;
712 
713   case Sema::TDK_SubstitutionFailure:
714     // FIXME: Destroy the template argument list?
715     Data = nullptr;
716     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717       Diag->~PartialDiagnosticAt();
718       HasDiagnostic = false;
719     }
720     break;
721 
722   case Sema::TDK_ConstraintsNotSatisfied:
723     // FIXME: Destroy the template argument list?
724     Data = nullptr;
725     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726       Diag->~PartialDiagnosticAt();
727       HasDiagnostic = false;
728     }
729     break;
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 }
736 
737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738   if (HasDiagnostic)
739     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740   return nullptr;
741 }
742 
743 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745   case Sema::TDK_Success:
746   case Sema::TDK_Invalid:
747   case Sema::TDK_InstantiationDepth:
748   case Sema::TDK_TooManyArguments:
749   case Sema::TDK_TooFewArguments:
750   case Sema::TDK_SubstitutionFailure:
751   case Sema::TDK_DeducedMismatch:
752   case Sema::TDK_DeducedMismatchNested:
753   case Sema::TDK_NonDeducedMismatch:
754   case Sema::TDK_CUDATargetMismatch:
755   case Sema::TDK_NonDependentConversionFailure:
756   case Sema::TDK_ConstraintsNotSatisfied:
757     return TemplateParameter();
758 
759   case Sema::TDK_Incomplete:
760   case Sema::TDK_InvalidExplicitArguments:
761     return TemplateParameter::getFromOpaqueValue(Data);
762 
763   case Sema::TDK_IncompletePack:
764   case Sema::TDK_Inconsistent:
765   case Sema::TDK_Underqualified:
766     return static_cast<DFIParamWithArguments*>(Data)->Param;
767 
768   // Unhandled
769   case Sema::TDK_MiscellaneousDeductionFailure:
770     break;
771   }
772 
773   return TemplateParameter();
774 }
775 
776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778   case Sema::TDK_Success:
779   case Sema::TDK_Invalid:
780   case Sema::TDK_InstantiationDepth:
781   case Sema::TDK_TooManyArguments:
782   case Sema::TDK_TooFewArguments:
783   case Sema::TDK_Incomplete:
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_InvalidExplicitArguments:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_NonDeducedMismatch:
789   case Sema::TDK_CUDATargetMismatch:
790   case Sema::TDK_NonDependentConversionFailure:
791     return nullptr;
792 
793   case Sema::TDK_DeducedMismatch:
794   case Sema::TDK_DeducedMismatchNested:
795     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796 
797   case Sema::TDK_SubstitutionFailure:
798     return static_cast<TemplateArgumentList*>(Data);
799 
800   case Sema::TDK_ConstraintsNotSatisfied:
801     return static_cast<CNSInfo*>(Data)->TemplateArgs;
802 
803   // Unhandled
804   case Sema::TDK_MiscellaneousDeductionFailure:
805     break;
806   }
807 
808   return nullptr;
809 }
810 
811 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813   case Sema::TDK_Success:
814   case Sema::TDK_Invalid:
815   case Sema::TDK_InstantiationDepth:
816   case Sema::TDK_Incomplete:
817   case Sema::TDK_TooManyArguments:
818   case Sema::TDK_TooFewArguments:
819   case Sema::TDK_InvalidExplicitArguments:
820   case Sema::TDK_SubstitutionFailure:
821   case Sema::TDK_CUDATargetMismatch:
822   case Sema::TDK_NonDependentConversionFailure:
823   case Sema::TDK_ConstraintsNotSatisfied:
824     return nullptr;
825 
826   case Sema::TDK_IncompletePack:
827   case Sema::TDK_Inconsistent:
828   case Sema::TDK_Underqualified:
829   case Sema::TDK_DeducedMismatch:
830   case Sema::TDK_DeducedMismatchNested:
831   case Sema::TDK_NonDeducedMismatch:
832     return &static_cast<DFIArguments*>(Data)->FirstArg;
833 
834   // Unhandled
835   case Sema::TDK_MiscellaneousDeductionFailure:
836     break;
837   }
838 
839   return nullptr;
840 }
841 
842 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844   case Sema::TDK_Success:
845   case Sema::TDK_Invalid:
846   case Sema::TDK_InstantiationDepth:
847   case Sema::TDK_Incomplete:
848   case Sema::TDK_IncompletePack:
849   case Sema::TDK_TooManyArguments:
850   case Sema::TDK_TooFewArguments:
851   case Sema::TDK_InvalidExplicitArguments:
852   case Sema::TDK_SubstitutionFailure:
853   case Sema::TDK_CUDATargetMismatch:
854   case Sema::TDK_NonDependentConversionFailure:
855   case Sema::TDK_ConstraintsNotSatisfied:
856     return nullptr;
857 
858   case Sema::TDK_Inconsistent:
859   case Sema::TDK_Underqualified:
860   case Sema::TDK_DeducedMismatch:
861   case Sema::TDK_DeducedMismatchNested:
862   case Sema::TDK_NonDeducedMismatch:
863     return &static_cast<DFIArguments*>(Data)->SecondArg;
864 
865   // Unhandled
866   case Sema::TDK_MiscellaneousDeductionFailure:
867     break;
868   }
869 
870   return nullptr;
871 }
872 
873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875   case Sema::TDK_DeducedMismatch:
876   case Sema::TDK_DeducedMismatchNested:
877     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878 
879   default:
880     return llvm::None;
881   }
882 }
883 
884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885     OverloadedOperatorKind Op) {
886   if (!AllowRewrittenCandidates)
887     return false;
888   return Op == OO_EqualEqual || Op == OO_Spaceship;
889 }
890 
891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892     ASTContext &Ctx, const FunctionDecl *FD) {
893   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894     return false;
895   // Don't bother adding a reversed candidate that can never be a better
896   // match than the non-reversed version.
897   return FD->getNumParams() != 2 ||
898          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899                                      FD->getParamDecl(1)->getType()) ||
900          FD->hasAttr<EnableIfAttr>();
901 }
902 
903 void OverloadCandidateSet::destroyCandidates() {
904   for (iterator i = begin(), e = end(); i != e; ++i) {
905     for (auto &C : i->Conversions)
906       C.~ImplicitConversionSequence();
907     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908       i->DeductionFailure.Destroy();
909   }
910 }
911 
912 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913   destroyCandidates();
914   SlabAllocator.Reset();
915   NumInlineBytesUsed = 0;
916   Candidates.clear();
917   Functions.clear();
918   Kind = CSK;
919 }
920 
921 namespace {
922   class UnbridgedCastsSet {
923     struct Entry {
924       Expr **Addr;
925       Expr *Saved;
926     };
927     SmallVector<Entry, 2> Entries;
928 
929   public:
930     void save(Sema &S, Expr *&E) {
931       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
932       Entry entry = { &E, E };
933       Entries.push_back(entry);
934       E = S.stripARCUnbridgedCast(E);
935     }
936 
937     void restore() {
938       for (SmallVectorImpl<Entry>::iterator
939              i = Entries.begin(), e = Entries.end(); i != e; ++i)
940         *i->Addr = i->Saved;
941     }
942   };
943 }
944 
945 /// checkPlaceholderForOverload - Do any interesting placeholder-like
946 /// preprocessing on the given expression.
947 ///
948 /// \param unbridgedCasts a collection to which to add unbridged casts;
949 ///   without this, they will be immediately diagnosed as errors
950 ///
951 /// Return true on unrecoverable error.
952 static bool
953 checkPlaceholderForOverload(Sema &S, Expr *&E,
954                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
955   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
956     // We can't handle overloaded expressions here because overload
957     // resolution might reasonably tweak them.
958     if (placeholder->getKind() == BuiltinType::Overload) return false;
959 
960     // If the context potentially accepts unbridged ARC casts, strip
961     // the unbridged cast and add it to the collection for later restoration.
962     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963         unbridgedCasts) {
964       unbridgedCasts->save(S, E);
965       return false;
966     }
967 
968     // Go ahead and check everything else.
969     ExprResult result = S.CheckPlaceholderExpr(E);
970     if (result.isInvalid())
971       return true;
972 
973     E = result.get();
974     return false;
975   }
976 
977   // Nothing to do.
978   return false;
979 }
980 
981 /// checkArgPlaceholdersForOverload - Check a set of call operands for
982 /// placeholders.
983 static bool checkArgPlaceholdersForOverload(Sema &S,
984                                             MultiExprArg Args,
985                                             UnbridgedCastsSet &unbridged) {
986   for (unsigned i = 0, e = Args.size(); i != e; ++i)
987     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988       return true;
989 
990   return false;
991 }
992 
993 /// Determine whether the given New declaration is an overload of the
994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995 /// New and Old cannot be overloaded, e.g., if New has the same signature as
996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997 /// functions (or function templates) at all. When it does return Ovl_Match or
998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000 /// declaration.
1001 ///
1002 /// Example: Given the following input:
1003 ///
1004 ///   void f(int, float); // #1
1005 ///   void f(int, int); // #2
1006 ///   int f(int, int); // #3
1007 ///
1008 /// When we process #1, there is no previous declaration of "f", so IsOverload
1009 /// will not be used.
1010 ///
1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014 /// unchanged.
1015 ///
1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1020 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1021 ///
1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023 /// by a using declaration. The rules for whether to hide shadow declarations
1024 /// ignore some properties which otherwise figure into a function template's
1025 /// signature.
1026 Sema::OverloadKind
1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028                     NamedDecl *&Match, bool NewIsUsingDecl) {
1029   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030          I != E; ++I) {
1031     NamedDecl *OldD = *I;
1032 
1033     bool OldIsUsingDecl = false;
1034     if (isa<UsingShadowDecl>(OldD)) {
1035       OldIsUsingDecl = true;
1036 
1037       // We can always introduce two using declarations into the same
1038       // context, even if they have identical signatures.
1039       if (NewIsUsingDecl) continue;
1040 
1041       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042     }
1043 
1044     // A using-declaration does not conflict with another declaration
1045     // if one of them is hidden.
1046     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047       continue;
1048 
1049     // If either declaration was introduced by a using declaration,
1050     // we'll need to use slightly different rules for matching.
1051     // Essentially, these rules are the normal rules, except that
1052     // function templates hide function templates with different
1053     // return types or template parameter lists.
1054     bool UseMemberUsingDeclRules =
1055       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056       !New->getFriendObjectKind();
1057 
1058     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062           continue;
1063         }
1064 
1065         if (!isa<FunctionTemplateDecl>(OldD) &&
1066             !shouldLinkPossiblyHiddenDecl(*I, New))
1067           continue;
1068 
1069         Match = *I;
1070         return Ovl_Match;
1071       }
1072 
1073       // Builtins that have custom typechecking or have a reference should
1074       // not be overloadable or redeclarable.
1075       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076         Match = *I;
1077         return Ovl_NonFunction;
1078       }
1079     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080       // We can overload with these, which can show up when doing
1081       // redeclaration checks for UsingDecls.
1082       assert(Old.getLookupKind() == LookupUsingDeclName);
1083     } else if (isa<TagDecl>(OldD)) {
1084       // We can always overload with tags by hiding them.
1085     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086       // Optimistically assume that an unresolved using decl will
1087       // overload; if it doesn't, we'll have to diagnose during
1088       // template instantiation.
1089       //
1090       // Exception: if the scope is dependent and this is not a class
1091       // member, the using declaration can only introduce an enumerator.
1092       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093         Match = *I;
1094         return Ovl_NonFunction;
1095       }
1096     } else {
1097       // (C++ 13p1):
1098       //   Only function declarations can be overloaded; object and type
1099       //   declarations cannot be overloaded.
1100       Match = *I;
1101       return Ovl_NonFunction;
1102     }
1103   }
1104 
1105   // C++ [temp.friend]p1:
1106   //   For a friend function declaration that is not a template declaration:
1107   //    -- if the name of the friend is a qualified or unqualified template-id,
1108   //       [...], otherwise
1109   //    -- if the name of the friend is a qualified-id and a matching
1110   //       non-template function is found in the specified class or namespace,
1111   //       the friend declaration refers to that function, otherwise,
1112   //    -- if the name of the friend is a qualified-id and a matching function
1113   //       template is found in the specified class or namespace, the friend
1114   //       declaration refers to the deduced specialization of that function
1115   //       template, otherwise
1116   //    -- the name shall be an unqualified-id [...]
1117   // If we get here for a qualified friend declaration, we've just reached the
1118   // third bullet. If the type of the friend is dependent, skip this lookup
1119   // until instantiation.
1120   if (New->getFriendObjectKind() && New->getQualifier() &&
1121       !New->getDescribedFunctionTemplate() &&
1122       !New->getDependentSpecializationInfo() &&
1123       !New->getType()->isDependentType()) {
1124     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125     TemplateSpecResult.addAllDecls(Old);
1126     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127                                             /*QualifiedFriend*/true)) {
1128       New->setInvalidDecl();
1129       return Ovl_Overload;
1130     }
1131 
1132     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133     return Ovl_Match;
1134   }
1135 
1136   return Ovl_Overload;
1137 }
1138 
1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141                       bool ConsiderRequiresClauses) {
1142   // C++ [basic.start.main]p2: This function shall not be overloaded.
1143   if (New->isMain())
1144     return false;
1145 
1146   // MSVCRT user defined entry points cannot be overloaded.
1147   if (New->isMSVCRTEntryPoint())
1148     return false;
1149 
1150   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1152 
1153   // C++ [temp.fct]p2:
1154   //   A function template can be overloaded with other function templates
1155   //   and with normal (non-template) functions.
1156   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1157     return true;
1158 
1159   // Is the function New an overload of the function Old?
1160   QualType OldQType = Context.getCanonicalType(Old->getType());
1161   QualType NewQType = Context.getCanonicalType(New->getType());
1162 
1163   // Compare the signatures (C++ 1.3.10) of the two functions to
1164   // determine whether they are overloads. If we find any mismatch
1165   // in the signature, they are overloads.
1166 
1167   // If either of these functions is a K&R-style function (no
1168   // prototype), then we consider them to have matching signatures.
1169   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1171     return false;
1172 
1173   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1175 
1176   // The signature of a function includes the types of its
1177   // parameters (C++ 1.3.10), which includes the presence or absence
1178   // of the ellipsis; see C++ DR 357).
1179   if (OldQType != NewQType &&
1180       (OldType->getNumParams() != NewType->getNumParams() ||
1181        OldType->isVariadic() != NewType->isVariadic() ||
1182        !FunctionParamTypesAreEqual(OldType, NewType)))
1183     return true;
1184 
1185   // C++ [temp.over.link]p4:
1186   //   The signature of a function template consists of its function
1187   //   signature, its return type and its template parameter list. The names
1188   //   of the template parameters are significant only for establishing the
1189   //   relationship between the template parameters and the rest of the
1190   //   signature.
1191   //
1192   // We check the return type and template parameter lists for function
1193   // templates first; the remaining checks follow.
1194   //
1195   // However, we don't consider either of these when deciding whether
1196   // a member introduced by a shadow declaration is hidden.
1197   if (!UseMemberUsingDeclRules && NewTemplate &&
1198       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199                                        OldTemplate->getTemplateParameters(),
1200                                        false, TPL_TemplateMatch) ||
1201        !Context.hasSameType(Old->getDeclaredReturnType(),
1202                             New->getDeclaredReturnType())))
1203     return true;
1204 
1205   // If the function is a class member, its signature includes the
1206   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1207   //
1208   // As part of this, also check whether one of the member functions
1209   // is static, in which case they are not overloads (C++
1210   // 13.1p2). While not part of the definition of the signature,
1211   // this check is important to determine whether these functions
1212   // can be overloaded.
1213   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215   if (OldMethod && NewMethod &&
1216       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218       if (!UseMemberUsingDeclRules &&
1219           (OldMethod->getRefQualifier() == RQ_None ||
1220            NewMethod->getRefQualifier() == RQ_None)) {
1221         // C++0x [over.load]p2:
1222         //   - Member function declarations with the same name and the same
1223         //     parameter-type-list as well as member function template
1224         //     declarations with the same name, the same parameter-type-list, and
1225         //     the same template parameter lists cannot be overloaded if any of
1226         //     them, but not all, have a ref-qualifier (8.3.5).
1227         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1230       }
1231       return true;
1232     }
1233 
1234     // We may not have applied the implicit const for a constexpr member
1235     // function yet (because we haven't yet resolved whether this is a static
1236     // or non-static member function). Add it now, on the assumption that this
1237     // is a redeclaration of OldMethod.
1238     auto OldQuals = OldMethod->getMethodQualifiers();
1239     auto NewQuals = NewMethod->getMethodQualifiers();
1240     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241         !isa<CXXConstructorDecl>(NewMethod))
1242       NewQuals.addConst();
1243     // We do not allow overloading based off of '__restrict'.
1244     OldQuals.removeRestrict();
1245     NewQuals.removeRestrict();
1246     if (OldQuals != NewQuals)
1247       return true;
1248   }
1249 
1250   // Though pass_object_size is placed on parameters and takes an argument, we
1251   // consider it to be a function-level modifier for the sake of function
1252   // identity. Either the function has one or more parameters with
1253   // pass_object_size or it doesn't.
1254   if (functionHasPassObjectSizeParams(New) !=
1255       functionHasPassObjectSizeParams(Old))
1256     return true;
1257 
1258   // enable_if attributes are an order-sensitive part of the signature.
1259   for (specific_attr_iterator<EnableIfAttr>
1260          NewI = New->specific_attr_begin<EnableIfAttr>(),
1261          NewE = New->specific_attr_end<EnableIfAttr>(),
1262          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263          OldE = Old->specific_attr_end<EnableIfAttr>();
1264        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265     if (NewI == NewE || OldI == OldE)
1266       return true;
1267     llvm::FoldingSetNodeID NewID, OldID;
1268     NewI->getCond()->Profile(NewID, Context, true);
1269     OldI->getCond()->Profile(OldID, Context, true);
1270     if (NewID != OldID)
1271       return true;
1272   }
1273 
1274   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275     // Don't allow overloading of destructors.  (In theory we could, but it
1276     // would be a giant change to clang.)
1277     if (!isa<CXXDestructorDecl>(New)) {
1278       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279                          OldTarget = IdentifyCUDATarget(Old);
1280       if (NewTarget != CFT_InvalidTarget) {
1281         assert((OldTarget != CFT_InvalidTarget) &&
1282                "Unexpected invalid target.");
1283 
1284         // Allow overloading of functions with same signature and different CUDA
1285         // target attributes.
1286         if (NewTarget != OldTarget)
1287           return true;
1288       }
1289     }
1290   }
1291 
1292   if (ConsiderRequiresClauses) {
1293     Expr *NewRC = New->getTrailingRequiresClause(),
1294          *OldRC = Old->getTrailingRequiresClause();
1295     if ((NewRC != nullptr) != (OldRC != nullptr))
1296       // RC are most certainly different - these are overloads.
1297       return true;
1298 
1299     if (NewRC) {
1300       llvm::FoldingSetNodeID NewID, OldID;
1301       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1303       if (NewID != OldID)
1304         // RCs are not equivalent - these are overloads.
1305         return true;
1306     }
1307   }
1308 
1309   // The signatures match; this is not an overload.
1310   return false;
1311 }
1312 
1313 /// Tries a user-defined conversion from From to ToType.
1314 ///
1315 /// Produces an implicit conversion sequence for when a standard conversion
1316 /// is not an option. See TryImplicitConversion for more information.
1317 static ImplicitConversionSequence
1318 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319                          bool SuppressUserConversions,
1320                          bool AllowExplicit,
1321                          bool InOverloadResolution,
1322                          bool CStyle,
1323                          bool AllowObjCWritebackConversion,
1324                          bool AllowObjCConversionOnExplicit) {
1325   ImplicitConversionSequence ICS;
1326 
1327   if (SuppressUserConversions) {
1328     // We're not in the case above, so there is no conversion that
1329     // we can perform.
1330     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1331     return ICS;
1332   }
1333 
1334   // Attempt user-defined conversion.
1335   OverloadCandidateSet Conversions(From->getExprLoc(),
1336                                    OverloadCandidateSet::CSK_Normal);
1337   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338                                   Conversions, AllowExplicit,
1339                                   AllowObjCConversionOnExplicit)) {
1340   case OR_Success:
1341   case OR_Deleted:
1342     ICS.setUserDefined();
1343     // C++ [over.ics.user]p4:
1344     //   A conversion of an expression of class type to the same class
1345     //   type is given Exact Match rank, and a conversion of an
1346     //   expression of class type to a base class of that type is
1347     //   given Conversion rank, in spite of the fact that a copy
1348     //   constructor (i.e., a user-defined conversion function) is
1349     //   called for those cases.
1350     if (CXXConstructorDecl *Constructor
1351           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1352       QualType FromCanon
1353         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1354       QualType ToCanon
1355         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356       if (Constructor->isCopyConstructor() &&
1357           (FromCanon == ToCanon ||
1358            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359         // Turn this into a "standard" conversion sequence, so that it
1360         // gets ranked with standard conversion sequences.
1361         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1362         ICS.setStandard();
1363         ICS.Standard.setAsIdentityConversion();
1364         ICS.Standard.setFromType(From->getType());
1365         ICS.Standard.setAllToTypes(ToType);
1366         ICS.Standard.CopyConstructor = Constructor;
1367         ICS.Standard.FoundCopyConstructor = Found;
1368         if (ToCanon != FromCanon)
1369           ICS.Standard.Second = ICK_Derived_To_Base;
1370       }
1371     }
1372     break;
1373 
1374   case OR_Ambiguous:
1375     ICS.setAmbiguous();
1376     ICS.Ambiguous.setFromType(From->getType());
1377     ICS.Ambiguous.setToType(ToType);
1378     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379          Cand != Conversions.end(); ++Cand)
1380       if (Cand->Best)
1381         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1382     break;
1383 
1384     // Fall through.
1385   case OR_No_Viable_Function:
1386     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1387     break;
1388   }
1389 
1390   return ICS;
1391 }
1392 
1393 /// TryImplicitConversion - Attempt to perform an implicit conversion
1394 /// from the given expression (Expr) to the given type (ToType). This
1395 /// function returns an implicit conversion sequence that can be used
1396 /// to perform the initialization. Given
1397 ///
1398 ///   void f(float f);
1399 ///   void g(int i) { f(i); }
1400 ///
1401 /// this routine would produce an implicit conversion sequence to
1402 /// describe the initialization of f from i, which will be a standard
1403 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1405 //
1406 /// Note that this routine only determines how the conversion can be
1407 /// performed; it does not actually perform the conversion. As such,
1408 /// it will not produce any diagnostics if no conversion is available,
1409 /// but will instead return an implicit conversion sequence of kind
1410 /// "BadConversion".
1411 ///
1412 /// If @p SuppressUserConversions, then user-defined conversions are
1413 /// not permitted.
1414 /// If @p AllowExplicit, then explicit user-defined conversions are
1415 /// permitted.
1416 ///
1417 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418 /// writeback conversion, which allows __autoreleasing id* parameters to
1419 /// be initialized with __strong id* or __weak id* arguments.
1420 static ImplicitConversionSequence
1421 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422                       bool SuppressUserConversions,
1423                       bool AllowExplicit,
1424                       bool InOverloadResolution,
1425                       bool CStyle,
1426                       bool AllowObjCWritebackConversion,
1427                       bool AllowObjCConversionOnExplicit) {
1428   ImplicitConversionSequence ICS;
1429   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1431     ICS.setStandard();
1432     return ICS;
1433   }
1434 
1435   if (!S.getLangOpts().CPlusPlus) {
1436     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1437     return ICS;
1438   }
1439 
1440   // C++ [over.ics.user]p4:
1441   //   A conversion of an expression of class type to the same class
1442   //   type is given Exact Match rank, and a conversion of an
1443   //   expression of class type to a base class of that type is
1444   //   given Conversion rank, in spite of the fact that a copy/move
1445   //   constructor (i.e., a user-defined conversion function) is
1446   //   called for those cases.
1447   QualType FromType = From->getType();
1448   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1451     ICS.setStandard();
1452     ICS.Standard.setAsIdentityConversion();
1453     ICS.Standard.setFromType(FromType);
1454     ICS.Standard.setAllToTypes(ToType);
1455 
1456     // We don't actually check at this point whether there is a valid
1457     // copy/move constructor, since overloading just assumes that it
1458     // exists. When we actually perform initialization, we'll find the
1459     // appropriate constructor to copy the returned object, if needed.
1460     ICS.Standard.CopyConstructor = nullptr;
1461 
1462     // Determine whether this is considered a derived-to-base conversion.
1463     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464       ICS.Standard.Second = ICK_Derived_To_Base;
1465 
1466     return ICS;
1467   }
1468 
1469   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470                                   AllowExplicit, InOverloadResolution, CStyle,
1471                                   AllowObjCWritebackConversion,
1472                                   AllowObjCConversionOnExplicit);
1473 }
1474 
1475 ImplicitConversionSequence
1476 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477                             bool SuppressUserConversions,
1478                             bool AllowExplicit,
1479                             bool InOverloadResolution,
1480                             bool CStyle,
1481                             bool AllowObjCWritebackConversion) {
1482   return ::TryImplicitConversion(*this, From, ToType,
1483                                  SuppressUserConversions, AllowExplicit,
1484                                  InOverloadResolution, CStyle,
1485                                  AllowObjCWritebackConversion,
1486                                  /*AllowObjCConversionOnExplicit=*/false);
1487 }
1488 
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1494 ExprResult
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                 AssignmentAction Action, bool AllowExplicit) {
1497   ImplicitConversionSequence ICS;
1498   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499 }
1500 
1501 ExprResult
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503                                 AssignmentAction Action, bool AllowExplicit,
1504                                 ImplicitConversionSequence& ICS) {
1505   if (checkPlaceholderForOverload(*this, From))
1506     return ExprError();
1507 
1508   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509   bool AllowObjCWritebackConversion
1510     = getLangOpts().ObjCAutoRefCount &&
1511       (Action == AA_Passing || Action == AA_Sending);
1512   if (getLangOpts().ObjC)
1513     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514                                       From->getType(), From);
1515   ICS = ::TryImplicitConversion(*this, From, ToType,
1516                                 /*SuppressUserConversions=*/false,
1517                                 AllowExplicit,
1518                                 /*InOverloadResolution=*/false,
1519                                 /*CStyle=*/false,
1520                                 AllowObjCWritebackConversion,
1521                                 /*AllowObjCConversionOnExplicit=*/false);
1522   return PerformImplicitConversion(From, ToType, ICS, Action);
1523 }
1524 
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1527 /// type.
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529                                 QualType &ResultTy) {
1530   if (Context.hasSameUnqualifiedType(FromType, ToType))
1531     return false;
1532 
1533   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534   //                    or F(t noexcept) -> F(t)
1535   // where F adds one of the following at most once:
1536   //   - a pointer
1537   //   - a member pointer
1538   //   - a block pointer
1539   // Changes here need matching changes in FindCompositePointerType.
1540   CanQualType CanTo = Context.getCanonicalType(ToType);
1541   CanQualType CanFrom = Context.getCanonicalType(FromType);
1542   Type::TypeClass TyClass = CanTo->getTypeClass();
1543   if (TyClass != CanFrom->getTypeClass()) return false;
1544   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545     if (TyClass == Type::Pointer) {
1546       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548     } else if (TyClass == Type::BlockPointer) {
1549       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551     } else if (TyClass == Type::MemberPointer) {
1552       auto ToMPT = CanTo.castAs<MemberPointerType>();
1553       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554       // A function pointer conversion cannot change the class of the function.
1555       if (ToMPT->getClass() != FromMPT->getClass())
1556         return false;
1557       CanTo = ToMPT->getPointeeType();
1558       CanFrom = FromMPT->getPointeeType();
1559     } else {
1560       return false;
1561     }
1562 
1563     TyClass = CanTo->getTypeClass();
1564     if (TyClass != CanFrom->getTypeClass()) return false;
1565     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566       return false;
1567   }
1568 
1569   const auto *FromFn = cast<FunctionType>(CanFrom);
1570   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571 
1572   const auto *ToFn = cast<FunctionType>(CanTo);
1573   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574 
1575   bool Changed = false;
1576 
1577   // Drop 'noreturn' if not present in target type.
1578   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580     Changed = true;
1581   }
1582 
1583   // Drop 'noexcept' if not present in target type.
1584   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587       FromFn = cast<FunctionType>(
1588           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589                                                    EST_None)
1590                  .getTypePtr());
1591       Changed = true;
1592     }
1593 
1594     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595     // only if the ExtParameterInfo lists of the two function prototypes can be
1596     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598     bool CanUseToFPT, CanUseFromFPT;
1599     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600                                       CanUseFromFPT, NewParamInfos) &&
1601         CanUseToFPT && !CanUseFromFPT) {
1602       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603       ExtInfo.ExtParameterInfos =
1604           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606                                             FromFPT->getParamTypes(), ExtInfo);
1607       FromFn = QT->getAs<FunctionType>();
1608       Changed = true;
1609     }
1610   }
1611 
1612   if (!Changed)
1613     return false;
1614 
1615   assert(QualType(FromFn, 0).isCanonical());
1616   if (QualType(FromFn, 0) != CanTo) return false;
1617 
1618   ResultTy = ToType;
1619   return true;
1620 }
1621 
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1624 ///
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1626 /// conversion.
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628                                QualType ToType, ImplicitConversionKind &ICK) {
1629   // We need at least one of these types to be a vector type to have a vector
1630   // conversion.
1631   if (!ToType->isVectorType() && !FromType->isVectorType())
1632     return false;
1633 
1634   // Identical types require no conversions.
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636     return false;
1637 
1638   // There are no conversions between extended vector types, only identity.
1639   if (ToType->isExtVectorType()) {
1640     // There are no conversions between extended vector types other than the
1641     // identity conversion.
1642     if (FromType->isExtVectorType())
1643       return false;
1644 
1645     // Vector splat from any arithmetic type to a vector.
1646     if (FromType->isArithmeticType()) {
1647       ICK = ICK_Vector_Splat;
1648       return true;
1649     }
1650   }
1651 
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   // 3)the destination type does not have the ARM MVE strict-polymorphism
1657   //   attribute, which inhibits lax vector conversion for overload resolution
1658   //   only
1659   if (ToType->isVectorType() && FromType->isVectorType()) {
1660     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661         (S.isLaxVectorConversion(FromType, ToType) &&
1662          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663       ICK = ICK_Vector_Conversion;
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672                                 bool InOverloadResolution,
1673                                 StandardConversionSequence &SCS,
1674                                 bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685                                  bool InOverloadResolution,
1686                                  StandardConversionSequence &SCS,
1687                                  bool CStyle,
1688                                  bool AllowObjCWritebackConversion) {
1689   QualType FromType = From->getType();
1690 
1691   // Standard conversions (C++ [conv])
1692   SCS.setAsIdentityConversion();
1693   SCS.IncompatibleObjC = false;
1694   SCS.setFromType(FromType);
1695   SCS.CopyConstructor = nullptr;
1696 
1697   // There are no standard conversions for class types in C++, so
1698   // abort early. When overloading in C, however, we do permit them.
1699   if (S.getLangOpts().CPlusPlus &&
1700       (FromType->isRecordType() || ToType->isRecordType()))
1701     return false;
1702 
1703   // The first conversion can be an lvalue-to-rvalue conversion,
1704   // array-to-pointer conversion, or function-to-pointer conversion
1705   // (C++ 4p1).
1706 
1707   if (FromType == S.Context.OverloadTy) {
1708     DeclAccessPair AccessPair;
1709     if (FunctionDecl *Fn
1710           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711                                                  AccessPair)) {
1712       // We were able to resolve the address of the overloaded function,
1713       // so we can convert to the type of that function.
1714       FromType = Fn->getType();
1715       SCS.setFromType(FromType);
1716 
1717       // we can sometimes resolve &foo<int> regardless of ToType, so check
1718       // if the type matches (identity) or we are converting to bool
1719       if (!S.Context.hasSameUnqualifiedType(
1720                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721         QualType resultTy;
1722         // if the function type matches except for [[noreturn]], it's ok
1723         if (!S.IsFunctionConversion(FromType,
1724               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725           // otherwise, only a boolean conversion is standard
1726           if (!ToType->isBooleanType())
1727             return false;
1728       }
1729 
1730       // Check if the "from" expression is taking the address of an overloaded
1731       // function and recompute the FromType accordingly. Take advantage of the
1732       // fact that non-static member functions *must* have such an address-of
1733       // expression.
1734       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735       if (Method && !Method->isStatic()) {
1736         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737                "Non-unary operator on non-static member address");
1738         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739                == UO_AddrOf &&
1740                "Non-address-of operator on non-static member address");
1741         const Type *ClassType
1742           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746                UO_AddrOf &&
1747                "Non-address-of operator for overloaded function expression");
1748         FromType = S.Context.getPointerType(FromType);
1749       }
1750 
1751       // Check that we've computed the proper type after overload resolution.
1752       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1753       // be calling it from within an NDEBUG block.
1754       assert(S.Context.hasSameType(
1755         FromType,
1756         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757     } else {
1758       return false;
1759     }
1760   }
1761   // Lvalue-to-rvalue conversion (C++11 4.1):
1762   //   A glvalue (3.10) of a non-function, non-array type T can
1763   //   be converted to a prvalue.
1764   bool argIsLValue = From->isGLValue();
1765   if (argIsLValue &&
1766       !FromType->isFunctionType() && !FromType->isArrayType() &&
1767       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1768     SCS.First = ICK_Lvalue_To_Rvalue;
1769 
1770     // C11 6.3.2.1p2:
1771     //   ... if the lvalue has atomic type, the value has the non-atomic version
1772     //   of the type of the lvalue ...
1773     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1774       FromType = Atomic->getValueType();
1775 
1776     // If T is a non-class type, the type of the rvalue is the
1777     // cv-unqualified version of T. Otherwise, the type of the rvalue
1778     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1779     // just strip the qualifiers because they don't matter.
1780     FromType = FromType.getUnqualifiedType();
1781   } else if (FromType->isArrayType()) {
1782     // Array-to-pointer conversion (C++ 4.2)
1783     SCS.First = ICK_Array_To_Pointer;
1784 
1785     // An lvalue or rvalue of type "array of N T" or "array of unknown
1786     // bound of T" can be converted to an rvalue of type "pointer to
1787     // T" (C++ 4.2p1).
1788     FromType = S.Context.getArrayDecayedType(FromType);
1789 
1790     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1791       // This conversion is deprecated in C++03 (D.4)
1792       SCS.DeprecatedStringLiteralToCharPtr = true;
1793 
1794       // For the purpose of ranking in overload resolution
1795       // (13.3.3.1.1), this conversion is considered an
1796       // array-to-pointer conversion followed by a qualification
1797       // conversion (4.4). (C++ 4.2p2)
1798       SCS.Second = ICK_Identity;
1799       SCS.Third = ICK_Qualification;
1800       SCS.QualificationIncludesObjCLifetime = false;
1801       SCS.setAllToTypes(FromType);
1802       return true;
1803     }
1804   } else if (FromType->isFunctionType() && argIsLValue) {
1805     // Function-to-pointer conversion (C++ 4.3).
1806     SCS.First = ICK_Function_To_Pointer;
1807 
1808     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1809       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1810         if (!S.checkAddressOfFunctionIsAvailable(FD))
1811           return false;
1812 
1813     // An lvalue of function type T can be converted to an rvalue of
1814     // type "pointer to T." The result is a pointer to the
1815     // function. (C++ 4.3p1).
1816     FromType = S.Context.getPointerType(FromType);
1817   } else {
1818     // We don't require any conversions for the first step.
1819     SCS.First = ICK_Identity;
1820   }
1821   SCS.setToType(0, FromType);
1822 
1823   // The second conversion can be an integral promotion, floating
1824   // point promotion, integral conversion, floating point conversion,
1825   // floating-integral conversion, pointer conversion,
1826   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1827   // For overloading in C, this can also be a "compatible-type"
1828   // conversion.
1829   bool IncompatibleObjC = false;
1830   ImplicitConversionKind SecondICK = ICK_Identity;
1831   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1832     // The unqualified versions of the types are the same: there's no
1833     // conversion to do.
1834     SCS.Second = ICK_Identity;
1835   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1836     // Integral promotion (C++ 4.5).
1837     SCS.Second = ICK_Integral_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1840     // Floating point promotion (C++ 4.6).
1841     SCS.Second = ICK_Floating_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsComplexPromotion(FromType, ToType)) {
1844     // Complex promotion (Clang extension)
1845     SCS.Second = ICK_Complex_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (ToType->isBooleanType() &&
1848              (FromType->isArithmeticType() ||
1849               FromType->isAnyPointerType() ||
1850               FromType->isBlockPointerType() ||
1851               FromType->isMemberPointerType() ||
1852               FromType->isNullPtrType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double and __float128 if
1872     // their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874     if (&S.Context.getFloatTypeSemantics(FromType) !=
1875         &S.Context.getFloatTypeSemantics(ToType)) {
1876       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1877                                     ToType == S.Context.LongDoubleTy) ||
1878                                    (FromType == S.Context.LongDoubleTy &&
1879                                     ToType == S.Context.Float128Ty));
1880       if (Float128AndLongDouble &&
1881           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1882            &llvm::APFloat::PPCDoubleDouble()))
1883         return false;
1884     }
1885     // Floating point conversions (C++ 4.8).
1886     SCS.Second = ICK_Floating_Conversion;
1887     FromType = ToType.getUnqualifiedType();
1888   } else if ((FromType->isRealFloatingType() &&
1889               ToType->isIntegralType(S.Context)) ||
1890              (FromType->isIntegralOrUnscopedEnumerationType() &&
1891               ToType->isRealFloatingType())) {
1892     // Floating-integral conversions (C++ 4.9).
1893     SCS.Second = ICK_Floating_Integral;
1894     FromType = ToType.getUnqualifiedType();
1895   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1896     SCS.Second = ICK_Block_Pointer_Conversion;
1897   } else if (AllowObjCWritebackConversion &&
1898              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1899     SCS.Second = ICK_Writeback_Conversion;
1900   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1901                                    FromType, IncompatibleObjC)) {
1902     // Pointer conversions (C++ 4.10).
1903     SCS.Second = ICK_Pointer_Conversion;
1904     SCS.IncompatibleObjC = IncompatibleObjC;
1905     FromType = FromType.getUnqualifiedType();
1906   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1907                                          InOverloadResolution, FromType)) {
1908     // Pointer to member conversions (4.11).
1909     SCS.Second = ICK_Pointer_Member;
1910   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1911     SCS.Second = SecondICK;
1912     FromType = ToType.getUnqualifiedType();
1913   } else if (!S.getLangOpts().CPlusPlus &&
1914              S.Context.typesAreCompatible(ToType, FromType)) {
1915     // Compatible conversions (Clang extension for C function overloading)
1916     SCS.Second = ICK_Compatible_Conversion;
1917     FromType = ToType.getUnqualifiedType();
1918   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1919                                              InOverloadResolution,
1920                                              SCS, CStyle)) {
1921     SCS.Second = ICK_TransparentUnionConversion;
1922     FromType = ToType;
1923   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1924                                  CStyle)) {
1925     // tryAtomicConversion has updated the standard conversion sequence
1926     // appropriately.
1927     return true;
1928   } else if (ToType->isEventT() &&
1929              From->isIntegerConstantExpr(S.getASTContext()) &&
1930              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1931     SCS.Second = ICK_Zero_Event_Conversion;
1932     FromType = ToType;
1933   } else if (ToType->isQueueT() &&
1934              From->isIntegerConstantExpr(S.getASTContext()) &&
1935              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1936     SCS.Second = ICK_Zero_Queue_Conversion;
1937     FromType = ToType;
1938   } else if (ToType->isSamplerT() &&
1939              From->isIntegerConstantExpr(S.getASTContext())) {
1940     SCS.Second = ICK_Compatible_Conversion;
1941     FromType = ToType;
1942   } else {
1943     // No second conversion required.
1944     SCS.Second = ICK_Identity;
1945   }
1946   SCS.setToType(1, FromType);
1947 
1948   // The third conversion can be a function pointer conversion or a
1949   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1950   bool ObjCLifetimeConversion;
1951   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1952     // Function pointer conversions (removing 'noexcept') including removal of
1953     // 'noreturn' (Clang extension).
1954     SCS.Third = ICK_Function_Conversion;
1955   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1956                                          ObjCLifetimeConversion)) {
1957     SCS.Third = ICK_Qualification;
1958     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1959     FromType = ToType;
1960   } else {
1961     // No conversion required
1962     SCS.Third = ICK_Identity;
1963   }
1964 
1965   // C++ [over.best.ics]p6:
1966   //   [...] Any difference in top-level cv-qualification is
1967   //   subsumed by the initialization itself and does not constitute
1968   //   a conversion. [...]
1969   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1970   QualType CanonTo = S.Context.getCanonicalType(ToType);
1971   if (CanonFrom.getLocalUnqualifiedType()
1972                                      == CanonTo.getLocalUnqualifiedType() &&
1973       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1974     FromType = ToType;
1975     CanonFrom = CanonTo;
1976   }
1977 
1978   SCS.setToType(2, FromType);
1979 
1980   if (CanonFrom == CanonTo)
1981     return true;
1982 
1983   // If we have not converted the argument type to the parameter type,
1984   // this is a bad conversion sequence, unless we're resolving an overload in C.
1985   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1986     return false;
1987 
1988   ExprResult ER = ExprResult{From};
1989   Sema::AssignConvertType Conv =
1990       S.CheckSingleAssignmentConstraints(ToType, ER,
1991                                          /*Diagnose=*/false,
1992                                          /*DiagnoseCFAudited=*/false,
1993                                          /*ConvertRHS=*/false);
1994   ImplicitConversionKind SecondConv;
1995   switch (Conv) {
1996   case Sema::Compatible:
1997     SecondConv = ICK_C_Only_Conversion;
1998     break;
1999   // For our purposes, discarding qualifiers is just as bad as using an
2000   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2001   // qualifiers, as well.
2002   case Sema::CompatiblePointerDiscardsQualifiers:
2003   case Sema::IncompatiblePointer:
2004   case Sema::IncompatiblePointerSign:
2005     SecondConv = ICK_Incompatible_Pointer_Conversion;
2006     break;
2007   default:
2008     return false;
2009   }
2010 
2011   // First can only be an lvalue conversion, so we pretend that this was the
2012   // second conversion. First should already be valid from earlier in the
2013   // function.
2014   SCS.Second = SecondConv;
2015   SCS.setToType(1, ToType);
2016 
2017   // Third is Identity, because Second should rank us worse than any other
2018   // conversion. This could also be ICK_Qualification, but it's simpler to just
2019   // lump everything in with the second conversion, and we don't gain anything
2020   // from making this ICK_Qualification.
2021   SCS.Third = ICK_Identity;
2022   SCS.setToType(2, ToType);
2023   return true;
2024 }
2025 
2026 static bool
2027 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2028                                      QualType &ToType,
2029                                      bool InOverloadResolution,
2030                                      StandardConversionSequence &SCS,
2031                                      bool CStyle) {
2032 
2033   const RecordType *UT = ToType->getAsUnionType();
2034   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2035     return false;
2036   // The field to initialize within the transparent union.
2037   RecordDecl *UD = UT->getDecl();
2038   // It's compatible if the expression matches any of the fields.
2039   for (const auto *it : UD->fields()) {
2040     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2041                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2042       ToType = it->getType();
2043       return true;
2044     }
2045   }
2046   return false;
2047 }
2048 
2049 /// IsIntegralPromotion - Determines whether the conversion from the
2050 /// expression From (whose potentially-adjusted type is FromType) to
2051 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2052 /// sets PromotedType to the promoted type.
2053 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2054   const BuiltinType *To = ToType->getAs<BuiltinType>();
2055   // All integers are built-in.
2056   if (!To) {
2057     return false;
2058   }
2059 
2060   // An rvalue of type char, signed char, unsigned char, short int, or
2061   // unsigned short int can be converted to an rvalue of type int if
2062   // int can represent all the values of the source type; otherwise,
2063   // the source rvalue can be converted to an rvalue of type unsigned
2064   // int (C++ 4.5p1).
2065   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2066       !FromType->isEnumeralType()) {
2067     if (// We can promote any signed, promotable integer type to an int
2068         (FromType->isSignedIntegerType() ||
2069          // We can promote any unsigned integer type whose size is
2070          // less than int to an int.
2071          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2072       return To->getKind() == BuiltinType::Int;
2073     }
2074 
2075     return To->getKind() == BuiltinType::UInt;
2076   }
2077 
2078   // C++11 [conv.prom]p3:
2079   //   A prvalue of an unscoped enumeration type whose underlying type is not
2080   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2081   //   following types that can represent all the values of the enumeration
2082   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2083   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2084   //   long long int. If none of the types in that list can represent all the
2085   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2086   //   type can be converted to an rvalue a prvalue of the extended integer type
2087   //   with lowest integer conversion rank (4.13) greater than the rank of long
2088   //   long in which all the values of the enumeration can be represented. If
2089   //   there are two such extended types, the signed one is chosen.
2090   // C++11 [conv.prom]p4:
2091   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2092   //   can be converted to a prvalue of its underlying type. Moreover, if
2093   //   integral promotion can be applied to its underlying type, a prvalue of an
2094   //   unscoped enumeration type whose underlying type is fixed can also be
2095   //   converted to a prvalue of the promoted underlying type.
2096   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2097     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2098     // provided for a scoped enumeration.
2099     if (FromEnumType->getDecl()->isScoped())
2100       return false;
2101 
2102     // We can perform an integral promotion to the underlying type of the enum,
2103     // even if that's not the promoted type. Note that the check for promoting
2104     // the underlying type is based on the type alone, and does not consider
2105     // the bitfield-ness of the actual source expression.
2106     if (FromEnumType->getDecl()->isFixed()) {
2107       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2108       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2109              IsIntegralPromotion(nullptr, Underlying, ToType);
2110     }
2111 
2112     // We have already pre-calculated the promotion type, so this is trivial.
2113     if (ToType->isIntegerType() &&
2114         isCompleteType(From->getBeginLoc(), FromType))
2115       return Context.hasSameUnqualifiedType(
2116           ToType, FromEnumType->getDecl()->getPromotionType());
2117 
2118     // C++ [conv.prom]p5:
2119     //   If the bit-field has an enumerated type, it is treated as any other
2120     //   value of that type for promotion purposes.
2121     //
2122     // ... so do not fall through into the bit-field checks below in C++.
2123     if (getLangOpts().CPlusPlus)
2124       return false;
2125   }
2126 
2127   // C++0x [conv.prom]p2:
2128   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2129   //   to an rvalue a prvalue of the first of the following types that can
2130   //   represent all the values of its underlying type: int, unsigned int,
2131   //   long int, unsigned long int, long long int, or unsigned long long int.
2132   //   If none of the types in that list can represent all the values of its
2133   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2134   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2135   //   type.
2136   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2137       ToType->isIntegerType()) {
2138     // Determine whether the type we're converting from is signed or
2139     // unsigned.
2140     bool FromIsSigned = FromType->isSignedIntegerType();
2141     uint64_t FromSize = Context.getTypeSize(FromType);
2142 
2143     // The types we'll try to promote to, in the appropriate
2144     // order. Try each of these types.
2145     QualType PromoteTypes[6] = {
2146       Context.IntTy, Context.UnsignedIntTy,
2147       Context.LongTy, Context.UnsignedLongTy ,
2148       Context.LongLongTy, Context.UnsignedLongLongTy
2149     };
2150     for (int Idx = 0; Idx < 6; ++Idx) {
2151       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2152       if (FromSize < ToSize ||
2153           (FromSize == ToSize &&
2154            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2155         // We found the type that we can promote to. If this is the
2156         // type we wanted, we have a promotion. Otherwise, no
2157         // promotion.
2158         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2159       }
2160     }
2161   }
2162 
2163   // An rvalue for an integral bit-field (9.6) can be converted to an
2164   // rvalue of type int if int can represent all the values of the
2165   // bit-field; otherwise, it can be converted to unsigned int if
2166   // unsigned int can represent all the values of the bit-field. If
2167   // the bit-field is larger yet, no integral promotion applies to
2168   // it. If the bit-field has an enumerated type, it is treated as any
2169   // other value of that type for promotion purposes (C++ 4.5p3).
2170   // FIXME: We should delay checking of bit-fields until we actually perform the
2171   // conversion.
2172   //
2173   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2174   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2175   // bit-fields and those whose underlying type is larger than int) for GCC
2176   // compatibility.
2177   if (From) {
2178     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2179       llvm::APSInt BitWidth;
2180       if (FromType->isIntegralType(Context) &&
2181           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2182         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2183         ToSize = Context.getTypeSize(ToType);
2184 
2185         // Are we promoting to an int from a bitfield that fits in an int?
2186         if (BitWidth < ToSize ||
2187             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2188           return To->getKind() == BuiltinType::Int;
2189         }
2190 
2191         // Are we promoting to an unsigned int from an unsigned bitfield
2192         // that fits into an unsigned int?
2193         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2194           return To->getKind() == BuiltinType::UInt;
2195         }
2196 
2197         return false;
2198       }
2199     }
2200   }
2201 
2202   // An rvalue of type bool can be converted to an rvalue of type int,
2203   // with false becoming zero and true becoming one (C++ 4.5p4).
2204   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2205     return true;
2206   }
2207 
2208   return false;
2209 }
2210 
2211 /// IsFloatingPointPromotion - Determines whether the conversion from
2212 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2213 /// returns true and sets PromotedType to the promoted type.
2214 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2215   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2216     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2217       /// An rvalue of type float can be converted to an rvalue of type
2218       /// double. (C++ 4.6p1).
2219       if (FromBuiltin->getKind() == BuiltinType::Float &&
2220           ToBuiltin->getKind() == BuiltinType::Double)
2221         return true;
2222 
2223       // C99 6.3.1.5p1:
2224       //   When a float is promoted to double or long double, or a
2225       //   double is promoted to long double [...].
2226       if (!getLangOpts().CPlusPlus &&
2227           (FromBuiltin->getKind() == BuiltinType::Float ||
2228            FromBuiltin->getKind() == BuiltinType::Double) &&
2229           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2230            ToBuiltin->getKind() == BuiltinType::Float128))
2231         return true;
2232 
2233       // Half can be promoted to float.
2234       if (!getLangOpts().NativeHalfType &&
2235            FromBuiltin->getKind() == BuiltinType::Half &&
2236           ToBuiltin->getKind() == BuiltinType::Float)
2237         return true;
2238     }
2239 
2240   return false;
2241 }
2242 
2243 /// Determine if a conversion is a complex promotion.
2244 ///
2245 /// A complex promotion is defined as a complex -> complex conversion
2246 /// where the conversion between the underlying real types is a
2247 /// floating-point or integral promotion.
2248 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2249   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2250   if (!FromComplex)
2251     return false;
2252 
2253   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2254   if (!ToComplex)
2255     return false;
2256 
2257   return IsFloatingPointPromotion(FromComplex->getElementType(),
2258                                   ToComplex->getElementType()) ||
2259     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2260                         ToComplex->getElementType());
2261 }
2262 
2263 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2264 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2265 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2266 /// if non-empty, will be a pointer to ToType that may or may not have
2267 /// the right set of qualifiers on its pointee.
2268 ///
2269 static QualType
2270 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2271                                    QualType ToPointee, QualType ToType,
2272                                    ASTContext &Context,
2273                                    bool StripObjCLifetime = false) {
2274   assert((FromPtr->getTypeClass() == Type::Pointer ||
2275           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2276          "Invalid similarly-qualified pointer type");
2277 
2278   /// Conversions to 'id' subsume cv-qualifier conversions.
2279   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2280     return ToType.getUnqualifiedType();
2281 
2282   QualType CanonFromPointee
2283     = Context.getCanonicalType(FromPtr->getPointeeType());
2284   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2285   Qualifiers Quals = CanonFromPointee.getQualifiers();
2286 
2287   if (StripObjCLifetime)
2288     Quals.removeObjCLifetime();
2289 
2290   // Exact qualifier match -> return the pointer type we're converting to.
2291   if (CanonToPointee.getLocalQualifiers() == Quals) {
2292     // ToType is exactly what we need. Return it.
2293     if (!ToType.isNull())
2294       return ToType.getUnqualifiedType();
2295 
2296     // Build a pointer to ToPointee. It has the right qualifiers
2297     // already.
2298     if (isa<ObjCObjectPointerType>(ToType))
2299       return Context.getObjCObjectPointerType(ToPointee);
2300     return Context.getPointerType(ToPointee);
2301   }
2302 
2303   // Just build a canonical type that has the right qualifiers.
2304   QualType QualifiedCanonToPointee
2305     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2306 
2307   if (isa<ObjCObjectPointerType>(ToType))
2308     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2309   return Context.getPointerType(QualifiedCanonToPointee);
2310 }
2311 
2312 static bool isNullPointerConstantForConversion(Expr *Expr,
2313                                                bool InOverloadResolution,
2314                                                ASTContext &Context) {
2315   // Handle value-dependent integral null pointer constants correctly.
2316   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2317   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2318       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2319     return !InOverloadResolution;
2320 
2321   return Expr->isNullPointerConstant(Context,
2322                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2323                                         : Expr::NPC_ValueDependentIsNull);
2324 }
2325 
2326 /// IsPointerConversion - Determines whether the conversion of the
2327 /// expression From, which has the (possibly adjusted) type FromType,
2328 /// can be converted to the type ToType via a pointer conversion (C++
2329 /// 4.10). If so, returns true and places the converted type (that
2330 /// might differ from ToType in its cv-qualifiers at some level) into
2331 /// ConvertedType.
2332 ///
2333 /// This routine also supports conversions to and from block pointers
2334 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2335 /// pointers to interfaces. FIXME: Once we've determined the
2336 /// appropriate overloading rules for Objective-C, we may want to
2337 /// split the Objective-C checks into a different routine; however,
2338 /// GCC seems to consider all of these conversions to be pointer
2339 /// conversions, so for now they live here. IncompatibleObjC will be
2340 /// set if the conversion is an allowed Objective-C conversion that
2341 /// should result in a warning.
2342 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2343                                bool InOverloadResolution,
2344                                QualType& ConvertedType,
2345                                bool &IncompatibleObjC) {
2346   IncompatibleObjC = false;
2347   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2348                               IncompatibleObjC))
2349     return true;
2350 
2351   // Conversion from a null pointer constant to any Objective-C pointer type.
2352   if (ToType->isObjCObjectPointerType() &&
2353       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2354     ConvertedType = ToType;
2355     return true;
2356   }
2357 
2358   // Blocks: Block pointers can be converted to void*.
2359   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2360       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2361     ConvertedType = ToType;
2362     return true;
2363   }
2364   // Blocks: A null pointer constant can be converted to a block
2365   // pointer type.
2366   if (ToType->isBlockPointerType() &&
2367       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2368     ConvertedType = ToType;
2369     return true;
2370   }
2371 
2372   // If the left-hand-side is nullptr_t, the right side can be a null
2373   // pointer constant.
2374   if (ToType->isNullPtrType() &&
2375       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2376     ConvertedType = ToType;
2377     return true;
2378   }
2379 
2380   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2381   if (!ToTypePtr)
2382     return false;
2383 
2384   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2385   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386     ConvertedType = ToType;
2387     return true;
2388   }
2389 
2390   // Beyond this point, both types need to be pointers
2391   // , including objective-c pointers.
2392   QualType ToPointeeType = ToTypePtr->getPointeeType();
2393   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2394       !getLangOpts().ObjCAutoRefCount) {
2395     ConvertedType = BuildSimilarlyQualifiedPointerType(
2396                                       FromType->getAs<ObjCObjectPointerType>(),
2397                                                        ToPointeeType,
2398                                                        ToType, Context);
2399     return true;
2400   }
2401   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2402   if (!FromTypePtr)
2403     return false;
2404 
2405   QualType FromPointeeType = FromTypePtr->getPointeeType();
2406 
2407   // If the unqualified pointee types are the same, this can't be a
2408   // pointer conversion, so don't do all of the work below.
2409   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2410     return false;
2411 
2412   // An rvalue of type "pointer to cv T," where T is an object type,
2413   // can be converted to an rvalue of type "pointer to cv void" (C++
2414   // 4.10p2).
2415   if (FromPointeeType->isIncompleteOrObjectType() &&
2416       ToPointeeType->isVoidType()) {
2417     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2418                                                        ToPointeeType,
2419                                                        ToType, Context,
2420                                                    /*StripObjCLifetime=*/true);
2421     return true;
2422   }
2423 
2424   // MSVC allows implicit function to void* type conversion.
2425   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2426       ToPointeeType->isVoidType()) {
2427     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428                                                        ToPointeeType,
2429                                                        ToType, Context);
2430     return true;
2431   }
2432 
2433   // When we're overloading in C, we allow a special kind of pointer
2434   // conversion for compatible-but-not-identical pointee types.
2435   if (!getLangOpts().CPlusPlus &&
2436       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2437     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438                                                        ToPointeeType,
2439                                                        ToType, Context);
2440     return true;
2441   }
2442 
2443   // C++ [conv.ptr]p3:
2444   //
2445   //   An rvalue of type "pointer to cv D," where D is a class type,
2446   //   can be converted to an rvalue of type "pointer to cv B," where
2447   //   B is a base class (clause 10) of D. If B is an inaccessible
2448   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2449   //   necessitates this conversion is ill-formed. The result of the
2450   //   conversion is a pointer to the base class sub-object of the
2451   //   derived class object. The null pointer value is converted to
2452   //   the null pointer value of the destination type.
2453   //
2454   // Note that we do not check for ambiguity or inaccessibility
2455   // here. That is handled by CheckPointerConversion.
2456   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2457       ToPointeeType->isRecordType() &&
2458       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2459       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2460     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2461                                                        ToPointeeType,
2462                                                        ToType, Context);
2463     return true;
2464   }
2465 
2466   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2467       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2468     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2469                                                        ToPointeeType,
2470                                                        ToType, Context);
2471     return true;
2472   }
2473 
2474   return false;
2475 }
2476 
2477 /// Adopt the given qualifiers for the given type.
2478 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2479   Qualifiers TQs = T.getQualifiers();
2480 
2481   // Check whether qualifiers already match.
2482   if (TQs == Qs)
2483     return T;
2484 
2485   if (Qs.compatiblyIncludes(TQs))
2486     return Context.getQualifiedType(T, Qs);
2487 
2488   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2489 }
2490 
2491 /// isObjCPointerConversion - Determines whether this is an
2492 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2493 /// with the same arguments and return values.
2494 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2495                                    QualType& ConvertedType,
2496                                    bool &IncompatibleObjC) {
2497   if (!getLangOpts().ObjC)
2498     return false;
2499 
2500   // The set of qualifiers on the type we're converting from.
2501   Qualifiers FromQualifiers = FromType.getQualifiers();
2502 
2503   // First, we handle all conversions on ObjC object pointer types.
2504   const ObjCObjectPointerType* ToObjCPtr =
2505     ToType->getAs<ObjCObjectPointerType>();
2506   const ObjCObjectPointerType *FromObjCPtr =
2507     FromType->getAs<ObjCObjectPointerType>();
2508 
2509   if (ToObjCPtr && FromObjCPtr) {
2510     // If the pointee types are the same (ignoring qualifications),
2511     // then this is not a pointer conversion.
2512     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2513                                        FromObjCPtr->getPointeeType()))
2514       return false;
2515 
2516     // Conversion between Objective-C pointers.
2517     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2518       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2519       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2520       if (getLangOpts().CPlusPlus && LHS && RHS &&
2521           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2522                                                 FromObjCPtr->getPointeeType()))
2523         return false;
2524       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2525                                                    ToObjCPtr->getPointeeType(),
2526                                                          ToType, Context);
2527       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2528       return true;
2529     }
2530 
2531     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2532       // Okay: this is some kind of implicit downcast of Objective-C
2533       // interfaces, which is permitted. However, we're going to
2534       // complain about it.
2535       IncompatibleObjC = true;
2536       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537                                                    ToObjCPtr->getPointeeType(),
2538                                                          ToType, Context);
2539       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540       return true;
2541     }
2542   }
2543   // Beyond this point, both types need to be C pointers or block pointers.
2544   QualType ToPointeeType;
2545   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2546     ToPointeeType = ToCPtr->getPointeeType();
2547   else if (const BlockPointerType *ToBlockPtr =
2548             ToType->getAs<BlockPointerType>()) {
2549     // Objective C++: We're able to convert from a pointer to any object
2550     // to a block pointer type.
2551     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2552       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2553       return true;
2554     }
2555     ToPointeeType = ToBlockPtr->getPointeeType();
2556   }
2557   else if (FromType->getAs<BlockPointerType>() &&
2558            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2559     // Objective C++: We're able to convert from a block pointer type to a
2560     // pointer to any object.
2561     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562     return true;
2563   }
2564   else
2565     return false;
2566 
2567   QualType FromPointeeType;
2568   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2569     FromPointeeType = FromCPtr->getPointeeType();
2570   else if (const BlockPointerType *FromBlockPtr =
2571            FromType->getAs<BlockPointerType>())
2572     FromPointeeType = FromBlockPtr->getPointeeType();
2573   else
2574     return false;
2575 
2576   // If we have pointers to pointers, recursively check whether this
2577   // is an Objective-C conversion.
2578   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2579       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2580                               IncompatibleObjC)) {
2581     // We always complain about this conversion.
2582     IncompatibleObjC = true;
2583     ConvertedType = Context.getPointerType(ConvertedType);
2584     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2585     return true;
2586   }
2587   // Allow conversion of pointee being objective-c pointer to another one;
2588   // as in I* to id.
2589   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2590       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2591       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592                               IncompatibleObjC)) {
2593 
2594     ConvertedType = Context.getPointerType(ConvertedType);
2595     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596     return true;
2597   }
2598 
2599   // If we have pointers to functions or blocks, check whether the only
2600   // differences in the argument and result types are in Objective-C
2601   // pointer conversions. If so, we permit the conversion (but
2602   // complain about it).
2603   const FunctionProtoType *FromFunctionType
2604     = FromPointeeType->getAs<FunctionProtoType>();
2605   const FunctionProtoType *ToFunctionType
2606     = ToPointeeType->getAs<FunctionProtoType>();
2607   if (FromFunctionType && ToFunctionType) {
2608     // If the function types are exactly the same, this isn't an
2609     // Objective-C pointer conversion.
2610     if (Context.getCanonicalType(FromPointeeType)
2611           == Context.getCanonicalType(ToPointeeType))
2612       return false;
2613 
2614     // Perform the quick checks that will tell us whether these
2615     // function types are obviously different.
2616     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2617         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2618         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2619       return false;
2620 
2621     bool HasObjCConversion = false;
2622     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2623         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2624       // Okay, the types match exactly. Nothing to do.
2625     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2626                                        ToFunctionType->getReturnType(),
2627                                        ConvertedType, IncompatibleObjC)) {
2628       // Okay, we have an Objective-C pointer conversion.
2629       HasObjCConversion = true;
2630     } else {
2631       // Function types are too different. Abort.
2632       return false;
2633     }
2634 
2635     // Check argument types.
2636     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2637          ArgIdx != NumArgs; ++ArgIdx) {
2638       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2639       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2640       if (Context.getCanonicalType(FromArgType)
2641             == Context.getCanonicalType(ToArgType)) {
2642         // Okay, the types match exactly. Nothing to do.
2643       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2644                                          ConvertedType, IncompatibleObjC)) {
2645         // Okay, we have an Objective-C pointer conversion.
2646         HasObjCConversion = true;
2647       } else {
2648         // Argument types are too different. Abort.
2649         return false;
2650       }
2651     }
2652 
2653     if (HasObjCConversion) {
2654       // We had an Objective-C conversion. Allow this pointer
2655       // conversion, but complain about it.
2656       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2657       IncompatibleObjC = true;
2658       return true;
2659     }
2660   }
2661 
2662   return false;
2663 }
2664 
2665 /// Determine whether this is an Objective-C writeback conversion,
2666 /// used for parameter passing when performing automatic reference counting.
2667 ///
2668 /// \param FromType The type we're converting form.
2669 ///
2670 /// \param ToType The type we're converting to.
2671 ///
2672 /// \param ConvertedType The type that will be produced after applying
2673 /// this conversion.
2674 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2675                                      QualType &ConvertedType) {
2676   if (!getLangOpts().ObjCAutoRefCount ||
2677       Context.hasSameUnqualifiedType(FromType, ToType))
2678     return false;
2679 
2680   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2681   QualType ToPointee;
2682   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2683     ToPointee = ToPointer->getPointeeType();
2684   else
2685     return false;
2686 
2687   Qualifiers ToQuals = ToPointee.getQualifiers();
2688   if (!ToPointee->isObjCLifetimeType() ||
2689       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2690       !ToQuals.withoutObjCLifetime().empty())
2691     return false;
2692 
2693   // Argument must be a pointer to __strong to __weak.
2694   QualType FromPointee;
2695   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2696     FromPointee = FromPointer->getPointeeType();
2697   else
2698     return false;
2699 
2700   Qualifiers FromQuals = FromPointee.getQualifiers();
2701   if (!FromPointee->isObjCLifetimeType() ||
2702       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2703        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2704     return false;
2705 
2706   // Make sure that we have compatible qualifiers.
2707   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2708   if (!ToQuals.compatiblyIncludes(FromQuals))
2709     return false;
2710 
2711   // Remove qualifiers from the pointee type we're converting from; they
2712   // aren't used in the compatibility check belong, and we'll be adding back
2713   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2714   FromPointee = FromPointee.getUnqualifiedType();
2715 
2716   // The unqualified form of the pointee types must be compatible.
2717   ToPointee = ToPointee.getUnqualifiedType();
2718   bool IncompatibleObjC;
2719   if (Context.typesAreCompatible(FromPointee, ToPointee))
2720     FromPointee = ToPointee;
2721   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2722                                     IncompatibleObjC))
2723     return false;
2724 
2725   /// Construct the type we're converting to, which is a pointer to
2726   /// __autoreleasing pointee.
2727   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2728   ConvertedType = Context.getPointerType(FromPointee);
2729   return true;
2730 }
2731 
2732 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2733                                     QualType& ConvertedType) {
2734   QualType ToPointeeType;
2735   if (const BlockPointerType *ToBlockPtr =
2736         ToType->getAs<BlockPointerType>())
2737     ToPointeeType = ToBlockPtr->getPointeeType();
2738   else
2739     return false;
2740 
2741   QualType FromPointeeType;
2742   if (const BlockPointerType *FromBlockPtr =
2743       FromType->getAs<BlockPointerType>())
2744     FromPointeeType = FromBlockPtr->getPointeeType();
2745   else
2746     return false;
2747   // We have pointer to blocks, check whether the only
2748   // differences in the argument and result types are in Objective-C
2749   // pointer conversions. If so, we permit the conversion.
2750 
2751   const FunctionProtoType *FromFunctionType
2752     = FromPointeeType->getAs<FunctionProtoType>();
2753   const FunctionProtoType *ToFunctionType
2754     = ToPointeeType->getAs<FunctionProtoType>();
2755 
2756   if (!FromFunctionType || !ToFunctionType)
2757     return false;
2758 
2759   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2760     return true;
2761 
2762   // Perform the quick checks that will tell us whether these
2763   // function types are obviously different.
2764   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2765       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2766     return false;
2767 
2768   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2769   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2770   if (FromEInfo != ToEInfo)
2771     return false;
2772 
2773   bool IncompatibleObjC = false;
2774   if (Context.hasSameType(FromFunctionType->getReturnType(),
2775                           ToFunctionType->getReturnType())) {
2776     // Okay, the types match exactly. Nothing to do.
2777   } else {
2778     QualType RHS = FromFunctionType->getReturnType();
2779     QualType LHS = ToFunctionType->getReturnType();
2780     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2781         !RHS.hasQualifiers() && LHS.hasQualifiers())
2782        LHS = LHS.getUnqualifiedType();
2783 
2784      if (Context.hasSameType(RHS,LHS)) {
2785        // OK exact match.
2786      } else if (isObjCPointerConversion(RHS, LHS,
2787                                         ConvertedType, IncompatibleObjC)) {
2788      if (IncompatibleObjC)
2789        return false;
2790      // Okay, we have an Objective-C pointer conversion.
2791      }
2792      else
2793        return false;
2794    }
2795 
2796    // Check argument types.
2797    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2798         ArgIdx != NumArgs; ++ArgIdx) {
2799      IncompatibleObjC = false;
2800      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2801      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2802      if (Context.hasSameType(FromArgType, ToArgType)) {
2803        // Okay, the types match exactly. Nothing to do.
2804      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2805                                         ConvertedType, IncompatibleObjC)) {
2806        if (IncompatibleObjC)
2807          return false;
2808        // Okay, we have an Objective-C pointer conversion.
2809      } else
2810        // Argument types are too different. Abort.
2811        return false;
2812    }
2813 
2814    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2815    bool CanUseToFPT, CanUseFromFPT;
2816    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2817                                       CanUseToFPT, CanUseFromFPT,
2818                                       NewParamInfos))
2819      return false;
2820 
2821    ConvertedType = ToType;
2822    return true;
2823 }
2824 
2825 enum {
2826   ft_default,
2827   ft_different_class,
2828   ft_parameter_arity,
2829   ft_parameter_mismatch,
2830   ft_return_type,
2831   ft_qualifer_mismatch,
2832   ft_noexcept
2833 };
2834 
2835 /// Attempts to get the FunctionProtoType from a Type. Handles
2836 /// MemberFunctionPointers properly.
2837 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2838   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2839     return FPT;
2840 
2841   if (auto *MPT = FromType->getAs<MemberPointerType>())
2842     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2843 
2844   return nullptr;
2845 }
2846 
2847 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2848 /// function types.  Catches different number of parameter, mismatch in
2849 /// parameter types, and different return types.
2850 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2851                                       QualType FromType, QualType ToType) {
2852   // If either type is not valid, include no extra info.
2853   if (FromType.isNull() || ToType.isNull()) {
2854     PDiag << ft_default;
2855     return;
2856   }
2857 
2858   // Get the function type from the pointers.
2859   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2860     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2861                *ToMember = ToType->castAs<MemberPointerType>();
2862     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2863       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2864             << QualType(FromMember->getClass(), 0);
2865       return;
2866     }
2867     FromType = FromMember->getPointeeType();
2868     ToType = ToMember->getPointeeType();
2869   }
2870 
2871   if (FromType->isPointerType())
2872     FromType = FromType->getPointeeType();
2873   if (ToType->isPointerType())
2874     ToType = ToType->getPointeeType();
2875 
2876   // Remove references.
2877   FromType = FromType.getNonReferenceType();
2878   ToType = ToType.getNonReferenceType();
2879 
2880   // Don't print extra info for non-specialized template functions.
2881   if (FromType->isInstantiationDependentType() &&
2882       !FromType->getAs<TemplateSpecializationType>()) {
2883     PDiag << ft_default;
2884     return;
2885   }
2886 
2887   // No extra info for same types.
2888   if (Context.hasSameType(FromType, ToType)) {
2889     PDiag << ft_default;
2890     return;
2891   }
2892 
2893   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2894                           *ToFunction = tryGetFunctionProtoType(ToType);
2895 
2896   // Both types need to be function types.
2897   if (!FromFunction || !ToFunction) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2903     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2904           << FromFunction->getNumParams();
2905     return;
2906   }
2907 
2908   // Handle different parameter types.
2909   unsigned ArgPos;
2910   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2911     PDiag << ft_parameter_mismatch << ArgPos + 1
2912           << ToFunction->getParamType(ArgPos)
2913           << FromFunction->getParamType(ArgPos);
2914     return;
2915   }
2916 
2917   // Handle different return type.
2918   if (!Context.hasSameType(FromFunction->getReturnType(),
2919                            ToFunction->getReturnType())) {
2920     PDiag << ft_return_type << ToFunction->getReturnType()
2921           << FromFunction->getReturnType();
2922     return;
2923   }
2924 
2925   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2926     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2927           << FromFunction->getMethodQuals();
2928     return;
2929   }
2930 
2931   // Handle exception specification differences on canonical type (in C++17
2932   // onwards).
2933   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2934           ->isNothrow() !=
2935       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2936           ->isNothrow()) {
2937     PDiag << ft_noexcept;
2938     return;
2939   }
2940 
2941   // Unable to find a difference, so add no extra info.
2942   PDiag << ft_default;
2943 }
2944 
2945 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2946 /// for equality of their argument types. Caller has already checked that
2947 /// they have same number of arguments.  If the parameters are different,
2948 /// ArgPos will have the parameter index of the first different parameter.
2949 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2950                                       const FunctionProtoType *NewType,
2951                                       unsigned *ArgPos) {
2952   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2953                                               N = NewType->param_type_begin(),
2954                                               E = OldType->param_type_end();
2955        O && (O != E); ++O, ++N) {
2956     // Ignore address spaces in pointee type. This is to disallow overloading
2957     // on __ptr32/__ptr64 address spaces.
2958     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2959     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2960 
2961     if (!Context.hasSameType(Old, New)) {
2962       if (ArgPos)
2963         *ArgPos = O - OldType->param_type_begin();
2964       return false;
2965     }
2966   }
2967   return true;
2968 }
2969 
2970 /// CheckPointerConversion - Check the pointer conversion from the
2971 /// expression From to the type ToType. This routine checks for
2972 /// ambiguous or inaccessible derived-to-base pointer
2973 /// conversions for which IsPointerConversion has already returned
2974 /// true. It returns true and produces a diagnostic if there was an
2975 /// error, or returns false otherwise.
2976 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2977                                   CastKind &Kind,
2978                                   CXXCastPath& BasePath,
2979                                   bool IgnoreBaseAccess,
2980                                   bool Diagnose) {
2981   QualType FromType = From->getType();
2982   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2983 
2984   Kind = CK_BitCast;
2985 
2986   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2987       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2988           Expr::NPCK_ZeroExpression) {
2989     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2990       DiagRuntimeBehavior(From->getExprLoc(), From,
2991                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2992                             << ToType << From->getSourceRange());
2993     else if (!isUnevaluatedContext())
2994       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2995         << ToType << From->getSourceRange();
2996   }
2997   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2998     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2999       QualType FromPointeeType = FromPtrType->getPointeeType(),
3000                ToPointeeType   = ToPtrType->getPointeeType();
3001 
3002       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3003           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3004         // We must have a derived-to-base conversion. Check an
3005         // ambiguous or inaccessible conversion.
3006         unsigned InaccessibleID = 0;
3007         unsigned AmbigiousID = 0;
3008         if (Diagnose) {
3009           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3010           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3011         }
3012         if (CheckDerivedToBaseConversion(
3013                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3014                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3015                 &BasePath, IgnoreBaseAccess))
3016           return true;
3017 
3018         // The conversion was successful.
3019         Kind = CK_DerivedToBase;
3020       }
3021 
3022       if (Diagnose && !IsCStyleOrFunctionalCast &&
3023           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3024         assert(getLangOpts().MSVCCompat &&
3025                "this should only be possible with MSVCCompat!");
3026         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3027             << From->getSourceRange();
3028       }
3029     }
3030   } else if (const ObjCObjectPointerType *ToPtrType =
3031                ToType->getAs<ObjCObjectPointerType>()) {
3032     if (const ObjCObjectPointerType *FromPtrType =
3033           FromType->getAs<ObjCObjectPointerType>()) {
3034       // Objective-C++ conversions are always okay.
3035       // FIXME: We should have a different class of conversions for the
3036       // Objective-C++ implicit conversions.
3037       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3038         return false;
3039     } else if (FromType->isBlockPointerType()) {
3040       Kind = CK_BlockPointerToObjCPointerCast;
3041     } else {
3042       Kind = CK_CPointerToObjCPointerCast;
3043     }
3044   } else if (ToType->isBlockPointerType()) {
3045     if (!FromType->isBlockPointerType())
3046       Kind = CK_AnyPointerToBlockPointerCast;
3047   }
3048 
3049   // We shouldn't fall into this case unless it's valid for other
3050   // reasons.
3051   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3052     Kind = CK_NullToPointer;
3053 
3054   return false;
3055 }
3056 
3057 /// IsMemberPointerConversion - Determines whether the conversion of the
3058 /// expression From, which has the (possibly adjusted) type FromType, can be
3059 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3060 /// If so, returns true and places the converted type (that might differ from
3061 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3062 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3063                                      QualType ToType,
3064                                      bool InOverloadResolution,
3065                                      QualType &ConvertedType) {
3066   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3067   if (!ToTypePtr)
3068     return false;
3069 
3070   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3071   if (From->isNullPointerConstant(Context,
3072                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3073                                         : Expr::NPC_ValueDependentIsNull)) {
3074     ConvertedType = ToType;
3075     return true;
3076   }
3077 
3078   // Otherwise, both types have to be member pointers.
3079   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3080   if (!FromTypePtr)
3081     return false;
3082 
3083   // A pointer to member of B can be converted to a pointer to member of D,
3084   // where D is derived from B (C++ 4.11p2).
3085   QualType FromClass(FromTypePtr->getClass(), 0);
3086   QualType ToClass(ToTypePtr->getClass(), 0);
3087 
3088   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3089       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3090     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3091                                                  ToClass.getTypePtr());
3092     return true;
3093   }
3094 
3095   return false;
3096 }
3097 
3098 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3099 /// expression From to the type ToType. This routine checks for ambiguous or
3100 /// virtual or inaccessible base-to-derived member pointer conversions
3101 /// for which IsMemberPointerConversion has already returned true. It returns
3102 /// true and produces a diagnostic if there was an error, or returns false
3103 /// otherwise.
3104 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3105                                         CastKind &Kind,
3106                                         CXXCastPath &BasePath,
3107                                         bool IgnoreBaseAccess) {
3108   QualType FromType = From->getType();
3109   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3110   if (!FromPtrType) {
3111     // This must be a null pointer to member pointer conversion
3112     assert(From->isNullPointerConstant(Context,
3113                                        Expr::NPC_ValueDependentIsNull) &&
3114            "Expr must be null pointer constant!");
3115     Kind = CK_NullToMemberPointer;
3116     return false;
3117   }
3118 
3119   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3120   assert(ToPtrType && "No member pointer cast has a target type "
3121                       "that is not a member pointer.");
3122 
3123   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3124   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3125 
3126   // FIXME: What about dependent types?
3127   assert(FromClass->isRecordType() && "Pointer into non-class.");
3128   assert(ToClass->isRecordType() && "Pointer into non-class.");
3129 
3130   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131                      /*DetectVirtual=*/true);
3132   bool DerivationOkay =
3133       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3134   assert(DerivationOkay &&
3135          "Should not have been called if derivation isn't OK.");
3136   (void)DerivationOkay;
3137 
3138   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3139                                   getUnqualifiedType())) {
3140     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3141     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3142       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3143     return true;
3144   }
3145 
3146   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3147     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3148       << FromClass << ToClass << QualType(VBase, 0)
3149       << From->getSourceRange();
3150     return true;
3151   }
3152 
3153   if (!IgnoreBaseAccess)
3154     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3155                          Paths.front(),
3156                          diag::err_downcast_from_inaccessible_base);
3157 
3158   // Must be a base to derived member conversion.
3159   BuildBasePathArray(Paths, BasePath);
3160   Kind = CK_BaseToDerivedMemberPointer;
3161   return false;
3162 }
3163 
3164 /// Determine whether the lifetime conversion between the two given
3165 /// qualifiers sets is nontrivial.
3166 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3167                                                Qualifiers ToQuals) {
3168   // Converting anything to const __unsafe_unretained is trivial.
3169   if (ToQuals.hasConst() &&
3170       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3171     return false;
3172 
3173   return true;
3174 }
3175 
3176 /// Perform a single iteration of the loop for checking if a qualification
3177 /// conversion is valid.
3178 ///
3179 /// Specifically, check whether any change between the qualifiers of \p
3180 /// FromType and \p ToType is permissible, given knowledge about whether every
3181 /// outer layer is const-qualified.
3182 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3183                                           bool CStyle,
3184                                           bool &PreviousToQualsIncludeConst,
3185                                           bool &ObjCLifetimeConversion) {
3186   Qualifiers FromQuals = FromType.getQualifiers();
3187   Qualifiers ToQuals = ToType.getQualifiers();
3188 
3189   // Ignore __unaligned qualifier if this type is void.
3190   if (ToType.getUnqualifiedType()->isVoidType())
3191     FromQuals.removeUnaligned();
3192 
3193   // Objective-C ARC:
3194   //   Check Objective-C lifetime conversions.
3195   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3196     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3197       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3198         ObjCLifetimeConversion = true;
3199       FromQuals.removeObjCLifetime();
3200       ToQuals.removeObjCLifetime();
3201     } else {
3202       // Qualification conversions cannot cast between different
3203       // Objective-C lifetime qualifiers.
3204       return false;
3205     }
3206   }
3207 
3208   // Allow addition/removal of GC attributes but not changing GC attributes.
3209   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3210       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3211     FromQuals.removeObjCGCAttr();
3212     ToQuals.removeObjCGCAttr();
3213   }
3214 
3215   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3216   //      2,j, and similarly for volatile.
3217   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3218     return false;
3219 
3220   // For a C-style cast, just require the address spaces to overlap.
3221   // FIXME: Does "superset" also imply the representation of a pointer is the
3222   // same? We're assuming that it does here and in compatiblyIncludes.
3223   if (CStyle && !ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3224       !FromQuals.isAddressSpaceSupersetOf(ToQuals))
3225     return false;
3226 
3227   //   -- if the cv 1,j and cv 2,j are different, then const is in
3228   //      every cv for 0 < k < j.
3229   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3230       !PreviousToQualsIncludeConst)
3231     return false;
3232 
3233   // Keep track of whether all prior cv-qualifiers in the "to" type
3234   // include const.
3235   PreviousToQualsIncludeConst =
3236       PreviousToQualsIncludeConst && ToQuals.hasConst();
3237   return true;
3238 }
3239 
3240 /// IsQualificationConversion - Determines whether the conversion from
3241 /// an rvalue of type FromType to ToType is a qualification conversion
3242 /// (C++ 4.4).
3243 ///
3244 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3245 /// when the qualification conversion involves a change in the Objective-C
3246 /// object lifetime.
3247 bool
3248 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3249                                 bool CStyle, bool &ObjCLifetimeConversion) {
3250   FromType = Context.getCanonicalType(FromType);
3251   ToType = Context.getCanonicalType(ToType);
3252   ObjCLifetimeConversion = false;
3253 
3254   // If FromType and ToType are the same type, this is not a
3255   // qualification conversion.
3256   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3257     return false;
3258 
3259   // (C++ 4.4p4):
3260   //   A conversion can add cv-qualifiers at levels other than the first
3261   //   in multi-level pointers, subject to the following rules: [...]
3262   bool PreviousToQualsIncludeConst = true;
3263   bool UnwrappedAnyPointer = false;
3264   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3265     if (!isQualificationConversionStep(FromType, ToType, CStyle,
3266                                        PreviousToQualsIncludeConst,
3267                                        ObjCLifetimeConversion))
3268       return false;
3269     UnwrappedAnyPointer = true;
3270   }
3271 
3272   // We are left with FromType and ToType being the pointee types
3273   // after unwrapping the original FromType and ToType the same number
3274   // of times. If we unwrapped any pointers, and if FromType and
3275   // ToType have the same unqualified type (since we checked
3276   // qualifiers above), then this is a qualification conversion.
3277   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3278 }
3279 
3280 /// - Determine whether this is a conversion from a scalar type to an
3281 /// atomic type.
3282 ///
3283 /// If successful, updates \c SCS's second and third steps in the conversion
3284 /// sequence to finish the conversion.
3285 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3286                                 bool InOverloadResolution,
3287                                 StandardConversionSequence &SCS,
3288                                 bool CStyle) {
3289   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3290   if (!ToAtomic)
3291     return false;
3292 
3293   StandardConversionSequence InnerSCS;
3294   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3295                             InOverloadResolution, InnerSCS,
3296                             CStyle, /*AllowObjCWritebackConversion=*/false))
3297     return false;
3298 
3299   SCS.Second = InnerSCS.Second;
3300   SCS.setToType(1, InnerSCS.getToType(1));
3301   SCS.Third = InnerSCS.Third;
3302   SCS.QualificationIncludesObjCLifetime
3303     = InnerSCS.QualificationIncludesObjCLifetime;
3304   SCS.setToType(2, InnerSCS.getToType(2));
3305   return true;
3306 }
3307 
3308 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3309                                               CXXConstructorDecl *Constructor,
3310                                               QualType Type) {
3311   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3312   if (CtorType->getNumParams() > 0) {
3313     QualType FirstArg = CtorType->getParamType(0);
3314     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3315       return true;
3316   }
3317   return false;
3318 }
3319 
3320 static OverloadingResult
3321 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3322                                        CXXRecordDecl *To,
3323                                        UserDefinedConversionSequence &User,
3324                                        OverloadCandidateSet &CandidateSet,
3325                                        bool AllowExplicit) {
3326   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3327   for (auto *D : S.LookupConstructors(To)) {
3328     auto Info = getConstructorInfo(D);
3329     if (!Info)
3330       continue;
3331 
3332     bool Usable = !Info.Constructor->isInvalidDecl() &&
3333                   S.isInitListConstructor(Info.Constructor);
3334     if (Usable) {
3335       // If the first argument is (a reference to) the target type,
3336       // suppress conversions.
3337       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3338           S.Context, Info.Constructor, ToType);
3339       if (Info.ConstructorTmpl)
3340         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3341                                        /*ExplicitArgs*/ nullptr, From,
3342                                        CandidateSet, SuppressUserConversions,
3343                                        /*PartialOverloading*/ false,
3344                                        AllowExplicit);
3345       else
3346         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3347                                CandidateSet, SuppressUserConversions,
3348                                /*PartialOverloading*/ false, AllowExplicit);
3349     }
3350   }
3351 
3352   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3353 
3354   OverloadCandidateSet::iterator Best;
3355   switch (auto Result =
3356               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3357   case OR_Deleted:
3358   case OR_Success: {
3359     // Record the standard conversion we used and the conversion function.
3360     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3361     QualType ThisType = Constructor->getThisType();
3362     // Initializer lists don't have conversions as such.
3363     User.Before.setAsIdentityConversion();
3364     User.HadMultipleCandidates = HadMultipleCandidates;
3365     User.ConversionFunction = Constructor;
3366     User.FoundConversionFunction = Best->FoundDecl;
3367     User.After.setAsIdentityConversion();
3368     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3369     User.After.setAllToTypes(ToType);
3370     return Result;
3371   }
3372 
3373   case OR_No_Viable_Function:
3374     return OR_No_Viable_Function;
3375   case OR_Ambiguous:
3376     return OR_Ambiguous;
3377   }
3378 
3379   llvm_unreachable("Invalid OverloadResult!");
3380 }
3381 
3382 /// Determines whether there is a user-defined conversion sequence
3383 /// (C++ [over.ics.user]) that converts expression From to the type
3384 /// ToType. If such a conversion exists, User will contain the
3385 /// user-defined conversion sequence that performs such a conversion
3386 /// and this routine will return true. Otherwise, this routine returns
3387 /// false and User is unspecified.
3388 ///
3389 /// \param AllowExplicit  true if the conversion should consider C++0x
3390 /// "explicit" conversion functions as well as non-explicit conversion
3391 /// functions (C++0x [class.conv.fct]p2).
3392 ///
3393 /// \param AllowObjCConversionOnExplicit true if the conversion should
3394 /// allow an extra Objective-C pointer conversion on uses of explicit
3395 /// constructors. Requires \c AllowExplicit to also be set.
3396 static OverloadingResult
3397 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3398                         UserDefinedConversionSequence &User,
3399                         OverloadCandidateSet &CandidateSet,
3400                         bool AllowExplicit,
3401                         bool AllowObjCConversionOnExplicit) {
3402   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3403   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3404 
3405   // Whether we will only visit constructors.
3406   bool ConstructorsOnly = false;
3407 
3408   // If the type we are conversion to is a class type, enumerate its
3409   // constructors.
3410   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3411     // C++ [over.match.ctor]p1:
3412     //   When objects of class type are direct-initialized (8.5), or
3413     //   copy-initialized from an expression of the same or a
3414     //   derived class type (8.5), overload resolution selects the
3415     //   constructor. [...] For copy-initialization, the candidate
3416     //   functions are all the converting constructors (12.3.1) of
3417     //   that class. The argument list is the expression-list within
3418     //   the parentheses of the initializer.
3419     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3420         (From->getType()->getAs<RecordType>() &&
3421          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3422       ConstructorsOnly = true;
3423 
3424     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3425       // We're not going to find any constructors.
3426     } else if (CXXRecordDecl *ToRecordDecl
3427                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3428 
3429       Expr **Args = &From;
3430       unsigned NumArgs = 1;
3431       bool ListInitializing = false;
3432       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3433         // But first, see if there is an init-list-constructor that will work.
3434         OverloadingResult Result = IsInitializerListConstructorConversion(
3435             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3436         if (Result != OR_No_Viable_Function)
3437           return Result;
3438         // Never mind.
3439         CandidateSet.clear(
3440             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3441 
3442         // If we're list-initializing, we pass the individual elements as
3443         // arguments, not the entire list.
3444         Args = InitList->getInits();
3445         NumArgs = InitList->getNumInits();
3446         ListInitializing = true;
3447       }
3448 
3449       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3450         auto Info = getConstructorInfo(D);
3451         if (!Info)
3452           continue;
3453 
3454         bool Usable = !Info.Constructor->isInvalidDecl();
3455         if (!ListInitializing)
3456           Usable = Usable && Info.Constructor->isConvertingConstructor(
3457                                  /*AllowExplicit*/ true);
3458         if (Usable) {
3459           bool SuppressUserConversions = !ConstructorsOnly;
3460           if (SuppressUserConversions && ListInitializing) {
3461             SuppressUserConversions = false;
3462             if (NumArgs == 1) {
3463               // If the first argument is (a reference to) the target type,
3464               // suppress conversions.
3465               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3466                   S.Context, Info.Constructor, ToType);
3467             }
3468           }
3469           if (Info.ConstructorTmpl)
3470             S.AddTemplateOverloadCandidate(
3471                 Info.ConstructorTmpl, Info.FoundDecl,
3472                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3473                 CandidateSet, SuppressUserConversions,
3474                 /*PartialOverloading*/ false, AllowExplicit);
3475           else
3476             // Allow one user-defined conversion when user specifies a
3477             // From->ToType conversion via an static cast (c-style, etc).
3478             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3479                                    llvm::makeArrayRef(Args, NumArgs),
3480                                    CandidateSet, SuppressUserConversions,
3481                                    /*PartialOverloading*/ false, AllowExplicit);
3482         }
3483       }
3484     }
3485   }
3486 
3487   // Enumerate conversion functions, if we're allowed to.
3488   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3489   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3490     // No conversion functions from incomplete types.
3491   } else if (const RecordType *FromRecordType =
3492                  From->getType()->getAs<RecordType>()) {
3493     if (CXXRecordDecl *FromRecordDecl
3494          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3495       // Add all of the conversion functions as candidates.
3496       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3497       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3498         DeclAccessPair FoundDecl = I.getPair();
3499         NamedDecl *D = FoundDecl.getDecl();
3500         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3501         if (isa<UsingShadowDecl>(D))
3502           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3503 
3504         CXXConversionDecl *Conv;
3505         FunctionTemplateDecl *ConvTemplate;
3506         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3507           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3508         else
3509           Conv = cast<CXXConversionDecl>(D);
3510 
3511         if (ConvTemplate)
3512           S.AddTemplateConversionCandidate(
3513               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3514               CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3515         else
3516           S.AddConversionCandidate(
3517               Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3518               AllowObjCConversionOnExplicit, AllowExplicit);
3519       }
3520     }
3521   }
3522 
3523   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3524 
3525   OverloadCandidateSet::iterator Best;
3526   switch (auto Result =
3527               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3528   case OR_Success:
3529   case OR_Deleted:
3530     // Record the standard conversion we used and the conversion function.
3531     if (CXXConstructorDecl *Constructor
3532           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3533       // C++ [over.ics.user]p1:
3534       //   If the user-defined conversion is specified by a
3535       //   constructor (12.3.1), the initial standard conversion
3536       //   sequence converts the source type to the type required by
3537       //   the argument of the constructor.
3538       //
3539       QualType ThisType = Constructor->getThisType();
3540       if (isa<InitListExpr>(From)) {
3541         // Initializer lists don't have conversions as such.
3542         User.Before.setAsIdentityConversion();
3543       } else {
3544         if (Best->Conversions[0].isEllipsis())
3545           User.EllipsisConversion = true;
3546         else {
3547           User.Before = Best->Conversions[0].Standard;
3548           User.EllipsisConversion = false;
3549         }
3550       }
3551       User.HadMultipleCandidates = HadMultipleCandidates;
3552       User.ConversionFunction = Constructor;
3553       User.FoundConversionFunction = Best->FoundDecl;
3554       User.After.setAsIdentityConversion();
3555       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3556       User.After.setAllToTypes(ToType);
3557       return Result;
3558     }
3559     if (CXXConversionDecl *Conversion
3560                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3561       // C++ [over.ics.user]p1:
3562       //
3563       //   [...] If the user-defined conversion is specified by a
3564       //   conversion function (12.3.2), the initial standard
3565       //   conversion sequence converts the source type to the
3566       //   implicit object parameter of the conversion function.
3567       User.Before = Best->Conversions[0].Standard;
3568       User.HadMultipleCandidates = HadMultipleCandidates;
3569       User.ConversionFunction = Conversion;
3570       User.FoundConversionFunction = Best->FoundDecl;
3571       User.EllipsisConversion = false;
3572 
3573       // C++ [over.ics.user]p2:
3574       //   The second standard conversion sequence converts the
3575       //   result of the user-defined conversion to the target type
3576       //   for the sequence. Since an implicit conversion sequence
3577       //   is an initialization, the special rules for
3578       //   initialization by user-defined conversion apply when
3579       //   selecting the best user-defined conversion for a
3580       //   user-defined conversion sequence (see 13.3.3 and
3581       //   13.3.3.1).
3582       User.After = Best->FinalConversion;
3583       return Result;
3584     }
3585     llvm_unreachable("Not a constructor or conversion function?");
3586 
3587   case OR_No_Viable_Function:
3588     return OR_No_Viable_Function;
3589 
3590   case OR_Ambiguous:
3591     return OR_Ambiguous;
3592   }
3593 
3594   llvm_unreachable("Invalid OverloadResult!");
3595 }
3596 
3597 bool
3598 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3599   ImplicitConversionSequence ICS;
3600   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3601                                     OverloadCandidateSet::CSK_Normal);
3602   OverloadingResult OvResult =
3603     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3604                             CandidateSet, false, false);
3605 
3606   if (!(OvResult == OR_Ambiguous ||
3607         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3608     return false;
3609 
3610   auto Cands = CandidateSet.CompleteCandidates(
3611       *this,
3612       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3613       From);
3614   if (OvResult == OR_Ambiguous)
3615     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3616         << From->getType() << ToType << From->getSourceRange();
3617   else { // OR_No_Viable_Function && !CandidateSet.empty()
3618     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3619                              diag::err_typecheck_nonviable_condition_incomplete,
3620                              From->getType(), From->getSourceRange()))
3621       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3622           << false << From->getType() << From->getSourceRange() << ToType;
3623   }
3624 
3625   CandidateSet.NoteCandidates(
3626                               *this, From, Cands);
3627   return true;
3628 }
3629 
3630 /// Compare the user-defined conversion functions or constructors
3631 /// of two user-defined conversion sequences to determine whether any ordering
3632 /// is possible.
3633 static ImplicitConversionSequence::CompareKind
3634 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3635                            FunctionDecl *Function2) {
3636   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3637     return ImplicitConversionSequence::Indistinguishable;
3638 
3639   // Objective-C++:
3640   //   If both conversion functions are implicitly-declared conversions from
3641   //   a lambda closure type to a function pointer and a block pointer,
3642   //   respectively, always prefer the conversion to a function pointer,
3643   //   because the function pointer is more lightweight and is more likely
3644   //   to keep code working.
3645   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3646   if (!Conv1)
3647     return ImplicitConversionSequence::Indistinguishable;
3648 
3649   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3650   if (!Conv2)
3651     return ImplicitConversionSequence::Indistinguishable;
3652 
3653   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3654     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3655     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3656     if (Block1 != Block2)
3657       return Block1 ? ImplicitConversionSequence::Worse
3658                     : ImplicitConversionSequence::Better;
3659   }
3660 
3661   return ImplicitConversionSequence::Indistinguishable;
3662 }
3663 
3664 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3665     const ImplicitConversionSequence &ICS) {
3666   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3667          (ICS.isUserDefined() &&
3668           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3669 }
3670 
3671 /// CompareImplicitConversionSequences - Compare two implicit
3672 /// conversion sequences to determine whether one is better than the
3673 /// other or if they are indistinguishable (C++ 13.3.3.2).
3674 static ImplicitConversionSequence::CompareKind
3675 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3676                                    const ImplicitConversionSequence& ICS1,
3677                                    const ImplicitConversionSequence& ICS2)
3678 {
3679   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3680   // conversion sequences (as defined in 13.3.3.1)
3681   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3682   //      conversion sequence than a user-defined conversion sequence or
3683   //      an ellipsis conversion sequence, and
3684   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3685   //      conversion sequence than an ellipsis conversion sequence
3686   //      (13.3.3.1.3).
3687   //
3688   // C++0x [over.best.ics]p10:
3689   //   For the purpose of ranking implicit conversion sequences as
3690   //   described in 13.3.3.2, the ambiguous conversion sequence is
3691   //   treated as a user-defined sequence that is indistinguishable
3692   //   from any other user-defined conversion sequence.
3693 
3694   // String literal to 'char *' conversion has been deprecated in C++03. It has
3695   // been removed from C++11. We still accept this conversion, if it happens at
3696   // the best viable function. Otherwise, this conversion is considered worse
3697   // than ellipsis conversion. Consider this as an extension; this is not in the
3698   // standard. For example:
3699   //
3700   // int &f(...);    // #1
3701   // void f(char*);  // #2
3702   // void g() { int &r = f("foo"); }
3703   //
3704   // In C++03, we pick #2 as the best viable function.
3705   // In C++11, we pick #1 as the best viable function, because ellipsis
3706   // conversion is better than string-literal to char* conversion (since there
3707   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3708   // convert arguments, #2 would be the best viable function in C++11.
3709   // If the best viable function has this conversion, a warning will be issued
3710   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3711 
3712   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3713       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3714       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3715     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3716                ? ImplicitConversionSequence::Worse
3717                : ImplicitConversionSequence::Better;
3718 
3719   if (ICS1.getKindRank() < ICS2.getKindRank())
3720     return ImplicitConversionSequence::Better;
3721   if (ICS2.getKindRank() < ICS1.getKindRank())
3722     return ImplicitConversionSequence::Worse;
3723 
3724   // The following checks require both conversion sequences to be of
3725   // the same kind.
3726   if (ICS1.getKind() != ICS2.getKind())
3727     return ImplicitConversionSequence::Indistinguishable;
3728 
3729   ImplicitConversionSequence::CompareKind Result =
3730       ImplicitConversionSequence::Indistinguishable;
3731 
3732   // Two implicit conversion sequences of the same form are
3733   // indistinguishable conversion sequences unless one of the
3734   // following rules apply: (C++ 13.3.3.2p3):
3735 
3736   // List-initialization sequence L1 is a better conversion sequence than
3737   // list-initialization sequence L2 if:
3738   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3739   //   if not that,
3740   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3741   //   and N1 is smaller than N2.,
3742   // even if one of the other rules in this paragraph would otherwise apply.
3743   if (!ICS1.isBad()) {
3744     if (ICS1.isStdInitializerListElement() &&
3745         !ICS2.isStdInitializerListElement())
3746       return ImplicitConversionSequence::Better;
3747     if (!ICS1.isStdInitializerListElement() &&
3748         ICS2.isStdInitializerListElement())
3749       return ImplicitConversionSequence::Worse;
3750   }
3751 
3752   if (ICS1.isStandard())
3753     // Standard conversion sequence S1 is a better conversion sequence than
3754     // standard conversion sequence S2 if [...]
3755     Result = CompareStandardConversionSequences(S, Loc,
3756                                                 ICS1.Standard, ICS2.Standard);
3757   else if (ICS1.isUserDefined()) {
3758     // User-defined conversion sequence U1 is a better conversion
3759     // sequence than another user-defined conversion sequence U2 if
3760     // they contain the same user-defined conversion function or
3761     // constructor and if the second standard conversion sequence of
3762     // U1 is better than the second standard conversion sequence of
3763     // U2 (C++ 13.3.3.2p3).
3764     if (ICS1.UserDefined.ConversionFunction ==
3765           ICS2.UserDefined.ConversionFunction)
3766       Result = CompareStandardConversionSequences(S, Loc,
3767                                                   ICS1.UserDefined.After,
3768                                                   ICS2.UserDefined.After);
3769     else
3770       Result = compareConversionFunctions(S,
3771                                           ICS1.UserDefined.ConversionFunction,
3772                                           ICS2.UserDefined.ConversionFunction);
3773   }
3774 
3775   return Result;
3776 }
3777 
3778 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3779 // determine if one is a proper subset of the other.
3780 static ImplicitConversionSequence::CompareKind
3781 compareStandardConversionSubsets(ASTContext &Context,
3782                                  const StandardConversionSequence& SCS1,
3783                                  const StandardConversionSequence& SCS2) {
3784   ImplicitConversionSequence::CompareKind Result
3785     = ImplicitConversionSequence::Indistinguishable;
3786 
3787   // the identity conversion sequence is considered to be a subsequence of
3788   // any non-identity conversion sequence
3789   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3790     return ImplicitConversionSequence::Better;
3791   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3792     return ImplicitConversionSequence::Worse;
3793 
3794   if (SCS1.Second != SCS2.Second) {
3795     if (SCS1.Second == ICK_Identity)
3796       Result = ImplicitConversionSequence::Better;
3797     else if (SCS2.Second == ICK_Identity)
3798       Result = ImplicitConversionSequence::Worse;
3799     else
3800       return ImplicitConversionSequence::Indistinguishable;
3801   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3802     return ImplicitConversionSequence::Indistinguishable;
3803 
3804   if (SCS1.Third == SCS2.Third) {
3805     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3806                              : ImplicitConversionSequence::Indistinguishable;
3807   }
3808 
3809   if (SCS1.Third == ICK_Identity)
3810     return Result == ImplicitConversionSequence::Worse
3811              ? ImplicitConversionSequence::Indistinguishable
3812              : ImplicitConversionSequence::Better;
3813 
3814   if (SCS2.Third == ICK_Identity)
3815     return Result == ImplicitConversionSequence::Better
3816              ? ImplicitConversionSequence::Indistinguishable
3817              : ImplicitConversionSequence::Worse;
3818 
3819   return ImplicitConversionSequence::Indistinguishable;
3820 }
3821 
3822 /// Determine whether one of the given reference bindings is better
3823 /// than the other based on what kind of bindings they are.
3824 static bool
3825 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3826                              const StandardConversionSequence &SCS2) {
3827   // C++0x [over.ics.rank]p3b4:
3828   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3829   //      implicit object parameter of a non-static member function declared
3830   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3831   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3832   //      lvalue reference to a function lvalue and S2 binds an rvalue
3833   //      reference*.
3834   //
3835   // FIXME: Rvalue references. We're going rogue with the above edits,
3836   // because the semantics in the current C++0x working paper (N3225 at the
3837   // time of this writing) break the standard definition of std::forward
3838   // and std::reference_wrapper when dealing with references to functions.
3839   // Proposed wording changes submitted to CWG for consideration.
3840   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3841       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3842     return false;
3843 
3844   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3845           SCS2.IsLvalueReference) ||
3846          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3847           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3848 }
3849 
3850 enum class FixedEnumPromotion {
3851   None,
3852   ToUnderlyingType,
3853   ToPromotedUnderlyingType
3854 };
3855 
3856 /// Returns kind of fixed enum promotion the \a SCS uses.
3857 static FixedEnumPromotion
3858 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3859 
3860   if (SCS.Second != ICK_Integral_Promotion)
3861     return FixedEnumPromotion::None;
3862 
3863   QualType FromType = SCS.getFromType();
3864   if (!FromType->isEnumeralType())
3865     return FixedEnumPromotion::None;
3866 
3867   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3868   if (!Enum->isFixed())
3869     return FixedEnumPromotion::None;
3870 
3871   QualType UnderlyingType = Enum->getIntegerType();
3872   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3873     return FixedEnumPromotion::ToUnderlyingType;
3874 
3875   return FixedEnumPromotion::ToPromotedUnderlyingType;
3876 }
3877 
3878 /// CompareStandardConversionSequences - Compare two standard
3879 /// conversion sequences to determine whether one is better than the
3880 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3881 static ImplicitConversionSequence::CompareKind
3882 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3883                                    const StandardConversionSequence& SCS1,
3884                                    const StandardConversionSequence& SCS2)
3885 {
3886   // Standard conversion sequence S1 is a better conversion sequence
3887   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3888 
3889   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3890   //     sequences in the canonical form defined by 13.3.3.1.1,
3891   //     excluding any Lvalue Transformation; the identity conversion
3892   //     sequence is considered to be a subsequence of any
3893   //     non-identity conversion sequence) or, if not that,
3894   if (ImplicitConversionSequence::CompareKind CK
3895         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3896     return CK;
3897 
3898   //  -- the rank of S1 is better than the rank of S2 (by the rules
3899   //     defined below), or, if not that,
3900   ImplicitConversionRank Rank1 = SCS1.getRank();
3901   ImplicitConversionRank Rank2 = SCS2.getRank();
3902   if (Rank1 < Rank2)
3903     return ImplicitConversionSequence::Better;
3904   else if (Rank2 < Rank1)
3905     return ImplicitConversionSequence::Worse;
3906 
3907   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3908   // are indistinguishable unless one of the following rules
3909   // applies:
3910 
3911   //   A conversion that is not a conversion of a pointer, or
3912   //   pointer to member, to bool is better than another conversion
3913   //   that is such a conversion.
3914   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3915     return SCS2.isPointerConversionToBool()
3916              ? ImplicitConversionSequence::Better
3917              : ImplicitConversionSequence::Worse;
3918 
3919   // C++14 [over.ics.rank]p4b2:
3920   // This is retroactively applied to C++11 by CWG 1601.
3921   //
3922   //   A conversion that promotes an enumeration whose underlying type is fixed
3923   //   to its underlying type is better than one that promotes to the promoted
3924   //   underlying type, if the two are different.
3925   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3926   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3927   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3928       FEP1 != FEP2)
3929     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3930                ? ImplicitConversionSequence::Better
3931                : ImplicitConversionSequence::Worse;
3932 
3933   // C++ [over.ics.rank]p4b2:
3934   //
3935   //   If class B is derived directly or indirectly from class A,
3936   //   conversion of B* to A* is better than conversion of B* to
3937   //   void*, and conversion of A* to void* is better than conversion
3938   //   of B* to void*.
3939   bool SCS1ConvertsToVoid
3940     = SCS1.isPointerConversionToVoidPointer(S.Context);
3941   bool SCS2ConvertsToVoid
3942     = SCS2.isPointerConversionToVoidPointer(S.Context);
3943   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3944     // Exactly one of the conversion sequences is a conversion to
3945     // a void pointer; it's the worse conversion.
3946     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3947                               : ImplicitConversionSequence::Worse;
3948   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3949     // Neither conversion sequence converts to a void pointer; compare
3950     // their derived-to-base conversions.
3951     if (ImplicitConversionSequence::CompareKind DerivedCK
3952           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3953       return DerivedCK;
3954   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3955              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3956     // Both conversion sequences are conversions to void
3957     // pointers. Compare the source types to determine if there's an
3958     // inheritance relationship in their sources.
3959     QualType FromType1 = SCS1.getFromType();
3960     QualType FromType2 = SCS2.getFromType();
3961 
3962     // Adjust the types we're converting from via the array-to-pointer
3963     // conversion, if we need to.
3964     if (SCS1.First == ICK_Array_To_Pointer)
3965       FromType1 = S.Context.getArrayDecayedType(FromType1);
3966     if (SCS2.First == ICK_Array_To_Pointer)
3967       FromType2 = S.Context.getArrayDecayedType(FromType2);
3968 
3969     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3970     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3971 
3972     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3973       return ImplicitConversionSequence::Better;
3974     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3975       return ImplicitConversionSequence::Worse;
3976 
3977     // Objective-C++: If one interface is more specific than the
3978     // other, it is the better one.
3979     const ObjCObjectPointerType* FromObjCPtr1
3980       = FromType1->getAs<ObjCObjectPointerType>();
3981     const ObjCObjectPointerType* FromObjCPtr2
3982       = FromType2->getAs<ObjCObjectPointerType>();
3983     if (FromObjCPtr1 && FromObjCPtr2) {
3984       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3985                                                           FromObjCPtr2);
3986       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3987                                                            FromObjCPtr1);
3988       if (AssignLeft != AssignRight) {
3989         return AssignLeft? ImplicitConversionSequence::Better
3990                          : ImplicitConversionSequence::Worse;
3991       }
3992     }
3993   }
3994 
3995   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3996     // Check for a better reference binding based on the kind of bindings.
3997     if (isBetterReferenceBindingKind(SCS1, SCS2))
3998       return ImplicitConversionSequence::Better;
3999     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4000       return ImplicitConversionSequence::Worse;
4001   }
4002 
4003   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4004   // bullet 3).
4005   if (ImplicitConversionSequence::CompareKind QualCK
4006         = CompareQualificationConversions(S, SCS1, SCS2))
4007     return QualCK;
4008 
4009   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4010     // C++ [over.ics.rank]p3b4:
4011     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4012     //      which the references refer are the same type except for
4013     //      top-level cv-qualifiers, and the type to which the reference
4014     //      initialized by S2 refers is more cv-qualified than the type
4015     //      to which the reference initialized by S1 refers.
4016     QualType T1 = SCS1.getToType(2);
4017     QualType T2 = SCS2.getToType(2);
4018     T1 = S.Context.getCanonicalType(T1);
4019     T2 = S.Context.getCanonicalType(T2);
4020     Qualifiers T1Quals, T2Quals;
4021     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4022     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4023     if (UnqualT1 == UnqualT2) {
4024       // Objective-C++ ARC: If the references refer to objects with different
4025       // lifetimes, prefer bindings that don't change lifetime.
4026       if (SCS1.ObjCLifetimeConversionBinding !=
4027                                           SCS2.ObjCLifetimeConversionBinding) {
4028         return SCS1.ObjCLifetimeConversionBinding
4029                                            ? ImplicitConversionSequence::Worse
4030                                            : ImplicitConversionSequence::Better;
4031       }
4032 
4033       // If the type is an array type, promote the element qualifiers to the
4034       // type for comparison.
4035       if (isa<ArrayType>(T1) && T1Quals)
4036         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4037       if (isa<ArrayType>(T2) && T2Quals)
4038         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4039       if (T2.isMoreQualifiedThan(T1))
4040         return ImplicitConversionSequence::Better;
4041       if (T1.isMoreQualifiedThan(T2))
4042         return ImplicitConversionSequence::Worse;
4043     }
4044   }
4045 
4046   // In Microsoft mode, prefer an integral conversion to a
4047   // floating-to-integral conversion if the integral conversion
4048   // is between types of the same size.
4049   // For example:
4050   // void f(float);
4051   // void f(int);
4052   // int main {
4053   //    long a;
4054   //    f(a);
4055   // }
4056   // Here, MSVC will call f(int) instead of generating a compile error
4057   // as clang will do in standard mode.
4058   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4059       SCS2.Second == ICK_Floating_Integral &&
4060       S.Context.getTypeSize(SCS1.getFromType()) ==
4061           S.Context.getTypeSize(SCS1.getToType(2)))
4062     return ImplicitConversionSequence::Better;
4063 
4064   // Prefer a compatible vector conversion over a lax vector conversion
4065   // For example:
4066   //
4067   // typedef float __v4sf __attribute__((__vector_size__(16)));
4068   // void f(vector float);
4069   // void f(vector signed int);
4070   // int main() {
4071   //   __v4sf a;
4072   //   f(a);
4073   // }
4074   // Here, we'd like to choose f(vector float) and not
4075   // report an ambiguous call error
4076   if (SCS1.Second == ICK_Vector_Conversion &&
4077       SCS2.Second == ICK_Vector_Conversion) {
4078     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4079         SCS1.getFromType(), SCS1.getToType(2));
4080     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4081         SCS2.getFromType(), SCS2.getToType(2));
4082 
4083     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4084       return SCS1IsCompatibleVectorConversion
4085                  ? ImplicitConversionSequence::Better
4086                  : ImplicitConversionSequence::Worse;
4087   }
4088 
4089   return ImplicitConversionSequence::Indistinguishable;
4090 }
4091 
4092 /// CompareQualificationConversions - Compares two standard conversion
4093 /// sequences to determine whether they can be ranked based on their
4094 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4095 static ImplicitConversionSequence::CompareKind
4096 CompareQualificationConversions(Sema &S,
4097                                 const StandardConversionSequence& SCS1,
4098                                 const StandardConversionSequence& SCS2) {
4099   // C++ 13.3.3.2p3:
4100   //  -- S1 and S2 differ only in their qualification conversion and
4101   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4102   //     cv-qualification signature of type T1 is a proper subset of
4103   //     the cv-qualification signature of type T2, and S1 is not the
4104   //     deprecated string literal array-to-pointer conversion (4.2).
4105   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4106       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4107     return ImplicitConversionSequence::Indistinguishable;
4108 
4109   // FIXME: the example in the standard doesn't use a qualification
4110   // conversion (!)
4111   QualType T1 = SCS1.getToType(2);
4112   QualType T2 = SCS2.getToType(2);
4113   T1 = S.Context.getCanonicalType(T1);
4114   T2 = S.Context.getCanonicalType(T2);
4115   assert(!T1->isReferenceType() && !T2->isReferenceType());
4116   Qualifiers T1Quals, T2Quals;
4117   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4118   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4119 
4120   // If the types are the same, we won't learn anything by unwrapping
4121   // them.
4122   if (UnqualT1 == UnqualT2)
4123     return ImplicitConversionSequence::Indistinguishable;
4124 
4125   ImplicitConversionSequence::CompareKind Result
4126     = ImplicitConversionSequence::Indistinguishable;
4127 
4128   // Objective-C++ ARC:
4129   //   Prefer qualification conversions not involving a change in lifetime
4130   //   to qualification conversions that do not change lifetime.
4131   if (SCS1.QualificationIncludesObjCLifetime !=
4132                                       SCS2.QualificationIncludesObjCLifetime) {
4133     Result = SCS1.QualificationIncludesObjCLifetime
4134                ? ImplicitConversionSequence::Worse
4135                : ImplicitConversionSequence::Better;
4136   }
4137 
4138   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4139     // Within each iteration of the loop, we check the qualifiers to
4140     // determine if this still looks like a qualification
4141     // conversion. Then, if all is well, we unwrap one more level of
4142     // pointers or pointers-to-members and do it all again
4143     // until there are no more pointers or pointers-to-members left
4144     // to unwrap. This essentially mimics what
4145     // IsQualificationConversion does, but here we're checking for a
4146     // strict subset of qualifiers.
4147     if (T1.getQualifiers().withoutObjCLifetime() ==
4148         T2.getQualifiers().withoutObjCLifetime())
4149       // The qualifiers are the same, so this doesn't tell us anything
4150       // about how the sequences rank.
4151       // ObjC ownership quals are omitted above as they interfere with
4152       // the ARC overload rule.
4153       ;
4154     else if (T2.isMoreQualifiedThan(T1)) {
4155       // T1 has fewer qualifiers, so it could be the better sequence.
4156       if (Result == ImplicitConversionSequence::Worse)
4157         // Neither has qualifiers that are a subset of the other's
4158         // qualifiers.
4159         return ImplicitConversionSequence::Indistinguishable;
4160 
4161       Result = ImplicitConversionSequence::Better;
4162     } else if (T1.isMoreQualifiedThan(T2)) {
4163       // T2 has fewer qualifiers, so it could be the better sequence.
4164       if (Result == ImplicitConversionSequence::Better)
4165         // Neither has qualifiers that are a subset of the other's
4166         // qualifiers.
4167         return ImplicitConversionSequence::Indistinguishable;
4168 
4169       Result = ImplicitConversionSequence::Worse;
4170     } else {
4171       // Qualifiers are disjoint.
4172       return ImplicitConversionSequence::Indistinguishable;
4173     }
4174 
4175     // If the types after this point are equivalent, we're done.
4176     if (S.Context.hasSameUnqualifiedType(T1, T2))
4177       break;
4178   }
4179 
4180   // Check that the winning standard conversion sequence isn't using
4181   // the deprecated string literal array to pointer conversion.
4182   switch (Result) {
4183   case ImplicitConversionSequence::Better:
4184     if (SCS1.DeprecatedStringLiteralToCharPtr)
4185       Result = ImplicitConversionSequence::Indistinguishable;
4186     break;
4187 
4188   case ImplicitConversionSequence::Indistinguishable:
4189     break;
4190 
4191   case ImplicitConversionSequence::Worse:
4192     if (SCS2.DeprecatedStringLiteralToCharPtr)
4193       Result = ImplicitConversionSequence::Indistinguishable;
4194     break;
4195   }
4196 
4197   return Result;
4198 }
4199 
4200 /// CompareDerivedToBaseConversions - Compares two standard conversion
4201 /// sequences to determine whether they can be ranked based on their
4202 /// various kinds of derived-to-base conversions (C++
4203 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4204 /// conversions between Objective-C interface types.
4205 static ImplicitConversionSequence::CompareKind
4206 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4207                                 const StandardConversionSequence& SCS1,
4208                                 const StandardConversionSequence& SCS2) {
4209   QualType FromType1 = SCS1.getFromType();
4210   QualType ToType1 = SCS1.getToType(1);
4211   QualType FromType2 = SCS2.getFromType();
4212   QualType ToType2 = SCS2.getToType(1);
4213 
4214   // Adjust the types we're converting from via the array-to-pointer
4215   // conversion, if we need to.
4216   if (SCS1.First == ICK_Array_To_Pointer)
4217     FromType1 = S.Context.getArrayDecayedType(FromType1);
4218   if (SCS2.First == ICK_Array_To_Pointer)
4219     FromType2 = S.Context.getArrayDecayedType(FromType2);
4220 
4221   // Canonicalize all of the types.
4222   FromType1 = S.Context.getCanonicalType(FromType1);
4223   ToType1 = S.Context.getCanonicalType(ToType1);
4224   FromType2 = S.Context.getCanonicalType(FromType2);
4225   ToType2 = S.Context.getCanonicalType(ToType2);
4226 
4227   // C++ [over.ics.rank]p4b3:
4228   //
4229   //   If class B is derived directly or indirectly from class A and
4230   //   class C is derived directly or indirectly from B,
4231   //
4232   // Compare based on pointer conversions.
4233   if (SCS1.Second == ICK_Pointer_Conversion &&
4234       SCS2.Second == ICK_Pointer_Conversion &&
4235       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4236       FromType1->isPointerType() && FromType2->isPointerType() &&
4237       ToType1->isPointerType() && ToType2->isPointerType()) {
4238     QualType FromPointee1 =
4239         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4240     QualType ToPointee1 =
4241         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4242     QualType FromPointee2 =
4243         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4244     QualType ToPointee2 =
4245         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4246 
4247     //   -- conversion of C* to B* is better than conversion of C* to A*,
4248     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4249       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4250         return ImplicitConversionSequence::Better;
4251       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4252         return ImplicitConversionSequence::Worse;
4253     }
4254 
4255     //   -- conversion of B* to A* is better than conversion of C* to A*,
4256     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4257       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4258         return ImplicitConversionSequence::Better;
4259       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4260         return ImplicitConversionSequence::Worse;
4261     }
4262   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4263              SCS2.Second == ICK_Pointer_Conversion) {
4264     const ObjCObjectPointerType *FromPtr1
4265       = FromType1->getAs<ObjCObjectPointerType>();
4266     const ObjCObjectPointerType *FromPtr2
4267       = FromType2->getAs<ObjCObjectPointerType>();
4268     const ObjCObjectPointerType *ToPtr1
4269       = ToType1->getAs<ObjCObjectPointerType>();
4270     const ObjCObjectPointerType *ToPtr2
4271       = ToType2->getAs<ObjCObjectPointerType>();
4272 
4273     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4274       // Apply the same conversion ranking rules for Objective-C pointer types
4275       // that we do for C++ pointers to class types. However, we employ the
4276       // Objective-C pseudo-subtyping relationship used for assignment of
4277       // Objective-C pointer types.
4278       bool FromAssignLeft
4279         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4280       bool FromAssignRight
4281         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4282       bool ToAssignLeft
4283         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4284       bool ToAssignRight
4285         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4286 
4287       // A conversion to an a non-id object pointer type or qualified 'id'
4288       // type is better than a conversion to 'id'.
4289       if (ToPtr1->isObjCIdType() &&
4290           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4291         return ImplicitConversionSequence::Worse;
4292       if (ToPtr2->isObjCIdType() &&
4293           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4294         return ImplicitConversionSequence::Better;
4295 
4296       // A conversion to a non-id object pointer type is better than a
4297       // conversion to a qualified 'id' type
4298       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4299         return ImplicitConversionSequence::Worse;
4300       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4301         return ImplicitConversionSequence::Better;
4302 
4303       // A conversion to an a non-Class object pointer type or qualified 'Class'
4304       // type is better than a conversion to 'Class'.
4305       if (ToPtr1->isObjCClassType() &&
4306           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4307         return ImplicitConversionSequence::Worse;
4308       if (ToPtr2->isObjCClassType() &&
4309           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4310         return ImplicitConversionSequence::Better;
4311 
4312       // A conversion to a non-Class object pointer type is better than a
4313       // conversion to a qualified 'Class' type.
4314       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4315         return ImplicitConversionSequence::Worse;
4316       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4317         return ImplicitConversionSequence::Better;
4318 
4319       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4320       if (S.Context.hasSameType(FromType1, FromType2) &&
4321           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4322           (ToAssignLeft != ToAssignRight)) {
4323         if (FromPtr1->isSpecialized()) {
4324           // "conversion of B<A> * to B * is better than conversion of B * to
4325           // C *.
4326           bool IsFirstSame =
4327               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4328           bool IsSecondSame =
4329               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4330           if (IsFirstSame) {
4331             if (!IsSecondSame)
4332               return ImplicitConversionSequence::Better;
4333           } else if (IsSecondSame)
4334             return ImplicitConversionSequence::Worse;
4335         }
4336         return ToAssignLeft? ImplicitConversionSequence::Worse
4337                            : ImplicitConversionSequence::Better;
4338       }
4339 
4340       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4341       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4342           (FromAssignLeft != FromAssignRight))
4343         return FromAssignLeft? ImplicitConversionSequence::Better
4344         : ImplicitConversionSequence::Worse;
4345     }
4346   }
4347 
4348   // Ranking of member-pointer types.
4349   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4350       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4351       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4352     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4353     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4354     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4355     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4356     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4357     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4358     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4359     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4360     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4361     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4362     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4363     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4364     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4365     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4366       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4367         return ImplicitConversionSequence::Worse;
4368       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4369         return ImplicitConversionSequence::Better;
4370     }
4371     // conversion of B::* to C::* is better than conversion of A::* to C::*
4372     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4373       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4374         return ImplicitConversionSequence::Better;
4375       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4376         return ImplicitConversionSequence::Worse;
4377     }
4378   }
4379 
4380   if (SCS1.Second == ICK_Derived_To_Base) {
4381     //   -- conversion of C to B is better than conversion of C to A,
4382     //   -- binding of an expression of type C to a reference of type
4383     //      B& is better than binding an expression of type C to a
4384     //      reference of type A&,
4385     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4386         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4387       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4388         return ImplicitConversionSequence::Better;
4389       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4390         return ImplicitConversionSequence::Worse;
4391     }
4392 
4393     //   -- conversion of B to A is better than conversion of C to A.
4394     //   -- binding of an expression of type B to a reference of type
4395     //      A& is better than binding an expression of type C to a
4396     //      reference of type A&,
4397     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4398         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4399       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4400         return ImplicitConversionSequence::Better;
4401       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4402         return ImplicitConversionSequence::Worse;
4403     }
4404   }
4405 
4406   return ImplicitConversionSequence::Indistinguishable;
4407 }
4408 
4409 /// Determine whether the given type is valid, e.g., it is not an invalid
4410 /// C++ class.
4411 static bool isTypeValid(QualType T) {
4412   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4413     return !Record->isInvalidDecl();
4414 
4415   return true;
4416 }
4417 
4418 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4419   if (!T.getQualifiers().hasUnaligned())
4420     return T;
4421 
4422   Qualifiers Q;
4423   T = Ctx.getUnqualifiedArrayType(T, Q);
4424   Q.removeUnaligned();
4425   return Ctx.getQualifiedType(T, Q);
4426 }
4427 
4428 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4429 /// determine whether they are reference-compatible,
4430 /// reference-related, or incompatible, for use in C++ initialization by
4431 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4432 /// type, and the first type (T1) is the pointee type of the reference
4433 /// type being initialized.
4434 Sema::ReferenceCompareResult
4435 Sema::CompareReferenceRelationship(SourceLocation Loc,
4436                                    QualType OrigT1, QualType OrigT2,
4437                                    ReferenceConversions *ConvOut) {
4438   assert(!OrigT1->isReferenceType() &&
4439     "T1 must be the pointee type of the reference type");
4440   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4441 
4442   QualType T1 = Context.getCanonicalType(OrigT1);
4443   QualType T2 = Context.getCanonicalType(OrigT2);
4444   Qualifiers T1Quals, T2Quals;
4445   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4446   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4447 
4448   ReferenceConversions ConvTmp;
4449   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4450   Conv = ReferenceConversions();
4451 
4452   // C++2a [dcl.init.ref]p4:
4453   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4454   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4455   //   T1 is a base class of T2.
4456   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4457   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4458   //   "pointer to cv1 T1" via a standard conversion sequence.
4459 
4460   // Check for standard conversions we can apply to pointers: derived-to-base
4461   // conversions, ObjC pointer conversions, and function pointer conversions.
4462   // (Qualification conversions are checked last.)
4463   QualType ConvertedT2;
4464   if (UnqualT1 == UnqualT2) {
4465     // Nothing to do.
4466   } else if (isCompleteType(Loc, OrigT2) &&
4467              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4468              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4469     Conv |= ReferenceConversions::DerivedToBase;
4470   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4471            UnqualT2->isObjCObjectOrInterfaceType() &&
4472            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4473     Conv |= ReferenceConversions::ObjC;
4474   else if (UnqualT2->isFunctionType() &&
4475            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4476     Conv |= ReferenceConversions::Function;
4477     // No need to check qualifiers; function types don't have them.
4478     return Ref_Compatible;
4479   }
4480   bool ConvertedReferent = Conv != 0;
4481 
4482   // We can have a qualification conversion. Compute whether the types are
4483   // similar at the same time.
4484   bool PreviousToQualsIncludeConst = true;
4485   bool TopLevel = true;
4486   do {
4487     if (T1 == T2)
4488       break;
4489 
4490     // We will need a qualification conversion.
4491     Conv |= ReferenceConversions::Qualification;
4492 
4493     // Track whether we performed a qualification conversion anywhere other
4494     // than the top level. This matters for ranking reference bindings in
4495     // overload resolution.
4496     if (!TopLevel)
4497       Conv |= ReferenceConversions::NestedQualification;
4498 
4499     // MS compiler ignores __unaligned qualifier for references; do the same.
4500     T1 = withoutUnaligned(Context, T1);
4501     T2 = withoutUnaligned(Context, T2);
4502 
4503     // If we find a qualifier mismatch, the types are not reference-compatible,
4504     // but are still be reference-related if they're similar.
4505     bool ObjCLifetimeConversion = false;
4506     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false,
4507                                        PreviousToQualsIncludeConst,
4508                                        ObjCLifetimeConversion))
4509       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4510                  ? Ref_Related
4511                  : Ref_Incompatible;
4512 
4513     // FIXME: Should we track this for any level other than the first?
4514     if (ObjCLifetimeConversion)
4515       Conv |= ReferenceConversions::ObjCLifetime;
4516 
4517     TopLevel = false;
4518   } while (Context.UnwrapSimilarTypes(T1, T2));
4519 
4520   // At this point, if the types are reference-related, we must either have the
4521   // same inner type (ignoring qualifiers), or must have already worked out how
4522   // to convert the referent.
4523   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4524              ? Ref_Compatible
4525              : Ref_Incompatible;
4526 }
4527 
4528 /// Look for a user-defined conversion to a value reference-compatible
4529 ///        with DeclType. Return true if something definite is found.
4530 static bool
4531 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4532                          QualType DeclType, SourceLocation DeclLoc,
4533                          Expr *Init, QualType T2, bool AllowRvalues,
4534                          bool AllowExplicit) {
4535   assert(T2->isRecordType() && "Can only find conversions of record types.");
4536   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4537 
4538   OverloadCandidateSet CandidateSet(
4539       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4540   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4541   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4542     NamedDecl *D = *I;
4543     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4544     if (isa<UsingShadowDecl>(D))
4545       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4546 
4547     FunctionTemplateDecl *ConvTemplate
4548       = dyn_cast<FunctionTemplateDecl>(D);
4549     CXXConversionDecl *Conv;
4550     if (ConvTemplate)
4551       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4552     else
4553       Conv = cast<CXXConversionDecl>(D);
4554 
4555     if (AllowRvalues) {
4556       // If we are initializing an rvalue reference, don't permit conversion
4557       // functions that return lvalues.
4558       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4559         const ReferenceType *RefType
4560           = Conv->getConversionType()->getAs<LValueReferenceType>();
4561         if (RefType && !RefType->getPointeeType()->isFunctionType())
4562           continue;
4563       }
4564 
4565       if (!ConvTemplate &&
4566           S.CompareReferenceRelationship(
4567               DeclLoc,
4568               Conv->getConversionType()
4569                   .getNonReferenceType()
4570                   .getUnqualifiedType(),
4571               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4572               Sema::Ref_Incompatible)
4573         continue;
4574     } else {
4575       // If the conversion function doesn't return a reference type,
4576       // it can't be considered for this conversion. An rvalue reference
4577       // is only acceptable if its referencee is a function type.
4578 
4579       const ReferenceType *RefType =
4580         Conv->getConversionType()->getAs<ReferenceType>();
4581       if (!RefType ||
4582           (!RefType->isLValueReferenceType() &&
4583            !RefType->getPointeeType()->isFunctionType()))
4584         continue;
4585     }
4586 
4587     if (ConvTemplate)
4588       S.AddTemplateConversionCandidate(
4589           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4590           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4591     else
4592       S.AddConversionCandidate(
4593           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4594           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4595   }
4596 
4597   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4598 
4599   OverloadCandidateSet::iterator Best;
4600   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4601   case OR_Success:
4602     // C++ [over.ics.ref]p1:
4603     //
4604     //   [...] If the parameter binds directly to the result of
4605     //   applying a conversion function to the argument
4606     //   expression, the implicit conversion sequence is a
4607     //   user-defined conversion sequence (13.3.3.1.2), with the
4608     //   second standard conversion sequence either an identity
4609     //   conversion or, if the conversion function returns an
4610     //   entity of a type that is a derived class of the parameter
4611     //   type, a derived-to-base Conversion.
4612     if (!Best->FinalConversion.DirectBinding)
4613       return false;
4614 
4615     ICS.setUserDefined();
4616     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4617     ICS.UserDefined.After = Best->FinalConversion;
4618     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4619     ICS.UserDefined.ConversionFunction = Best->Function;
4620     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4621     ICS.UserDefined.EllipsisConversion = false;
4622     assert(ICS.UserDefined.After.ReferenceBinding &&
4623            ICS.UserDefined.After.DirectBinding &&
4624            "Expected a direct reference binding!");
4625     return true;
4626 
4627   case OR_Ambiguous:
4628     ICS.setAmbiguous();
4629     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4630          Cand != CandidateSet.end(); ++Cand)
4631       if (Cand->Best)
4632         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4633     return true;
4634 
4635   case OR_No_Viable_Function:
4636   case OR_Deleted:
4637     // There was no suitable conversion, or we found a deleted
4638     // conversion; continue with other checks.
4639     return false;
4640   }
4641 
4642   llvm_unreachable("Invalid OverloadResult!");
4643 }
4644 
4645 /// Compute an implicit conversion sequence for reference
4646 /// initialization.
4647 static ImplicitConversionSequence
4648 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4649                  SourceLocation DeclLoc,
4650                  bool SuppressUserConversions,
4651                  bool AllowExplicit) {
4652   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4653 
4654   // Most paths end in a failed conversion.
4655   ImplicitConversionSequence ICS;
4656   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4657 
4658   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4659   QualType T2 = Init->getType();
4660 
4661   // If the initializer is the address of an overloaded function, try
4662   // to resolve the overloaded function. If all goes well, T2 is the
4663   // type of the resulting function.
4664   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4665     DeclAccessPair Found;
4666     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4667                                                                 false, Found))
4668       T2 = Fn->getType();
4669   }
4670 
4671   // Compute some basic properties of the types and the initializer.
4672   bool isRValRef = DeclType->isRValueReferenceType();
4673   Expr::Classification InitCategory = Init->Classify(S.Context);
4674 
4675   Sema::ReferenceConversions RefConv;
4676   Sema::ReferenceCompareResult RefRelationship =
4677       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4678 
4679   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4680     ICS.setStandard();
4681     ICS.Standard.First = ICK_Identity;
4682     // FIXME: A reference binding can be a function conversion too. We should
4683     // consider that when ordering reference-to-function bindings.
4684     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4685                               ? ICK_Derived_To_Base
4686                               : (RefConv & Sema::ReferenceConversions::ObjC)
4687                                     ? ICK_Compatible_Conversion
4688                                     : ICK_Identity;
4689     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4690     // a reference binding that performs a non-top-level qualification
4691     // conversion as a qualification conversion, not as an identity conversion.
4692     ICS.Standard.Third = (RefConv &
4693                               Sema::ReferenceConversions::NestedQualification)
4694                              ? ICK_Qualification
4695                              : ICK_Identity;
4696     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4697     ICS.Standard.setToType(0, T2);
4698     ICS.Standard.setToType(1, T1);
4699     ICS.Standard.setToType(2, T1);
4700     ICS.Standard.ReferenceBinding = true;
4701     ICS.Standard.DirectBinding = BindsDirectly;
4702     ICS.Standard.IsLvalueReference = !isRValRef;
4703     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4704     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4705     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4706     ICS.Standard.ObjCLifetimeConversionBinding =
4707         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4708     ICS.Standard.CopyConstructor = nullptr;
4709     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4710   };
4711 
4712   // C++0x [dcl.init.ref]p5:
4713   //   A reference to type "cv1 T1" is initialized by an expression
4714   //   of type "cv2 T2" as follows:
4715 
4716   //     -- If reference is an lvalue reference and the initializer expression
4717   if (!isRValRef) {
4718     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4719     //        reference-compatible with "cv2 T2," or
4720     //
4721     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4722     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4723       // C++ [over.ics.ref]p1:
4724       //   When a parameter of reference type binds directly (8.5.3)
4725       //   to an argument expression, the implicit conversion sequence
4726       //   is the identity conversion, unless the argument expression
4727       //   has a type that is a derived class of the parameter type,
4728       //   in which case the implicit conversion sequence is a
4729       //   derived-to-base Conversion (13.3.3.1).
4730       SetAsReferenceBinding(/*BindsDirectly=*/true);
4731 
4732       // Nothing more to do: the inaccessibility/ambiguity check for
4733       // derived-to-base conversions is suppressed when we're
4734       // computing the implicit conversion sequence (C++
4735       // [over.best.ics]p2).
4736       return ICS;
4737     }
4738 
4739     //       -- has a class type (i.e., T2 is a class type), where T1 is
4740     //          not reference-related to T2, and can be implicitly
4741     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4742     //          is reference-compatible with "cv3 T3" 92) (this
4743     //          conversion is selected by enumerating the applicable
4744     //          conversion functions (13.3.1.6) and choosing the best
4745     //          one through overload resolution (13.3)),
4746     if (!SuppressUserConversions && T2->isRecordType() &&
4747         S.isCompleteType(DeclLoc, T2) &&
4748         RefRelationship == Sema::Ref_Incompatible) {
4749       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4750                                    Init, T2, /*AllowRvalues=*/false,
4751                                    AllowExplicit))
4752         return ICS;
4753     }
4754   }
4755 
4756   //     -- Otherwise, the reference shall be an lvalue reference to a
4757   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4758   //        shall be an rvalue reference.
4759   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4760     return ICS;
4761 
4762   //       -- If the initializer expression
4763   //
4764   //            -- is an xvalue, class prvalue, array prvalue or function
4765   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4766   if (RefRelationship == Sema::Ref_Compatible &&
4767       (InitCategory.isXValue() ||
4768        (InitCategory.isPRValue() &&
4769           (T2->isRecordType() || T2->isArrayType())) ||
4770        (InitCategory.isLValue() && T2->isFunctionType()))) {
4771     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4772     // binding unless we're binding to a class prvalue.
4773     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4774     // allow the use of rvalue references in C++98/03 for the benefit of
4775     // standard library implementors; therefore, we need the xvalue check here.
4776     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4777                           !(InitCategory.isPRValue() || T2->isRecordType()));
4778     return ICS;
4779   }
4780 
4781   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4782   //               reference-related to T2, and can be implicitly converted to
4783   //               an xvalue, class prvalue, or function lvalue of type
4784   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4785   //               "cv3 T3",
4786   //
4787   //          then the reference is bound to the value of the initializer
4788   //          expression in the first case and to the result of the conversion
4789   //          in the second case (or, in either case, to an appropriate base
4790   //          class subobject).
4791   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4792       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4793       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4794                                Init, T2, /*AllowRvalues=*/true,
4795                                AllowExplicit)) {
4796     // In the second case, if the reference is an rvalue reference
4797     // and the second standard conversion sequence of the
4798     // user-defined conversion sequence includes an lvalue-to-rvalue
4799     // conversion, the program is ill-formed.
4800     if (ICS.isUserDefined() && isRValRef &&
4801         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4802       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4803 
4804     return ICS;
4805   }
4806 
4807   // A temporary of function type cannot be created; don't even try.
4808   if (T1->isFunctionType())
4809     return ICS;
4810 
4811   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4812   //          initialized from the initializer expression using the
4813   //          rules for a non-reference copy initialization (8.5). The
4814   //          reference is then bound to the temporary. If T1 is
4815   //          reference-related to T2, cv1 must be the same
4816   //          cv-qualification as, or greater cv-qualification than,
4817   //          cv2; otherwise, the program is ill-formed.
4818   if (RefRelationship == Sema::Ref_Related) {
4819     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4820     // we would be reference-compatible or reference-compatible with
4821     // added qualification. But that wasn't the case, so the reference
4822     // initialization fails.
4823     //
4824     // Note that we only want to check address spaces and cvr-qualifiers here.
4825     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4826     Qualifiers T1Quals = T1.getQualifiers();
4827     Qualifiers T2Quals = T2.getQualifiers();
4828     T1Quals.removeObjCGCAttr();
4829     T1Quals.removeObjCLifetime();
4830     T2Quals.removeObjCGCAttr();
4831     T2Quals.removeObjCLifetime();
4832     // MS compiler ignores __unaligned qualifier for references; do the same.
4833     T1Quals.removeUnaligned();
4834     T2Quals.removeUnaligned();
4835     if (!T1Quals.compatiblyIncludes(T2Quals))
4836       return ICS;
4837   }
4838 
4839   // If at least one of the types is a class type, the types are not
4840   // related, and we aren't allowed any user conversions, the
4841   // reference binding fails. This case is important for breaking
4842   // recursion, since TryImplicitConversion below will attempt to
4843   // create a temporary through the use of a copy constructor.
4844   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4845       (T1->isRecordType() || T2->isRecordType()))
4846     return ICS;
4847 
4848   // If T1 is reference-related to T2 and the reference is an rvalue
4849   // reference, the initializer expression shall not be an lvalue.
4850   if (RefRelationship >= Sema::Ref_Related &&
4851       isRValRef && Init->Classify(S.Context).isLValue())
4852     return ICS;
4853 
4854   // C++ [over.ics.ref]p2:
4855   //   When a parameter of reference type is not bound directly to
4856   //   an argument expression, the conversion sequence is the one
4857   //   required to convert the argument expression to the
4858   //   underlying type of the reference according to
4859   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4860   //   to copy-initializing a temporary of the underlying type with
4861   //   the argument expression. Any difference in top-level
4862   //   cv-qualification is subsumed by the initialization itself
4863   //   and does not constitute a conversion.
4864   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4865                               /*AllowExplicit=*/false,
4866                               /*InOverloadResolution=*/false,
4867                               /*CStyle=*/false,
4868                               /*AllowObjCWritebackConversion=*/false,
4869                               /*AllowObjCConversionOnExplicit=*/false);
4870 
4871   // Of course, that's still a reference binding.
4872   if (ICS.isStandard()) {
4873     ICS.Standard.ReferenceBinding = true;
4874     ICS.Standard.IsLvalueReference = !isRValRef;
4875     ICS.Standard.BindsToFunctionLvalue = false;
4876     ICS.Standard.BindsToRvalue = true;
4877     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4878     ICS.Standard.ObjCLifetimeConversionBinding = false;
4879   } else if (ICS.isUserDefined()) {
4880     const ReferenceType *LValRefType =
4881         ICS.UserDefined.ConversionFunction->getReturnType()
4882             ->getAs<LValueReferenceType>();
4883 
4884     // C++ [over.ics.ref]p3:
4885     //   Except for an implicit object parameter, for which see 13.3.1, a
4886     //   standard conversion sequence cannot be formed if it requires [...]
4887     //   binding an rvalue reference to an lvalue other than a function
4888     //   lvalue.
4889     // Note that the function case is not possible here.
4890     if (DeclType->isRValueReferenceType() && LValRefType) {
4891       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4892       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4893       // reference to an rvalue!
4894       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4895       return ICS;
4896     }
4897 
4898     ICS.UserDefined.After.ReferenceBinding = true;
4899     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4900     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4901     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4902     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4903     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4904   }
4905 
4906   return ICS;
4907 }
4908 
4909 static ImplicitConversionSequence
4910 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4911                       bool SuppressUserConversions,
4912                       bool InOverloadResolution,
4913                       bool AllowObjCWritebackConversion,
4914                       bool AllowExplicit = false);
4915 
4916 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4917 /// initializer list From.
4918 static ImplicitConversionSequence
4919 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4920                   bool SuppressUserConversions,
4921                   bool InOverloadResolution,
4922                   bool AllowObjCWritebackConversion) {
4923   // C++11 [over.ics.list]p1:
4924   //   When an argument is an initializer list, it is not an expression and
4925   //   special rules apply for converting it to a parameter type.
4926 
4927   ImplicitConversionSequence Result;
4928   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4929 
4930   // We need a complete type for what follows. Incomplete types can never be
4931   // initialized from init lists.
4932   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4933     return Result;
4934 
4935   // Per DR1467:
4936   //   If the parameter type is a class X and the initializer list has a single
4937   //   element of type cv U, where U is X or a class derived from X, the
4938   //   implicit conversion sequence is the one required to convert the element
4939   //   to the parameter type.
4940   //
4941   //   Otherwise, if the parameter type is a character array [... ]
4942   //   and the initializer list has a single element that is an
4943   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4944   //   implicit conversion sequence is the identity conversion.
4945   if (From->getNumInits() == 1) {
4946     if (ToType->isRecordType()) {
4947       QualType InitType = From->getInit(0)->getType();
4948       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4949           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4950         return TryCopyInitialization(S, From->getInit(0), ToType,
4951                                      SuppressUserConversions,
4952                                      InOverloadResolution,
4953                                      AllowObjCWritebackConversion);
4954     }
4955     // FIXME: Check the other conditions here: array of character type,
4956     // initializer is a string literal.
4957     if (ToType->isArrayType()) {
4958       InitializedEntity Entity =
4959         InitializedEntity::InitializeParameter(S.Context, ToType,
4960                                                /*Consumed=*/false);
4961       if (S.CanPerformCopyInitialization(Entity, From)) {
4962         Result.setStandard();
4963         Result.Standard.setAsIdentityConversion();
4964         Result.Standard.setFromType(ToType);
4965         Result.Standard.setAllToTypes(ToType);
4966         return Result;
4967       }
4968     }
4969   }
4970 
4971   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4972   // C++11 [over.ics.list]p2:
4973   //   If the parameter type is std::initializer_list<X> or "array of X" and
4974   //   all the elements can be implicitly converted to X, the implicit
4975   //   conversion sequence is the worst conversion necessary to convert an
4976   //   element of the list to X.
4977   //
4978   // C++14 [over.ics.list]p3:
4979   //   Otherwise, if the parameter type is "array of N X", if the initializer
4980   //   list has exactly N elements or if it has fewer than N elements and X is
4981   //   default-constructible, and if all the elements of the initializer list
4982   //   can be implicitly converted to X, the implicit conversion sequence is
4983   //   the worst conversion necessary to convert an element of the list to X.
4984   //
4985   // FIXME: We're missing a lot of these checks.
4986   bool toStdInitializerList = false;
4987   QualType X;
4988   if (ToType->isArrayType())
4989     X = S.Context.getAsArrayType(ToType)->getElementType();
4990   else
4991     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4992   if (!X.isNull()) {
4993     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4994       Expr *Init = From->getInit(i);
4995       ImplicitConversionSequence ICS =
4996           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4997                                 InOverloadResolution,
4998                                 AllowObjCWritebackConversion);
4999       // If a single element isn't convertible, fail.
5000       if (ICS.isBad()) {
5001         Result = ICS;
5002         break;
5003       }
5004       // Otherwise, look for the worst conversion.
5005       if (Result.isBad() || CompareImplicitConversionSequences(
5006                                 S, From->getBeginLoc(), ICS, Result) ==
5007                                 ImplicitConversionSequence::Worse)
5008         Result = ICS;
5009     }
5010 
5011     // For an empty list, we won't have computed any conversion sequence.
5012     // Introduce the identity conversion sequence.
5013     if (From->getNumInits() == 0) {
5014       Result.setStandard();
5015       Result.Standard.setAsIdentityConversion();
5016       Result.Standard.setFromType(ToType);
5017       Result.Standard.setAllToTypes(ToType);
5018     }
5019 
5020     Result.setStdInitializerListElement(toStdInitializerList);
5021     return Result;
5022   }
5023 
5024   // C++14 [over.ics.list]p4:
5025   // C++11 [over.ics.list]p3:
5026   //   Otherwise, if the parameter is a non-aggregate class X and overload
5027   //   resolution chooses a single best constructor [...] the implicit
5028   //   conversion sequence is a user-defined conversion sequence. If multiple
5029   //   constructors are viable but none is better than the others, the
5030   //   implicit conversion sequence is a user-defined conversion sequence.
5031   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5032     // This function can deal with initializer lists.
5033     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5034                                     /*AllowExplicit=*/false,
5035                                     InOverloadResolution, /*CStyle=*/false,
5036                                     AllowObjCWritebackConversion,
5037                                     /*AllowObjCConversionOnExplicit=*/false);
5038   }
5039 
5040   // C++14 [over.ics.list]p5:
5041   // C++11 [over.ics.list]p4:
5042   //   Otherwise, if the parameter has an aggregate type which can be
5043   //   initialized from the initializer list [...] the implicit conversion
5044   //   sequence is a user-defined conversion sequence.
5045   if (ToType->isAggregateType()) {
5046     // Type is an aggregate, argument is an init list. At this point it comes
5047     // down to checking whether the initialization works.
5048     // FIXME: Find out whether this parameter is consumed or not.
5049     InitializedEntity Entity =
5050         InitializedEntity::InitializeParameter(S.Context, ToType,
5051                                                /*Consumed=*/false);
5052     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5053                                                                  From)) {
5054       Result.setUserDefined();
5055       Result.UserDefined.Before.setAsIdentityConversion();
5056       // Initializer lists don't have a type.
5057       Result.UserDefined.Before.setFromType(QualType());
5058       Result.UserDefined.Before.setAllToTypes(QualType());
5059 
5060       Result.UserDefined.After.setAsIdentityConversion();
5061       Result.UserDefined.After.setFromType(ToType);
5062       Result.UserDefined.After.setAllToTypes(ToType);
5063       Result.UserDefined.ConversionFunction = nullptr;
5064     }
5065     return Result;
5066   }
5067 
5068   // C++14 [over.ics.list]p6:
5069   // C++11 [over.ics.list]p5:
5070   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5071   if (ToType->isReferenceType()) {
5072     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5073     // mention initializer lists in any way. So we go by what list-
5074     // initialization would do and try to extrapolate from that.
5075 
5076     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5077 
5078     // If the initializer list has a single element that is reference-related
5079     // to the parameter type, we initialize the reference from that.
5080     if (From->getNumInits() == 1) {
5081       Expr *Init = From->getInit(0);
5082 
5083       QualType T2 = Init->getType();
5084 
5085       // If the initializer is the address of an overloaded function, try
5086       // to resolve the overloaded function. If all goes well, T2 is the
5087       // type of the resulting function.
5088       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5089         DeclAccessPair Found;
5090         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5091                                    Init, ToType, false, Found))
5092           T2 = Fn->getType();
5093       }
5094 
5095       // Compute some basic properties of the types and the initializer.
5096       Sema::ReferenceCompareResult RefRelationship =
5097           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5098 
5099       if (RefRelationship >= Sema::Ref_Related) {
5100         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5101                                 SuppressUserConversions,
5102                                 /*AllowExplicit=*/false);
5103       }
5104     }
5105 
5106     // Otherwise, we bind the reference to a temporary created from the
5107     // initializer list.
5108     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5109                                InOverloadResolution,
5110                                AllowObjCWritebackConversion);
5111     if (Result.isFailure())
5112       return Result;
5113     assert(!Result.isEllipsis() &&
5114            "Sub-initialization cannot result in ellipsis conversion.");
5115 
5116     // Can we even bind to a temporary?
5117     if (ToType->isRValueReferenceType() ||
5118         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5119       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5120                                             Result.UserDefined.After;
5121       SCS.ReferenceBinding = true;
5122       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5123       SCS.BindsToRvalue = true;
5124       SCS.BindsToFunctionLvalue = false;
5125       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5126       SCS.ObjCLifetimeConversionBinding = false;
5127     } else
5128       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5129                     From, ToType);
5130     return Result;
5131   }
5132 
5133   // C++14 [over.ics.list]p7:
5134   // C++11 [over.ics.list]p6:
5135   //   Otherwise, if the parameter type is not a class:
5136   if (!ToType->isRecordType()) {
5137     //    - if the initializer list has one element that is not itself an
5138     //      initializer list, the implicit conversion sequence is the one
5139     //      required to convert the element to the parameter type.
5140     unsigned NumInits = From->getNumInits();
5141     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5142       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5143                                      SuppressUserConversions,
5144                                      InOverloadResolution,
5145                                      AllowObjCWritebackConversion);
5146     //    - if the initializer list has no elements, the implicit conversion
5147     //      sequence is the identity conversion.
5148     else if (NumInits == 0) {
5149       Result.setStandard();
5150       Result.Standard.setAsIdentityConversion();
5151       Result.Standard.setFromType(ToType);
5152       Result.Standard.setAllToTypes(ToType);
5153     }
5154     return Result;
5155   }
5156 
5157   // C++14 [over.ics.list]p8:
5158   // C++11 [over.ics.list]p7:
5159   //   In all cases other than those enumerated above, no conversion is possible
5160   return Result;
5161 }
5162 
5163 /// TryCopyInitialization - Try to copy-initialize a value of type
5164 /// ToType from the expression From. Return the implicit conversion
5165 /// sequence required to pass this argument, which may be a bad
5166 /// conversion sequence (meaning that the argument cannot be passed to
5167 /// a parameter of this type). If @p SuppressUserConversions, then we
5168 /// do not permit any user-defined conversion sequences.
5169 static ImplicitConversionSequence
5170 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5171                       bool SuppressUserConversions,
5172                       bool InOverloadResolution,
5173                       bool AllowObjCWritebackConversion,
5174                       bool AllowExplicit) {
5175   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5176     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5177                              InOverloadResolution,AllowObjCWritebackConversion);
5178 
5179   if (ToType->isReferenceType())
5180     return TryReferenceInit(S, From, ToType,
5181                             /*FIXME:*/ From->getBeginLoc(),
5182                             SuppressUserConversions, AllowExplicit);
5183 
5184   return TryImplicitConversion(S, From, ToType,
5185                                SuppressUserConversions,
5186                                /*AllowExplicit=*/false,
5187                                InOverloadResolution,
5188                                /*CStyle=*/false,
5189                                AllowObjCWritebackConversion,
5190                                /*AllowObjCConversionOnExplicit=*/false);
5191 }
5192 
5193 static bool TryCopyInitialization(const CanQualType FromQTy,
5194                                   const CanQualType ToQTy,
5195                                   Sema &S,
5196                                   SourceLocation Loc,
5197                                   ExprValueKind FromVK) {
5198   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5199   ImplicitConversionSequence ICS =
5200     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5201 
5202   return !ICS.isBad();
5203 }
5204 
5205 /// TryObjectArgumentInitialization - Try to initialize the object
5206 /// parameter of the given member function (@c Method) from the
5207 /// expression @p From.
5208 static ImplicitConversionSequence
5209 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5210                                 Expr::Classification FromClassification,
5211                                 CXXMethodDecl *Method,
5212                                 CXXRecordDecl *ActingContext) {
5213   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5214   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5215   //                 const volatile object.
5216   Qualifiers Quals = Method->getMethodQualifiers();
5217   if (isa<CXXDestructorDecl>(Method)) {
5218     Quals.addConst();
5219     Quals.addVolatile();
5220   }
5221 
5222   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5223 
5224   // Set up the conversion sequence as a "bad" conversion, to allow us
5225   // to exit early.
5226   ImplicitConversionSequence ICS;
5227 
5228   // We need to have an object of class type.
5229   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5230     FromType = PT->getPointeeType();
5231 
5232     // When we had a pointer, it's implicitly dereferenced, so we
5233     // better have an lvalue.
5234     assert(FromClassification.isLValue());
5235   }
5236 
5237   assert(FromType->isRecordType());
5238 
5239   // C++0x [over.match.funcs]p4:
5240   //   For non-static member functions, the type of the implicit object
5241   //   parameter is
5242   //
5243   //     - "lvalue reference to cv X" for functions declared without a
5244   //        ref-qualifier or with the & ref-qualifier
5245   //     - "rvalue reference to cv X" for functions declared with the &&
5246   //        ref-qualifier
5247   //
5248   // where X is the class of which the function is a member and cv is the
5249   // cv-qualification on the member function declaration.
5250   //
5251   // However, when finding an implicit conversion sequence for the argument, we
5252   // are not allowed to perform user-defined conversions
5253   // (C++ [over.match.funcs]p5). We perform a simplified version of
5254   // reference binding here, that allows class rvalues to bind to
5255   // non-constant references.
5256 
5257   // First check the qualifiers.
5258   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5259   if (ImplicitParamType.getCVRQualifiers()
5260                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5261       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5262     ICS.setBad(BadConversionSequence::bad_qualifiers,
5263                FromType, ImplicitParamType);
5264     return ICS;
5265   }
5266 
5267   if (FromTypeCanon.hasAddressSpace()) {
5268     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5269     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5270     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5271       ICS.setBad(BadConversionSequence::bad_qualifiers,
5272                  FromType, ImplicitParamType);
5273       return ICS;
5274     }
5275   }
5276 
5277   // Check that we have either the same type or a derived type. It
5278   // affects the conversion rank.
5279   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5280   ImplicitConversionKind SecondKind;
5281   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5282     SecondKind = ICK_Identity;
5283   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5284     SecondKind = ICK_Derived_To_Base;
5285   else {
5286     ICS.setBad(BadConversionSequence::unrelated_class,
5287                FromType, ImplicitParamType);
5288     return ICS;
5289   }
5290 
5291   // Check the ref-qualifier.
5292   switch (Method->getRefQualifier()) {
5293   case RQ_None:
5294     // Do nothing; we don't care about lvalueness or rvalueness.
5295     break;
5296 
5297   case RQ_LValue:
5298     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5299       // non-const lvalue reference cannot bind to an rvalue
5300       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5301                  ImplicitParamType);
5302       return ICS;
5303     }
5304     break;
5305 
5306   case RQ_RValue:
5307     if (!FromClassification.isRValue()) {
5308       // rvalue reference cannot bind to an lvalue
5309       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5310                  ImplicitParamType);
5311       return ICS;
5312     }
5313     break;
5314   }
5315 
5316   // Success. Mark this as a reference binding.
5317   ICS.setStandard();
5318   ICS.Standard.setAsIdentityConversion();
5319   ICS.Standard.Second = SecondKind;
5320   ICS.Standard.setFromType(FromType);
5321   ICS.Standard.setAllToTypes(ImplicitParamType);
5322   ICS.Standard.ReferenceBinding = true;
5323   ICS.Standard.DirectBinding = true;
5324   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5325   ICS.Standard.BindsToFunctionLvalue = false;
5326   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5327   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5328     = (Method->getRefQualifier() == RQ_None);
5329   return ICS;
5330 }
5331 
5332 /// PerformObjectArgumentInitialization - Perform initialization of
5333 /// the implicit object parameter for the given Method with the given
5334 /// expression.
5335 ExprResult
5336 Sema::PerformObjectArgumentInitialization(Expr *From,
5337                                           NestedNameSpecifier *Qualifier,
5338                                           NamedDecl *FoundDecl,
5339                                           CXXMethodDecl *Method) {
5340   QualType FromRecordType, DestType;
5341   QualType ImplicitParamRecordType  =
5342     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5343 
5344   Expr::Classification FromClassification;
5345   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5346     FromRecordType = PT->getPointeeType();
5347     DestType = Method->getThisType();
5348     FromClassification = Expr::Classification::makeSimpleLValue();
5349   } else {
5350     FromRecordType = From->getType();
5351     DestType = ImplicitParamRecordType;
5352     FromClassification = From->Classify(Context);
5353 
5354     // When performing member access on an rvalue, materialize a temporary.
5355     if (From->isRValue()) {
5356       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5357                                             Method->getRefQualifier() !=
5358                                                 RefQualifierKind::RQ_RValue);
5359     }
5360   }
5361 
5362   // Note that we always use the true parent context when performing
5363   // the actual argument initialization.
5364   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5365       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5366       Method->getParent());
5367   if (ICS.isBad()) {
5368     switch (ICS.Bad.Kind) {
5369     case BadConversionSequence::bad_qualifiers: {
5370       Qualifiers FromQs = FromRecordType.getQualifiers();
5371       Qualifiers ToQs = DestType.getQualifiers();
5372       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5373       if (CVR) {
5374         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5375             << Method->getDeclName() << FromRecordType << (CVR - 1)
5376             << From->getSourceRange();
5377         Diag(Method->getLocation(), diag::note_previous_decl)
5378           << Method->getDeclName();
5379         return ExprError();
5380       }
5381       break;
5382     }
5383 
5384     case BadConversionSequence::lvalue_ref_to_rvalue:
5385     case BadConversionSequence::rvalue_ref_to_lvalue: {
5386       bool IsRValueQualified =
5387         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5388       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5389           << Method->getDeclName() << FromClassification.isRValue()
5390           << IsRValueQualified;
5391       Diag(Method->getLocation(), diag::note_previous_decl)
5392         << Method->getDeclName();
5393       return ExprError();
5394     }
5395 
5396     case BadConversionSequence::no_conversion:
5397     case BadConversionSequence::unrelated_class:
5398       break;
5399     }
5400 
5401     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5402            << ImplicitParamRecordType << FromRecordType
5403            << From->getSourceRange();
5404   }
5405 
5406   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5407     ExprResult FromRes =
5408       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5409     if (FromRes.isInvalid())
5410       return ExprError();
5411     From = FromRes.get();
5412   }
5413 
5414   if (!Context.hasSameType(From->getType(), DestType)) {
5415     CastKind CK;
5416     QualType PteeTy = DestType->getPointeeType();
5417     LangAS DestAS =
5418         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5419     if (FromRecordType.getAddressSpace() != DestAS)
5420       CK = CK_AddressSpaceConversion;
5421     else
5422       CK = CK_NoOp;
5423     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5424   }
5425   return From;
5426 }
5427 
5428 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5429 /// expression From to bool (C++0x [conv]p3).
5430 static ImplicitConversionSequence
5431 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5432   return TryImplicitConversion(S, From, S.Context.BoolTy,
5433                                /*SuppressUserConversions=*/false,
5434                                /*AllowExplicit=*/true,
5435                                /*InOverloadResolution=*/false,
5436                                /*CStyle=*/false,
5437                                /*AllowObjCWritebackConversion=*/false,
5438                                /*AllowObjCConversionOnExplicit=*/false);
5439 }
5440 
5441 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5442 /// of the expression From to bool (C++0x [conv]p3).
5443 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5444   if (checkPlaceholderForOverload(*this, From))
5445     return ExprError();
5446 
5447   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5448   if (!ICS.isBad())
5449     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5450 
5451   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5452     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5453            << From->getType() << From->getSourceRange();
5454   return ExprError();
5455 }
5456 
5457 /// Check that the specified conversion is permitted in a converted constant
5458 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5459 /// is acceptable.
5460 static bool CheckConvertedConstantConversions(Sema &S,
5461                                               StandardConversionSequence &SCS) {
5462   // Since we know that the target type is an integral or unscoped enumeration
5463   // type, most conversion kinds are impossible. All possible First and Third
5464   // conversions are fine.
5465   switch (SCS.Second) {
5466   case ICK_Identity:
5467   case ICK_Function_Conversion:
5468   case ICK_Integral_Promotion:
5469   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5470   case ICK_Zero_Queue_Conversion:
5471     return true;
5472 
5473   case ICK_Boolean_Conversion:
5474     // Conversion from an integral or unscoped enumeration type to bool is
5475     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5476     // conversion, so we allow it in a converted constant expression.
5477     //
5478     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5479     // a lot of popular code. We should at least add a warning for this
5480     // (non-conforming) extension.
5481     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5482            SCS.getToType(2)->isBooleanType();
5483 
5484   case ICK_Pointer_Conversion:
5485   case ICK_Pointer_Member:
5486     // C++1z: null pointer conversions and null member pointer conversions are
5487     // only permitted if the source type is std::nullptr_t.
5488     return SCS.getFromType()->isNullPtrType();
5489 
5490   case ICK_Floating_Promotion:
5491   case ICK_Complex_Promotion:
5492   case ICK_Floating_Conversion:
5493   case ICK_Complex_Conversion:
5494   case ICK_Floating_Integral:
5495   case ICK_Compatible_Conversion:
5496   case ICK_Derived_To_Base:
5497   case ICK_Vector_Conversion:
5498   case ICK_Vector_Splat:
5499   case ICK_Complex_Real:
5500   case ICK_Block_Pointer_Conversion:
5501   case ICK_TransparentUnionConversion:
5502   case ICK_Writeback_Conversion:
5503   case ICK_Zero_Event_Conversion:
5504   case ICK_C_Only_Conversion:
5505   case ICK_Incompatible_Pointer_Conversion:
5506     return false;
5507 
5508   case ICK_Lvalue_To_Rvalue:
5509   case ICK_Array_To_Pointer:
5510   case ICK_Function_To_Pointer:
5511     llvm_unreachable("found a first conversion kind in Second");
5512 
5513   case ICK_Qualification:
5514     llvm_unreachable("found a third conversion kind in Second");
5515 
5516   case ICK_Num_Conversion_Kinds:
5517     break;
5518   }
5519 
5520   llvm_unreachable("unknown conversion kind");
5521 }
5522 
5523 /// CheckConvertedConstantExpression - Check that the expression From is a
5524 /// converted constant expression of type T, perform the conversion and produce
5525 /// the converted expression, per C++11 [expr.const]p3.
5526 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5527                                                    QualType T, APValue &Value,
5528                                                    Sema::CCEKind CCE,
5529                                                    bool RequireInt) {
5530   assert(S.getLangOpts().CPlusPlus11 &&
5531          "converted constant expression outside C++11");
5532 
5533   if (checkPlaceholderForOverload(S, From))
5534     return ExprError();
5535 
5536   // C++1z [expr.const]p3:
5537   //  A converted constant expression of type T is an expression,
5538   //  implicitly converted to type T, where the converted
5539   //  expression is a constant expression and the implicit conversion
5540   //  sequence contains only [... list of conversions ...].
5541   // C++1z [stmt.if]p2:
5542   //  If the if statement is of the form if constexpr, the value of the
5543   //  condition shall be a contextually converted constant expression of type
5544   //  bool.
5545   ImplicitConversionSequence ICS =
5546       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5547           ? TryContextuallyConvertToBool(S, From)
5548           : TryCopyInitialization(S, From, T,
5549                                   /*SuppressUserConversions=*/false,
5550                                   /*InOverloadResolution=*/false,
5551                                   /*AllowObjCWritebackConversion=*/false,
5552                                   /*AllowExplicit=*/false);
5553   StandardConversionSequence *SCS = nullptr;
5554   switch (ICS.getKind()) {
5555   case ImplicitConversionSequence::StandardConversion:
5556     SCS = &ICS.Standard;
5557     break;
5558   case ImplicitConversionSequence::UserDefinedConversion:
5559     // We are converting to a non-class type, so the Before sequence
5560     // must be trivial.
5561     SCS = &ICS.UserDefined.After;
5562     break;
5563   case ImplicitConversionSequence::AmbiguousConversion:
5564   case ImplicitConversionSequence::BadConversion:
5565     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5566       return S.Diag(From->getBeginLoc(),
5567                     diag::err_typecheck_converted_constant_expression)
5568              << From->getType() << From->getSourceRange() << T;
5569     return ExprError();
5570 
5571   case ImplicitConversionSequence::EllipsisConversion:
5572     llvm_unreachable("ellipsis conversion in converted constant expression");
5573   }
5574 
5575   // Check that we would only use permitted conversions.
5576   if (!CheckConvertedConstantConversions(S, *SCS)) {
5577     return S.Diag(From->getBeginLoc(),
5578                   diag::err_typecheck_converted_constant_expression_disallowed)
5579            << From->getType() << From->getSourceRange() << T;
5580   }
5581   // [...] and where the reference binding (if any) binds directly.
5582   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5583     return S.Diag(From->getBeginLoc(),
5584                   diag::err_typecheck_converted_constant_expression_indirect)
5585            << From->getType() << From->getSourceRange() << T;
5586   }
5587 
5588   ExprResult Result =
5589       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5590   if (Result.isInvalid())
5591     return Result;
5592 
5593   // C++2a [intro.execution]p5:
5594   //   A full-expression is [...] a constant-expression [...]
5595   Result =
5596       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5597                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5598   if (Result.isInvalid())
5599     return Result;
5600 
5601   // Check for a narrowing implicit conversion.
5602   APValue PreNarrowingValue;
5603   QualType PreNarrowingType;
5604   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5605                                 PreNarrowingType)) {
5606   case NK_Dependent_Narrowing:
5607     // Implicit conversion to a narrower type, but the expression is
5608     // value-dependent so we can't tell whether it's actually narrowing.
5609   case NK_Variable_Narrowing:
5610     // Implicit conversion to a narrower type, and the value is not a constant
5611     // expression. We'll diagnose this in a moment.
5612   case NK_Not_Narrowing:
5613     break;
5614 
5615   case NK_Constant_Narrowing:
5616     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5617         << CCE << /*Constant*/ 1
5618         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5619     break;
5620 
5621   case NK_Type_Narrowing:
5622     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5623         << CCE << /*Constant*/ 0 << From->getType() << T;
5624     break;
5625   }
5626 
5627   if (Result.get()->isValueDependent()) {
5628     Value = APValue();
5629     return Result;
5630   }
5631 
5632   // Check the expression is a constant expression.
5633   SmallVector<PartialDiagnosticAt, 8> Notes;
5634   Expr::EvalResult Eval;
5635   Eval.Diag = &Notes;
5636   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5637                                    ? Expr::EvaluateForMangling
5638                                    : Expr::EvaluateForCodeGen;
5639 
5640   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5641       (RequireInt && !Eval.Val.isInt())) {
5642     // The expression can't be folded, so we can't keep it at this position in
5643     // the AST.
5644     Result = ExprError();
5645   } else {
5646     Value = Eval.Val;
5647 
5648     if (Notes.empty()) {
5649       // It's a constant expression.
5650       return ConstantExpr::Create(S.Context, Result.get(), Value);
5651     }
5652   }
5653 
5654   // It's not a constant expression. Produce an appropriate diagnostic.
5655   if (Notes.size() == 1 &&
5656       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5657     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5658   else {
5659     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5660         << CCE << From->getSourceRange();
5661     for (unsigned I = 0; I < Notes.size(); ++I)
5662       S.Diag(Notes[I].first, Notes[I].second);
5663   }
5664   return ExprError();
5665 }
5666 
5667 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5668                                                   APValue &Value, CCEKind CCE) {
5669   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5670 }
5671 
5672 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5673                                                   llvm::APSInt &Value,
5674                                                   CCEKind CCE) {
5675   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5676 
5677   APValue V;
5678   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5679   if (!R.isInvalid() && !R.get()->isValueDependent())
5680     Value = V.getInt();
5681   return R;
5682 }
5683 
5684 
5685 /// dropPointerConversions - If the given standard conversion sequence
5686 /// involves any pointer conversions, remove them.  This may change
5687 /// the result type of the conversion sequence.
5688 static void dropPointerConversion(StandardConversionSequence &SCS) {
5689   if (SCS.Second == ICK_Pointer_Conversion) {
5690     SCS.Second = ICK_Identity;
5691     SCS.Third = ICK_Identity;
5692     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5693   }
5694 }
5695 
5696 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5697 /// convert the expression From to an Objective-C pointer type.
5698 static ImplicitConversionSequence
5699 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5700   // Do an implicit conversion to 'id'.
5701   QualType Ty = S.Context.getObjCIdType();
5702   ImplicitConversionSequence ICS
5703     = TryImplicitConversion(S, From, Ty,
5704                             // FIXME: Are these flags correct?
5705                             /*SuppressUserConversions=*/false,
5706                             /*AllowExplicit=*/true,
5707                             /*InOverloadResolution=*/false,
5708                             /*CStyle=*/false,
5709                             /*AllowObjCWritebackConversion=*/false,
5710                             /*AllowObjCConversionOnExplicit=*/true);
5711 
5712   // Strip off any final conversions to 'id'.
5713   switch (ICS.getKind()) {
5714   case ImplicitConversionSequence::BadConversion:
5715   case ImplicitConversionSequence::AmbiguousConversion:
5716   case ImplicitConversionSequence::EllipsisConversion:
5717     break;
5718 
5719   case ImplicitConversionSequence::UserDefinedConversion:
5720     dropPointerConversion(ICS.UserDefined.After);
5721     break;
5722 
5723   case ImplicitConversionSequence::StandardConversion:
5724     dropPointerConversion(ICS.Standard);
5725     break;
5726   }
5727 
5728   return ICS;
5729 }
5730 
5731 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5732 /// conversion of the expression From to an Objective-C pointer type.
5733 /// Returns a valid but null ExprResult if no conversion sequence exists.
5734 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5735   if (checkPlaceholderForOverload(*this, From))
5736     return ExprError();
5737 
5738   QualType Ty = Context.getObjCIdType();
5739   ImplicitConversionSequence ICS =
5740     TryContextuallyConvertToObjCPointer(*this, From);
5741   if (!ICS.isBad())
5742     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5743   return ExprResult();
5744 }
5745 
5746 /// Determine whether the provided type is an integral type, or an enumeration
5747 /// type of a permitted flavor.
5748 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5749   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5750                                  : T->isIntegralOrUnscopedEnumerationType();
5751 }
5752 
5753 static ExprResult
5754 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5755                             Sema::ContextualImplicitConverter &Converter,
5756                             QualType T, UnresolvedSetImpl &ViableConversions) {
5757 
5758   if (Converter.Suppress)
5759     return ExprError();
5760 
5761   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5762   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5763     CXXConversionDecl *Conv =
5764         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5765     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5766     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5767   }
5768   return From;
5769 }
5770 
5771 static bool
5772 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5773                            Sema::ContextualImplicitConverter &Converter,
5774                            QualType T, bool HadMultipleCandidates,
5775                            UnresolvedSetImpl &ExplicitConversions) {
5776   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5777     DeclAccessPair Found = ExplicitConversions[0];
5778     CXXConversionDecl *Conversion =
5779         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5780 
5781     // The user probably meant to invoke the given explicit
5782     // conversion; use it.
5783     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5784     std::string TypeStr;
5785     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5786 
5787     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5788         << FixItHint::CreateInsertion(From->getBeginLoc(),
5789                                       "static_cast<" + TypeStr + ">(")
5790         << FixItHint::CreateInsertion(
5791                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5792     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5793 
5794     // If we aren't in a SFINAE context, build a call to the
5795     // explicit conversion function.
5796     if (SemaRef.isSFINAEContext())
5797       return true;
5798 
5799     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5800     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5801                                                        HadMultipleCandidates);
5802     if (Result.isInvalid())
5803       return true;
5804     // Record usage of conversion in an implicit cast.
5805     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5806                                     CK_UserDefinedConversion, Result.get(),
5807                                     nullptr, Result.get()->getValueKind());
5808   }
5809   return false;
5810 }
5811 
5812 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5813                              Sema::ContextualImplicitConverter &Converter,
5814                              QualType T, bool HadMultipleCandidates,
5815                              DeclAccessPair &Found) {
5816   CXXConversionDecl *Conversion =
5817       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5818   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5819 
5820   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5821   if (!Converter.SuppressConversion) {
5822     if (SemaRef.isSFINAEContext())
5823       return true;
5824 
5825     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5826         << From->getSourceRange();
5827   }
5828 
5829   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5830                                                      HadMultipleCandidates);
5831   if (Result.isInvalid())
5832     return true;
5833   // Record usage of conversion in an implicit cast.
5834   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5835                                   CK_UserDefinedConversion, Result.get(),
5836                                   nullptr, Result.get()->getValueKind());
5837   return false;
5838 }
5839 
5840 static ExprResult finishContextualImplicitConversion(
5841     Sema &SemaRef, SourceLocation Loc, Expr *From,
5842     Sema::ContextualImplicitConverter &Converter) {
5843   if (!Converter.match(From->getType()) && !Converter.Suppress)
5844     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5845         << From->getSourceRange();
5846 
5847   return SemaRef.DefaultLvalueConversion(From);
5848 }
5849 
5850 static void
5851 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5852                                   UnresolvedSetImpl &ViableConversions,
5853                                   OverloadCandidateSet &CandidateSet) {
5854   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5855     DeclAccessPair FoundDecl = ViableConversions[I];
5856     NamedDecl *D = FoundDecl.getDecl();
5857     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5858     if (isa<UsingShadowDecl>(D))
5859       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5860 
5861     CXXConversionDecl *Conv;
5862     FunctionTemplateDecl *ConvTemplate;
5863     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5864       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5865     else
5866       Conv = cast<CXXConversionDecl>(D);
5867 
5868     if (ConvTemplate)
5869       SemaRef.AddTemplateConversionCandidate(
5870           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5871           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5872     else
5873       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5874                                      ToType, CandidateSet,
5875                                      /*AllowObjCConversionOnExplicit=*/false,
5876                                      /*AllowExplicit*/ true);
5877   }
5878 }
5879 
5880 /// Attempt to convert the given expression to a type which is accepted
5881 /// by the given converter.
5882 ///
5883 /// This routine will attempt to convert an expression of class type to a
5884 /// type accepted by the specified converter. In C++11 and before, the class
5885 /// must have a single non-explicit conversion function converting to a matching
5886 /// type. In C++1y, there can be multiple such conversion functions, but only
5887 /// one target type.
5888 ///
5889 /// \param Loc The source location of the construct that requires the
5890 /// conversion.
5891 ///
5892 /// \param From The expression we're converting from.
5893 ///
5894 /// \param Converter Used to control and diagnose the conversion process.
5895 ///
5896 /// \returns The expression, converted to an integral or enumeration type if
5897 /// successful.
5898 ExprResult Sema::PerformContextualImplicitConversion(
5899     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5900   // We can't perform any more checking for type-dependent expressions.
5901   if (From->isTypeDependent())
5902     return From;
5903 
5904   // Process placeholders immediately.
5905   if (From->hasPlaceholderType()) {
5906     ExprResult result = CheckPlaceholderExpr(From);
5907     if (result.isInvalid())
5908       return result;
5909     From = result.get();
5910   }
5911 
5912   // If the expression already has a matching type, we're golden.
5913   QualType T = From->getType();
5914   if (Converter.match(T))
5915     return DefaultLvalueConversion(From);
5916 
5917   // FIXME: Check for missing '()' if T is a function type?
5918 
5919   // We can only perform contextual implicit conversions on objects of class
5920   // type.
5921   const RecordType *RecordTy = T->getAs<RecordType>();
5922   if (!RecordTy || !getLangOpts().CPlusPlus) {
5923     if (!Converter.Suppress)
5924       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5925     return From;
5926   }
5927 
5928   // We must have a complete class type.
5929   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5930     ContextualImplicitConverter &Converter;
5931     Expr *From;
5932 
5933     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5934         : Converter(Converter), From(From) {}
5935 
5936     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5937       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5938     }
5939   } IncompleteDiagnoser(Converter, From);
5940 
5941   if (Converter.Suppress ? !isCompleteType(Loc, T)
5942                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5943     return From;
5944 
5945   // Look for a conversion to an integral or enumeration type.
5946   UnresolvedSet<4>
5947       ViableConversions; // These are *potentially* viable in C++1y.
5948   UnresolvedSet<4> ExplicitConversions;
5949   const auto &Conversions =
5950       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5951 
5952   bool HadMultipleCandidates =
5953       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5954 
5955   // To check that there is only one target type, in C++1y:
5956   QualType ToType;
5957   bool HasUniqueTargetType = true;
5958 
5959   // Collect explicit or viable (potentially in C++1y) conversions.
5960   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5961     NamedDecl *D = (*I)->getUnderlyingDecl();
5962     CXXConversionDecl *Conversion;
5963     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5964     if (ConvTemplate) {
5965       if (getLangOpts().CPlusPlus14)
5966         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5967       else
5968         continue; // C++11 does not consider conversion operator templates(?).
5969     } else
5970       Conversion = cast<CXXConversionDecl>(D);
5971 
5972     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5973            "Conversion operator templates are considered potentially "
5974            "viable in C++1y");
5975 
5976     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5977     if (Converter.match(CurToType) || ConvTemplate) {
5978 
5979       if (Conversion->isExplicit()) {
5980         // FIXME: For C++1y, do we need this restriction?
5981         // cf. diagnoseNoViableConversion()
5982         if (!ConvTemplate)
5983           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5984       } else {
5985         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5986           if (ToType.isNull())
5987             ToType = CurToType.getUnqualifiedType();
5988           else if (HasUniqueTargetType &&
5989                    (CurToType.getUnqualifiedType() != ToType))
5990             HasUniqueTargetType = false;
5991         }
5992         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5993       }
5994     }
5995   }
5996 
5997   if (getLangOpts().CPlusPlus14) {
5998     // C++1y [conv]p6:
5999     // ... An expression e of class type E appearing in such a context
6000     // is said to be contextually implicitly converted to a specified
6001     // type T and is well-formed if and only if e can be implicitly
6002     // converted to a type T that is determined as follows: E is searched
6003     // for conversion functions whose return type is cv T or reference to
6004     // cv T such that T is allowed by the context. There shall be
6005     // exactly one such T.
6006 
6007     // If no unique T is found:
6008     if (ToType.isNull()) {
6009       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6010                                      HadMultipleCandidates,
6011                                      ExplicitConversions))
6012         return ExprError();
6013       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6014     }
6015 
6016     // If more than one unique Ts are found:
6017     if (!HasUniqueTargetType)
6018       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6019                                          ViableConversions);
6020 
6021     // If one unique T is found:
6022     // First, build a candidate set from the previously recorded
6023     // potentially viable conversions.
6024     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6025     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6026                                       CandidateSet);
6027 
6028     // Then, perform overload resolution over the candidate set.
6029     OverloadCandidateSet::iterator Best;
6030     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6031     case OR_Success: {
6032       // Apply this conversion.
6033       DeclAccessPair Found =
6034           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6035       if (recordConversion(*this, Loc, From, Converter, T,
6036                            HadMultipleCandidates, Found))
6037         return ExprError();
6038       break;
6039     }
6040     case OR_Ambiguous:
6041       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6042                                          ViableConversions);
6043     case OR_No_Viable_Function:
6044       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6045                                      HadMultipleCandidates,
6046                                      ExplicitConversions))
6047         return ExprError();
6048       LLVM_FALLTHROUGH;
6049     case OR_Deleted:
6050       // We'll complain below about a non-integral condition type.
6051       break;
6052     }
6053   } else {
6054     switch (ViableConversions.size()) {
6055     case 0: {
6056       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6057                                      HadMultipleCandidates,
6058                                      ExplicitConversions))
6059         return ExprError();
6060 
6061       // We'll complain below about a non-integral condition type.
6062       break;
6063     }
6064     case 1: {
6065       // Apply this conversion.
6066       DeclAccessPair Found = ViableConversions[0];
6067       if (recordConversion(*this, Loc, From, Converter, T,
6068                            HadMultipleCandidates, Found))
6069         return ExprError();
6070       break;
6071     }
6072     default:
6073       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6074                                          ViableConversions);
6075     }
6076   }
6077 
6078   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6079 }
6080 
6081 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6082 /// an acceptable non-member overloaded operator for a call whose
6083 /// arguments have types T1 (and, if non-empty, T2). This routine
6084 /// implements the check in C++ [over.match.oper]p3b2 concerning
6085 /// enumeration types.
6086 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6087                                                    FunctionDecl *Fn,
6088                                                    ArrayRef<Expr *> Args) {
6089   QualType T1 = Args[0]->getType();
6090   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6091 
6092   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6093     return true;
6094 
6095   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6096     return true;
6097 
6098   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6099   if (Proto->getNumParams() < 1)
6100     return false;
6101 
6102   if (T1->isEnumeralType()) {
6103     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6104     if (Context.hasSameUnqualifiedType(T1, ArgType))
6105       return true;
6106   }
6107 
6108   if (Proto->getNumParams() < 2)
6109     return false;
6110 
6111   if (!T2.isNull() && T2->isEnumeralType()) {
6112     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6113     if (Context.hasSameUnqualifiedType(T2, ArgType))
6114       return true;
6115   }
6116 
6117   return false;
6118 }
6119 
6120 /// AddOverloadCandidate - Adds the given function to the set of
6121 /// candidate functions, using the given function call arguments.  If
6122 /// @p SuppressUserConversions, then don't allow user-defined
6123 /// conversions via constructors or conversion operators.
6124 ///
6125 /// \param PartialOverloading true if we are performing "partial" overloading
6126 /// based on an incomplete set of function arguments. This feature is used by
6127 /// code completion.
6128 void Sema::AddOverloadCandidate(
6129     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6130     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6131     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6132     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6133     OverloadCandidateParamOrder PO) {
6134   const FunctionProtoType *Proto
6135     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6136   assert(Proto && "Functions without a prototype cannot be overloaded");
6137   assert(!Function->getDescribedFunctionTemplate() &&
6138          "Use AddTemplateOverloadCandidate for function templates");
6139 
6140   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6141     if (!isa<CXXConstructorDecl>(Method)) {
6142       // If we get here, it's because we're calling a member function
6143       // that is named without a member access expression (e.g.,
6144       // "this->f") that was either written explicitly or created
6145       // implicitly. This can happen with a qualified call to a member
6146       // function, e.g., X::f(). We use an empty type for the implied
6147       // object argument (C++ [over.call.func]p3), and the acting context
6148       // is irrelevant.
6149       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6150                          Expr::Classification::makeSimpleLValue(), Args,
6151                          CandidateSet, SuppressUserConversions,
6152                          PartialOverloading, EarlyConversions, PO);
6153       return;
6154     }
6155     // We treat a constructor like a non-member function, since its object
6156     // argument doesn't participate in overload resolution.
6157   }
6158 
6159   if (!CandidateSet.isNewCandidate(Function, PO))
6160     return;
6161 
6162   // C++11 [class.copy]p11: [DR1402]
6163   //   A defaulted move constructor that is defined as deleted is ignored by
6164   //   overload resolution.
6165   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6166   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6167       Constructor->isMoveConstructor())
6168     return;
6169 
6170   // Overload resolution is always an unevaluated context.
6171   EnterExpressionEvaluationContext Unevaluated(
6172       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6173 
6174   // C++ [over.match.oper]p3:
6175   //   if no operand has a class type, only those non-member functions in the
6176   //   lookup set that have a first parameter of type T1 or "reference to
6177   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6178   //   is a right operand) a second parameter of type T2 or "reference to
6179   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6180   //   candidate functions.
6181   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6182       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6183     return;
6184 
6185   // Add this candidate
6186   OverloadCandidate &Candidate =
6187       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6188   Candidate.FoundDecl = FoundDecl;
6189   Candidate.Function = Function;
6190   Candidate.Viable = true;
6191   Candidate.RewriteKind =
6192       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6193   Candidate.IsSurrogate = false;
6194   Candidate.IsADLCandidate = IsADLCandidate;
6195   Candidate.IgnoreObjectArgument = false;
6196   Candidate.ExplicitCallArguments = Args.size();
6197 
6198   // Explicit functions are not actually candidates at all if we're not
6199   // allowing them in this context, but keep them around so we can point
6200   // to them in diagnostics.
6201   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6202     Candidate.Viable = false;
6203     Candidate.FailureKind = ovl_fail_explicit;
6204     return;
6205   }
6206 
6207   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6208       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6209     Candidate.Viable = false;
6210     Candidate.FailureKind = ovl_non_default_multiversion_function;
6211     return;
6212   }
6213 
6214   if (Constructor) {
6215     // C++ [class.copy]p3:
6216     //   A member function template is never instantiated to perform the copy
6217     //   of a class object to an object of its class type.
6218     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6219     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6220         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6221          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6222                        ClassType))) {
6223       Candidate.Viable = false;
6224       Candidate.FailureKind = ovl_fail_illegal_constructor;
6225       return;
6226     }
6227 
6228     // C++ [over.match.funcs]p8: (proposed DR resolution)
6229     //   A constructor inherited from class type C that has a first parameter
6230     //   of type "reference to P" (including such a constructor instantiated
6231     //   from a template) is excluded from the set of candidate functions when
6232     //   constructing an object of type cv D if the argument list has exactly
6233     //   one argument and D is reference-related to P and P is reference-related
6234     //   to C.
6235     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6236     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6237         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6238       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6239       QualType C = Context.getRecordType(Constructor->getParent());
6240       QualType D = Context.getRecordType(Shadow->getParent());
6241       SourceLocation Loc = Args.front()->getExprLoc();
6242       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6243           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6244         Candidate.Viable = false;
6245         Candidate.FailureKind = ovl_fail_inhctor_slice;
6246         return;
6247       }
6248     }
6249 
6250     // Check that the constructor is capable of constructing an object in the
6251     // destination address space.
6252     if (!Qualifiers::isAddressSpaceSupersetOf(
6253             Constructor->getMethodQualifiers().getAddressSpace(),
6254             CandidateSet.getDestAS())) {
6255       Candidate.Viable = false;
6256       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6257     }
6258   }
6259 
6260   unsigned NumParams = Proto->getNumParams();
6261 
6262   // (C++ 13.3.2p2): A candidate function having fewer than m
6263   // parameters is viable only if it has an ellipsis in its parameter
6264   // list (8.3.5).
6265   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6266       !Proto->isVariadic()) {
6267     Candidate.Viable = false;
6268     Candidate.FailureKind = ovl_fail_too_many_arguments;
6269     return;
6270   }
6271 
6272   // (C++ 13.3.2p2): A candidate function having more than m parameters
6273   // is viable only if the (m+1)st parameter has a default argument
6274   // (8.3.6). For the purposes of overload resolution, the
6275   // parameter list is truncated on the right, so that there are
6276   // exactly m parameters.
6277   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6278   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6279     // Not enough arguments.
6280     Candidate.Viable = false;
6281     Candidate.FailureKind = ovl_fail_too_few_arguments;
6282     return;
6283   }
6284 
6285   // (CUDA B.1): Check for invalid calls between targets.
6286   if (getLangOpts().CUDA)
6287     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6288       // Skip the check for callers that are implicit members, because in this
6289       // case we may not yet know what the member's target is; the target is
6290       // inferred for the member automatically, based on the bases and fields of
6291       // the class.
6292       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6293         Candidate.Viable = false;
6294         Candidate.FailureKind = ovl_fail_bad_target;
6295         return;
6296       }
6297 
6298   if (Expr *RequiresClause = Function->getTrailingRequiresClause()) {
6299     ConstraintSatisfaction Satisfaction;
6300     if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6301         !Satisfaction.IsSatisfied) {
6302       Candidate.Viable = false;
6303       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6304       return;
6305     }
6306   }
6307 
6308   // Determine the implicit conversion sequences for each of the
6309   // arguments.
6310   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6311     unsigned ConvIdx =
6312         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6313     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6314       // We already formed a conversion sequence for this parameter during
6315       // template argument deduction.
6316     } else if (ArgIdx < NumParams) {
6317       // (C++ 13.3.2p3): for F to be a viable function, there shall
6318       // exist for each argument an implicit conversion sequence
6319       // (13.3.3.1) that converts that argument to the corresponding
6320       // parameter of F.
6321       QualType ParamType = Proto->getParamType(ArgIdx);
6322       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6323           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6324           /*InOverloadResolution=*/true,
6325           /*AllowObjCWritebackConversion=*/
6326           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6327       if (Candidate.Conversions[ConvIdx].isBad()) {
6328         Candidate.Viable = false;
6329         Candidate.FailureKind = ovl_fail_bad_conversion;
6330         return;
6331       }
6332     } else {
6333       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6334       // argument for which there is no corresponding parameter is
6335       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6336       Candidate.Conversions[ConvIdx].setEllipsis();
6337     }
6338   }
6339 
6340   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6341     Candidate.Viable = false;
6342     Candidate.FailureKind = ovl_fail_enable_if;
6343     Candidate.DeductionFailure.Data = FailedAttr;
6344     return;
6345   }
6346 
6347   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6348     Candidate.Viable = false;
6349     Candidate.FailureKind = ovl_fail_ext_disabled;
6350     return;
6351   }
6352 }
6353 
6354 ObjCMethodDecl *
6355 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6356                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6357   if (Methods.size() <= 1)
6358     return nullptr;
6359 
6360   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6361     bool Match = true;
6362     ObjCMethodDecl *Method = Methods[b];
6363     unsigned NumNamedArgs = Sel.getNumArgs();
6364     // Method might have more arguments than selector indicates. This is due
6365     // to addition of c-style arguments in method.
6366     if (Method->param_size() > NumNamedArgs)
6367       NumNamedArgs = Method->param_size();
6368     if (Args.size() < NumNamedArgs)
6369       continue;
6370 
6371     for (unsigned i = 0; i < NumNamedArgs; i++) {
6372       // We can't do any type-checking on a type-dependent argument.
6373       if (Args[i]->isTypeDependent()) {
6374         Match = false;
6375         break;
6376       }
6377 
6378       ParmVarDecl *param = Method->parameters()[i];
6379       Expr *argExpr = Args[i];
6380       assert(argExpr && "SelectBestMethod(): missing expression");
6381 
6382       // Strip the unbridged-cast placeholder expression off unless it's
6383       // a consumed argument.
6384       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6385           !param->hasAttr<CFConsumedAttr>())
6386         argExpr = stripARCUnbridgedCast(argExpr);
6387 
6388       // If the parameter is __unknown_anytype, move on to the next method.
6389       if (param->getType() == Context.UnknownAnyTy) {
6390         Match = false;
6391         break;
6392       }
6393 
6394       ImplicitConversionSequence ConversionState
6395         = TryCopyInitialization(*this, argExpr, param->getType(),
6396                                 /*SuppressUserConversions*/false,
6397                                 /*InOverloadResolution=*/true,
6398                                 /*AllowObjCWritebackConversion=*/
6399                                 getLangOpts().ObjCAutoRefCount,
6400                                 /*AllowExplicit*/false);
6401       // This function looks for a reasonably-exact match, so we consider
6402       // incompatible pointer conversions to be a failure here.
6403       if (ConversionState.isBad() ||
6404           (ConversionState.isStandard() &&
6405            ConversionState.Standard.Second ==
6406                ICK_Incompatible_Pointer_Conversion)) {
6407         Match = false;
6408         break;
6409       }
6410     }
6411     // Promote additional arguments to variadic methods.
6412     if (Match && Method->isVariadic()) {
6413       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6414         if (Args[i]->isTypeDependent()) {
6415           Match = false;
6416           break;
6417         }
6418         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6419                                                           nullptr);
6420         if (Arg.isInvalid()) {
6421           Match = false;
6422           break;
6423         }
6424       }
6425     } else {
6426       // Check for extra arguments to non-variadic methods.
6427       if (Args.size() != NumNamedArgs)
6428         Match = false;
6429       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6430         // Special case when selectors have no argument. In this case, select
6431         // one with the most general result type of 'id'.
6432         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6433           QualType ReturnT = Methods[b]->getReturnType();
6434           if (ReturnT->isObjCIdType())
6435             return Methods[b];
6436         }
6437       }
6438     }
6439 
6440     if (Match)
6441       return Method;
6442   }
6443   return nullptr;
6444 }
6445 
6446 static bool
6447 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6448                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6449                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6450                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6451   if (ThisArg) {
6452     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6453     assert(!isa<CXXConstructorDecl>(Method) &&
6454            "Shouldn't have `this` for ctors!");
6455     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6456     ExprResult R = S.PerformObjectArgumentInitialization(
6457         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6458     if (R.isInvalid())
6459       return false;
6460     ConvertedThis = R.get();
6461   } else {
6462     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6463       (void)MD;
6464       assert((MissingImplicitThis || MD->isStatic() ||
6465               isa<CXXConstructorDecl>(MD)) &&
6466              "Expected `this` for non-ctor instance methods");
6467     }
6468     ConvertedThis = nullptr;
6469   }
6470 
6471   // Ignore any variadic arguments. Converting them is pointless, since the
6472   // user can't refer to them in the function condition.
6473   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6474 
6475   // Convert the arguments.
6476   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6477     ExprResult R;
6478     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6479                                         S.Context, Function->getParamDecl(I)),
6480                                     SourceLocation(), Args[I]);
6481 
6482     if (R.isInvalid())
6483       return false;
6484 
6485     ConvertedArgs.push_back(R.get());
6486   }
6487 
6488   if (Trap.hasErrorOccurred())
6489     return false;
6490 
6491   // Push default arguments if needed.
6492   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6493     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6494       ParmVarDecl *P = Function->getParamDecl(i);
6495       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6496                          ? P->getUninstantiatedDefaultArg()
6497                          : P->getDefaultArg();
6498       // This can only happen in code completion, i.e. when PartialOverloading
6499       // is true.
6500       if (!DefArg)
6501         return false;
6502       ExprResult R =
6503           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6504                                           S.Context, Function->getParamDecl(i)),
6505                                       SourceLocation(), DefArg);
6506       if (R.isInvalid())
6507         return false;
6508       ConvertedArgs.push_back(R.get());
6509     }
6510 
6511     if (Trap.hasErrorOccurred())
6512       return false;
6513   }
6514   return true;
6515 }
6516 
6517 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6518                                   bool MissingImplicitThis) {
6519   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6520   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6521     return nullptr;
6522 
6523   SFINAETrap Trap(*this);
6524   SmallVector<Expr *, 16> ConvertedArgs;
6525   // FIXME: We should look into making enable_if late-parsed.
6526   Expr *DiscardedThis;
6527   if (!convertArgsForAvailabilityChecks(
6528           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6529           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6530     return *EnableIfAttrs.begin();
6531 
6532   for (auto *EIA : EnableIfAttrs) {
6533     APValue Result;
6534     // FIXME: This doesn't consider value-dependent cases, because doing so is
6535     // very difficult. Ideally, we should handle them more gracefully.
6536     if (EIA->getCond()->isValueDependent() ||
6537         !EIA->getCond()->EvaluateWithSubstitution(
6538             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6539       return EIA;
6540 
6541     if (!Result.isInt() || !Result.getInt().getBoolValue())
6542       return EIA;
6543   }
6544   return nullptr;
6545 }
6546 
6547 template <typename CheckFn>
6548 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6549                                         bool ArgDependent, SourceLocation Loc,
6550                                         CheckFn &&IsSuccessful) {
6551   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6552   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6553     if (ArgDependent == DIA->getArgDependent())
6554       Attrs.push_back(DIA);
6555   }
6556 
6557   // Common case: No diagnose_if attributes, so we can quit early.
6558   if (Attrs.empty())
6559     return false;
6560 
6561   auto WarningBegin = std::stable_partition(
6562       Attrs.begin(), Attrs.end(),
6563       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6564 
6565   // Note that diagnose_if attributes are late-parsed, so they appear in the
6566   // correct order (unlike enable_if attributes).
6567   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6568                                IsSuccessful);
6569   if (ErrAttr != WarningBegin) {
6570     const DiagnoseIfAttr *DIA = *ErrAttr;
6571     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6572     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6573         << DIA->getParent() << DIA->getCond()->getSourceRange();
6574     return true;
6575   }
6576 
6577   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6578     if (IsSuccessful(DIA)) {
6579       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6580       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6581           << DIA->getParent() << DIA->getCond()->getSourceRange();
6582     }
6583 
6584   return false;
6585 }
6586 
6587 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6588                                                const Expr *ThisArg,
6589                                                ArrayRef<const Expr *> Args,
6590                                                SourceLocation Loc) {
6591   return diagnoseDiagnoseIfAttrsWith(
6592       *this, Function, /*ArgDependent=*/true, Loc,
6593       [&](const DiagnoseIfAttr *DIA) {
6594         APValue Result;
6595         // It's sane to use the same Args for any redecl of this function, since
6596         // EvaluateWithSubstitution only cares about the position of each
6597         // argument in the arg list, not the ParmVarDecl* it maps to.
6598         if (!DIA->getCond()->EvaluateWithSubstitution(
6599                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6600           return false;
6601         return Result.isInt() && Result.getInt().getBoolValue();
6602       });
6603 }
6604 
6605 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6606                                                  SourceLocation Loc) {
6607   return diagnoseDiagnoseIfAttrsWith(
6608       *this, ND, /*ArgDependent=*/false, Loc,
6609       [&](const DiagnoseIfAttr *DIA) {
6610         bool Result;
6611         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6612                Result;
6613       });
6614 }
6615 
6616 /// Add all of the function declarations in the given function set to
6617 /// the overload candidate set.
6618 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6619                                  ArrayRef<Expr *> Args,
6620                                  OverloadCandidateSet &CandidateSet,
6621                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6622                                  bool SuppressUserConversions,
6623                                  bool PartialOverloading,
6624                                  bool FirstArgumentIsBase) {
6625   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6626     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6627     ArrayRef<Expr *> FunctionArgs = Args;
6628 
6629     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6630     FunctionDecl *FD =
6631         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6632 
6633     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6634       QualType ObjectType;
6635       Expr::Classification ObjectClassification;
6636       if (Args.size() > 0) {
6637         if (Expr *E = Args[0]) {
6638           // Use the explicit base to restrict the lookup:
6639           ObjectType = E->getType();
6640           // Pointers in the object arguments are implicitly dereferenced, so we
6641           // always classify them as l-values.
6642           if (!ObjectType.isNull() && ObjectType->isPointerType())
6643             ObjectClassification = Expr::Classification::makeSimpleLValue();
6644           else
6645             ObjectClassification = E->Classify(Context);
6646         } // .. else there is an implicit base.
6647         FunctionArgs = Args.slice(1);
6648       }
6649       if (FunTmpl) {
6650         AddMethodTemplateCandidate(
6651             FunTmpl, F.getPair(),
6652             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6653             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6654             FunctionArgs, CandidateSet, SuppressUserConversions,
6655             PartialOverloading);
6656       } else {
6657         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6658                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6659                            ObjectClassification, FunctionArgs, CandidateSet,
6660                            SuppressUserConversions, PartialOverloading);
6661       }
6662     } else {
6663       // This branch handles both standalone functions and static methods.
6664 
6665       // Slice the first argument (which is the base) when we access
6666       // static method as non-static.
6667       if (Args.size() > 0 &&
6668           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6669                         !isa<CXXConstructorDecl>(FD)))) {
6670         assert(cast<CXXMethodDecl>(FD)->isStatic());
6671         FunctionArgs = Args.slice(1);
6672       }
6673       if (FunTmpl) {
6674         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6675                                      ExplicitTemplateArgs, FunctionArgs,
6676                                      CandidateSet, SuppressUserConversions,
6677                                      PartialOverloading);
6678       } else {
6679         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6680                              SuppressUserConversions, PartialOverloading);
6681       }
6682     }
6683   }
6684 }
6685 
6686 /// AddMethodCandidate - Adds a named decl (which is some kind of
6687 /// method) as a method candidate to the given overload set.
6688 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6689                               Expr::Classification ObjectClassification,
6690                               ArrayRef<Expr *> Args,
6691                               OverloadCandidateSet &CandidateSet,
6692                               bool SuppressUserConversions,
6693                               OverloadCandidateParamOrder PO) {
6694   NamedDecl *Decl = FoundDecl.getDecl();
6695   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6696 
6697   if (isa<UsingShadowDecl>(Decl))
6698     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6699 
6700   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6701     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6702            "Expected a member function template");
6703     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6704                                /*ExplicitArgs*/ nullptr, ObjectType,
6705                                ObjectClassification, Args, CandidateSet,
6706                                SuppressUserConversions, false, PO);
6707   } else {
6708     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6709                        ObjectType, ObjectClassification, Args, CandidateSet,
6710                        SuppressUserConversions, false, None, PO);
6711   }
6712 }
6713 
6714 /// AddMethodCandidate - Adds the given C++ member function to the set
6715 /// of candidate functions, using the given function call arguments
6716 /// and the object argument (@c Object). For example, in a call
6717 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6718 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6719 /// allow user-defined conversions via constructors or conversion
6720 /// operators.
6721 void
6722 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6723                          CXXRecordDecl *ActingContext, QualType ObjectType,
6724                          Expr::Classification ObjectClassification,
6725                          ArrayRef<Expr *> Args,
6726                          OverloadCandidateSet &CandidateSet,
6727                          bool SuppressUserConversions,
6728                          bool PartialOverloading,
6729                          ConversionSequenceList EarlyConversions,
6730                          OverloadCandidateParamOrder PO) {
6731   const FunctionProtoType *Proto
6732     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6733   assert(Proto && "Methods without a prototype cannot be overloaded");
6734   assert(!isa<CXXConstructorDecl>(Method) &&
6735          "Use AddOverloadCandidate for constructors");
6736 
6737   if (!CandidateSet.isNewCandidate(Method, PO))
6738     return;
6739 
6740   // C++11 [class.copy]p23: [DR1402]
6741   //   A defaulted move assignment operator that is defined as deleted is
6742   //   ignored by overload resolution.
6743   if (Method->isDefaulted() && Method->isDeleted() &&
6744       Method->isMoveAssignmentOperator())
6745     return;
6746 
6747   // Overload resolution is always an unevaluated context.
6748   EnterExpressionEvaluationContext Unevaluated(
6749       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6750 
6751   // Add this candidate
6752   OverloadCandidate &Candidate =
6753       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6754   Candidate.FoundDecl = FoundDecl;
6755   Candidate.Function = Method;
6756   Candidate.RewriteKind =
6757       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6758   Candidate.IsSurrogate = false;
6759   Candidate.IgnoreObjectArgument = false;
6760   Candidate.ExplicitCallArguments = Args.size();
6761 
6762   unsigned NumParams = Proto->getNumParams();
6763 
6764   // (C++ 13.3.2p2): A candidate function having fewer than m
6765   // parameters is viable only if it has an ellipsis in its parameter
6766   // list (8.3.5).
6767   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6768       !Proto->isVariadic()) {
6769     Candidate.Viable = false;
6770     Candidate.FailureKind = ovl_fail_too_many_arguments;
6771     return;
6772   }
6773 
6774   // (C++ 13.3.2p2): A candidate function having more than m parameters
6775   // is viable only if the (m+1)st parameter has a default argument
6776   // (8.3.6). For the purposes of overload resolution, the
6777   // parameter list is truncated on the right, so that there are
6778   // exactly m parameters.
6779   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6780   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6781     // Not enough arguments.
6782     Candidate.Viable = false;
6783     Candidate.FailureKind = ovl_fail_too_few_arguments;
6784     return;
6785   }
6786 
6787   Candidate.Viable = true;
6788 
6789   if (Method->isStatic() || ObjectType.isNull())
6790     // The implicit object argument is ignored.
6791     Candidate.IgnoreObjectArgument = true;
6792   else {
6793     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6794     // Determine the implicit conversion sequence for the object
6795     // parameter.
6796     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6797         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6798         Method, ActingContext);
6799     if (Candidate.Conversions[ConvIdx].isBad()) {
6800       Candidate.Viable = false;
6801       Candidate.FailureKind = ovl_fail_bad_conversion;
6802       return;
6803     }
6804   }
6805 
6806   // (CUDA B.1): Check for invalid calls between targets.
6807   if (getLangOpts().CUDA)
6808     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6809       if (!IsAllowedCUDACall(Caller, Method)) {
6810         Candidate.Viable = false;
6811         Candidate.FailureKind = ovl_fail_bad_target;
6812         return;
6813       }
6814 
6815   if (Expr *RequiresClause = Method->getTrailingRequiresClause()) {
6816     ConstraintSatisfaction Satisfaction;
6817     if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
6818         !Satisfaction.IsSatisfied) {
6819       Candidate.Viable = false;
6820       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6821       return;
6822     }
6823   }
6824 
6825   // Determine the implicit conversion sequences for each of the
6826   // arguments.
6827   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6828     unsigned ConvIdx =
6829         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6830     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6831       // We already formed a conversion sequence for this parameter during
6832       // template argument deduction.
6833     } else if (ArgIdx < NumParams) {
6834       // (C++ 13.3.2p3): for F to be a viable function, there shall
6835       // exist for each argument an implicit conversion sequence
6836       // (13.3.3.1) that converts that argument to the corresponding
6837       // parameter of F.
6838       QualType ParamType = Proto->getParamType(ArgIdx);
6839       Candidate.Conversions[ConvIdx]
6840         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6841                                 SuppressUserConversions,
6842                                 /*InOverloadResolution=*/true,
6843                                 /*AllowObjCWritebackConversion=*/
6844                                   getLangOpts().ObjCAutoRefCount);
6845       if (Candidate.Conversions[ConvIdx].isBad()) {
6846         Candidate.Viable = false;
6847         Candidate.FailureKind = ovl_fail_bad_conversion;
6848         return;
6849       }
6850     } else {
6851       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6852       // argument for which there is no corresponding parameter is
6853       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6854       Candidate.Conversions[ConvIdx].setEllipsis();
6855     }
6856   }
6857 
6858   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6859     Candidate.Viable = false;
6860     Candidate.FailureKind = ovl_fail_enable_if;
6861     Candidate.DeductionFailure.Data = FailedAttr;
6862     return;
6863   }
6864 
6865   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6866       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6867     Candidate.Viable = false;
6868     Candidate.FailureKind = ovl_non_default_multiversion_function;
6869   }
6870 }
6871 
6872 /// Add a C++ member function template as a candidate to the candidate
6873 /// set, using template argument deduction to produce an appropriate member
6874 /// function template specialization.
6875 void Sema::AddMethodTemplateCandidate(
6876     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6877     CXXRecordDecl *ActingContext,
6878     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6879     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6880     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6881     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6882   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6883     return;
6884 
6885   // C++ [over.match.funcs]p7:
6886   //   In each case where a candidate is a function template, candidate
6887   //   function template specializations are generated using template argument
6888   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6889   //   candidate functions in the usual way.113) A given name can refer to one
6890   //   or more function templates and also to a set of overloaded non-template
6891   //   functions. In such a case, the candidate functions generated from each
6892   //   function template are combined with the set of non-template candidate
6893   //   functions.
6894   TemplateDeductionInfo Info(CandidateSet.getLocation());
6895   FunctionDecl *Specialization = nullptr;
6896   ConversionSequenceList Conversions;
6897   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6898           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6899           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6900             return CheckNonDependentConversions(
6901                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6902                 SuppressUserConversions, ActingContext, ObjectType,
6903                 ObjectClassification, PO);
6904           })) {
6905     OverloadCandidate &Candidate =
6906         CandidateSet.addCandidate(Conversions.size(), Conversions);
6907     Candidate.FoundDecl = FoundDecl;
6908     Candidate.Function = MethodTmpl->getTemplatedDecl();
6909     Candidate.Viable = false;
6910     Candidate.RewriteKind =
6911       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6912     Candidate.IsSurrogate = false;
6913     Candidate.IgnoreObjectArgument =
6914         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6915         ObjectType.isNull();
6916     Candidate.ExplicitCallArguments = Args.size();
6917     if (Result == TDK_NonDependentConversionFailure)
6918       Candidate.FailureKind = ovl_fail_bad_conversion;
6919     else {
6920       Candidate.FailureKind = ovl_fail_bad_deduction;
6921       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6922                                                             Info);
6923     }
6924     return;
6925   }
6926 
6927   // Add the function template specialization produced by template argument
6928   // deduction as a candidate.
6929   assert(Specialization && "Missing member function template specialization?");
6930   assert(isa<CXXMethodDecl>(Specialization) &&
6931          "Specialization is not a member function?");
6932   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6933                      ActingContext, ObjectType, ObjectClassification, Args,
6934                      CandidateSet, SuppressUserConversions, PartialOverloading,
6935                      Conversions, PO);
6936 }
6937 
6938 /// Determine whether a given function template has a simple explicit specifier
6939 /// or a non-value-dependent explicit-specification that evaluates to true.
6940 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6941   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6942 }
6943 
6944 /// Add a C++ function template specialization as a candidate
6945 /// in the candidate set, using template argument deduction to produce
6946 /// an appropriate function template specialization.
6947 void Sema::AddTemplateOverloadCandidate(
6948     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6949     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6950     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6951     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6952     OverloadCandidateParamOrder PO) {
6953   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6954     return;
6955 
6956   // If the function template has a non-dependent explicit specification,
6957   // exclude it now if appropriate; we are not permitted to perform deduction
6958   // and substitution in this case.
6959   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6960     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6961     Candidate.FoundDecl = FoundDecl;
6962     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6963     Candidate.Viable = false;
6964     Candidate.FailureKind = ovl_fail_explicit;
6965     return;
6966   }
6967 
6968   // C++ [over.match.funcs]p7:
6969   //   In each case where a candidate is a function template, candidate
6970   //   function template specializations are generated using template argument
6971   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6972   //   candidate functions in the usual way.113) A given name can refer to one
6973   //   or more function templates and also to a set of overloaded non-template
6974   //   functions. In such a case, the candidate functions generated from each
6975   //   function template are combined with the set of non-template candidate
6976   //   functions.
6977   TemplateDeductionInfo Info(CandidateSet.getLocation());
6978   FunctionDecl *Specialization = nullptr;
6979   ConversionSequenceList Conversions;
6980   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6981           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6982           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6983             return CheckNonDependentConversions(
6984                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6985                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6986           })) {
6987     OverloadCandidate &Candidate =
6988         CandidateSet.addCandidate(Conversions.size(), Conversions);
6989     Candidate.FoundDecl = FoundDecl;
6990     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6991     Candidate.Viable = false;
6992     Candidate.RewriteKind =
6993       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6994     Candidate.IsSurrogate = false;
6995     Candidate.IsADLCandidate = IsADLCandidate;
6996     // Ignore the object argument if there is one, since we don't have an object
6997     // type.
6998     Candidate.IgnoreObjectArgument =
6999         isa<CXXMethodDecl>(Candidate.Function) &&
7000         !isa<CXXConstructorDecl>(Candidate.Function);
7001     Candidate.ExplicitCallArguments = Args.size();
7002     if (Result == TDK_NonDependentConversionFailure)
7003       Candidate.FailureKind = ovl_fail_bad_conversion;
7004     else {
7005       Candidate.FailureKind = ovl_fail_bad_deduction;
7006       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7007                                                             Info);
7008     }
7009     return;
7010   }
7011 
7012   // Add the function template specialization produced by template argument
7013   // deduction as a candidate.
7014   assert(Specialization && "Missing function template specialization?");
7015   AddOverloadCandidate(
7016       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7017       PartialOverloading, AllowExplicit,
7018       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7019 }
7020 
7021 /// Check that implicit conversion sequences can be formed for each argument
7022 /// whose corresponding parameter has a non-dependent type, per DR1391's
7023 /// [temp.deduct.call]p10.
7024 bool Sema::CheckNonDependentConversions(
7025     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7026     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7027     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7028     CXXRecordDecl *ActingContext, QualType ObjectType,
7029     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7030   // FIXME: The cases in which we allow explicit conversions for constructor
7031   // arguments never consider calling a constructor template. It's not clear
7032   // that is correct.
7033   const bool AllowExplicit = false;
7034 
7035   auto *FD = FunctionTemplate->getTemplatedDecl();
7036   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7037   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7038   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7039 
7040   Conversions =
7041       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7042 
7043   // Overload resolution is always an unevaluated context.
7044   EnterExpressionEvaluationContext Unevaluated(
7045       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7046 
7047   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7048   // require that, but this check should never result in a hard error, and
7049   // overload resolution is permitted to sidestep instantiations.
7050   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7051       !ObjectType.isNull()) {
7052     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7053     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7054         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7055         Method, ActingContext);
7056     if (Conversions[ConvIdx].isBad())
7057       return true;
7058   }
7059 
7060   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7061        ++I) {
7062     QualType ParamType = ParamTypes[I];
7063     if (!ParamType->isDependentType()) {
7064       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7065                              ? 0
7066                              : (ThisConversions + I);
7067       Conversions[ConvIdx]
7068         = TryCopyInitialization(*this, Args[I], ParamType,
7069                                 SuppressUserConversions,
7070                                 /*InOverloadResolution=*/true,
7071                                 /*AllowObjCWritebackConversion=*/
7072                                   getLangOpts().ObjCAutoRefCount,
7073                                 AllowExplicit);
7074       if (Conversions[ConvIdx].isBad())
7075         return true;
7076     }
7077   }
7078 
7079   return false;
7080 }
7081 
7082 /// Determine whether this is an allowable conversion from the result
7083 /// of an explicit conversion operator to the expected type, per C++
7084 /// [over.match.conv]p1 and [over.match.ref]p1.
7085 ///
7086 /// \param ConvType The return type of the conversion function.
7087 ///
7088 /// \param ToType The type we are converting to.
7089 ///
7090 /// \param AllowObjCPointerConversion Allow a conversion from one
7091 /// Objective-C pointer to another.
7092 ///
7093 /// \returns true if the conversion is allowable, false otherwise.
7094 static bool isAllowableExplicitConversion(Sema &S,
7095                                           QualType ConvType, QualType ToType,
7096                                           bool AllowObjCPointerConversion) {
7097   QualType ToNonRefType = ToType.getNonReferenceType();
7098 
7099   // Easy case: the types are the same.
7100   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7101     return true;
7102 
7103   // Allow qualification conversions.
7104   bool ObjCLifetimeConversion;
7105   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7106                                   ObjCLifetimeConversion))
7107     return true;
7108 
7109   // If we're not allowed to consider Objective-C pointer conversions,
7110   // we're done.
7111   if (!AllowObjCPointerConversion)
7112     return false;
7113 
7114   // Is this an Objective-C pointer conversion?
7115   bool IncompatibleObjC = false;
7116   QualType ConvertedType;
7117   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7118                                    IncompatibleObjC);
7119 }
7120 
7121 /// AddConversionCandidate - Add a C++ conversion function as a
7122 /// candidate in the candidate set (C++ [over.match.conv],
7123 /// C++ [over.match.copy]). From is the expression we're converting from,
7124 /// and ToType is the type that we're eventually trying to convert to
7125 /// (which may or may not be the same type as the type that the
7126 /// conversion function produces).
7127 void Sema::AddConversionCandidate(
7128     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7129     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7130     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7131     bool AllowExplicit, bool AllowResultConversion) {
7132   assert(!Conversion->getDescribedFunctionTemplate() &&
7133          "Conversion function templates use AddTemplateConversionCandidate");
7134   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7135   if (!CandidateSet.isNewCandidate(Conversion))
7136     return;
7137 
7138   // If the conversion function has an undeduced return type, trigger its
7139   // deduction now.
7140   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7141     if (DeduceReturnType(Conversion, From->getExprLoc()))
7142       return;
7143     ConvType = Conversion->getConversionType().getNonReferenceType();
7144   }
7145 
7146   // If we don't allow any conversion of the result type, ignore conversion
7147   // functions that don't convert to exactly (possibly cv-qualified) T.
7148   if (!AllowResultConversion &&
7149       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7150     return;
7151 
7152   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7153   // operator is only a candidate if its return type is the target type or
7154   // can be converted to the target type with a qualification conversion.
7155   //
7156   // FIXME: Include such functions in the candidate list and explain why we
7157   // can't select them.
7158   if (Conversion->isExplicit() &&
7159       !isAllowableExplicitConversion(*this, ConvType, ToType,
7160                                      AllowObjCConversionOnExplicit))
7161     return;
7162 
7163   // Overload resolution is always an unevaluated context.
7164   EnterExpressionEvaluationContext Unevaluated(
7165       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7166 
7167   // Add this candidate
7168   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7169   Candidate.FoundDecl = FoundDecl;
7170   Candidate.Function = Conversion;
7171   Candidate.IsSurrogate = false;
7172   Candidate.IgnoreObjectArgument = false;
7173   Candidate.FinalConversion.setAsIdentityConversion();
7174   Candidate.FinalConversion.setFromType(ConvType);
7175   Candidate.FinalConversion.setAllToTypes(ToType);
7176   Candidate.Viable = true;
7177   Candidate.ExplicitCallArguments = 1;
7178 
7179   // Explicit functions are not actually candidates at all if we're not
7180   // allowing them in this context, but keep them around so we can point
7181   // to them in diagnostics.
7182   if (!AllowExplicit && Conversion->isExplicit()) {
7183     Candidate.Viable = false;
7184     Candidate.FailureKind = ovl_fail_explicit;
7185     return;
7186   }
7187 
7188   // C++ [over.match.funcs]p4:
7189   //   For conversion functions, the function is considered to be a member of
7190   //   the class of the implicit implied object argument for the purpose of
7191   //   defining the type of the implicit object parameter.
7192   //
7193   // Determine the implicit conversion sequence for the implicit
7194   // object parameter.
7195   QualType ImplicitParamType = From->getType();
7196   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7197     ImplicitParamType = FromPtrType->getPointeeType();
7198   CXXRecordDecl *ConversionContext
7199     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7200 
7201   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7202       *this, CandidateSet.getLocation(), From->getType(),
7203       From->Classify(Context), Conversion, ConversionContext);
7204 
7205   if (Candidate.Conversions[0].isBad()) {
7206     Candidate.Viable = false;
7207     Candidate.FailureKind = ovl_fail_bad_conversion;
7208     return;
7209   }
7210 
7211   Expr *RequiresClause = Conversion->getTrailingRequiresClause();
7212   if (RequiresClause) {
7213     ConstraintSatisfaction Satisfaction;
7214     if (CheckConstraintSatisfaction(RequiresClause, Satisfaction) ||
7215         !Satisfaction.IsSatisfied) {
7216       Candidate.Viable = false;
7217       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7218       return;
7219     }
7220   }
7221 
7222   // We won't go through a user-defined type conversion function to convert a
7223   // derived to base as such conversions are given Conversion Rank. They only
7224   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7225   QualType FromCanon
7226     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7227   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7228   if (FromCanon == ToCanon ||
7229       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7230     Candidate.Viable = false;
7231     Candidate.FailureKind = ovl_fail_trivial_conversion;
7232     return;
7233   }
7234 
7235   // To determine what the conversion from the result of calling the
7236   // conversion function to the type we're eventually trying to
7237   // convert to (ToType), we need to synthesize a call to the
7238   // conversion function and attempt copy initialization from it. This
7239   // makes sure that we get the right semantics with respect to
7240   // lvalues/rvalues and the type. Fortunately, we can allocate this
7241   // call on the stack and we don't need its arguments to be
7242   // well-formed.
7243   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7244                             VK_LValue, From->getBeginLoc());
7245   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7246                                 Context.getPointerType(Conversion->getType()),
7247                                 CK_FunctionToPointerDecay,
7248                                 &ConversionRef, VK_RValue);
7249 
7250   QualType ConversionType = Conversion->getConversionType();
7251   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7252     Candidate.Viable = false;
7253     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7254     return;
7255   }
7256 
7257   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7258 
7259   // Note that it is safe to allocate CallExpr on the stack here because
7260   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7261   // allocator).
7262   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7263 
7264   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7265   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7266       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7267 
7268   ImplicitConversionSequence ICS =
7269       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7270                             /*SuppressUserConversions=*/true,
7271                             /*InOverloadResolution=*/false,
7272                             /*AllowObjCWritebackConversion=*/false);
7273 
7274   switch (ICS.getKind()) {
7275   case ImplicitConversionSequence::StandardConversion:
7276     Candidate.FinalConversion = ICS.Standard;
7277 
7278     // C++ [over.ics.user]p3:
7279     //   If the user-defined conversion is specified by a specialization of a
7280     //   conversion function template, the second standard conversion sequence
7281     //   shall have exact match rank.
7282     if (Conversion->getPrimaryTemplate() &&
7283         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7284       Candidate.Viable = false;
7285       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7286       return;
7287     }
7288 
7289     // C++0x [dcl.init.ref]p5:
7290     //    In the second case, if the reference is an rvalue reference and
7291     //    the second standard conversion sequence of the user-defined
7292     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7293     //    program is ill-formed.
7294     if (ToType->isRValueReferenceType() &&
7295         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7296       Candidate.Viable = false;
7297       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7298       return;
7299     }
7300     break;
7301 
7302   case ImplicitConversionSequence::BadConversion:
7303     Candidate.Viable = false;
7304     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7305     return;
7306 
7307   default:
7308     llvm_unreachable(
7309            "Can only end up with a standard conversion sequence or failure");
7310   }
7311 
7312   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7313     Candidate.Viable = false;
7314     Candidate.FailureKind = ovl_fail_enable_if;
7315     Candidate.DeductionFailure.Data = FailedAttr;
7316     return;
7317   }
7318 
7319   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7320       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7321     Candidate.Viable = false;
7322     Candidate.FailureKind = ovl_non_default_multiversion_function;
7323   }
7324 }
7325 
7326 /// Adds a conversion function template specialization
7327 /// candidate to the overload set, using template argument deduction
7328 /// to deduce the template arguments of the conversion function
7329 /// template from the type that we are converting to (C++
7330 /// [temp.deduct.conv]).
7331 void Sema::AddTemplateConversionCandidate(
7332     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7333     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7334     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7335     bool AllowExplicit, bool AllowResultConversion) {
7336   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7337          "Only conversion function templates permitted here");
7338 
7339   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7340     return;
7341 
7342   // If the function template has a non-dependent explicit specification,
7343   // exclude it now if appropriate; we are not permitted to perform deduction
7344   // and substitution in this case.
7345   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7346     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7347     Candidate.FoundDecl = FoundDecl;
7348     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7349     Candidate.Viable = false;
7350     Candidate.FailureKind = ovl_fail_explicit;
7351     return;
7352   }
7353 
7354   TemplateDeductionInfo Info(CandidateSet.getLocation());
7355   CXXConversionDecl *Specialization = nullptr;
7356   if (TemplateDeductionResult Result
7357         = DeduceTemplateArguments(FunctionTemplate, ToType,
7358                                   Specialization, Info)) {
7359     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7360     Candidate.FoundDecl = FoundDecl;
7361     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7362     Candidate.Viable = false;
7363     Candidate.FailureKind = ovl_fail_bad_deduction;
7364     Candidate.IsSurrogate = false;
7365     Candidate.IgnoreObjectArgument = false;
7366     Candidate.ExplicitCallArguments = 1;
7367     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7368                                                           Info);
7369     return;
7370   }
7371 
7372   // Add the conversion function template specialization produced by
7373   // template argument deduction as a candidate.
7374   assert(Specialization && "Missing function template specialization?");
7375   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7376                          CandidateSet, AllowObjCConversionOnExplicit,
7377                          AllowExplicit, AllowResultConversion);
7378 }
7379 
7380 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7381 /// converts the given @c Object to a function pointer via the
7382 /// conversion function @c Conversion, and then attempts to call it
7383 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7384 /// the type of function that we'll eventually be calling.
7385 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7386                                  DeclAccessPair FoundDecl,
7387                                  CXXRecordDecl *ActingContext,
7388                                  const FunctionProtoType *Proto,
7389                                  Expr *Object,
7390                                  ArrayRef<Expr *> Args,
7391                                  OverloadCandidateSet& CandidateSet) {
7392   if (!CandidateSet.isNewCandidate(Conversion))
7393     return;
7394 
7395   // Overload resolution is always an unevaluated context.
7396   EnterExpressionEvaluationContext Unevaluated(
7397       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7398 
7399   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7400   Candidate.FoundDecl = FoundDecl;
7401   Candidate.Function = nullptr;
7402   Candidate.Surrogate = Conversion;
7403   Candidate.Viable = true;
7404   Candidate.IsSurrogate = true;
7405   Candidate.IgnoreObjectArgument = false;
7406   Candidate.ExplicitCallArguments = Args.size();
7407 
7408   // Determine the implicit conversion sequence for the implicit
7409   // object parameter.
7410   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7411       *this, CandidateSet.getLocation(), Object->getType(),
7412       Object->Classify(Context), Conversion, ActingContext);
7413   if (ObjectInit.isBad()) {
7414     Candidate.Viable = false;
7415     Candidate.FailureKind = ovl_fail_bad_conversion;
7416     Candidate.Conversions[0] = ObjectInit;
7417     return;
7418   }
7419 
7420   // The first conversion is actually a user-defined conversion whose
7421   // first conversion is ObjectInit's standard conversion (which is
7422   // effectively a reference binding). Record it as such.
7423   Candidate.Conversions[0].setUserDefined();
7424   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7425   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7426   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7427   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7428   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7429   Candidate.Conversions[0].UserDefined.After
7430     = Candidate.Conversions[0].UserDefined.Before;
7431   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7432 
7433   // Find the
7434   unsigned NumParams = Proto->getNumParams();
7435 
7436   // (C++ 13.3.2p2): A candidate function having fewer than m
7437   // parameters is viable only if it has an ellipsis in its parameter
7438   // list (8.3.5).
7439   if (Args.size() > NumParams && !Proto->isVariadic()) {
7440     Candidate.Viable = false;
7441     Candidate.FailureKind = ovl_fail_too_many_arguments;
7442     return;
7443   }
7444 
7445   // Function types don't have any default arguments, so just check if
7446   // we have enough arguments.
7447   if (Args.size() < NumParams) {
7448     // Not enough arguments.
7449     Candidate.Viable = false;
7450     Candidate.FailureKind = ovl_fail_too_few_arguments;
7451     return;
7452   }
7453 
7454   // Determine the implicit conversion sequences for each of the
7455   // arguments.
7456   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7457     if (ArgIdx < NumParams) {
7458       // (C++ 13.3.2p3): for F to be a viable function, there shall
7459       // exist for each argument an implicit conversion sequence
7460       // (13.3.3.1) that converts that argument to the corresponding
7461       // parameter of F.
7462       QualType ParamType = Proto->getParamType(ArgIdx);
7463       Candidate.Conversions[ArgIdx + 1]
7464         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7465                                 /*SuppressUserConversions=*/false,
7466                                 /*InOverloadResolution=*/false,
7467                                 /*AllowObjCWritebackConversion=*/
7468                                   getLangOpts().ObjCAutoRefCount);
7469       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7470         Candidate.Viable = false;
7471         Candidate.FailureKind = ovl_fail_bad_conversion;
7472         return;
7473       }
7474     } else {
7475       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7476       // argument for which there is no corresponding parameter is
7477       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7478       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7479     }
7480   }
7481 
7482   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7483     Candidate.Viable = false;
7484     Candidate.FailureKind = ovl_fail_enable_if;
7485     Candidate.DeductionFailure.Data = FailedAttr;
7486     return;
7487   }
7488 }
7489 
7490 /// Add all of the non-member operator function declarations in the given
7491 /// function set to the overload candidate set.
7492 void Sema::AddNonMemberOperatorCandidates(
7493     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7494     OverloadCandidateSet &CandidateSet,
7495     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7496   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7497     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7498     ArrayRef<Expr *> FunctionArgs = Args;
7499 
7500     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7501     FunctionDecl *FD =
7502         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7503 
7504     // Don't consider rewritten functions if we're not rewriting.
7505     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7506       continue;
7507 
7508     assert(!isa<CXXMethodDecl>(FD) &&
7509            "unqualified operator lookup found a member function");
7510 
7511     if (FunTmpl) {
7512       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7513                                    FunctionArgs, CandidateSet);
7514       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7515         AddTemplateOverloadCandidate(
7516             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7517             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7518             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7519     } else {
7520       if (ExplicitTemplateArgs)
7521         continue;
7522       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7523       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7524         AddOverloadCandidate(FD, F.getPair(),
7525                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7526                              false, false, true, false, ADLCallKind::NotADL,
7527                              None, OverloadCandidateParamOrder::Reversed);
7528     }
7529   }
7530 }
7531 
7532 /// Add overload candidates for overloaded operators that are
7533 /// member functions.
7534 ///
7535 /// Add the overloaded operator candidates that are member functions
7536 /// for the operator Op that was used in an operator expression such
7537 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7538 /// CandidateSet will store the added overload candidates. (C++
7539 /// [over.match.oper]).
7540 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7541                                        SourceLocation OpLoc,
7542                                        ArrayRef<Expr *> Args,
7543                                        OverloadCandidateSet &CandidateSet,
7544                                        OverloadCandidateParamOrder PO) {
7545   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7546 
7547   // C++ [over.match.oper]p3:
7548   //   For a unary operator @ with an operand of a type whose
7549   //   cv-unqualified version is T1, and for a binary operator @ with
7550   //   a left operand of a type whose cv-unqualified version is T1 and
7551   //   a right operand of a type whose cv-unqualified version is T2,
7552   //   three sets of candidate functions, designated member
7553   //   candidates, non-member candidates and built-in candidates, are
7554   //   constructed as follows:
7555   QualType T1 = Args[0]->getType();
7556 
7557   //     -- If T1 is a complete class type or a class currently being
7558   //        defined, the set of member candidates is the result of the
7559   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7560   //        the set of member candidates is empty.
7561   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7562     // Complete the type if it can be completed.
7563     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7564       return;
7565     // If the type is neither complete nor being defined, bail out now.
7566     if (!T1Rec->getDecl()->getDefinition())
7567       return;
7568 
7569     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7570     LookupQualifiedName(Operators, T1Rec->getDecl());
7571     Operators.suppressDiagnostics();
7572 
7573     for (LookupResult::iterator Oper = Operators.begin(),
7574                              OperEnd = Operators.end();
7575          Oper != OperEnd;
7576          ++Oper)
7577       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7578                          Args[0]->Classify(Context), Args.slice(1),
7579                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7580   }
7581 }
7582 
7583 /// AddBuiltinCandidate - Add a candidate for a built-in
7584 /// operator. ResultTy and ParamTys are the result and parameter types
7585 /// of the built-in candidate, respectively. Args and NumArgs are the
7586 /// arguments being passed to the candidate. IsAssignmentOperator
7587 /// should be true when this built-in candidate is an assignment
7588 /// operator. NumContextualBoolArguments is the number of arguments
7589 /// (at the beginning of the argument list) that will be contextually
7590 /// converted to bool.
7591 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7592                                OverloadCandidateSet& CandidateSet,
7593                                bool IsAssignmentOperator,
7594                                unsigned NumContextualBoolArguments) {
7595   // Overload resolution is always an unevaluated context.
7596   EnterExpressionEvaluationContext Unevaluated(
7597       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7598 
7599   // Add this candidate
7600   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7601   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7602   Candidate.Function = nullptr;
7603   Candidate.IsSurrogate = false;
7604   Candidate.IgnoreObjectArgument = false;
7605   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7606 
7607   // Determine the implicit conversion sequences for each of the
7608   // arguments.
7609   Candidate.Viable = true;
7610   Candidate.ExplicitCallArguments = Args.size();
7611   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7612     // C++ [over.match.oper]p4:
7613     //   For the built-in assignment operators, conversions of the
7614     //   left operand are restricted as follows:
7615     //     -- no temporaries are introduced to hold the left operand, and
7616     //     -- no user-defined conversions are applied to the left
7617     //        operand to achieve a type match with the left-most
7618     //        parameter of a built-in candidate.
7619     //
7620     // We block these conversions by turning off user-defined
7621     // conversions, since that is the only way that initialization of
7622     // a reference to a non-class type can occur from something that
7623     // is not of the same type.
7624     if (ArgIdx < NumContextualBoolArguments) {
7625       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7626              "Contextual conversion to bool requires bool type");
7627       Candidate.Conversions[ArgIdx]
7628         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7629     } else {
7630       Candidate.Conversions[ArgIdx]
7631         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7632                                 ArgIdx == 0 && IsAssignmentOperator,
7633                                 /*InOverloadResolution=*/false,
7634                                 /*AllowObjCWritebackConversion=*/
7635                                   getLangOpts().ObjCAutoRefCount);
7636     }
7637     if (Candidate.Conversions[ArgIdx].isBad()) {
7638       Candidate.Viable = false;
7639       Candidate.FailureKind = ovl_fail_bad_conversion;
7640       break;
7641     }
7642   }
7643 }
7644 
7645 namespace {
7646 
7647 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7648 /// candidate operator functions for built-in operators (C++
7649 /// [over.built]). The types are separated into pointer types and
7650 /// enumeration types.
7651 class BuiltinCandidateTypeSet  {
7652   /// TypeSet - A set of types.
7653   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7654                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7655 
7656   /// PointerTypes - The set of pointer types that will be used in the
7657   /// built-in candidates.
7658   TypeSet PointerTypes;
7659 
7660   /// MemberPointerTypes - The set of member pointer types that will be
7661   /// used in the built-in candidates.
7662   TypeSet MemberPointerTypes;
7663 
7664   /// EnumerationTypes - The set of enumeration types that will be
7665   /// used in the built-in candidates.
7666   TypeSet EnumerationTypes;
7667 
7668   /// The set of vector types that will be used in the built-in
7669   /// candidates.
7670   TypeSet VectorTypes;
7671 
7672   /// A flag indicating non-record types are viable candidates
7673   bool HasNonRecordTypes;
7674 
7675   /// A flag indicating whether either arithmetic or enumeration types
7676   /// were present in the candidate set.
7677   bool HasArithmeticOrEnumeralTypes;
7678 
7679   /// A flag indicating whether the nullptr type was present in the
7680   /// candidate set.
7681   bool HasNullPtrType;
7682 
7683   /// Sema - The semantic analysis instance where we are building the
7684   /// candidate type set.
7685   Sema &SemaRef;
7686 
7687   /// Context - The AST context in which we will build the type sets.
7688   ASTContext &Context;
7689 
7690   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7691                                                const Qualifiers &VisibleQuals);
7692   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7693 
7694 public:
7695   /// iterator - Iterates through the types that are part of the set.
7696   typedef TypeSet::iterator iterator;
7697 
7698   BuiltinCandidateTypeSet(Sema &SemaRef)
7699     : HasNonRecordTypes(false),
7700       HasArithmeticOrEnumeralTypes(false),
7701       HasNullPtrType(false),
7702       SemaRef(SemaRef),
7703       Context(SemaRef.Context) { }
7704 
7705   void AddTypesConvertedFrom(QualType Ty,
7706                              SourceLocation Loc,
7707                              bool AllowUserConversions,
7708                              bool AllowExplicitConversions,
7709                              const Qualifiers &VisibleTypeConversionsQuals);
7710 
7711   /// pointer_begin - First pointer type found;
7712   iterator pointer_begin() { return PointerTypes.begin(); }
7713 
7714   /// pointer_end - Past the last pointer type found;
7715   iterator pointer_end() { return PointerTypes.end(); }
7716 
7717   /// member_pointer_begin - First member pointer type found;
7718   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7719 
7720   /// member_pointer_end - Past the last member pointer type found;
7721   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7722 
7723   /// enumeration_begin - First enumeration type found;
7724   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7725 
7726   /// enumeration_end - Past the last enumeration type found;
7727   iterator enumeration_end() { return EnumerationTypes.end(); }
7728 
7729   iterator vector_begin() { return VectorTypes.begin(); }
7730   iterator vector_end() { return VectorTypes.end(); }
7731 
7732   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7733   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7734   bool hasNullPtrType() const { return HasNullPtrType; }
7735 };
7736 
7737 } // end anonymous namespace
7738 
7739 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7740 /// the set of pointer types along with any more-qualified variants of
7741 /// that type. For example, if @p Ty is "int const *", this routine
7742 /// will add "int const *", "int const volatile *", "int const
7743 /// restrict *", and "int const volatile restrict *" to the set of
7744 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7745 /// false otherwise.
7746 ///
7747 /// FIXME: what to do about extended qualifiers?
7748 bool
7749 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7750                                              const Qualifiers &VisibleQuals) {
7751 
7752   // Insert this type.
7753   if (!PointerTypes.insert(Ty))
7754     return false;
7755 
7756   QualType PointeeTy;
7757   const PointerType *PointerTy = Ty->getAs<PointerType>();
7758   bool buildObjCPtr = false;
7759   if (!PointerTy) {
7760     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7761     PointeeTy = PTy->getPointeeType();
7762     buildObjCPtr = true;
7763   } else {
7764     PointeeTy = PointerTy->getPointeeType();
7765   }
7766 
7767   // Don't add qualified variants of arrays. For one, they're not allowed
7768   // (the qualifier would sink to the element type), and for another, the
7769   // only overload situation where it matters is subscript or pointer +- int,
7770   // and those shouldn't have qualifier variants anyway.
7771   if (PointeeTy->isArrayType())
7772     return true;
7773 
7774   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7775   bool hasVolatile = VisibleQuals.hasVolatile();
7776   bool hasRestrict = VisibleQuals.hasRestrict();
7777 
7778   // Iterate through all strict supersets of BaseCVR.
7779   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7780     if ((CVR | BaseCVR) != CVR) continue;
7781     // Skip over volatile if no volatile found anywhere in the types.
7782     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7783 
7784     // Skip over restrict if no restrict found anywhere in the types, or if
7785     // the type cannot be restrict-qualified.
7786     if ((CVR & Qualifiers::Restrict) &&
7787         (!hasRestrict ||
7788          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7789       continue;
7790 
7791     // Build qualified pointee type.
7792     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7793 
7794     // Build qualified pointer type.
7795     QualType QPointerTy;
7796     if (!buildObjCPtr)
7797       QPointerTy = Context.getPointerType(QPointeeTy);
7798     else
7799       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7800 
7801     // Insert qualified pointer type.
7802     PointerTypes.insert(QPointerTy);
7803   }
7804 
7805   return true;
7806 }
7807 
7808 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7809 /// to the set of pointer types along with any more-qualified variants of
7810 /// that type. For example, if @p Ty is "int const *", this routine
7811 /// will add "int const *", "int const volatile *", "int const
7812 /// restrict *", and "int const volatile restrict *" to the set of
7813 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7814 /// false otherwise.
7815 ///
7816 /// FIXME: what to do about extended qualifiers?
7817 bool
7818 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7819     QualType Ty) {
7820   // Insert this type.
7821   if (!MemberPointerTypes.insert(Ty))
7822     return false;
7823 
7824   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7825   assert(PointerTy && "type was not a member pointer type!");
7826 
7827   QualType PointeeTy = PointerTy->getPointeeType();
7828   // Don't add qualified variants of arrays. For one, they're not allowed
7829   // (the qualifier would sink to the element type), and for another, the
7830   // only overload situation where it matters is subscript or pointer +- int,
7831   // and those shouldn't have qualifier variants anyway.
7832   if (PointeeTy->isArrayType())
7833     return true;
7834   const Type *ClassTy = PointerTy->getClass();
7835 
7836   // Iterate through all strict supersets of the pointee type's CVR
7837   // qualifiers.
7838   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7839   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7840     if ((CVR | BaseCVR) != CVR) continue;
7841 
7842     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7843     MemberPointerTypes.insert(
7844       Context.getMemberPointerType(QPointeeTy, ClassTy));
7845   }
7846 
7847   return true;
7848 }
7849 
7850 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7851 /// Ty can be implicit converted to the given set of @p Types. We're
7852 /// primarily interested in pointer types and enumeration types. We also
7853 /// take member pointer types, for the conditional operator.
7854 /// AllowUserConversions is true if we should look at the conversion
7855 /// functions of a class type, and AllowExplicitConversions if we
7856 /// should also include the explicit conversion functions of a class
7857 /// type.
7858 void
7859 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7860                                                SourceLocation Loc,
7861                                                bool AllowUserConversions,
7862                                                bool AllowExplicitConversions,
7863                                                const Qualifiers &VisibleQuals) {
7864   // Only deal with canonical types.
7865   Ty = Context.getCanonicalType(Ty);
7866 
7867   // Look through reference types; they aren't part of the type of an
7868   // expression for the purposes of conversions.
7869   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7870     Ty = RefTy->getPointeeType();
7871 
7872   // If we're dealing with an array type, decay to the pointer.
7873   if (Ty->isArrayType())
7874     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7875 
7876   // Otherwise, we don't care about qualifiers on the type.
7877   Ty = Ty.getLocalUnqualifiedType();
7878 
7879   // Flag if we ever add a non-record type.
7880   const RecordType *TyRec = Ty->getAs<RecordType>();
7881   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7882 
7883   // Flag if we encounter an arithmetic type.
7884   HasArithmeticOrEnumeralTypes =
7885     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7886 
7887   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7888     PointerTypes.insert(Ty);
7889   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7890     // Insert our type, and its more-qualified variants, into the set
7891     // of types.
7892     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7893       return;
7894   } else if (Ty->isMemberPointerType()) {
7895     // Member pointers are far easier, since the pointee can't be converted.
7896     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7897       return;
7898   } else if (Ty->isEnumeralType()) {
7899     HasArithmeticOrEnumeralTypes = true;
7900     EnumerationTypes.insert(Ty);
7901   } else if (Ty->isVectorType()) {
7902     // We treat vector types as arithmetic types in many contexts as an
7903     // extension.
7904     HasArithmeticOrEnumeralTypes = true;
7905     VectorTypes.insert(Ty);
7906   } else if (Ty->isNullPtrType()) {
7907     HasNullPtrType = true;
7908   } else if (AllowUserConversions && TyRec) {
7909     // No conversion functions in incomplete types.
7910     if (!SemaRef.isCompleteType(Loc, Ty))
7911       return;
7912 
7913     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7914     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7915       if (isa<UsingShadowDecl>(D))
7916         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7917 
7918       // Skip conversion function templates; they don't tell us anything
7919       // about which builtin types we can convert to.
7920       if (isa<FunctionTemplateDecl>(D))
7921         continue;
7922 
7923       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7924       if (AllowExplicitConversions || !Conv->isExplicit()) {
7925         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7926                               VisibleQuals);
7927       }
7928     }
7929   }
7930 }
7931 /// Helper function for adjusting address spaces for the pointer or reference
7932 /// operands of builtin operators depending on the argument.
7933 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7934                                                         Expr *Arg) {
7935   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7936 }
7937 
7938 /// Helper function for AddBuiltinOperatorCandidates() that adds
7939 /// the volatile- and non-volatile-qualified assignment operators for the
7940 /// given type to the candidate set.
7941 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7942                                                    QualType T,
7943                                                    ArrayRef<Expr *> Args,
7944                                     OverloadCandidateSet &CandidateSet) {
7945   QualType ParamTypes[2];
7946 
7947   // T& operator=(T&, T)
7948   ParamTypes[0] = S.Context.getLValueReferenceType(
7949       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7950   ParamTypes[1] = T;
7951   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7952                         /*IsAssignmentOperator=*/true);
7953 
7954   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7955     // volatile T& operator=(volatile T&, T)
7956     ParamTypes[0] = S.Context.getLValueReferenceType(
7957         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7958                                                 Args[0]));
7959     ParamTypes[1] = T;
7960     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7961                           /*IsAssignmentOperator=*/true);
7962   }
7963 }
7964 
7965 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7966 /// if any, found in visible type conversion functions found in ArgExpr's type.
7967 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7968     Qualifiers VRQuals;
7969     const RecordType *TyRec;
7970     if (const MemberPointerType *RHSMPType =
7971         ArgExpr->getType()->getAs<MemberPointerType>())
7972       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7973     else
7974       TyRec = ArgExpr->getType()->getAs<RecordType>();
7975     if (!TyRec) {
7976       // Just to be safe, assume the worst case.
7977       VRQuals.addVolatile();
7978       VRQuals.addRestrict();
7979       return VRQuals;
7980     }
7981 
7982     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7983     if (!ClassDecl->hasDefinition())
7984       return VRQuals;
7985 
7986     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7987       if (isa<UsingShadowDecl>(D))
7988         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7989       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7990         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7991         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7992           CanTy = ResTypeRef->getPointeeType();
7993         // Need to go down the pointer/mempointer chain and add qualifiers
7994         // as see them.
7995         bool done = false;
7996         while (!done) {
7997           if (CanTy.isRestrictQualified())
7998             VRQuals.addRestrict();
7999           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8000             CanTy = ResTypePtr->getPointeeType();
8001           else if (const MemberPointerType *ResTypeMPtr =
8002                 CanTy->getAs<MemberPointerType>())
8003             CanTy = ResTypeMPtr->getPointeeType();
8004           else
8005             done = true;
8006           if (CanTy.isVolatileQualified())
8007             VRQuals.addVolatile();
8008           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8009             return VRQuals;
8010         }
8011       }
8012     }
8013     return VRQuals;
8014 }
8015 
8016 namespace {
8017 
8018 /// Helper class to manage the addition of builtin operator overload
8019 /// candidates. It provides shared state and utility methods used throughout
8020 /// the process, as well as a helper method to add each group of builtin
8021 /// operator overloads from the standard to a candidate set.
8022 class BuiltinOperatorOverloadBuilder {
8023   // Common instance state available to all overload candidate addition methods.
8024   Sema &S;
8025   ArrayRef<Expr *> Args;
8026   Qualifiers VisibleTypeConversionsQuals;
8027   bool HasArithmeticOrEnumeralCandidateType;
8028   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8029   OverloadCandidateSet &CandidateSet;
8030 
8031   static constexpr int ArithmeticTypesCap = 24;
8032   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8033 
8034   // Define some indices used to iterate over the arithmetic types in
8035   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8036   // types are that preserved by promotion (C++ [over.built]p2).
8037   unsigned FirstIntegralType,
8038            LastIntegralType;
8039   unsigned FirstPromotedIntegralType,
8040            LastPromotedIntegralType;
8041   unsigned FirstPromotedArithmeticType,
8042            LastPromotedArithmeticType;
8043   unsigned NumArithmeticTypes;
8044 
8045   void InitArithmeticTypes() {
8046     // Start of promoted types.
8047     FirstPromotedArithmeticType = 0;
8048     ArithmeticTypes.push_back(S.Context.FloatTy);
8049     ArithmeticTypes.push_back(S.Context.DoubleTy);
8050     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8051     if (S.Context.getTargetInfo().hasFloat128Type())
8052       ArithmeticTypes.push_back(S.Context.Float128Ty);
8053 
8054     // Start of integral types.
8055     FirstIntegralType = ArithmeticTypes.size();
8056     FirstPromotedIntegralType = ArithmeticTypes.size();
8057     ArithmeticTypes.push_back(S.Context.IntTy);
8058     ArithmeticTypes.push_back(S.Context.LongTy);
8059     ArithmeticTypes.push_back(S.Context.LongLongTy);
8060     if (S.Context.getTargetInfo().hasInt128Type())
8061       ArithmeticTypes.push_back(S.Context.Int128Ty);
8062     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8063     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8064     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8065     if (S.Context.getTargetInfo().hasInt128Type())
8066       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8067     LastPromotedIntegralType = ArithmeticTypes.size();
8068     LastPromotedArithmeticType = ArithmeticTypes.size();
8069     // End of promoted types.
8070 
8071     ArithmeticTypes.push_back(S.Context.BoolTy);
8072     ArithmeticTypes.push_back(S.Context.CharTy);
8073     ArithmeticTypes.push_back(S.Context.WCharTy);
8074     if (S.Context.getLangOpts().Char8)
8075       ArithmeticTypes.push_back(S.Context.Char8Ty);
8076     ArithmeticTypes.push_back(S.Context.Char16Ty);
8077     ArithmeticTypes.push_back(S.Context.Char32Ty);
8078     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8079     ArithmeticTypes.push_back(S.Context.ShortTy);
8080     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8081     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8082     LastIntegralType = ArithmeticTypes.size();
8083     NumArithmeticTypes = ArithmeticTypes.size();
8084     // End of integral types.
8085     // FIXME: What about complex? What about half?
8086 
8087     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8088            "Enough inline storage for all arithmetic types.");
8089   }
8090 
8091   /// Helper method to factor out the common pattern of adding overloads
8092   /// for '++' and '--' builtin operators.
8093   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8094                                            bool HasVolatile,
8095                                            bool HasRestrict) {
8096     QualType ParamTypes[2] = {
8097       S.Context.getLValueReferenceType(CandidateTy),
8098       S.Context.IntTy
8099     };
8100 
8101     // Non-volatile version.
8102     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8103 
8104     // Use a heuristic to reduce number of builtin candidates in the set:
8105     // add volatile version only if there are conversions to a volatile type.
8106     if (HasVolatile) {
8107       ParamTypes[0] =
8108         S.Context.getLValueReferenceType(
8109           S.Context.getVolatileType(CandidateTy));
8110       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8111     }
8112 
8113     // Add restrict version only if there are conversions to a restrict type
8114     // and our candidate type is a non-restrict-qualified pointer.
8115     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8116         !CandidateTy.isRestrictQualified()) {
8117       ParamTypes[0]
8118         = S.Context.getLValueReferenceType(
8119             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8120       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8121 
8122       if (HasVolatile) {
8123         ParamTypes[0]
8124           = S.Context.getLValueReferenceType(
8125               S.Context.getCVRQualifiedType(CandidateTy,
8126                                             (Qualifiers::Volatile |
8127                                              Qualifiers::Restrict)));
8128         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129       }
8130     }
8131 
8132   }
8133 
8134 public:
8135   BuiltinOperatorOverloadBuilder(
8136     Sema &S, ArrayRef<Expr *> Args,
8137     Qualifiers VisibleTypeConversionsQuals,
8138     bool HasArithmeticOrEnumeralCandidateType,
8139     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8140     OverloadCandidateSet &CandidateSet)
8141     : S(S), Args(Args),
8142       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8143       HasArithmeticOrEnumeralCandidateType(
8144         HasArithmeticOrEnumeralCandidateType),
8145       CandidateTypes(CandidateTypes),
8146       CandidateSet(CandidateSet) {
8147 
8148     InitArithmeticTypes();
8149   }
8150 
8151   // Increment is deprecated for bool since C++17.
8152   //
8153   // C++ [over.built]p3:
8154   //
8155   //   For every pair (T, VQ), where T is an arithmetic type other
8156   //   than bool, and VQ is either volatile or empty, there exist
8157   //   candidate operator functions of the form
8158   //
8159   //       VQ T&      operator++(VQ T&);
8160   //       T          operator++(VQ T&, int);
8161   //
8162   // C++ [over.built]p4:
8163   //
8164   //   For every pair (T, VQ), where T is an arithmetic type other
8165   //   than bool, and VQ is either volatile or empty, there exist
8166   //   candidate operator functions of the form
8167   //
8168   //       VQ T&      operator--(VQ T&);
8169   //       T          operator--(VQ T&, int);
8170   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8171     if (!HasArithmeticOrEnumeralCandidateType)
8172       return;
8173 
8174     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8175       const auto TypeOfT = ArithmeticTypes[Arith];
8176       if (TypeOfT == S.Context.BoolTy) {
8177         if (Op == OO_MinusMinus)
8178           continue;
8179         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8180           continue;
8181       }
8182       addPlusPlusMinusMinusStyleOverloads(
8183         TypeOfT,
8184         VisibleTypeConversionsQuals.hasVolatile(),
8185         VisibleTypeConversionsQuals.hasRestrict());
8186     }
8187   }
8188 
8189   // C++ [over.built]p5:
8190   //
8191   //   For every pair (T, VQ), where T is a cv-qualified or
8192   //   cv-unqualified object type, and VQ is either volatile or
8193   //   empty, there exist candidate operator functions of the form
8194   //
8195   //       T*VQ&      operator++(T*VQ&);
8196   //       T*VQ&      operator--(T*VQ&);
8197   //       T*         operator++(T*VQ&, int);
8198   //       T*         operator--(T*VQ&, int);
8199   void addPlusPlusMinusMinusPointerOverloads() {
8200     for (BuiltinCandidateTypeSet::iterator
8201               Ptr = CandidateTypes[0].pointer_begin(),
8202            PtrEnd = CandidateTypes[0].pointer_end();
8203          Ptr != PtrEnd; ++Ptr) {
8204       // Skip pointer types that aren't pointers to object types.
8205       if (!(*Ptr)->getPointeeType()->isObjectType())
8206         continue;
8207 
8208       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8209         (!(*Ptr).isVolatileQualified() &&
8210          VisibleTypeConversionsQuals.hasVolatile()),
8211         (!(*Ptr).isRestrictQualified() &&
8212          VisibleTypeConversionsQuals.hasRestrict()));
8213     }
8214   }
8215 
8216   // C++ [over.built]p6:
8217   //   For every cv-qualified or cv-unqualified object type T, there
8218   //   exist candidate operator functions of the form
8219   //
8220   //       T&         operator*(T*);
8221   //
8222   // C++ [over.built]p7:
8223   //   For every function type T that does not have cv-qualifiers or a
8224   //   ref-qualifier, there exist candidate operator functions of the form
8225   //       T&         operator*(T*);
8226   void addUnaryStarPointerOverloads() {
8227     for (BuiltinCandidateTypeSet::iterator
8228               Ptr = CandidateTypes[0].pointer_begin(),
8229            PtrEnd = CandidateTypes[0].pointer_end();
8230          Ptr != PtrEnd; ++Ptr) {
8231       QualType ParamTy = *Ptr;
8232       QualType PointeeTy = ParamTy->getPointeeType();
8233       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8234         continue;
8235 
8236       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8237         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8238           continue;
8239 
8240       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8241     }
8242   }
8243 
8244   // C++ [over.built]p9:
8245   //  For every promoted arithmetic type T, there exist candidate
8246   //  operator functions of the form
8247   //
8248   //       T         operator+(T);
8249   //       T         operator-(T);
8250   void addUnaryPlusOrMinusArithmeticOverloads() {
8251     if (!HasArithmeticOrEnumeralCandidateType)
8252       return;
8253 
8254     for (unsigned Arith = FirstPromotedArithmeticType;
8255          Arith < LastPromotedArithmeticType; ++Arith) {
8256       QualType ArithTy = ArithmeticTypes[Arith];
8257       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8258     }
8259 
8260     // Extension: We also add these operators for vector types.
8261     for (BuiltinCandidateTypeSet::iterator
8262               Vec = CandidateTypes[0].vector_begin(),
8263            VecEnd = CandidateTypes[0].vector_end();
8264          Vec != VecEnd; ++Vec) {
8265       QualType VecTy = *Vec;
8266       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8267     }
8268   }
8269 
8270   // C++ [over.built]p8:
8271   //   For every type T, there exist candidate operator functions of
8272   //   the form
8273   //
8274   //       T*         operator+(T*);
8275   void addUnaryPlusPointerOverloads() {
8276     for (BuiltinCandidateTypeSet::iterator
8277               Ptr = CandidateTypes[0].pointer_begin(),
8278            PtrEnd = CandidateTypes[0].pointer_end();
8279          Ptr != PtrEnd; ++Ptr) {
8280       QualType ParamTy = *Ptr;
8281       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8282     }
8283   }
8284 
8285   // C++ [over.built]p10:
8286   //   For every promoted integral type T, there exist candidate
8287   //   operator functions of the form
8288   //
8289   //        T         operator~(T);
8290   void addUnaryTildePromotedIntegralOverloads() {
8291     if (!HasArithmeticOrEnumeralCandidateType)
8292       return;
8293 
8294     for (unsigned Int = FirstPromotedIntegralType;
8295          Int < LastPromotedIntegralType; ++Int) {
8296       QualType IntTy = ArithmeticTypes[Int];
8297       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8298     }
8299 
8300     // Extension: We also add this operator for vector types.
8301     for (BuiltinCandidateTypeSet::iterator
8302               Vec = CandidateTypes[0].vector_begin(),
8303            VecEnd = CandidateTypes[0].vector_end();
8304          Vec != VecEnd; ++Vec) {
8305       QualType VecTy = *Vec;
8306       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8307     }
8308   }
8309 
8310   // C++ [over.match.oper]p16:
8311   //   For every pointer to member type T or type std::nullptr_t, there
8312   //   exist candidate operator functions of the form
8313   //
8314   //        bool operator==(T,T);
8315   //        bool operator!=(T,T);
8316   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8317     /// Set of (canonical) types that we've already handled.
8318     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8319 
8320     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8321       for (BuiltinCandidateTypeSet::iterator
8322                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8323              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8324            MemPtr != MemPtrEnd;
8325            ++MemPtr) {
8326         // Don't add the same builtin candidate twice.
8327         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8328           continue;
8329 
8330         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8331         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8332       }
8333 
8334       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8335         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8336         if (AddedTypes.insert(NullPtrTy).second) {
8337           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8338           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8339         }
8340       }
8341     }
8342   }
8343 
8344   // C++ [over.built]p15:
8345   //
8346   //   For every T, where T is an enumeration type or a pointer type,
8347   //   there exist candidate operator functions of the form
8348   //
8349   //        bool       operator<(T, T);
8350   //        bool       operator>(T, T);
8351   //        bool       operator<=(T, T);
8352   //        bool       operator>=(T, T);
8353   //        bool       operator==(T, T);
8354   //        bool       operator!=(T, T);
8355   //           R       operator<=>(T, T)
8356   void addGenericBinaryPointerOrEnumeralOverloads() {
8357     // C++ [over.match.oper]p3:
8358     //   [...]the built-in candidates include all of the candidate operator
8359     //   functions defined in 13.6 that, compared to the given operator, [...]
8360     //   do not have the same parameter-type-list as any non-template non-member
8361     //   candidate.
8362     //
8363     // Note that in practice, this only affects enumeration types because there
8364     // aren't any built-in candidates of record type, and a user-defined operator
8365     // must have an operand of record or enumeration type. Also, the only other
8366     // overloaded operator with enumeration arguments, operator=,
8367     // cannot be overloaded for enumeration types, so this is the only place
8368     // where we must suppress candidates like this.
8369     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8370       UserDefinedBinaryOperators;
8371 
8372     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8373       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8374           CandidateTypes[ArgIdx].enumeration_end()) {
8375         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8376                                          CEnd = CandidateSet.end();
8377              C != CEnd; ++C) {
8378           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8379             continue;
8380 
8381           if (C->Function->isFunctionTemplateSpecialization())
8382             continue;
8383 
8384           // We interpret "same parameter-type-list" as applying to the
8385           // "synthesized candidate, with the order of the two parameters
8386           // reversed", not to the original function.
8387           bool Reversed = C->RewriteKind & CRK_Reversed;
8388           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8389                                         ->getType()
8390                                         .getUnqualifiedType();
8391           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8392                                          ->getType()
8393                                          .getUnqualifiedType();
8394 
8395           // Skip if either parameter isn't of enumeral type.
8396           if (!FirstParamType->isEnumeralType() ||
8397               !SecondParamType->isEnumeralType())
8398             continue;
8399 
8400           // Add this operator to the set of known user-defined operators.
8401           UserDefinedBinaryOperators.insert(
8402             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8403                            S.Context.getCanonicalType(SecondParamType)));
8404         }
8405       }
8406     }
8407 
8408     /// Set of (canonical) types that we've already handled.
8409     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8410 
8411     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8412       for (BuiltinCandidateTypeSet::iterator
8413                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8414              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8415            Ptr != PtrEnd; ++Ptr) {
8416         // Don't add the same builtin candidate twice.
8417         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8418           continue;
8419 
8420         QualType ParamTypes[2] = { *Ptr, *Ptr };
8421         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8422       }
8423       for (BuiltinCandidateTypeSet::iterator
8424                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8425              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8426            Enum != EnumEnd; ++Enum) {
8427         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8428 
8429         // Don't add the same builtin candidate twice, or if a user defined
8430         // candidate exists.
8431         if (!AddedTypes.insert(CanonType).second ||
8432             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8433                                                             CanonType)))
8434           continue;
8435         QualType ParamTypes[2] = { *Enum, *Enum };
8436         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8437       }
8438     }
8439   }
8440 
8441   // C++ [over.built]p13:
8442   //
8443   //   For every cv-qualified or cv-unqualified object type T
8444   //   there exist candidate operator functions of the form
8445   //
8446   //      T*         operator+(T*, ptrdiff_t);
8447   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8448   //      T*         operator-(T*, ptrdiff_t);
8449   //      T*         operator+(ptrdiff_t, T*);
8450   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8451   //
8452   // C++ [over.built]p14:
8453   //
8454   //   For every T, where T is a pointer to object type, there
8455   //   exist candidate operator functions of the form
8456   //
8457   //      ptrdiff_t  operator-(T, T);
8458   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8459     /// Set of (canonical) types that we've already handled.
8460     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8461 
8462     for (int Arg = 0; Arg < 2; ++Arg) {
8463       QualType AsymmetricParamTypes[2] = {
8464         S.Context.getPointerDiffType(),
8465         S.Context.getPointerDiffType(),
8466       };
8467       for (BuiltinCandidateTypeSet::iterator
8468                 Ptr = CandidateTypes[Arg].pointer_begin(),
8469              PtrEnd = CandidateTypes[Arg].pointer_end();
8470            Ptr != PtrEnd; ++Ptr) {
8471         QualType PointeeTy = (*Ptr)->getPointeeType();
8472         if (!PointeeTy->isObjectType())
8473           continue;
8474 
8475         AsymmetricParamTypes[Arg] = *Ptr;
8476         if (Arg == 0 || Op == OO_Plus) {
8477           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8478           // T* operator+(ptrdiff_t, T*);
8479           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8480         }
8481         if (Op == OO_Minus) {
8482           // ptrdiff_t operator-(T, T);
8483           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8484             continue;
8485 
8486           QualType ParamTypes[2] = { *Ptr, *Ptr };
8487           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8488         }
8489       }
8490     }
8491   }
8492 
8493   // C++ [over.built]p12:
8494   //
8495   //   For every pair of promoted arithmetic types L and R, there
8496   //   exist candidate operator functions of the form
8497   //
8498   //        LR         operator*(L, R);
8499   //        LR         operator/(L, R);
8500   //        LR         operator+(L, R);
8501   //        LR         operator-(L, R);
8502   //        bool       operator<(L, R);
8503   //        bool       operator>(L, R);
8504   //        bool       operator<=(L, R);
8505   //        bool       operator>=(L, R);
8506   //        bool       operator==(L, R);
8507   //        bool       operator!=(L, R);
8508   //
8509   //   where LR is the result of the usual arithmetic conversions
8510   //   between types L and R.
8511   //
8512   // C++ [over.built]p24:
8513   //
8514   //   For every pair of promoted arithmetic types L and R, there exist
8515   //   candidate operator functions of the form
8516   //
8517   //        LR       operator?(bool, L, R);
8518   //
8519   //   where LR is the result of the usual arithmetic conversions
8520   //   between types L and R.
8521   // Our candidates ignore the first parameter.
8522   void addGenericBinaryArithmeticOverloads() {
8523     if (!HasArithmeticOrEnumeralCandidateType)
8524       return;
8525 
8526     for (unsigned Left = FirstPromotedArithmeticType;
8527          Left < LastPromotedArithmeticType; ++Left) {
8528       for (unsigned Right = FirstPromotedArithmeticType;
8529            Right < LastPromotedArithmeticType; ++Right) {
8530         QualType LandR[2] = { ArithmeticTypes[Left],
8531                               ArithmeticTypes[Right] };
8532         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8533       }
8534     }
8535 
8536     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8537     // conditional operator for vector types.
8538     for (BuiltinCandidateTypeSet::iterator
8539               Vec1 = CandidateTypes[0].vector_begin(),
8540            Vec1End = CandidateTypes[0].vector_end();
8541          Vec1 != Vec1End; ++Vec1) {
8542       for (BuiltinCandidateTypeSet::iterator
8543                 Vec2 = CandidateTypes[1].vector_begin(),
8544              Vec2End = CandidateTypes[1].vector_end();
8545            Vec2 != Vec2End; ++Vec2) {
8546         QualType LandR[2] = { *Vec1, *Vec2 };
8547         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8548       }
8549     }
8550   }
8551 
8552   // C++2a [over.built]p14:
8553   //
8554   //   For every integral type T there exists a candidate operator function
8555   //   of the form
8556   //
8557   //        std::strong_ordering operator<=>(T, T)
8558   //
8559   // C++2a [over.built]p15:
8560   //
8561   //   For every pair of floating-point types L and R, there exists a candidate
8562   //   operator function of the form
8563   //
8564   //       std::partial_ordering operator<=>(L, R);
8565   //
8566   // FIXME: The current specification for integral types doesn't play nice with
8567   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8568   // comparisons. Under the current spec this can lead to ambiguity during
8569   // overload resolution. For example:
8570   //
8571   //   enum A : int {a};
8572   //   auto x = (a <=> (long)42);
8573   //
8574   //   error: call is ambiguous for arguments 'A' and 'long'.
8575   //   note: candidate operator<=>(int, int)
8576   //   note: candidate operator<=>(long, long)
8577   //
8578   // To avoid this error, this function deviates from the specification and adds
8579   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8580   // arithmetic types (the same as the generic relational overloads).
8581   //
8582   // For now this function acts as a placeholder.
8583   void addThreeWayArithmeticOverloads() {
8584     addGenericBinaryArithmeticOverloads();
8585   }
8586 
8587   // C++ [over.built]p17:
8588   //
8589   //   For every pair of promoted integral types L and R, there
8590   //   exist candidate operator functions of the form
8591   //
8592   //      LR         operator%(L, R);
8593   //      LR         operator&(L, R);
8594   //      LR         operator^(L, R);
8595   //      LR         operator|(L, R);
8596   //      L          operator<<(L, R);
8597   //      L          operator>>(L, R);
8598   //
8599   //   where LR is the result of the usual arithmetic conversions
8600   //   between types L and R.
8601   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8602     if (!HasArithmeticOrEnumeralCandidateType)
8603       return;
8604 
8605     for (unsigned Left = FirstPromotedIntegralType;
8606          Left < LastPromotedIntegralType; ++Left) {
8607       for (unsigned Right = FirstPromotedIntegralType;
8608            Right < LastPromotedIntegralType; ++Right) {
8609         QualType LandR[2] = { ArithmeticTypes[Left],
8610                               ArithmeticTypes[Right] };
8611         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8612       }
8613     }
8614   }
8615 
8616   // C++ [over.built]p20:
8617   //
8618   //   For every pair (T, VQ), where T is an enumeration or
8619   //   pointer to member type and VQ is either volatile or
8620   //   empty, there exist candidate operator functions of the form
8621   //
8622   //        VQ T&      operator=(VQ T&, T);
8623   void addAssignmentMemberPointerOrEnumeralOverloads() {
8624     /// Set of (canonical) types that we've already handled.
8625     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8626 
8627     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8628       for (BuiltinCandidateTypeSet::iterator
8629                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8630              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8631            Enum != EnumEnd; ++Enum) {
8632         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8633           continue;
8634 
8635         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8636       }
8637 
8638       for (BuiltinCandidateTypeSet::iterator
8639                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8640              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8641            MemPtr != MemPtrEnd; ++MemPtr) {
8642         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8643           continue;
8644 
8645         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8646       }
8647     }
8648   }
8649 
8650   // C++ [over.built]p19:
8651   //
8652   //   For every pair (T, VQ), where T is any type and VQ is either
8653   //   volatile or empty, there exist candidate operator functions
8654   //   of the form
8655   //
8656   //        T*VQ&      operator=(T*VQ&, T*);
8657   //
8658   // C++ [over.built]p21:
8659   //
8660   //   For every pair (T, VQ), where T is a cv-qualified or
8661   //   cv-unqualified object type and VQ is either volatile or
8662   //   empty, there exist candidate operator functions of the form
8663   //
8664   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8665   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8666   void addAssignmentPointerOverloads(bool isEqualOp) {
8667     /// Set of (canonical) types that we've already handled.
8668     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8669 
8670     for (BuiltinCandidateTypeSet::iterator
8671               Ptr = CandidateTypes[0].pointer_begin(),
8672            PtrEnd = CandidateTypes[0].pointer_end();
8673          Ptr != PtrEnd; ++Ptr) {
8674       // If this is operator=, keep track of the builtin candidates we added.
8675       if (isEqualOp)
8676         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8677       else if (!(*Ptr)->getPointeeType()->isObjectType())
8678         continue;
8679 
8680       // non-volatile version
8681       QualType ParamTypes[2] = {
8682         S.Context.getLValueReferenceType(*Ptr),
8683         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8684       };
8685       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8686                             /*IsAssignmentOperator=*/ isEqualOp);
8687 
8688       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8689                           VisibleTypeConversionsQuals.hasVolatile();
8690       if (NeedVolatile) {
8691         // volatile version
8692         ParamTypes[0] =
8693           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8694         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8695                               /*IsAssignmentOperator=*/isEqualOp);
8696       }
8697 
8698       if (!(*Ptr).isRestrictQualified() &&
8699           VisibleTypeConversionsQuals.hasRestrict()) {
8700         // restrict version
8701         ParamTypes[0]
8702           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8703         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8704                               /*IsAssignmentOperator=*/isEqualOp);
8705 
8706         if (NeedVolatile) {
8707           // volatile restrict version
8708           ParamTypes[0]
8709             = S.Context.getLValueReferenceType(
8710                 S.Context.getCVRQualifiedType(*Ptr,
8711                                               (Qualifiers::Volatile |
8712                                                Qualifiers::Restrict)));
8713           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8714                                 /*IsAssignmentOperator=*/isEqualOp);
8715         }
8716       }
8717     }
8718 
8719     if (isEqualOp) {
8720       for (BuiltinCandidateTypeSet::iterator
8721                 Ptr = CandidateTypes[1].pointer_begin(),
8722              PtrEnd = CandidateTypes[1].pointer_end();
8723            Ptr != PtrEnd; ++Ptr) {
8724         // Make sure we don't add the same candidate twice.
8725         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8726           continue;
8727 
8728         QualType ParamTypes[2] = {
8729           S.Context.getLValueReferenceType(*Ptr),
8730           *Ptr,
8731         };
8732 
8733         // non-volatile version
8734         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8735                               /*IsAssignmentOperator=*/true);
8736 
8737         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8738                            VisibleTypeConversionsQuals.hasVolatile();
8739         if (NeedVolatile) {
8740           // volatile version
8741           ParamTypes[0] =
8742             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8743           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8744                                 /*IsAssignmentOperator=*/true);
8745         }
8746 
8747         if (!(*Ptr).isRestrictQualified() &&
8748             VisibleTypeConversionsQuals.hasRestrict()) {
8749           // restrict version
8750           ParamTypes[0]
8751             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8752           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8753                                 /*IsAssignmentOperator=*/true);
8754 
8755           if (NeedVolatile) {
8756             // volatile restrict version
8757             ParamTypes[0]
8758               = S.Context.getLValueReferenceType(
8759                   S.Context.getCVRQualifiedType(*Ptr,
8760                                                 (Qualifiers::Volatile |
8761                                                  Qualifiers::Restrict)));
8762             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8763                                   /*IsAssignmentOperator=*/true);
8764           }
8765         }
8766       }
8767     }
8768   }
8769 
8770   // C++ [over.built]p18:
8771   //
8772   //   For every triple (L, VQ, R), where L is an arithmetic type,
8773   //   VQ is either volatile or empty, and R is a promoted
8774   //   arithmetic type, there exist candidate operator functions of
8775   //   the form
8776   //
8777   //        VQ L&      operator=(VQ L&, R);
8778   //        VQ L&      operator*=(VQ L&, R);
8779   //        VQ L&      operator/=(VQ L&, R);
8780   //        VQ L&      operator+=(VQ L&, R);
8781   //        VQ L&      operator-=(VQ L&, R);
8782   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8783     if (!HasArithmeticOrEnumeralCandidateType)
8784       return;
8785 
8786     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8787       for (unsigned Right = FirstPromotedArithmeticType;
8788            Right < LastPromotedArithmeticType; ++Right) {
8789         QualType ParamTypes[2];
8790         ParamTypes[1] = ArithmeticTypes[Right];
8791         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8792             S, ArithmeticTypes[Left], Args[0]);
8793         // Add this built-in operator as a candidate (VQ is empty).
8794         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8795         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8796                               /*IsAssignmentOperator=*/isEqualOp);
8797 
8798         // Add this built-in operator as a candidate (VQ is 'volatile').
8799         if (VisibleTypeConversionsQuals.hasVolatile()) {
8800           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8801           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8802           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8803                                 /*IsAssignmentOperator=*/isEqualOp);
8804         }
8805       }
8806     }
8807 
8808     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8809     for (BuiltinCandidateTypeSet::iterator
8810               Vec1 = CandidateTypes[0].vector_begin(),
8811            Vec1End = CandidateTypes[0].vector_end();
8812          Vec1 != Vec1End; ++Vec1) {
8813       for (BuiltinCandidateTypeSet::iterator
8814                 Vec2 = CandidateTypes[1].vector_begin(),
8815              Vec2End = CandidateTypes[1].vector_end();
8816            Vec2 != Vec2End; ++Vec2) {
8817         QualType ParamTypes[2];
8818         ParamTypes[1] = *Vec2;
8819         // Add this built-in operator as a candidate (VQ is empty).
8820         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8821         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8822                               /*IsAssignmentOperator=*/isEqualOp);
8823 
8824         // Add this built-in operator as a candidate (VQ is 'volatile').
8825         if (VisibleTypeConversionsQuals.hasVolatile()) {
8826           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8827           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8828           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8829                                 /*IsAssignmentOperator=*/isEqualOp);
8830         }
8831       }
8832     }
8833   }
8834 
8835   // C++ [over.built]p22:
8836   //
8837   //   For every triple (L, VQ, R), where L is an integral type, VQ
8838   //   is either volatile or empty, and R is a promoted integral
8839   //   type, there exist candidate operator functions of the form
8840   //
8841   //        VQ L&       operator%=(VQ L&, R);
8842   //        VQ L&       operator<<=(VQ L&, R);
8843   //        VQ L&       operator>>=(VQ L&, R);
8844   //        VQ L&       operator&=(VQ L&, R);
8845   //        VQ L&       operator^=(VQ L&, R);
8846   //        VQ L&       operator|=(VQ L&, R);
8847   void addAssignmentIntegralOverloads() {
8848     if (!HasArithmeticOrEnumeralCandidateType)
8849       return;
8850 
8851     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8852       for (unsigned Right = FirstPromotedIntegralType;
8853            Right < LastPromotedIntegralType; ++Right) {
8854         QualType ParamTypes[2];
8855         ParamTypes[1] = ArithmeticTypes[Right];
8856         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8857             S, ArithmeticTypes[Left], Args[0]);
8858         // Add this built-in operator as a candidate (VQ is empty).
8859         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8860         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8861         if (VisibleTypeConversionsQuals.hasVolatile()) {
8862           // Add this built-in operator as a candidate (VQ is 'volatile').
8863           ParamTypes[0] = LeftBaseTy;
8864           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8865           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8866           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8867         }
8868       }
8869     }
8870   }
8871 
8872   // C++ [over.operator]p23:
8873   //
8874   //   There also exist candidate operator functions of the form
8875   //
8876   //        bool        operator!(bool);
8877   //        bool        operator&&(bool, bool);
8878   //        bool        operator||(bool, bool);
8879   void addExclaimOverload() {
8880     QualType ParamTy = S.Context.BoolTy;
8881     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8882                           /*IsAssignmentOperator=*/false,
8883                           /*NumContextualBoolArguments=*/1);
8884   }
8885   void addAmpAmpOrPipePipeOverload() {
8886     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8887     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8888                           /*IsAssignmentOperator=*/false,
8889                           /*NumContextualBoolArguments=*/2);
8890   }
8891 
8892   // C++ [over.built]p13:
8893   //
8894   //   For every cv-qualified or cv-unqualified object type T there
8895   //   exist candidate operator functions of the form
8896   //
8897   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8898   //        T&         operator[](T*, ptrdiff_t);
8899   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8900   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8901   //        T&         operator[](ptrdiff_t, T*);
8902   void addSubscriptOverloads() {
8903     for (BuiltinCandidateTypeSet::iterator
8904               Ptr = CandidateTypes[0].pointer_begin(),
8905            PtrEnd = CandidateTypes[0].pointer_end();
8906          Ptr != PtrEnd; ++Ptr) {
8907       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8908       QualType PointeeType = (*Ptr)->getPointeeType();
8909       if (!PointeeType->isObjectType())
8910         continue;
8911 
8912       // T& operator[](T*, ptrdiff_t)
8913       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8914     }
8915 
8916     for (BuiltinCandidateTypeSet::iterator
8917               Ptr = CandidateTypes[1].pointer_begin(),
8918            PtrEnd = CandidateTypes[1].pointer_end();
8919          Ptr != PtrEnd; ++Ptr) {
8920       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8921       QualType PointeeType = (*Ptr)->getPointeeType();
8922       if (!PointeeType->isObjectType())
8923         continue;
8924 
8925       // T& operator[](ptrdiff_t, T*)
8926       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8927     }
8928   }
8929 
8930   // C++ [over.built]p11:
8931   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8932   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8933   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8934   //    there exist candidate operator functions of the form
8935   //
8936   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8937   //
8938   //    where CV12 is the union of CV1 and CV2.
8939   void addArrowStarOverloads() {
8940     for (BuiltinCandidateTypeSet::iterator
8941              Ptr = CandidateTypes[0].pointer_begin(),
8942            PtrEnd = CandidateTypes[0].pointer_end();
8943          Ptr != PtrEnd; ++Ptr) {
8944       QualType C1Ty = (*Ptr);
8945       QualType C1;
8946       QualifierCollector Q1;
8947       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8948       if (!isa<RecordType>(C1))
8949         continue;
8950       // heuristic to reduce number of builtin candidates in the set.
8951       // Add volatile/restrict version only if there are conversions to a
8952       // volatile/restrict type.
8953       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8954         continue;
8955       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8956         continue;
8957       for (BuiltinCandidateTypeSet::iterator
8958                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8959              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8960            MemPtr != MemPtrEnd; ++MemPtr) {
8961         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8962         QualType C2 = QualType(mptr->getClass(), 0);
8963         C2 = C2.getUnqualifiedType();
8964         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8965           break;
8966         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8967         // build CV12 T&
8968         QualType T = mptr->getPointeeType();
8969         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8970             T.isVolatileQualified())
8971           continue;
8972         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8973             T.isRestrictQualified())
8974           continue;
8975         T = Q1.apply(S.Context, T);
8976         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8977       }
8978     }
8979   }
8980 
8981   // Note that we don't consider the first argument, since it has been
8982   // contextually converted to bool long ago. The candidates below are
8983   // therefore added as binary.
8984   //
8985   // C++ [over.built]p25:
8986   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8987   //   enumeration type, there exist candidate operator functions of the form
8988   //
8989   //        T        operator?(bool, T, T);
8990   //
8991   void addConditionalOperatorOverloads() {
8992     /// Set of (canonical) types that we've already handled.
8993     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8994 
8995     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8996       for (BuiltinCandidateTypeSet::iterator
8997                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8998              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8999            Ptr != PtrEnd; ++Ptr) {
9000         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9001           continue;
9002 
9003         QualType ParamTypes[2] = { *Ptr, *Ptr };
9004         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9005       }
9006 
9007       for (BuiltinCandidateTypeSet::iterator
9008                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9009              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9010            MemPtr != MemPtrEnd; ++MemPtr) {
9011         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9012           continue;
9013 
9014         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9015         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9016       }
9017 
9018       if (S.getLangOpts().CPlusPlus11) {
9019         for (BuiltinCandidateTypeSet::iterator
9020                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9021                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9022              Enum != EnumEnd; ++Enum) {
9023           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9024             continue;
9025 
9026           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9027             continue;
9028 
9029           QualType ParamTypes[2] = { *Enum, *Enum };
9030           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9031         }
9032       }
9033     }
9034   }
9035 };
9036 
9037 } // end anonymous namespace
9038 
9039 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9040 /// operator overloads to the candidate set (C++ [over.built]), based
9041 /// on the operator @p Op and the arguments given. For example, if the
9042 /// operator is a binary '+', this routine might add "int
9043 /// operator+(int, int)" to cover integer addition.
9044 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9045                                         SourceLocation OpLoc,
9046                                         ArrayRef<Expr *> Args,
9047                                         OverloadCandidateSet &CandidateSet) {
9048   // Find all of the types that the arguments can convert to, but only
9049   // if the operator we're looking at has built-in operator candidates
9050   // that make use of these types. Also record whether we encounter non-record
9051   // candidate types or either arithmetic or enumeral candidate types.
9052   Qualifiers VisibleTypeConversionsQuals;
9053   VisibleTypeConversionsQuals.addConst();
9054   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9055     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9056 
9057   bool HasNonRecordCandidateType = false;
9058   bool HasArithmeticOrEnumeralCandidateType = false;
9059   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9060   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9061     CandidateTypes.emplace_back(*this);
9062     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9063                                                  OpLoc,
9064                                                  true,
9065                                                  (Op == OO_Exclaim ||
9066                                                   Op == OO_AmpAmp ||
9067                                                   Op == OO_PipePipe),
9068                                                  VisibleTypeConversionsQuals);
9069     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9070         CandidateTypes[ArgIdx].hasNonRecordTypes();
9071     HasArithmeticOrEnumeralCandidateType =
9072         HasArithmeticOrEnumeralCandidateType ||
9073         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9074   }
9075 
9076   // Exit early when no non-record types have been added to the candidate set
9077   // for any of the arguments to the operator.
9078   //
9079   // We can't exit early for !, ||, or &&, since there we have always have
9080   // 'bool' overloads.
9081   if (!HasNonRecordCandidateType &&
9082       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9083     return;
9084 
9085   // Setup an object to manage the common state for building overloads.
9086   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9087                                            VisibleTypeConversionsQuals,
9088                                            HasArithmeticOrEnumeralCandidateType,
9089                                            CandidateTypes, CandidateSet);
9090 
9091   // Dispatch over the operation to add in only those overloads which apply.
9092   switch (Op) {
9093   case OO_None:
9094   case NUM_OVERLOADED_OPERATORS:
9095     llvm_unreachable("Expected an overloaded operator");
9096 
9097   case OO_New:
9098   case OO_Delete:
9099   case OO_Array_New:
9100   case OO_Array_Delete:
9101   case OO_Call:
9102     llvm_unreachable(
9103                     "Special operators don't use AddBuiltinOperatorCandidates");
9104 
9105   case OO_Comma:
9106   case OO_Arrow:
9107   case OO_Coawait:
9108     // C++ [over.match.oper]p3:
9109     //   -- For the operator ',', the unary operator '&', the
9110     //      operator '->', or the operator 'co_await', the
9111     //      built-in candidates set is empty.
9112     break;
9113 
9114   case OO_Plus: // '+' is either unary or binary
9115     if (Args.size() == 1)
9116       OpBuilder.addUnaryPlusPointerOverloads();
9117     LLVM_FALLTHROUGH;
9118 
9119   case OO_Minus: // '-' is either unary or binary
9120     if (Args.size() == 1) {
9121       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9122     } else {
9123       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9124       OpBuilder.addGenericBinaryArithmeticOverloads();
9125     }
9126     break;
9127 
9128   case OO_Star: // '*' is either unary or binary
9129     if (Args.size() == 1)
9130       OpBuilder.addUnaryStarPointerOverloads();
9131     else
9132       OpBuilder.addGenericBinaryArithmeticOverloads();
9133     break;
9134 
9135   case OO_Slash:
9136     OpBuilder.addGenericBinaryArithmeticOverloads();
9137     break;
9138 
9139   case OO_PlusPlus:
9140   case OO_MinusMinus:
9141     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9142     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9143     break;
9144 
9145   case OO_EqualEqual:
9146   case OO_ExclaimEqual:
9147     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9148     LLVM_FALLTHROUGH;
9149 
9150   case OO_Less:
9151   case OO_Greater:
9152   case OO_LessEqual:
9153   case OO_GreaterEqual:
9154     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9155     OpBuilder.addGenericBinaryArithmeticOverloads();
9156     break;
9157 
9158   case OO_Spaceship:
9159     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9160     OpBuilder.addThreeWayArithmeticOverloads();
9161     break;
9162 
9163   case OO_Percent:
9164   case OO_Caret:
9165   case OO_Pipe:
9166   case OO_LessLess:
9167   case OO_GreaterGreater:
9168     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9169     break;
9170 
9171   case OO_Amp: // '&' is either unary or binary
9172     if (Args.size() == 1)
9173       // C++ [over.match.oper]p3:
9174       //   -- For the operator ',', the unary operator '&', or the
9175       //      operator '->', the built-in candidates set is empty.
9176       break;
9177 
9178     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9179     break;
9180 
9181   case OO_Tilde:
9182     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9183     break;
9184 
9185   case OO_Equal:
9186     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9187     LLVM_FALLTHROUGH;
9188 
9189   case OO_PlusEqual:
9190   case OO_MinusEqual:
9191     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9192     LLVM_FALLTHROUGH;
9193 
9194   case OO_StarEqual:
9195   case OO_SlashEqual:
9196     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9197     break;
9198 
9199   case OO_PercentEqual:
9200   case OO_LessLessEqual:
9201   case OO_GreaterGreaterEqual:
9202   case OO_AmpEqual:
9203   case OO_CaretEqual:
9204   case OO_PipeEqual:
9205     OpBuilder.addAssignmentIntegralOverloads();
9206     break;
9207 
9208   case OO_Exclaim:
9209     OpBuilder.addExclaimOverload();
9210     break;
9211 
9212   case OO_AmpAmp:
9213   case OO_PipePipe:
9214     OpBuilder.addAmpAmpOrPipePipeOverload();
9215     break;
9216 
9217   case OO_Subscript:
9218     OpBuilder.addSubscriptOverloads();
9219     break;
9220 
9221   case OO_ArrowStar:
9222     OpBuilder.addArrowStarOverloads();
9223     break;
9224 
9225   case OO_Conditional:
9226     OpBuilder.addConditionalOperatorOverloads();
9227     OpBuilder.addGenericBinaryArithmeticOverloads();
9228     break;
9229   }
9230 }
9231 
9232 /// Add function candidates found via argument-dependent lookup
9233 /// to the set of overloading candidates.
9234 ///
9235 /// This routine performs argument-dependent name lookup based on the
9236 /// given function name (which may also be an operator name) and adds
9237 /// all of the overload candidates found by ADL to the overload
9238 /// candidate set (C++ [basic.lookup.argdep]).
9239 void
9240 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9241                                            SourceLocation Loc,
9242                                            ArrayRef<Expr *> Args,
9243                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9244                                            OverloadCandidateSet& CandidateSet,
9245                                            bool PartialOverloading) {
9246   ADLResult Fns;
9247 
9248   // FIXME: This approach for uniquing ADL results (and removing
9249   // redundant candidates from the set) relies on pointer-equality,
9250   // which means we need to key off the canonical decl.  However,
9251   // always going back to the canonical decl might not get us the
9252   // right set of default arguments.  What default arguments are
9253   // we supposed to consider on ADL candidates, anyway?
9254 
9255   // FIXME: Pass in the explicit template arguments?
9256   ArgumentDependentLookup(Name, Loc, Args, Fns);
9257 
9258   // Erase all of the candidates we already knew about.
9259   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9260                                    CandEnd = CandidateSet.end();
9261        Cand != CandEnd; ++Cand)
9262     if (Cand->Function) {
9263       Fns.erase(Cand->Function);
9264       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9265         Fns.erase(FunTmpl);
9266     }
9267 
9268   // For each of the ADL candidates we found, add it to the overload
9269   // set.
9270   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9271     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9272 
9273     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9274       if (ExplicitTemplateArgs)
9275         continue;
9276 
9277       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9278                            /*SuppressUserConversions=*/false, PartialOverloading,
9279                            /*AllowExplicit*/ true,
9280                            /*AllowExplicitConversions*/ false,
9281                            ADLCallKind::UsesADL);
9282     } else {
9283       AddTemplateOverloadCandidate(
9284           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9285           CandidateSet,
9286           /*SuppressUserConversions=*/false, PartialOverloading,
9287           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9288     }
9289   }
9290 }
9291 
9292 namespace {
9293 enum class Comparison { Equal, Better, Worse };
9294 }
9295 
9296 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9297 /// overload resolution.
9298 ///
9299 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9300 /// Cand1's first N enable_if attributes have precisely the same conditions as
9301 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9302 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9303 ///
9304 /// Note that you can have a pair of candidates such that Cand1's enable_if
9305 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9306 /// worse than Cand1's.
9307 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9308                                        const FunctionDecl *Cand2) {
9309   // Common case: One (or both) decls don't have enable_if attrs.
9310   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9311   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9312   if (!Cand1Attr || !Cand2Attr) {
9313     if (Cand1Attr == Cand2Attr)
9314       return Comparison::Equal;
9315     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9316   }
9317 
9318   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9319   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9320 
9321   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9322   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9323     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9324     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9325 
9326     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9327     // has fewer enable_if attributes than Cand2, and vice versa.
9328     if (!Cand1A)
9329       return Comparison::Worse;
9330     if (!Cand2A)
9331       return Comparison::Better;
9332 
9333     Cand1ID.clear();
9334     Cand2ID.clear();
9335 
9336     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9337     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9338     if (Cand1ID != Cand2ID)
9339       return Comparison::Worse;
9340   }
9341 
9342   return Comparison::Equal;
9343 }
9344 
9345 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9346                                           const OverloadCandidate &Cand2) {
9347   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9348       !Cand2.Function->isMultiVersion())
9349     return false;
9350 
9351   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9352   // is obviously better.
9353   if (Cand1.Function->isInvalidDecl()) return false;
9354   if (Cand2.Function->isInvalidDecl()) return true;
9355 
9356   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9357   // cpu_dispatch, else arbitrarily based on the identifiers.
9358   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9359   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9360   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9361   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9362 
9363   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9364     return false;
9365 
9366   if (Cand1CPUDisp && !Cand2CPUDisp)
9367     return true;
9368   if (Cand2CPUDisp && !Cand1CPUDisp)
9369     return false;
9370 
9371   if (Cand1CPUSpec && Cand2CPUSpec) {
9372     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9373       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9374 
9375     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9376         FirstDiff = std::mismatch(
9377             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9378             Cand2CPUSpec->cpus_begin(),
9379             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9380               return LHS->getName() == RHS->getName();
9381             });
9382 
9383     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9384            "Two different cpu-specific versions should not have the same "
9385            "identifier list, otherwise they'd be the same decl!");
9386     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9387   }
9388   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9389 }
9390 
9391 /// isBetterOverloadCandidate - Determines whether the first overload
9392 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9393 bool clang::isBetterOverloadCandidate(
9394     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9395     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9396   // Define viable functions to be better candidates than non-viable
9397   // functions.
9398   if (!Cand2.Viable)
9399     return Cand1.Viable;
9400   else if (!Cand1.Viable)
9401     return false;
9402 
9403   // C++ [over.match.best]p1:
9404   //
9405   //   -- if F is a static member function, ICS1(F) is defined such
9406   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9407   //      any function G, and, symmetrically, ICS1(G) is neither
9408   //      better nor worse than ICS1(F).
9409   unsigned StartArg = 0;
9410   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9411     StartArg = 1;
9412 
9413   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9414     // We don't allow incompatible pointer conversions in C++.
9415     if (!S.getLangOpts().CPlusPlus)
9416       return ICS.isStandard() &&
9417              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9418 
9419     // The only ill-formed conversion we allow in C++ is the string literal to
9420     // char* conversion, which is only considered ill-formed after C++11.
9421     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9422            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9423   };
9424 
9425   // Define functions that don't require ill-formed conversions for a given
9426   // argument to be better candidates than functions that do.
9427   unsigned NumArgs = Cand1.Conversions.size();
9428   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9429   bool HasBetterConversion = false;
9430   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9431     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9432     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9433     if (Cand1Bad != Cand2Bad) {
9434       if (Cand1Bad)
9435         return false;
9436       HasBetterConversion = true;
9437     }
9438   }
9439 
9440   if (HasBetterConversion)
9441     return true;
9442 
9443   // C++ [over.match.best]p1:
9444   //   A viable function F1 is defined to be a better function than another
9445   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9446   //   conversion sequence than ICSi(F2), and then...
9447   bool HasWorseConversion = false;
9448   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9449     switch (CompareImplicitConversionSequences(S, Loc,
9450                                                Cand1.Conversions[ArgIdx],
9451                                                Cand2.Conversions[ArgIdx])) {
9452     case ImplicitConversionSequence::Better:
9453       // Cand1 has a better conversion sequence.
9454       HasBetterConversion = true;
9455       break;
9456 
9457     case ImplicitConversionSequence::Worse:
9458       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9459           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9460         // Work around large-scale breakage caused by considering reversed
9461         // forms of operator== in C++20:
9462         //
9463         // When comparing a function against its reversed form, if we have a
9464         // better conversion for one argument and a worse conversion for the
9465         // other, we prefer the non-reversed form.
9466         //
9467         // This prevents a conversion function from being considered ambiguous
9468         // with its own reversed form in various where it's only incidentally
9469         // heterogeneous.
9470         //
9471         // We diagnose this as an extension from CreateOverloadedBinOp.
9472         HasWorseConversion = true;
9473         break;
9474       }
9475 
9476       // Cand1 can't be better than Cand2.
9477       return false;
9478 
9479     case ImplicitConversionSequence::Indistinguishable:
9480       // Do nothing.
9481       break;
9482     }
9483   }
9484 
9485   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9486   //       ICSj(F2), or, if not that,
9487   if (HasBetterConversion)
9488     return true;
9489   if (HasWorseConversion)
9490     return false;
9491 
9492   //   -- the context is an initialization by user-defined conversion
9493   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9494   //      from the return type of F1 to the destination type (i.e.,
9495   //      the type of the entity being initialized) is a better
9496   //      conversion sequence than the standard conversion sequence
9497   //      from the return type of F2 to the destination type.
9498   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9499       Cand1.Function && Cand2.Function &&
9500       isa<CXXConversionDecl>(Cand1.Function) &&
9501       isa<CXXConversionDecl>(Cand2.Function)) {
9502     // First check whether we prefer one of the conversion functions over the
9503     // other. This only distinguishes the results in non-standard, extension
9504     // cases such as the conversion from a lambda closure type to a function
9505     // pointer or block.
9506     ImplicitConversionSequence::CompareKind Result =
9507         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9508     if (Result == ImplicitConversionSequence::Indistinguishable)
9509       Result = CompareStandardConversionSequences(S, Loc,
9510                                                   Cand1.FinalConversion,
9511                                                   Cand2.FinalConversion);
9512 
9513     if (Result != ImplicitConversionSequence::Indistinguishable)
9514       return Result == ImplicitConversionSequence::Better;
9515 
9516     // FIXME: Compare kind of reference binding if conversion functions
9517     // convert to a reference type used in direct reference binding, per
9518     // C++14 [over.match.best]p1 section 2 bullet 3.
9519   }
9520 
9521   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9522   // as combined with the resolution to CWG issue 243.
9523   //
9524   // When the context is initialization by constructor ([over.match.ctor] or
9525   // either phase of [over.match.list]), a constructor is preferred over
9526   // a conversion function.
9527   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9528       Cand1.Function && Cand2.Function &&
9529       isa<CXXConstructorDecl>(Cand1.Function) !=
9530           isa<CXXConstructorDecl>(Cand2.Function))
9531     return isa<CXXConstructorDecl>(Cand1.Function);
9532 
9533   //    -- F1 is a non-template function and F2 is a function template
9534   //       specialization, or, if not that,
9535   bool Cand1IsSpecialization = Cand1.Function &&
9536                                Cand1.Function->getPrimaryTemplate();
9537   bool Cand2IsSpecialization = Cand2.Function &&
9538                                Cand2.Function->getPrimaryTemplate();
9539   if (Cand1IsSpecialization != Cand2IsSpecialization)
9540     return Cand2IsSpecialization;
9541 
9542   //   -- F1 and F2 are function template specializations, and the function
9543   //      template for F1 is more specialized than the template for F2
9544   //      according to the partial ordering rules described in 14.5.5.2, or,
9545   //      if not that,
9546   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9547     if (FunctionTemplateDecl *BetterTemplate
9548           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9549                                          Cand2.Function->getPrimaryTemplate(),
9550                                          Loc,
9551                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9552                                                              : TPOC_Call,
9553                                          Cand1.ExplicitCallArguments,
9554                                          Cand2.ExplicitCallArguments))
9555       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9556   }
9557 
9558   //   -— F1 and F2 are non-template functions with the same
9559   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9560   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9561       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9562       Cand2.Function->hasPrototype()) {
9563     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9564     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9565     if (PT1->getNumParams() == PT2->getNumParams() &&
9566         PT1->isVariadic() == PT2->isVariadic() &&
9567         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9568       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9569       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9570       if (RC1 && RC2) {
9571         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9572         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9573                                      {RC2}, AtLeastAsConstrained1))
9574           return false;
9575         if (!AtLeastAsConstrained1)
9576           return false;
9577         if (S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9578                                      {RC1}, AtLeastAsConstrained2))
9579           return false;
9580         if (!AtLeastAsConstrained2)
9581           return true;
9582       } else if (RC1 || RC2)
9583         return RC1 != nullptr;
9584     }
9585   }
9586 
9587   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9588   //      class B of D, and for all arguments the corresponding parameters of
9589   //      F1 and F2 have the same type.
9590   // FIXME: Implement the "all parameters have the same type" check.
9591   bool Cand1IsInherited =
9592       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9593   bool Cand2IsInherited =
9594       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9595   if (Cand1IsInherited != Cand2IsInherited)
9596     return Cand2IsInherited;
9597   else if (Cand1IsInherited) {
9598     assert(Cand2IsInherited);
9599     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9600     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9601     if (Cand1Class->isDerivedFrom(Cand2Class))
9602       return true;
9603     if (Cand2Class->isDerivedFrom(Cand1Class))
9604       return false;
9605     // Inherited from sibling base classes: still ambiguous.
9606   }
9607 
9608   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9609   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9610   //      with reversed order of parameters and F1 is not
9611   //
9612   // We rank reversed + different operator as worse than just reversed, but
9613   // that comparison can never happen, because we only consider reversing for
9614   // the maximally-rewritten operator (== or <=>).
9615   if (Cand1.RewriteKind != Cand2.RewriteKind)
9616     return Cand1.RewriteKind < Cand2.RewriteKind;
9617 
9618   // Check C++17 tie-breakers for deduction guides.
9619   {
9620     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9621     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9622     if (Guide1 && Guide2) {
9623       //  -- F1 is generated from a deduction-guide and F2 is not
9624       if (Guide1->isImplicit() != Guide2->isImplicit())
9625         return Guide2->isImplicit();
9626 
9627       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9628       if (Guide1->isCopyDeductionCandidate())
9629         return true;
9630     }
9631   }
9632 
9633   // Check for enable_if value-based overload resolution.
9634   if (Cand1.Function && Cand2.Function) {
9635     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9636     if (Cmp != Comparison::Equal)
9637       return Cmp == Comparison::Better;
9638   }
9639 
9640   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9641     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9642     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9643            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9644   }
9645 
9646   bool HasPS1 = Cand1.Function != nullptr &&
9647                 functionHasPassObjectSizeParams(Cand1.Function);
9648   bool HasPS2 = Cand2.Function != nullptr &&
9649                 functionHasPassObjectSizeParams(Cand2.Function);
9650   if (HasPS1 != HasPS2 && HasPS1)
9651     return true;
9652 
9653   return isBetterMultiversionCandidate(Cand1, Cand2);
9654 }
9655 
9656 /// Determine whether two declarations are "equivalent" for the purposes of
9657 /// name lookup and overload resolution. This applies when the same internal/no
9658 /// linkage entity is defined by two modules (probably by textually including
9659 /// the same header). In such a case, we don't consider the declarations to
9660 /// declare the same entity, but we also don't want lookups with both
9661 /// declarations visible to be ambiguous in some cases (this happens when using
9662 /// a modularized libstdc++).
9663 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9664                                                   const NamedDecl *B) {
9665   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9666   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9667   if (!VA || !VB)
9668     return false;
9669 
9670   // The declarations must be declaring the same name as an internal linkage
9671   // entity in different modules.
9672   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9673           VB->getDeclContext()->getRedeclContext()) ||
9674       getOwningModule(VA) == getOwningModule(VB) ||
9675       VA->isExternallyVisible() || VB->isExternallyVisible())
9676     return false;
9677 
9678   // Check that the declarations appear to be equivalent.
9679   //
9680   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9681   // For constants and functions, we should check the initializer or body is
9682   // the same. For non-constant variables, we shouldn't allow it at all.
9683   if (Context.hasSameType(VA->getType(), VB->getType()))
9684     return true;
9685 
9686   // Enum constants within unnamed enumerations will have different types, but
9687   // may still be similar enough to be interchangeable for our purposes.
9688   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9689     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9690       // Only handle anonymous enums. If the enumerations were named and
9691       // equivalent, they would have been merged to the same type.
9692       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9693       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9694       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9695           !Context.hasSameType(EnumA->getIntegerType(),
9696                                EnumB->getIntegerType()))
9697         return false;
9698       // Allow this only if the value is the same for both enumerators.
9699       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9700     }
9701   }
9702 
9703   // Nothing else is sufficiently similar.
9704   return false;
9705 }
9706 
9707 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9708     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9709   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9710 
9711   Module *M = getOwningModule(D);
9712   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9713       << !M << (M ? M->getFullModuleName() : "");
9714 
9715   for (auto *E : Equiv) {
9716     Module *M = getOwningModule(E);
9717     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9718         << !M << (M ? M->getFullModuleName() : "");
9719   }
9720 }
9721 
9722 /// Computes the best viable function (C++ 13.3.3)
9723 /// within an overload candidate set.
9724 ///
9725 /// \param Loc The location of the function name (or operator symbol) for
9726 /// which overload resolution occurs.
9727 ///
9728 /// \param Best If overload resolution was successful or found a deleted
9729 /// function, \p Best points to the candidate function found.
9730 ///
9731 /// \returns The result of overload resolution.
9732 OverloadingResult
9733 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9734                                          iterator &Best) {
9735   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9736   std::transform(begin(), end(), std::back_inserter(Candidates),
9737                  [](OverloadCandidate &Cand) { return &Cand; });
9738 
9739   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9740   // are accepted by both clang and NVCC. However, during a particular
9741   // compilation mode only one call variant is viable. We need to
9742   // exclude non-viable overload candidates from consideration based
9743   // only on their host/device attributes. Specifically, if one
9744   // candidate call is WrongSide and the other is SameSide, we ignore
9745   // the WrongSide candidate.
9746   if (S.getLangOpts().CUDA) {
9747     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9748     bool ContainsSameSideCandidate =
9749         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9750           // Check viable function only.
9751           return Cand->Viable && Cand->Function &&
9752                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9753                      Sema::CFP_SameSide;
9754         });
9755     if (ContainsSameSideCandidate) {
9756       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9757         // Check viable function only to avoid unnecessary data copying/moving.
9758         return Cand->Viable && Cand->Function &&
9759                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9760                    Sema::CFP_WrongSide;
9761       };
9762       llvm::erase_if(Candidates, IsWrongSideCandidate);
9763     }
9764   }
9765 
9766   // Find the best viable function.
9767   Best = end();
9768   for (auto *Cand : Candidates) {
9769     Cand->Best = false;
9770     if (Cand->Viable)
9771       if (Best == end() ||
9772           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9773         Best = Cand;
9774   }
9775 
9776   // If we didn't find any viable functions, abort.
9777   if (Best == end())
9778     return OR_No_Viable_Function;
9779 
9780   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9781 
9782   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9783   PendingBest.push_back(&*Best);
9784   Best->Best = true;
9785 
9786   // Make sure that this function is better than every other viable
9787   // function. If not, we have an ambiguity.
9788   while (!PendingBest.empty()) {
9789     auto *Curr = PendingBest.pop_back_val();
9790     for (auto *Cand : Candidates) {
9791       if (Cand->Viable && !Cand->Best &&
9792           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9793         PendingBest.push_back(Cand);
9794         Cand->Best = true;
9795 
9796         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9797                                                      Curr->Function))
9798           EquivalentCands.push_back(Cand->Function);
9799         else
9800           Best = end();
9801       }
9802     }
9803   }
9804 
9805   // If we found more than one best candidate, this is ambiguous.
9806   if (Best == end())
9807     return OR_Ambiguous;
9808 
9809   // Best is the best viable function.
9810   if (Best->Function && Best->Function->isDeleted())
9811     return OR_Deleted;
9812 
9813   if (!EquivalentCands.empty())
9814     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9815                                                     EquivalentCands);
9816 
9817   return OR_Success;
9818 }
9819 
9820 namespace {
9821 
9822 enum OverloadCandidateKind {
9823   oc_function,
9824   oc_method,
9825   oc_reversed_binary_operator,
9826   oc_constructor,
9827   oc_implicit_default_constructor,
9828   oc_implicit_copy_constructor,
9829   oc_implicit_move_constructor,
9830   oc_implicit_copy_assignment,
9831   oc_implicit_move_assignment,
9832   oc_implicit_equality_comparison,
9833   oc_inherited_constructor
9834 };
9835 
9836 enum OverloadCandidateSelect {
9837   ocs_non_template,
9838   ocs_template,
9839   ocs_described_template,
9840 };
9841 
9842 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9843 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9844                           OverloadCandidateRewriteKind CRK,
9845                           std::string &Description) {
9846 
9847   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9848   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9849     isTemplate = true;
9850     Description = S.getTemplateArgumentBindingsText(
9851         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9852   }
9853 
9854   OverloadCandidateSelect Select = [&]() {
9855     if (!Description.empty())
9856       return ocs_described_template;
9857     return isTemplate ? ocs_template : ocs_non_template;
9858   }();
9859 
9860   OverloadCandidateKind Kind = [&]() {
9861     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9862       return oc_implicit_equality_comparison;
9863 
9864     if (CRK & CRK_Reversed)
9865       return oc_reversed_binary_operator;
9866 
9867     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9868       if (!Ctor->isImplicit()) {
9869         if (isa<ConstructorUsingShadowDecl>(Found))
9870           return oc_inherited_constructor;
9871         else
9872           return oc_constructor;
9873       }
9874 
9875       if (Ctor->isDefaultConstructor())
9876         return oc_implicit_default_constructor;
9877 
9878       if (Ctor->isMoveConstructor())
9879         return oc_implicit_move_constructor;
9880 
9881       assert(Ctor->isCopyConstructor() &&
9882              "unexpected sort of implicit constructor");
9883       return oc_implicit_copy_constructor;
9884     }
9885 
9886     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9887       // This actually gets spelled 'candidate function' for now, but
9888       // it doesn't hurt to split it out.
9889       if (!Meth->isImplicit())
9890         return oc_method;
9891 
9892       if (Meth->isMoveAssignmentOperator())
9893         return oc_implicit_move_assignment;
9894 
9895       if (Meth->isCopyAssignmentOperator())
9896         return oc_implicit_copy_assignment;
9897 
9898       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9899       return oc_method;
9900     }
9901 
9902     return oc_function;
9903   }();
9904 
9905   return std::make_pair(Kind, Select);
9906 }
9907 
9908 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9909   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9910   // set.
9911   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9912     S.Diag(FoundDecl->getLocation(),
9913            diag::note_ovl_candidate_inherited_constructor)
9914       << Shadow->getNominatedBaseClass();
9915 }
9916 
9917 } // end anonymous namespace
9918 
9919 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9920                                     const FunctionDecl *FD) {
9921   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9922     bool AlwaysTrue;
9923     if (EnableIf->getCond()->isValueDependent() ||
9924         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9925       return false;
9926     if (!AlwaysTrue)
9927       return false;
9928   }
9929   return true;
9930 }
9931 
9932 /// Returns true if we can take the address of the function.
9933 ///
9934 /// \param Complain - If true, we'll emit a diagnostic
9935 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9936 ///   we in overload resolution?
9937 /// \param Loc - The location of the statement we're complaining about. Ignored
9938 ///   if we're not complaining, or if we're in overload resolution.
9939 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9940                                               bool Complain,
9941                                               bool InOverloadResolution,
9942                                               SourceLocation Loc) {
9943   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9944     if (Complain) {
9945       if (InOverloadResolution)
9946         S.Diag(FD->getBeginLoc(),
9947                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9948       else
9949         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9950     }
9951     return false;
9952   }
9953 
9954   if (const Expr *RC = FD->getTrailingRequiresClause()) {
9955     ConstraintSatisfaction Satisfaction;
9956     if (S.CheckConstraintSatisfaction(RC, Satisfaction))
9957       return false;
9958     if (!Satisfaction.IsSatisfied) {
9959       if (Complain) {
9960         if (InOverloadResolution)
9961           S.Diag(FD->getBeginLoc(),
9962                  diag::note_ovl_candidate_unsatisfied_constraints);
9963         else
9964           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9965               << FD;
9966         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9967       }
9968       return false;
9969     }
9970   }
9971 
9972   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9973     return P->hasAttr<PassObjectSizeAttr>();
9974   });
9975   if (I == FD->param_end())
9976     return true;
9977 
9978   if (Complain) {
9979     // Add one to ParamNo because it's user-facing
9980     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9981     if (InOverloadResolution)
9982       S.Diag(FD->getLocation(),
9983              diag::note_ovl_candidate_has_pass_object_size_params)
9984           << ParamNo;
9985     else
9986       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9987           << FD << ParamNo;
9988   }
9989   return false;
9990 }
9991 
9992 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9993                                                const FunctionDecl *FD) {
9994   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9995                                            /*InOverloadResolution=*/true,
9996                                            /*Loc=*/SourceLocation());
9997 }
9998 
9999 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10000                                              bool Complain,
10001                                              SourceLocation Loc) {
10002   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10003                                              /*InOverloadResolution=*/false,
10004                                              Loc);
10005 }
10006 
10007 // Notes the location of an overload candidate.
10008 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10009                                  OverloadCandidateRewriteKind RewriteKind,
10010                                  QualType DestType, bool TakingAddress) {
10011   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10012     return;
10013   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10014       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10015     return;
10016 
10017   std::string FnDesc;
10018   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10019       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10020   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10021                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10022                          << Fn << FnDesc;
10023 
10024   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10025   Diag(Fn->getLocation(), PD);
10026   MaybeEmitInheritedConstructorNote(*this, Found);
10027 }
10028 
10029 static void
10030 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10031   // Perhaps the ambiguity was caused by two atomic constraints that are
10032   // 'identical' but not equivalent:
10033   //
10034   // void foo() requires (sizeof(T) > 4) { } // #1
10035   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10036   //
10037   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10038   // #2 to subsume #1, but these constraint are not considered equivalent
10039   // according to the subsumption rules because they are not the same
10040   // source-level construct. This behavior is quite confusing and we should try
10041   // to help the user figure out what happened.
10042 
10043   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10044   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10045   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10046     if (!I->Function)
10047       continue;
10048     SmallVector<const Expr *, 3> AC;
10049     if (auto *Template = I->Function->getPrimaryTemplate())
10050       Template->getAssociatedConstraints(AC);
10051     else
10052       I->Function->getAssociatedConstraints(AC);
10053     if (AC.empty())
10054       continue;
10055     if (FirstCand == nullptr) {
10056       FirstCand = I->Function;
10057       FirstAC = AC;
10058     } else if (SecondCand == nullptr) {
10059       SecondCand = I->Function;
10060       SecondAC = AC;
10061     } else {
10062       // We have more than one pair of constrained functions - this check is
10063       // expensive and we'd rather not try to diagnose it.
10064       return;
10065     }
10066   }
10067   if (!SecondCand)
10068     return;
10069   // The diagnostic can only happen if there are associated constraints on
10070   // both sides (there needs to be some identical atomic constraint).
10071   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10072                                                       SecondCand, SecondAC))
10073     // Just show the user one diagnostic, they'll probably figure it out
10074     // from here.
10075     return;
10076 }
10077 
10078 // Notes the location of all overload candidates designated through
10079 // OverloadedExpr
10080 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10081                                      bool TakingAddress) {
10082   assert(OverloadedExpr->getType() == Context.OverloadTy);
10083 
10084   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10085   OverloadExpr *OvlExpr = Ovl.Expression;
10086 
10087   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10088                             IEnd = OvlExpr->decls_end();
10089        I != IEnd; ++I) {
10090     if (FunctionTemplateDecl *FunTmpl =
10091                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10092       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10093                             TakingAddress);
10094     } else if (FunctionDecl *Fun
10095                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10096       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10097     }
10098   }
10099 }
10100 
10101 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10102 /// "lead" diagnostic; it will be given two arguments, the source and
10103 /// target types of the conversion.
10104 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10105                                  Sema &S,
10106                                  SourceLocation CaretLoc,
10107                                  const PartialDiagnostic &PDiag) const {
10108   S.Diag(CaretLoc, PDiag)
10109     << Ambiguous.getFromType() << Ambiguous.getToType();
10110   // FIXME: The note limiting machinery is borrowed from
10111   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10112   // refactoring here.
10113   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10114   unsigned CandsShown = 0;
10115   AmbiguousConversionSequence::const_iterator I, E;
10116   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10117     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10118       break;
10119     ++CandsShown;
10120     S.NoteOverloadCandidate(I->first, I->second);
10121   }
10122   if (I != E)
10123     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10124 }
10125 
10126 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10127                                   unsigned I, bool TakingCandidateAddress) {
10128   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10129   assert(Conv.isBad());
10130   assert(Cand->Function && "for now, candidate must be a function");
10131   FunctionDecl *Fn = Cand->Function;
10132 
10133   // There's a conversion slot for the object argument if this is a
10134   // non-constructor method.  Note that 'I' corresponds the
10135   // conversion-slot index.
10136   bool isObjectArgument = false;
10137   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10138     if (I == 0)
10139       isObjectArgument = true;
10140     else
10141       I--;
10142   }
10143 
10144   std::string FnDesc;
10145   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10146       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10147                                 FnDesc);
10148 
10149   Expr *FromExpr = Conv.Bad.FromExpr;
10150   QualType FromTy = Conv.Bad.getFromType();
10151   QualType ToTy = Conv.Bad.getToType();
10152 
10153   if (FromTy == S.Context.OverloadTy) {
10154     assert(FromExpr && "overload set argument came from implicit argument?");
10155     Expr *E = FromExpr->IgnoreParens();
10156     if (isa<UnaryOperator>(E))
10157       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10158     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10159 
10160     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10161         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10162         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10163         << Name << I + 1;
10164     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10165     return;
10166   }
10167 
10168   // Do some hand-waving analysis to see if the non-viability is due
10169   // to a qualifier mismatch.
10170   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10171   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10172   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10173     CToTy = RT->getPointeeType();
10174   else {
10175     // TODO: detect and diagnose the full richness of const mismatches.
10176     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10177       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10178         CFromTy = FromPT->getPointeeType();
10179         CToTy = ToPT->getPointeeType();
10180       }
10181   }
10182 
10183   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10184       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10185     Qualifiers FromQs = CFromTy.getQualifiers();
10186     Qualifiers ToQs = CToTy.getQualifiers();
10187 
10188     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10189       if (isObjectArgument)
10190         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10191             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10192             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10193             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10194       else
10195         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10196             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10197             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10198             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10199             << ToTy->isReferenceType() << I + 1;
10200       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10201       return;
10202     }
10203 
10204     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10205       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10206           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10207           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10208           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10209           << (unsigned)isObjectArgument << I + 1;
10210       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10211       return;
10212     }
10213 
10214     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10215       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10216           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10217           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10218           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10219           << (unsigned)isObjectArgument << I + 1;
10220       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10221       return;
10222     }
10223 
10224     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10225       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10226           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10227           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10228           << FromQs.hasUnaligned() << I + 1;
10229       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10230       return;
10231     }
10232 
10233     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10234     assert(CVR && "unexpected qualifiers mismatch");
10235 
10236     if (isObjectArgument) {
10237       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10238           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10239           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10240           << (CVR - 1);
10241     } else {
10242       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10243           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10244           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10245           << (CVR - 1) << I + 1;
10246     }
10247     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10248     return;
10249   }
10250 
10251   // Special diagnostic for failure to convert an initializer list, since
10252   // telling the user that it has type void is not useful.
10253   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10254     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10255         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10256         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10257         << ToTy << (unsigned)isObjectArgument << I + 1;
10258     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10259     return;
10260   }
10261 
10262   // Diagnose references or pointers to incomplete types differently,
10263   // since it's far from impossible that the incompleteness triggered
10264   // the failure.
10265   QualType TempFromTy = FromTy.getNonReferenceType();
10266   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10267     TempFromTy = PTy->getPointeeType();
10268   if (TempFromTy->isIncompleteType()) {
10269     // Emit the generic diagnostic and, optionally, add the hints to it.
10270     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10271         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10272         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10273         << ToTy << (unsigned)isObjectArgument << I + 1
10274         << (unsigned)(Cand->Fix.Kind);
10275 
10276     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10277     return;
10278   }
10279 
10280   // Diagnose base -> derived pointer conversions.
10281   unsigned BaseToDerivedConversion = 0;
10282   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10283     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10284       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10285                                                FromPtrTy->getPointeeType()) &&
10286           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10287           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10288           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10289                           FromPtrTy->getPointeeType()))
10290         BaseToDerivedConversion = 1;
10291     }
10292   } else if (const ObjCObjectPointerType *FromPtrTy
10293                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10294     if (const ObjCObjectPointerType *ToPtrTy
10295                                         = ToTy->getAs<ObjCObjectPointerType>())
10296       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10297         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10298           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10299                                                 FromPtrTy->getPointeeType()) &&
10300               FromIface->isSuperClassOf(ToIface))
10301             BaseToDerivedConversion = 2;
10302   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10303     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10304         !FromTy->isIncompleteType() &&
10305         !ToRefTy->getPointeeType()->isIncompleteType() &&
10306         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10307       BaseToDerivedConversion = 3;
10308     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10309                ToTy.getNonReferenceType().getCanonicalType() ==
10310                FromTy.getNonReferenceType().getCanonicalType()) {
10311       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10312           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10313           << (unsigned)isObjectArgument << I + 1
10314           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10315       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10316       return;
10317     }
10318   }
10319 
10320   if (BaseToDerivedConversion) {
10321     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10322         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10323         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10324         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10325     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10326     return;
10327   }
10328 
10329   if (isa<ObjCObjectPointerType>(CFromTy) &&
10330       isa<PointerType>(CToTy)) {
10331       Qualifiers FromQs = CFromTy.getQualifiers();
10332       Qualifiers ToQs = CToTy.getQualifiers();
10333       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10334         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10335             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10336             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10337             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10338         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10339         return;
10340       }
10341   }
10342 
10343   if (TakingCandidateAddress &&
10344       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10345     return;
10346 
10347   // Emit the generic diagnostic and, optionally, add the hints to it.
10348   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10349   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10350         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10351         << ToTy << (unsigned)isObjectArgument << I + 1
10352         << (unsigned)(Cand->Fix.Kind);
10353 
10354   // If we can fix the conversion, suggest the FixIts.
10355   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10356        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10357     FDiag << *HI;
10358   S.Diag(Fn->getLocation(), FDiag);
10359 
10360   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10361 }
10362 
10363 /// Additional arity mismatch diagnosis specific to a function overload
10364 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10365 /// over a candidate in any candidate set.
10366 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10367                                unsigned NumArgs) {
10368   FunctionDecl *Fn = Cand->Function;
10369   unsigned MinParams = Fn->getMinRequiredArguments();
10370 
10371   // With invalid overloaded operators, it's possible that we think we
10372   // have an arity mismatch when in fact it looks like we have the
10373   // right number of arguments, because only overloaded operators have
10374   // the weird behavior of overloading member and non-member functions.
10375   // Just don't report anything.
10376   if (Fn->isInvalidDecl() &&
10377       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10378     return true;
10379 
10380   if (NumArgs < MinParams) {
10381     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10382            (Cand->FailureKind == ovl_fail_bad_deduction &&
10383             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10384   } else {
10385     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10386            (Cand->FailureKind == ovl_fail_bad_deduction &&
10387             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10388   }
10389 
10390   return false;
10391 }
10392 
10393 /// General arity mismatch diagnosis over a candidate in a candidate set.
10394 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10395                                   unsigned NumFormalArgs) {
10396   assert(isa<FunctionDecl>(D) &&
10397       "The templated declaration should at least be a function"
10398       " when diagnosing bad template argument deduction due to too many"
10399       " or too few arguments");
10400 
10401   FunctionDecl *Fn = cast<FunctionDecl>(D);
10402 
10403   // TODO: treat calls to a missing default constructor as a special case
10404   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10405   unsigned MinParams = Fn->getMinRequiredArguments();
10406 
10407   // at least / at most / exactly
10408   unsigned mode, modeCount;
10409   if (NumFormalArgs < MinParams) {
10410     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10411         FnTy->isTemplateVariadic())
10412       mode = 0; // "at least"
10413     else
10414       mode = 2; // "exactly"
10415     modeCount = MinParams;
10416   } else {
10417     if (MinParams != FnTy->getNumParams())
10418       mode = 1; // "at most"
10419     else
10420       mode = 2; // "exactly"
10421     modeCount = FnTy->getNumParams();
10422   }
10423 
10424   std::string Description;
10425   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10426       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10427 
10428   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10429     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10430         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10431         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10432   else
10433     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10434         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10435         << Description << mode << modeCount << NumFormalArgs;
10436 
10437   MaybeEmitInheritedConstructorNote(S, Found);
10438 }
10439 
10440 /// Arity mismatch diagnosis specific to a function overload candidate.
10441 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10442                                   unsigned NumFormalArgs) {
10443   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10444     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10445 }
10446 
10447 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10448   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10449     return TD;
10450   llvm_unreachable("Unsupported: Getting the described template declaration"
10451                    " for bad deduction diagnosis");
10452 }
10453 
10454 /// Diagnose a failed template-argument deduction.
10455 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10456                                  DeductionFailureInfo &DeductionFailure,
10457                                  unsigned NumArgs,
10458                                  bool TakingCandidateAddress) {
10459   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10460   NamedDecl *ParamD;
10461   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10462   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10463   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10464   switch (DeductionFailure.Result) {
10465   case Sema::TDK_Success:
10466     llvm_unreachable("TDK_success while diagnosing bad deduction");
10467 
10468   case Sema::TDK_Incomplete: {
10469     assert(ParamD && "no parameter found for incomplete deduction result");
10470     S.Diag(Templated->getLocation(),
10471            diag::note_ovl_candidate_incomplete_deduction)
10472         << ParamD->getDeclName();
10473     MaybeEmitInheritedConstructorNote(S, Found);
10474     return;
10475   }
10476 
10477   case Sema::TDK_IncompletePack: {
10478     assert(ParamD && "no parameter found for incomplete deduction result");
10479     S.Diag(Templated->getLocation(),
10480            diag::note_ovl_candidate_incomplete_deduction_pack)
10481         << ParamD->getDeclName()
10482         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10483         << *DeductionFailure.getFirstArg();
10484     MaybeEmitInheritedConstructorNote(S, Found);
10485     return;
10486   }
10487 
10488   case Sema::TDK_Underqualified: {
10489     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10490     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10491 
10492     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10493 
10494     // Param will have been canonicalized, but it should just be a
10495     // qualified version of ParamD, so move the qualifiers to that.
10496     QualifierCollector Qs;
10497     Qs.strip(Param);
10498     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10499     assert(S.Context.hasSameType(Param, NonCanonParam));
10500 
10501     // Arg has also been canonicalized, but there's nothing we can do
10502     // about that.  It also doesn't matter as much, because it won't
10503     // have any template parameters in it (because deduction isn't
10504     // done on dependent types).
10505     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10506 
10507     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10508         << ParamD->getDeclName() << Arg << NonCanonParam;
10509     MaybeEmitInheritedConstructorNote(S, Found);
10510     return;
10511   }
10512 
10513   case Sema::TDK_Inconsistent: {
10514     assert(ParamD && "no parameter found for inconsistent deduction result");
10515     int which = 0;
10516     if (isa<TemplateTypeParmDecl>(ParamD))
10517       which = 0;
10518     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10519       // Deduction might have failed because we deduced arguments of two
10520       // different types for a non-type template parameter.
10521       // FIXME: Use a different TDK value for this.
10522       QualType T1 =
10523           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10524       QualType T2 =
10525           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10526       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10527         S.Diag(Templated->getLocation(),
10528                diag::note_ovl_candidate_inconsistent_deduction_types)
10529           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10530           << *DeductionFailure.getSecondArg() << T2;
10531         MaybeEmitInheritedConstructorNote(S, Found);
10532         return;
10533       }
10534 
10535       which = 1;
10536     } else {
10537       which = 2;
10538     }
10539 
10540     // Tweak the diagnostic if the problem is that we deduced packs of
10541     // different arities. We'll print the actual packs anyway in case that
10542     // includes additional useful information.
10543     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10544         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10545         DeductionFailure.getFirstArg()->pack_size() !=
10546             DeductionFailure.getSecondArg()->pack_size()) {
10547       which = 3;
10548     }
10549 
10550     S.Diag(Templated->getLocation(),
10551            diag::note_ovl_candidate_inconsistent_deduction)
10552         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10553         << *DeductionFailure.getSecondArg();
10554     MaybeEmitInheritedConstructorNote(S, Found);
10555     return;
10556   }
10557 
10558   case Sema::TDK_InvalidExplicitArguments:
10559     assert(ParamD && "no parameter found for invalid explicit arguments");
10560     if (ParamD->getDeclName())
10561       S.Diag(Templated->getLocation(),
10562              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10563           << ParamD->getDeclName();
10564     else {
10565       int index = 0;
10566       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10567         index = TTP->getIndex();
10568       else if (NonTypeTemplateParmDecl *NTTP
10569                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10570         index = NTTP->getIndex();
10571       else
10572         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10573       S.Diag(Templated->getLocation(),
10574              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10575           << (index + 1);
10576     }
10577     MaybeEmitInheritedConstructorNote(S, Found);
10578     return;
10579 
10580   case Sema::TDK_ConstraintsNotSatisfied: {
10581     // Format the template argument list into the argument string.
10582     SmallString<128> TemplateArgString;
10583     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10584     TemplateArgString = " ";
10585     TemplateArgString += S.getTemplateArgumentBindingsText(
10586         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10587     if (TemplateArgString.size() == 1)
10588       TemplateArgString.clear();
10589     S.Diag(Templated->getLocation(),
10590            diag::note_ovl_candidate_unsatisfied_constraints)
10591         << TemplateArgString;
10592 
10593     S.DiagnoseUnsatisfiedConstraint(
10594         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10595     return;
10596   }
10597   case Sema::TDK_TooManyArguments:
10598   case Sema::TDK_TooFewArguments:
10599     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10600     return;
10601 
10602   case Sema::TDK_InstantiationDepth:
10603     S.Diag(Templated->getLocation(),
10604            diag::note_ovl_candidate_instantiation_depth);
10605     MaybeEmitInheritedConstructorNote(S, Found);
10606     return;
10607 
10608   case Sema::TDK_SubstitutionFailure: {
10609     // Format the template argument list into the argument string.
10610     SmallString<128> TemplateArgString;
10611     if (TemplateArgumentList *Args =
10612             DeductionFailure.getTemplateArgumentList()) {
10613       TemplateArgString = " ";
10614       TemplateArgString += S.getTemplateArgumentBindingsText(
10615           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10616       if (TemplateArgString.size() == 1)
10617         TemplateArgString.clear();
10618     }
10619 
10620     // If this candidate was disabled by enable_if, say so.
10621     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10622     if (PDiag && PDiag->second.getDiagID() ==
10623           diag::err_typename_nested_not_found_enable_if) {
10624       // FIXME: Use the source range of the condition, and the fully-qualified
10625       //        name of the enable_if template. These are both present in PDiag.
10626       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10627         << "'enable_if'" << TemplateArgString;
10628       return;
10629     }
10630 
10631     // We found a specific requirement that disabled the enable_if.
10632     if (PDiag && PDiag->second.getDiagID() ==
10633         diag::err_typename_nested_not_found_requirement) {
10634       S.Diag(Templated->getLocation(),
10635              diag::note_ovl_candidate_disabled_by_requirement)
10636         << PDiag->second.getStringArg(0) << TemplateArgString;
10637       return;
10638     }
10639 
10640     // Format the SFINAE diagnostic into the argument string.
10641     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10642     //        formatted message in another diagnostic.
10643     SmallString<128> SFINAEArgString;
10644     SourceRange R;
10645     if (PDiag) {
10646       SFINAEArgString = ": ";
10647       R = SourceRange(PDiag->first, PDiag->first);
10648       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10649     }
10650 
10651     S.Diag(Templated->getLocation(),
10652            diag::note_ovl_candidate_substitution_failure)
10653         << TemplateArgString << SFINAEArgString << R;
10654     MaybeEmitInheritedConstructorNote(S, Found);
10655     return;
10656   }
10657 
10658   case Sema::TDK_DeducedMismatch:
10659   case Sema::TDK_DeducedMismatchNested: {
10660     // Format the template argument list into the argument string.
10661     SmallString<128> TemplateArgString;
10662     if (TemplateArgumentList *Args =
10663             DeductionFailure.getTemplateArgumentList()) {
10664       TemplateArgString = " ";
10665       TemplateArgString += S.getTemplateArgumentBindingsText(
10666           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10667       if (TemplateArgString.size() == 1)
10668         TemplateArgString.clear();
10669     }
10670 
10671     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10672         << (*DeductionFailure.getCallArgIndex() + 1)
10673         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10674         << TemplateArgString
10675         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10676     break;
10677   }
10678 
10679   case Sema::TDK_NonDeducedMismatch: {
10680     // FIXME: Provide a source location to indicate what we couldn't match.
10681     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10682     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10683     if (FirstTA.getKind() == TemplateArgument::Template &&
10684         SecondTA.getKind() == TemplateArgument::Template) {
10685       TemplateName FirstTN = FirstTA.getAsTemplate();
10686       TemplateName SecondTN = SecondTA.getAsTemplate();
10687       if (FirstTN.getKind() == TemplateName::Template &&
10688           SecondTN.getKind() == TemplateName::Template) {
10689         if (FirstTN.getAsTemplateDecl()->getName() ==
10690             SecondTN.getAsTemplateDecl()->getName()) {
10691           // FIXME: This fixes a bad diagnostic where both templates are named
10692           // the same.  This particular case is a bit difficult since:
10693           // 1) It is passed as a string to the diagnostic printer.
10694           // 2) The diagnostic printer only attempts to find a better
10695           //    name for types, not decls.
10696           // Ideally, this should folded into the diagnostic printer.
10697           S.Diag(Templated->getLocation(),
10698                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10699               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10700           return;
10701         }
10702       }
10703     }
10704 
10705     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10706         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10707       return;
10708 
10709     // FIXME: For generic lambda parameters, check if the function is a lambda
10710     // call operator, and if so, emit a prettier and more informative
10711     // diagnostic that mentions 'auto' and lambda in addition to
10712     // (or instead of?) the canonical template type parameters.
10713     S.Diag(Templated->getLocation(),
10714            diag::note_ovl_candidate_non_deduced_mismatch)
10715         << FirstTA << SecondTA;
10716     return;
10717   }
10718   // TODO: diagnose these individually, then kill off
10719   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10720   case Sema::TDK_MiscellaneousDeductionFailure:
10721     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10722     MaybeEmitInheritedConstructorNote(S, Found);
10723     return;
10724   case Sema::TDK_CUDATargetMismatch:
10725     S.Diag(Templated->getLocation(),
10726            diag::note_cuda_ovl_candidate_target_mismatch);
10727     return;
10728   }
10729 }
10730 
10731 /// Diagnose a failed template-argument deduction, for function calls.
10732 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10733                                  unsigned NumArgs,
10734                                  bool TakingCandidateAddress) {
10735   unsigned TDK = Cand->DeductionFailure.Result;
10736   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10737     if (CheckArityMismatch(S, Cand, NumArgs))
10738       return;
10739   }
10740   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10741                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10742 }
10743 
10744 /// CUDA: diagnose an invalid call across targets.
10745 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10746   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10747   FunctionDecl *Callee = Cand->Function;
10748 
10749   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10750                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10751 
10752   std::string FnDesc;
10753   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10754       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10755                                 Cand->getRewriteKind(), FnDesc);
10756 
10757   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10758       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10759       << FnDesc /* Ignored */
10760       << CalleeTarget << CallerTarget;
10761 
10762   // This could be an implicit constructor for which we could not infer the
10763   // target due to a collsion. Diagnose that case.
10764   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10765   if (Meth != nullptr && Meth->isImplicit()) {
10766     CXXRecordDecl *ParentClass = Meth->getParent();
10767     Sema::CXXSpecialMember CSM;
10768 
10769     switch (FnKindPair.first) {
10770     default:
10771       return;
10772     case oc_implicit_default_constructor:
10773       CSM = Sema::CXXDefaultConstructor;
10774       break;
10775     case oc_implicit_copy_constructor:
10776       CSM = Sema::CXXCopyConstructor;
10777       break;
10778     case oc_implicit_move_constructor:
10779       CSM = Sema::CXXMoveConstructor;
10780       break;
10781     case oc_implicit_copy_assignment:
10782       CSM = Sema::CXXCopyAssignment;
10783       break;
10784     case oc_implicit_move_assignment:
10785       CSM = Sema::CXXMoveAssignment;
10786       break;
10787     };
10788 
10789     bool ConstRHS = false;
10790     if (Meth->getNumParams()) {
10791       if (const ReferenceType *RT =
10792               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10793         ConstRHS = RT->getPointeeType().isConstQualified();
10794       }
10795     }
10796 
10797     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10798                                               /* ConstRHS */ ConstRHS,
10799                                               /* Diagnose */ true);
10800   }
10801 }
10802 
10803 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10804   FunctionDecl *Callee = Cand->Function;
10805   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10806 
10807   S.Diag(Callee->getLocation(),
10808          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10809       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10810 }
10811 
10812 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10813   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10814   assert(ES.isExplicit() && "not an explicit candidate");
10815 
10816   unsigned Kind;
10817   switch (Cand->Function->getDeclKind()) {
10818   case Decl::Kind::CXXConstructor:
10819     Kind = 0;
10820     break;
10821   case Decl::Kind::CXXConversion:
10822     Kind = 1;
10823     break;
10824   case Decl::Kind::CXXDeductionGuide:
10825     Kind = Cand->Function->isImplicit() ? 0 : 2;
10826     break;
10827   default:
10828     llvm_unreachable("invalid Decl");
10829   }
10830 
10831   // Note the location of the first (in-class) declaration; a redeclaration
10832   // (particularly an out-of-class definition) will typically lack the
10833   // 'explicit' specifier.
10834   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10835   FunctionDecl *First = Cand->Function->getFirstDecl();
10836   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10837     First = Pattern->getFirstDecl();
10838 
10839   S.Diag(First->getLocation(),
10840          diag::note_ovl_candidate_explicit)
10841       << Kind << (ES.getExpr() ? 1 : 0)
10842       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10843 }
10844 
10845 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10846   FunctionDecl *Callee = Cand->Function;
10847 
10848   S.Diag(Callee->getLocation(),
10849          diag::note_ovl_candidate_disabled_by_extension)
10850     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10851 }
10852 
10853 /// Generates a 'note' diagnostic for an overload candidate.  We've
10854 /// already generated a primary error at the call site.
10855 ///
10856 /// It really does need to be a single diagnostic with its caret
10857 /// pointed at the candidate declaration.  Yes, this creates some
10858 /// major challenges of technical writing.  Yes, this makes pointing
10859 /// out problems with specific arguments quite awkward.  It's still
10860 /// better than generating twenty screens of text for every failed
10861 /// overload.
10862 ///
10863 /// It would be great to be able to express per-candidate problems
10864 /// more richly for those diagnostic clients that cared, but we'd
10865 /// still have to be just as careful with the default diagnostics.
10866 /// \param CtorDestAS Addr space of object being constructed (for ctor
10867 /// candidates only).
10868 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10869                                   unsigned NumArgs,
10870                                   bool TakingCandidateAddress,
10871                                   LangAS CtorDestAS = LangAS::Default) {
10872   FunctionDecl *Fn = Cand->Function;
10873 
10874   // Note deleted candidates, but only if they're viable.
10875   if (Cand->Viable) {
10876     if (Fn->isDeleted()) {
10877       std::string FnDesc;
10878       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10879           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10880                                     Cand->getRewriteKind(), FnDesc);
10881 
10882       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10883           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10884           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10885       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10886       return;
10887     }
10888 
10889     // We don't really have anything else to say about viable candidates.
10890     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10891     return;
10892   }
10893 
10894   switch (Cand->FailureKind) {
10895   case ovl_fail_too_many_arguments:
10896   case ovl_fail_too_few_arguments:
10897     return DiagnoseArityMismatch(S, Cand, NumArgs);
10898 
10899   case ovl_fail_bad_deduction:
10900     return DiagnoseBadDeduction(S, Cand, NumArgs,
10901                                 TakingCandidateAddress);
10902 
10903   case ovl_fail_illegal_constructor: {
10904     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10905       << (Fn->getPrimaryTemplate() ? 1 : 0);
10906     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10907     return;
10908   }
10909 
10910   case ovl_fail_object_addrspace_mismatch: {
10911     Qualifiers QualsForPrinting;
10912     QualsForPrinting.setAddressSpace(CtorDestAS);
10913     S.Diag(Fn->getLocation(),
10914            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10915         << QualsForPrinting;
10916     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10917     return;
10918   }
10919 
10920   case ovl_fail_trivial_conversion:
10921   case ovl_fail_bad_final_conversion:
10922   case ovl_fail_final_conversion_not_exact:
10923     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10924 
10925   case ovl_fail_bad_conversion: {
10926     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10927     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10928       if (Cand->Conversions[I].isBad())
10929         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10930 
10931     // FIXME: this currently happens when we're called from SemaInit
10932     // when user-conversion overload fails.  Figure out how to handle
10933     // those conditions and diagnose them well.
10934     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10935   }
10936 
10937   case ovl_fail_bad_target:
10938     return DiagnoseBadTarget(S, Cand);
10939 
10940   case ovl_fail_enable_if:
10941     return DiagnoseFailedEnableIfAttr(S, Cand);
10942 
10943   case ovl_fail_explicit:
10944     return DiagnoseFailedExplicitSpec(S, Cand);
10945 
10946   case ovl_fail_ext_disabled:
10947     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10948 
10949   case ovl_fail_inhctor_slice:
10950     // It's generally not interesting to note copy/move constructors here.
10951     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10952       return;
10953     S.Diag(Fn->getLocation(),
10954            diag::note_ovl_candidate_inherited_constructor_slice)
10955       << (Fn->getPrimaryTemplate() ? 1 : 0)
10956       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10957     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10958     return;
10959 
10960   case ovl_fail_addr_not_available: {
10961     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10962     (void)Available;
10963     assert(!Available);
10964     break;
10965   }
10966   case ovl_non_default_multiversion_function:
10967     // Do nothing, these should simply be ignored.
10968     break;
10969 
10970   case ovl_fail_constraints_not_satisfied: {
10971     std::string FnDesc;
10972     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10973         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10974                                   Cand->getRewriteKind(), FnDesc);
10975 
10976     S.Diag(Fn->getLocation(),
10977            diag::note_ovl_candidate_constraints_not_satisfied)
10978         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10979         << FnDesc /* Ignored */;
10980     ConstraintSatisfaction Satisfaction;
10981     if (S.CheckConstraintSatisfaction(Fn->getTrailingRequiresClause(),
10982                                       Satisfaction))
10983       break;
10984     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10985   }
10986   }
10987 }
10988 
10989 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10990   // Desugar the type of the surrogate down to a function type,
10991   // retaining as many typedefs as possible while still showing
10992   // the function type (and, therefore, its parameter types).
10993   QualType FnType = Cand->Surrogate->getConversionType();
10994   bool isLValueReference = false;
10995   bool isRValueReference = false;
10996   bool isPointer = false;
10997   if (const LValueReferenceType *FnTypeRef =
10998         FnType->getAs<LValueReferenceType>()) {
10999     FnType = FnTypeRef->getPointeeType();
11000     isLValueReference = true;
11001   } else if (const RValueReferenceType *FnTypeRef =
11002                FnType->getAs<RValueReferenceType>()) {
11003     FnType = FnTypeRef->getPointeeType();
11004     isRValueReference = true;
11005   }
11006   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11007     FnType = FnTypePtr->getPointeeType();
11008     isPointer = true;
11009   }
11010   // Desugar down to a function type.
11011   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11012   // Reconstruct the pointer/reference as appropriate.
11013   if (isPointer) FnType = S.Context.getPointerType(FnType);
11014   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11015   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11016 
11017   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11018     << FnType;
11019 }
11020 
11021 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11022                                          SourceLocation OpLoc,
11023                                          OverloadCandidate *Cand) {
11024   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11025   std::string TypeStr("operator");
11026   TypeStr += Opc;
11027   TypeStr += "(";
11028   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11029   if (Cand->Conversions.size() == 1) {
11030     TypeStr += ")";
11031     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11032   } else {
11033     TypeStr += ", ";
11034     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11035     TypeStr += ")";
11036     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11037   }
11038 }
11039 
11040 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11041                                          OverloadCandidate *Cand) {
11042   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11043     if (ICS.isBad()) break; // all meaningless after first invalid
11044     if (!ICS.isAmbiguous()) continue;
11045 
11046     ICS.DiagnoseAmbiguousConversion(
11047         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11048   }
11049 }
11050 
11051 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11052   if (Cand->Function)
11053     return Cand->Function->getLocation();
11054   if (Cand->IsSurrogate)
11055     return Cand->Surrogate->getLocation();
11056   return SourceLocation();
11057 }
11058 
11059 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11060   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11061   case Sema::TDK_Success:
11062   case Sema::TDK_NonDependentConversionFailure:
11063     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11064 
11065   case Sema::TDK_Invalid:
11066   case Sema::TDK_Incomplete:
11067   case Sema::TDK_IncompletePack:
11068     return 1;
11069 
11070   case Sema::TDK_Underqualified:
11071   case Sema::TDK_Inconsistent:
11072     return 2;
11073 
11074   case Sema::TDK_SubstitutionFailure:
11075   case Sema::TDK_DeducedMismatch:
11076   case Sema::TDK_ConstraintsNotSatisfied:
11077   case Sema::TDK_DeducedMismatchNested:
11078   case Sema::TDK_NonDeducedMismatch:
11079   case Sema::TDK_MiscellaneousDeductionFailure:
11080   case Sema::TDK_CUDATargetMismatch:
11081     return 3;
11082 
11083   case Sema::TDK_InstantiationDepth:
11084     return 4;
11085 
11086   case Sema::TDK_InvalidExplicitArguments:
11087     return 5;
11088 
11089   case Sema::TDK_TooManyArguments:
11090   case Sema::TDK_TooFewArguments:
11091     return 6;
11092   }
11093   llvm_unreachable("Unhandled deduction result");
11094 }
11095 
11096 namespace {
11097 struct CompareOverloadCandidatesForDisplay {
11098   Sema &S;
11099   SourceLocation Loc;
11100   size_t NumArgs;
11101   OverloadCandidateSet::CandidateSetKind CSK;
11102 
11103   CompareOverloadCandidatesForDisplay(
11104       Sema &S, SourceLocation Loc, size_t NArgs,
11105       OverloadCandidateSet::CandidateSetKind CSK)
11106       : S(S), NumArgs(NArgs), CSK(CSK) {}
11107 
11108   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11109     // If there are too many or too few arguments, that's the high-order bit we
11110     // want to sort by, even if the immediate failure kind was something else.
11111     if (C->FailureKind == ovl_fail_too_many_arguments ||
11112         C->FailureKind == ovl_fail_too_few_arguments)
11113       return static_cast<OverloadFailureKind>(C->FailureKind);
11114 
11115     if (C->Function) {
11116       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11117         return ovl_fail_too_many_arguments;
11118       if (NumArgs < C->Function->getMinRequiredArguments())
11119         return ovl_fail_too_few_arguments;
11120     }
11121 
11122     return static_cast<OverloadFailureKind>(C->FailureKind);
11123   }
11124 
11125   bool operator()(const OverloadCandidate *L,
11126                   const OverloadCandidate *R) {
11127     // Fast-path this check.
11128     if (L == R) return false;
11129 
11130     // Order first by viability.
11131     if (L->Viable) {
11132       if (!R->Viable) return true;
11133 
11134       // TODO: introduce a tri-valued comparison for overload
11135       // candidates.  Would be more worthwhile if we had a sort
11136       // that could exploit it.
11137       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11138         return true;
11139       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11140         return false;
11141     } else if (R->Viable)
11142       return false;
11143 
11144     assert(L->Viable == R->Viable);
11145 
11146     // Criteria by which we can sort non-viable candidates:
11147     if (!L->Viable) {
11148       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11149       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11150 
11151       // 1. Arity mismatches come after other candidates.
11152       if (LFailureKind == ovl_fail_too_many_arguments ||
11153           LFailureKind == ovl_fail_too_few_arguments) {
11154         if (RFailureKind == ovl_fail_too_many_arguments ||
11155             RFailureKind == ovl_fail_too_few_arguments) {
11156           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11157           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11158           if (LDist == RDist) {
11159             if (LFailureKind == RFailureKind)
11160               // Sort non-surrogates before surrogates.
11161               return !L->IsSurrogate && R->IsSurrogate;
11162             // Sort candidates requiring fewer parameters than there were
11163             // arguments given after candidates requiring more parameters
11164             // than there were arguments given.
11165             return LFailureKind == ovl_fail_too_many_arguments;
11166           }
11167           return LDist < RDist;
11168         }
11169         return false;
11170       }
11171       if (RFailureKind == ovl_fail_too_many_arguments ||
11172           RFailureKind == ovl_fail_too_few_arguments)
11173         return true;
11174 
11175       // 2. Bad conversions come first and are ordered by the number
11176       // of bad conversions and quality of good conversions.
11177       if (LFailureKind == ovl_fail_bad_conversion) {
11178         if (RFailureKind != ovl_fail_bad_conversion)
11179           return true;
11180 
11181         // The conversion that can be fixed with a smaller number of changes,
11182         // comes first.
11183         unsigned numLFixes = L->Fix.NumConversionsFixed;
11184         unsigned numRFixes = R->Fix.NumConversionsFixed;
11185         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11186         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11187         if (numLFixes != numRFixes) {
11188           return numLFixes < numRFixes;
11189         }
11190 
11191         // If there's any ordering between the defined conversions...
11192         // FIXME: this might not be transitive.
11193         assert(L->Conversions.size() == R->Conversions.size());
11194 
11195         int leftBetter = 0;
11196         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11197         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11198           switch (CompareImplicitConversionSequences(S, Loc,
11199                                                      L->Conversions[I],
11200                                                      R->Conversions[I])) {
11201           case ImplicitConversionSequence::Better:
11202             leftBetter++;
11203             break;
11204 
11205           case ImplicitConversionSequence::Worse:
11206             leftBetter--;
11207             break;
11208 
11209           case ImplicitConversionSequence::Indistinguishable:
11210             break;
11211           }
11212         }
11213         if (leftBetter > 0) return true;
11214         if (leftBetter < 0) return false;
11215 
11216       } else if (RFailureKind == ovl_fail_bad_conversion)
11217         return false;
11218 
11219       if (LFailureKind == ovl_fail_bad_deduction) {
11220         if (RFailureKind != ovl_fail_bad_deduction)
11221           return true;
11222 
11223         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11224           return RankDeductionFailure(L->DeductionFailure)
11225                < RankDeductionFailure(R->DeductionFailure);
11226       } else if (RFailureKind == ovl_fail_bad_deduction)
11227         return false;
11228 
11229       // TODO: others?
11230     }
11231 
11232     // Sort everything else by location.
11233     SourceLocation LLoc = GetLocationForCandidate(L);
11234     SourceLocation RLoc = GetLocationForCandidate(R);
11235 
11236     // Put candidates without locations (e.g. builtins) at the end.
11237     if (LLoc.isInvalid()) return false;
11238     if (RLoc.isInvalid()) return true;
11239 
11240     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11241   }
11242 };
11243 }
11244 
11245 /// CompleteNonViableCandidate - Normally, overload resolution only
11246 /// computes up to the first bad conversion. Produces the FixIt set if
11247 /// possible.
11248 static void
11249 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11250                            ArrayRef<Expr *> Args,
11251                            OverloadCandidateSet::CandidateSetKind CSK) {
11252   assert(!Cand->Viable);
11253 
11254   // Don't do anything on failures other than bad conversion.
11255   if (Cand->FailureKind != ovl_fail_bad_conversion)
11256     return;
11257 
11258   // We only want the FixIts if all the arguments can be corrected.
11259   bool Unfixable = false;
11260   // Use a implicit copy initialization to check conversion fixes.
11261   Cand->Fix.setConversionChecker(TryCopyInitialization);
11262 
11263   // Attempt to fix the bad conversion.
11264   unsigned ConvCount = Cand->Conversions.size();
11265   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11266        ++ConvIdx) {
11267     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11268     if (Cand->Conversions[ConvIdx].isInitialized() &&
11269         Cand->Conversions[ConvIdx].isBad()) {
11270       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11271       break;
11272     }
11273   }
11274 
11275   // FIXME: this should probably be preserved from the overload
11276   // operation somehow.
11277   bool SuppressUserConversions = false;
11278 
11279   unsigned ConvIdx = 0;
11280   unsigned ArgIdx = 0;
11281   ArrayRef<QualType> ParamTypes;
11282   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11283 
11284   if (Cand->IsSurrogate) {
11285     QualType ConvType
11286       = Cand->Surrogate->getConversionType().getNonReferenceType();
11287     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11288       ConvType = ConvPtrType->getPointeeType();
11289     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11290     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11291     ConvIdx = 1;
11292   } else if (Cand->Function) {
11293     ParamTypes =
11294         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11295     if (isa<CXXMethodDecl>(Cand->Function) &&
11296         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11297       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11298       ConvIdx = 1;
11299       if (CSK == OverloadCandidateSet::CSK_Operator &&
11300           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11301         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11302         ArgIdx = 1;
11303     }
11304   } else {
11305     // Builtin operator.
11306     assert(ConvCount <= 3);
11307     ParamTypes = Cand->BuiltinParamTypes;
11308   }
11309 
11310   // Fill in the rest of the conversions.
11311   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11312        ConvIdx != ConvCount;
11313        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11314     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11315     if (Cand->Conversions[ConvIdx].isInitialized()) {
11316       // We've already checked this conversion.
11317     } else if (ParamIdx < ParamTypes.size()) {
11318       if (ParamTypes[ParamIdx]->isDependentType())
11319         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11320             Args[ArgIdx]->getType());
11321       else {
11322         Cand->Conversions[ConvIdx] =
11323             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11324                                   SuppressUserConversions,
11325                                   /*InOverloadResolution=*/true,
11326                                   /*AllowObjCWritebackConversion=*/
11327                                   S.getLangOpts().ObjCAutoRefCount);
11328         // Store the FixIt in the candidate if it exists.
11329         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11330           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11331       }
11332     } else
11333       Cand->Conversions[ConvIdx].setEllipsis();
11334   }
11335 }
11336 
11337 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11338     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11339     SourceLocation OpLoc,
11340     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11341   // Sort the candidates by viability and position.  Sorting directly would
11342   // be prohibitive, so we make a set of pointers and sort those.
11343   SmallVector<OverloadCandidate*, 32> Cands;
11344   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11345   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11346     if (!Filter(*Cand))
11347       continue;
11348     switch (OCD) {
11349     case OCD_AllCandidates:
11350       if (!Cand->Viable) {
11351         if (!Cand->Function && !Cand->IsSurrogate) {
11352           // This a non-viable builtin candidate.  We do not, in general,
11353           // want to list every possible builtin candidate.
11354           continue;
11355         }
11356         CompleteNonViableCandidate(S, Cand, Args, Kind);
11357       }
11358       break;
11359 
11360     case OCD_ViableCandidates:
11361       if (!Cand->Viable)
11362         continue;
11363       break;
11364 
11365     case OCD_AmbiguousCandidates:
11366       if (!Cand->Best)
11367         continue;
11368       break;
11369     }
11370 
11371     Cands.push_back(Cand);
11372   }
11373 
11374   llvm::stable_sort(
11375       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11376 
11377   return Cands;
11378 }
11379 
11380 /// When overload resolution fails, prints diagnostic messages containing the
11381 /// candidates in the candidate set.
11382 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11383     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11384     StringRef Opc, SourceLocation OpLoc,
11385     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11386 
11387   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11388 
11389   S.Diag(PD.first, PD.second);
11390 
11391   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11392 
11393   if (OCD == OCD_AmbiguousCandidates)
11394     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11395 }
11396 
11397 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11398                                           ArrayRef<OverloadCandidate *> Cands,
11399                                           StringRef Opc, SourceLocation OpLoc) {
11400   bool ReportedAmbiguousConversions = false;
11401 
11402   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11403   unsigned CandsShown = 0;
11404   auto I = Cands.begin(), E = Cands.end();
11405   for (; I != E; ++I) {
11406     OverloadCandidate *Cand = *I;
11407 
11408     // Set an arbitrary limit on the number of candidate functions we'll spam
11409     // the user with.  FIXME: This limit should depend on details of the
11410     // candidate list.
11411     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11412       break;
11413     }
11414     ++CandsShown;
11415 
11416     if (Cand->Function)
11417       NoteFunctionCandidate(S, Cand, Args.size(),
11418                             /*TakingCandidateAddress=*/false, DestAS);
11419     else if (Cand->IsSurrogate)
11420       NoteSurrogateCandidate(S, Cand);
11421     else {
11422       assert(Cand->Viable &&
11423              "Non-viable built-in candidates are not added to Cands.");
11424       // Generally we only see ambiguities including viable builtin
11425       // operators if overload resolution got screwed up by an
11426       // ambiguous user-defined conversion.
11427       //
11428       // FIXME: It's quite possible for different conversions to see
11429       // different ambiguities, though.
11430       if (!ReportedAmbiguousConversions) {
11431         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11432         ReportedAmbiguousConversions = true;
11433       }
11434 
11435       // If this is a viable builtin, print it.
11436       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11437     }
11438   }
11439 
11440   if (I != E)
11441     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11442 }
11443 
11444 static SourceLocation
11445 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11446   return Cand->Specialization ? Cand->Specialization->getLocation()
11447                               : SourceLocation();
11448 }
11449 
11450 namespace {
11451 struct CompareTemplateSpecCandidatesForDisplay {
11452   Sema &S;
11453   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11454 
11455   bool operator()(const TemplateSpecCandidate *L,
11456                   const TemplateSpecCandidate *R) {
11457     // Fast-path this check.
11458     if (L == R)
11459       return false;
11460 
11461     // Assuming that both candidates are not matches...
11462 
11463     // Sort by the ranking of deduction failures.
11464     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11465       return RankDeductionFailure(L->DeductionFailure) <
11466              RankDeductionFailure(R->DeductionFailure);
11467 
11468     // Sort everything else by location.
11469     SourceLocation LLoc = GetLocationForCandidate(L);
11470     SourceLocation RLoc = GetLocationForCandidate(R);
11471 
11472     // Put candidates without locations (e.g. builtins) at the end.
11473     if (LLoc.isInvalid())
11474       return false;
11475     if (RLoc.isInvalid())
11476       return true;
11477 
11478     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11479   }
11480 };
11481 }
11482 
11483 /// Diagnose a template argument deduction failure.
11484 /// We are treating these failures as overload failures due to bad
11485 /// deductions.
11486 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11487                                                  bool ForTakingAddress) {
11488   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11489                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11490 }
11491 
11492 void TemplateSpecCandidateSet::destroyCandidates() {
11493   for (iterator i = begin(), e = end(); i != e; ++i) {
11494     i->DeductionFailure.Destroy();
11495   }
11496 }
11497 
11498 void TemplateSpecCandidateSet::clear() {
11499   destroyCandidates();
11500   Candidates.clear();
11501 }
11502 
11503 /// NoteCandidates - When no template specialization match is found, prints
11504 /// diagnostic messages containing the non-matching specializations that form
11505 /// the candidate set.
11506 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11507 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11508 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11509   // Sort the candidates by position (assuming no candidate is a match).
11510   // Sorting directly would be prohibitive, so we make a set of pointers
11511   // and sort those.
11512   SmallVector<TemplateSpecCandidate *, 32> Cands;
11513   Cands.reserve(size());
11514   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11515     if (Cand->Specialization)
11516       Cands.push_back(Cand);
11517     // Otherwise, this is a non-matching builtin candidate.  We do not,
11518     // in general, want to list every possible builtin candidate.
11519   }
11520 
11521   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11522 
11523   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11524   // for generalization purposes (?).
11525   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11526 
11527   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11528   unsigned CandsShown = 0;
11529   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11530     TemplateSpecCandidate *Cand = *I;
11531 
11532     // Set an arbitrary limit on the number of candidates we'll spam
11533     // the user with.  FIXME: This limit should depend on details of the
11534     // candidate list.
11535     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11536       break;
11537     ++CandsShown;
11538 
11539     assert(Cand->Specialization &&
11540            "Non-matching built-in candidates are not added to Cands.");
11541     Cand->NoteDeductionFailure(S, ForTakingAddress);
11542   }
11543 
11544   if (I != E)
11545     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11546 }
11547 
11548 // [PossiblyAFunctionType]  -->   [Return]
11549 // NonFunctionType --> NonFunctionType
11550 // R (A) --> R(A)
11551 // R (*)(A) --> R (A)
11552 // R (&)(A) --> R (A)
11553 // R (S::*)(A) --> R (A)
11554 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11555   QualType Ret = PossiblyAFunctionType;
11556   if (const PointerType *ToTypePtr =
11557     PossiblyAFunctionType->getAs<PointerType>())
11558     Ret = ToTypePtr->getPointeeType();
11559   else if (const ReferenceType *ToTypeRef =
11560     PossiblyAFunctionType->getAs<ReferenceType>())
11561     Ret = ToTypeRef->getPointeeType();
11562   else if (const MemberPointerType *MemTypePtr =
11563     PossiblyAFunctionType->getAs<MemberPointerType>())
11564     Ret = MemTypePtr->getPointeeType();
11565   Ret =
11566     Context.getCanonicalType(Ret).getUnqualifiedType();
11567   return Ret;
11568 }
11569 
11570 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11571                                  bool Complain = true) {
11572   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11573       S.DeduceReturnType(FD, Loc, Complain))
11574     return true;
11575 
11576   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11577   if (S.getLangOpts().CPlusPlus17 &&
11578       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11579       !S.ResolveExceptionSpec(Loc, FPT))
11580     return true;
11581 
11582   return false;
11583 }
11584 
11585 namespace {
11586 // A helper class to help with address of function resolution
11587 // - allows us to avoid passing around all those ugly parameters
11588 class AddressOfFunctionResolver {
11589   Sema& S;
11590   Expr* SourceExpr;
11591   const QualType& TargetType;
11592   QualType TargetFunctionType; // Extracted function type from target type
11593 
11594   bool Complain;
11595   //DeclAccessPair& ResultFunctionAccessPair;
11596   ASTContext& Context;
11597 
11598   bool TargetTypeIsNonStaticMemberFunction;
11599   bool FoundNonTemplateFunction;
11600   bool StaticMemberFunctionFromBoundPointer;
11601   bool HasComplained;
11602 
11603   OverloadExpr::FindResult OvlExprInfo;
11604   OverloadExpr *OvlExpr;
11605   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11606   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11607   TemplateSpecCandidateSet FailedCandidates;
11608 
11609 public:
11610   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11611                             const QualType &TargetType, bool Complain)
11612       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11613         Complain(Complain), Context(S.getASTContext()),
11614         TargetTypeIsNonStaticMemberFunction(
11615             !!TargetType->getAs<MemberPointerType>()),
11616         FoundNonTemplateFunction(false),
11617         StaticMemberFunctionFromBoundPointer(false),
11618         HasComplained(false),
11619         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11620         OvlExpr(OvlExprInfo.Expression),
11621         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11622     ExtractUnqualifiedFunctionTypeFromTargetType();
11623 
11624     if (TargetFunctionType->isFunctionType()) {
11625       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11626         if (!UME->isImplicitAccess() &&
11627             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11628           StaticMemberFunctionFromBoundPointer = true;
11629     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11630       DeclAccessPair dap;
11631       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11632               OvlExpr, false, &dap)) {
11633         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11634           if (!Method->isStatic()) {
11635             // If the target type is a non-function type and the function found
11636             // is a non-static member function, pretend as if that was the
11637             // target, it's the only possible type to end up with.
11638             TargetTypeIsNonStaticMemberFunction = true;
11639 
11640             // And skip adding the function if its not in the proper form.
11641             // We'll diagnose this due to an empty set of functions.
11642             if (!OvlExprInfo.HasFormOfMemberPointer)
11643               return;
11644           }
11645 
11646         Matches.push_back(std::make_pair(dap, Fn));
11647       }
11648       return;
11649     }
11650 
11651     if (OvlExpr->hasExplicitTemplateArgs())
11652       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11653 
11654     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11655       // C++ [over.over]p4:
11656       //   If more than one function is selected, [...]
11657       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11658         if (FoundNonTemplateFunction)
11659           EliminateAllTemplateMatches();
11660         else
11661           EliminateAllExceptMostSpecializedTemplate();
11662       }
11663     }
11664 
11665     if (S.getLangOpts().CUDA && Matches.size() > 1)
11666       EliminateSuboptimalCudaMatches();
11667   }
11668 
11669   bool hasComplained() const { return HasComplained; }
11670 
11671 private:
11672   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11673     QualType Discard;
11674     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11675            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11676   }
11677 
11678   /// \return true if A is considered a better overload candidate for the
11679   /// desired type than B.
11680   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11681     // If A doesn't have exactly the correct type, we don't want to classify it
11682     // as "better" than anything else. This way, the user is required to
11683     // disambiguate for us if there are multiple candidates and no exact match.
11684     return candidateHasExactlyCorrectType(A) &&
11685            (!candidateHasExactlyCorrectType(B) ||
11686             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11687   }
11688 
11689   /// \return true if we were able to eliminate all but one overload candidate,
11690   /// false otherwise.
11691   bool eliminiateSuboptimalOverloadCandidates() {
11692     // Same algorithm as overload resolution -- one pass to pick the "best",
11693     // another pass to be sure that nothing is better than the best.
11694     auto Best = Matches.begin();
11695     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11696       if (isBetterCandidate(I->second, Best->second))
11697         Best = I;
11698 
11699     const FunctionDecl *BestFn = Best->second;
11700     auto IsBestOrInferiorToBest = [this, BestFn](
11701         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11702       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11703     };
11704 
11705     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11706     // option, so we can potentially give the user a better error
11707     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11708       return false;
11709     Matches[0] = *Best;
11710     Matches.resize(1);
11711     return true;
11712   }
11713 
11714   bool isTargetTypeAFunction() const {
11715     return TargetFunctionType->isFunctionType();
11716   }
11717 
11718   // [ToType]     [Return]
11719 
11720   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11721   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11722   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11723   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11724     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11725   }
11726 
11727   // return true if any matching specializations were found
11728   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11729                                    const DeclAccessPair& CurAccessFunPair) {
11730     if (CXXMethodDecl *Method
11731               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11732       // Skip non-static function templates when converting to pointer, and
11733       // static when converting to member pointer.
11734       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11735         return false;
11736     }
11737     else if (TargetTypeIsNonStaticMemberFunction)
11738       return false;
11739 
11740     // C++ [over.over]p2:
11741     //   If the name is a function template, template argument deduction is
11742     //   done (14.8.2.2), and if the argument deduction succeeds, the
11743     //   resulting template argument list is used to generate a single
11744     //   function template specialization, which is added to the set of
11745     //   overloaded functions considered.
11746     FunctionDecl *Specialization = nullptr;
11747     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11748     if (Sema::TemplateDeductionResult Result
11749           = S.DeduceTemplateArguments(FunctionTemplate,
11750                                       &OvlExplicitTemplateArgs,
11751                                       TargetFunctionType, Specialization,
11752                                       Info, /*IsAddressOfFunction*/true)) {
11753       // Make a note of the failed deduction for diagnostics.
11754       FailedCandidates.addCandidate()
11755           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11756                MakeDeductionFailureInfo(Context, Result, Info));
11757       return false;
11758     }
11759 
11760     // Template argument deduction ensures that we have an exact match or
11761     // compatible pointer-to-function arguments that would be adjusted by ICS.
11762     // This function template specicalization works.
11763     assert(S.isSameOrCompatibleFunctionType(
11764               Context.getCanonicalType(Specialization->getType()),
11765               Context.getCanonicalType(TargetFunctionType)));
11766 
11767     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11768       return false;
11769 
11770     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11771     return true;
11772   }
11773 
11774   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11775                                       const DeclAccessPair& CurAccessFunPair) {
11776     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11777       // Skip non-static functions when converting to pointer, and static
11778       // when converting to member pointer.
11779       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11780         return false;
11781     }
11782     else if (TargetTypeIsNonStaticMemberFunction)
11783       return false;
11784 
11785     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11786       if (S.getLangOpts().CUDA)
11787         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11788           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11789             return false;
11790       if (FunDecl->isMultiVersion()) {
11791         const auto *TA = FunDecl->getAttr<TargetAttr>();
11792         if (TA && !TA->isDefaultVersion())
11793           return false;
11794       }
11795 
11796       // If any candidate has a placeholder return type, trigger its deduction
11797       // now.
11798       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11799                                Complain)) {
11800         HasComplained |= Complain;
11801         return false;
11802       }
11803 
11804       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11805         return false;
11806 
11807       // If we're in C, we need to support types that aren't exactly identical.
11808       if (!S.getLangOpts().CPlusPlus ||
11809           candidateHasExactlyCorrectType(FunDecl)) {
11810         Matches.push_back(std::make_pair(
11811             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11812         FoundNonTemplateFunction = true;
11813         return true;
11814       }
11815     }
11816 
11817     return false;
11818   }
11819 
11820   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11821     bool Ret = false;
11822 
11823     // If the overload expression doesn't have the form of a pointer to
11824     // member, don't try to convert it to a pointer-to-member type.
11825     if (IsInvalidFormOfPointerToMemberFunction())
11826       return false;
11827 
11828     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11829                                E = OvlExpr->decls_end();
11830          I != E; ++I) {
11831       // Look through any using declarations to find the underlying function.
11832       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11833 
11834       // C++ [over.over]p3:
11835       //   Non-member functions and static member functions match
11836       //   targets of type "pointer-to-function" or "reference-to-function."
11837       //   Nonstatic member functions match targets of
11838       //   type "pointer-to-member-function."
11839       // Note that according to DR 247, the containing class does not matter.
11840       if (FunctionTemplateDecl *FunctionTemplate
11841                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11842         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11843           Ret = true;
11844       }
11845       // If we have explicit template arguments supplied, skip non-templates.
11846       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11847                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11848         Ret = true;
11849     }
11850     assert(Ret || Matches.empty());
11851     return Ret;
11852   }
11853 
11854   void EliminateAllExceptMostSpecializedTemplate() {
11855     //   [...] and any given function template specialization F1 is
11856     //   eliminated if the set contains a second function template
11857     //   specialization whose function template is more specialized
11858     //   than the function template of F1 according to the partial
11859     //   ordering rules of 14.5.5.2.
11860 
11861     // The algorithm specified above is quadratic. We instead use a
11862     // two-pass algorithm (similar to the one used to identify the
11863     // best viable function in an overload set) that identifies the
11864     // best function template (if it exists).
11865 
11866     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11867     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11868       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11869 
11870     // TODO: It looks like FailedCandidates does not serve much purpose
11871     // here, since the no_viable diagnostic has index 0.
11872     UnresolvedSetIterator Result = S.getMostSpecialized(
11873         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11874         SourceExpr->getBeginLoc(), S.PDiag(),
11875         S.PDiag(diag::err_addr_ovl_ambiguous)
11876             << Matches[0].second->getDeclName(),
11877         S.PDiag(diag::note_ovl_candidate)
11878             << (unsigned)oc_function << (unsigned)ocs_described_template,
11879         Complain, TargetFunctionType);
11880 
11881     if (Result != MatchesCopy.end()) {
11882       // Make it the first and only element
11883       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11884       Matches[0].second = cast<FunctionDecl>(*Result);
11885       Matches.resize(1);
11886     } else
11887       HasComplained |= Complain;
11888   }
11889 
11890   void EliminateAllTemplateMatches() {
11891     //   [...] any function template specializations in the set are
11892     //   eliminated if the set also contains a non-template function, [...]
11893     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11894       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11895         ++I;
11896       else {
11897         Matches[I] = Matches[--N];
11898         Matches.resize(N);
11899       }
11900     }
11901   }
11902 
11903   void EliminateSuboptimalCudaMatches() {
11904     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11905   }
11906 
11907 public:
11908   void ComplainNoMatchesFound() const {
11909     assert(Matches.empty());
11910     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11911         << OvlExpr->getName() << TargetFunctionType
11912         << OvlExpr->getSourceRange();
11913     if (FailedCandidates.empty())
11914       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11915                                   /*TakingAddress=*/true);
11916     else {
11917       // We have some deduction failure messages. Use them to diagnose
11918       // the function templates, and diagnose the non-template candidates
11919       // normally.
11920       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11921                                  IEnd = OvlExpr->decls_end();
11922            I != IEnd; ++I)
11923         if (FunctionDecl *Fun =
11924                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11925           if (!functionHasPassObjectSizeParams(Fun))
11926             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11927                                     /*TakingAddress=*/true);
11928       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11929     }
11930   }
11931 
11932   bool IsInvalidFormOfPointerToMemberFunction() const {
11933     return TargetTypeIsNonStaticMemberFunction &&
11934       !OvlExprInfo.HasFormOfMemberPointer;
11935   }
11936 
11937   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11938       // TODO: Should we condition this on whether any functions might
11939       // have matched, or is it more appropriate to do that in callers?
11940       // TODO: a fixit wouldn't hurt.
11941       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11942         << TargetType << OvlExpr->getSourceRange();
11943   }
11944 
11945   bool IsStaticMemberFunctionFromBoundPointer() const {
11946     return StaticMemberFunctionFromBoundPointer;
11947   }
11948 
11949   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11950     S.Diag(OvlExpr->getBeginLoc(),
11951            diag::err_invalid_form_pointer_member_function)
11952         << OvlExpr->getSourceRange();
11953   }
11954 
11955   void ComplainOfInvalidConversion() const {
11956     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11957         << OvlExpr->getName() << TargetType;
11958   }
11959 
11960   void ComplainMultipleMatchesFound() const {
11961     assert(Matches.size() > 1);
11962     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11963         << OvlExpr->getName() << OvlExpr->getSourceRange();
11964     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11965                                 /*TakingAddress=*/true);
11966   }
11967 
11968   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11969 
11970   int getNumMatches() const { return Matches.size(); }
11971 
11972   FunctionDecl* getMatchingFunctionDecl() const {
11973     if (Matches.size() != 1) return nullptr;
11974     return Matches[0].second;
11975   }
11976 
11977   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11978     if (Matches.size() != 1) return nullptr;
11979     return &Matches[0].first;
11980   }
11981 };
11982 }
11983 
11984 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11985 /// an overloaded function (C++ [over.over]), where @p From is an
11986 /// expression with overloaded function type and @p ToType is the type
11987 /// we're trying to resolve to. For example:
11988 ///
11989 /// @code
11990 /// int f(double);
11991 /// int f(int);
11992 ///
11993 /// int (*pfd)(double) = f; // selects f(double)
11994 /// @endcode
11995 ///
11996 /// This routine returns the resulting FunctionDecl if it could be
11997 /// resolved, and NULL otherwise. When @p Complain is true, this
11998 /// routine will emit diagnostics if there is an error.
11999 FunctionDecl *
12000 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12001                                          QualType TargetType,
12002                                          bool Complain,
12003                                          DeclAccessPair &FoundResult,
12004                                          bool *pHadMultipleCandidates) {
12005   assert(AddressOfExpr->getType() == Context.OverloadTy);
12006 
12007   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12008                                      Complain);
12009   int NumMatches = Resolver.getNumMatches();
12010   FunctionDecl *Fn = nullptr;
12011   bool ShouldComplain = Complain && !Resolver.hasComplained();
12012   if (NumMatches == 0 && ShouldComplain) {
12013     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12014       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12015     else
12016       Resolver.ComplainNoMatchesFound();
12017   }
12018   else if (NumMatches > 1 && ShouldComplain)
12019     Resolver.ComplainMultipleMatchesFound();
12020   else if (NumMatches == 1) {
12021     Fn = Resolver.getMatchingFunctionDecl();
12022     assert(Fn);
12023     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12024       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12025     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12026     if (Complain) {
12027       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12028         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12029       else
12030         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12031     }
12032   }
12033 
12034   if (pHadMultipleCandidates)
12035     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12036   return Fn;
12037 }
12038 
12039 /// Given an expression that refers to an overloaded function, try to
12040 /// resolve that function to a single function that can have its address taken.
12041 /// This will modify `Pair` iff it returns non-null.
12042 ///
12043 /// This routine can only succeed if from all of the candidates in the overload
12044 /// set for SrcExpr that can have their addresses taken, there is one candidate
12045 /// that is more constrained than the rest.
12046 FunctionDecl *
12047 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12048   OverloadExpr::FindResult R = OverloadExpr::find(E);
12049   OverloadExpr *Ovl = R.Expression;
12050   bool IsResultAmbiguous = false;
12051   FunctionDecl *Result = nullptr;
12052   DeclAccessPair DAP;
12053   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12054 
12055   auto CheckMoreConstrained =
12056       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12057         SmallVector<const Expr *, 1> AC1, AC2;
12058         FD1->getAssociatedConstraints(AC1);
12059         FD2->getAssociatedConstraints(AC2);
12060         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12061         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12062           return None;
12063         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12064           return None;
12065         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12066           return None;
12067         return AtLeastAsConstrained1;
12068       };
12069 
12070   // Don't use the AddressOfResolver because we're specifically looking for
12071   // cases where we have one overload candidate that lacks
12072   // enable_if/pass_object_size/...
12073   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12074     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12075     if (!FD)
12076       return nullptr;
12077 
12078     if (!checkAddressOfFunctionIsAvailable(FD))
12079       continue;
12080 
12081     // We have more than one result - see if it is more constrained than the
12082     // previous one.
12083     if (Result) {
12084       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12085                                                                         Result);
12086       if (!MoreConstrainedThanPrevious) {
12087         IsResultAmbiguous = true;
12088         AmbiguousDecls.push_back(FD);
12089         continue;
12090       }
12091       if (!*MoreConstrainedThanPrevious)
12092         continue;
12093       // FD is more constrained - replace Result with it.
12094     }
12095     IsResultAmbiguous = false;
12096     DAP = I.getPair();
12097     Result = FD;
12098   }
12099 
12100   if (IsResultAmbiguous)
12101     return nullptr;
12102 
12103   if (Result) {
12104     SmallVector<const Expr *, 1> ResultAC;
12105     // We skipped over some ambiguous declarations which might be ambiguous with
12106     // the selected result.
12107     for (FunctionDecl *Skipped : AmbiguousDecls)
12108       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12109         return nullptr;
12110     Pair = DAP;
12111   }
12112   return Result;
12113 }
12114 
12115 /// Given an overloaded function, tries to turn it into a non-overloaded
12116 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12117 /// will perform access checks, diagnose the use of the resultant decl, and, if
12118 /// requested, potentially perform a function-to-pointer decay.
12119 ///
12120 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12121 /// Otherwise, returns true. This may emit diagnostics and return true.
12122 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12123     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12124   Expr *E = SrcExpr.get();
12125   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12126 
12127   DeclAccessPair DAP;
12128   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12129   if (!Found || Found->isCPUDispatchMultiVersion() ||
12130       Found->isCPUSpecificMultiVersion())
12131     return false;
12132 
12133   // Emitting multiple diagnostics for a function that is both inaccessible and
12134   // unavailable is consistent with our behavior elsewhere. So, always check
12135   // for both.
12136   DiagnoseUseOfDecl(Found, E->getExprLoc());
12137   CheckAddressOfMemberAccess(E, DAP);
12138   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12139   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12140     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12141   else
12142     SrcExpr = Fixed;
12143   return true;
12144 }
12145 
12146 /// Given an expression that refers to an overloaded function, try to
12147 /// resolve that overloaded function expression down to a single function.
12148 ///
12149 /// This routine can only resolve template-ids that refer to a single function
12150 /// template, where that template-id refers to a single template whose template
12151 /// arguments are either provided by the template-id or have defaults,
12152 /// as described in C++0x [temp.arg.explicit]p3.
12153 ///
12154 /// If no template-ids are found, no diagnostics are emitted and NULL is
12155 /// returned.
12156 FunctionDecl *
12157 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12158                                                   bool Complain,
12159                                                   DeclAccessPair *FoundResult) {
12160   // C++ [over.over]p1:
12161   //   [...] [Note: any redundant set of parentheses surrounding the
12162   //   overloaded function name is ignored (5.1). ]
12163   // C++ [over.over]p1:
12164   //   [...] The overloaded function name can be preceded by the &
12165   //   operator.
12166 
12167   // If we didn't actually find any template-ids, we're done.
12168   if (!ovl->hasExplicitTemplateArgs())
12169     return nullptr;
12170 
12171   TemplateArgumentListInfo ExplicitTemplateArgs;
12172   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12173   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12174 
12175   // Look through all of the overloaded functions, searching for one
12176   // whose type matches exactly.
12177   FunctionDecl *Matched = nullptr;
12178   for (UnresolvedSetIterator I = ovl->decls_begin(),
12179          E = ovl->decls_end(); I != E; ++I) {
12180     // C++0x [temp.arg.explicit]p3:
12181     //   [...] In contexts where deduction is done and fails, or in contexts
12182     //   where deduction is not done, if a template argument list is
12183     //   specified and it, along with any default template arguments,
12184     //   identifies a single function template specialization, then the
12185     //   template-id is an lvalue for the function template specialization.
12186     FunctionTemplateDecl *FunctionTemplate
12187       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12188 
12189     // C++ [over.over]p2:
12190     //   If the name is a function template, template argument deduction is
12191     //   done (14.8.2.2), and if the argument deduction succeeds, the
12192     //   resulting template argument list is used to generate a single
12193     //   function template specialization, which is added to the set of
12194     //   overloaded functions considered.
12195     FunctionDecl *Specialization = nullptr;
12196     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12197     if (TemplateDeductionResult Result
12198           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12199                                     Specialization, Info,
12200                                     /*IsAddressOfFunction*/true)) {
12201       // Make a note of the failed deduction for diagnostics.
12202       // TODO: Actually use the failed-deduction info?
12203       FailedCandidates.addCandidate()
12204           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12205                MakeDeductionFailureInfo(Context, Result, Info));
12206       continue;
12207     }
12208 
12209     assert(Specialization && "no specialization and no error?");
12210 
12211     // Multiple matches; we can't resolve to a single declaration.
12212     if (Matched) {
12213       if (Complain) {
12214         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12215           << ovl->getName();
12216         NoteAllOverloadCandidates(ovl);
12217       }
12218       return nullptr;
12219     }
12220 
12221     Matched = Specialization;
12222     if (FoundResult) *FoundResult = I.getPair();
12223   }
12224 
12225   if (Matched &&
12226       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12227     return nullptr;
12228 
12229   return Matched;
12230 }
12231 
12232 // Resolve and fix an overloaded expression that can be resolved
12233 // because it identifies a single function template specialization.
12234 //
12235 // Last three arguments should only be supplied if Complain = true
12236 //
12237 // Return true if it was logically possible to so resolve the
12238 // expression, regardless of whether or not it succeeded.  Always
12239 // returns true if 'complain' is set.
12240 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12241                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12242                       bool complain, SourceRange OpRangeForComplaining,
12243                                            QualType DestTypeForComplaining,
12244                                             unsigned DiagIDForComplaining) {
12245   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12246 
12247   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12248 
12249   DeclAccessPair found;
12250   ExprResult SingleFunctionExpression;
12251   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12252                            ovl.Expression, /*complain*/ false, &found)) {
12253     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12254       SrcExpr = ExprError();
12255       return true;
12256     }
12257 
12258     // It is only correct to resolve to an instance method if we're
12259     // resolving a form that's permitted to be a pointer to member.
12260     // Otherwise we'll end up making a bound member expression, which
12261     // is illegal in all the contexts we resolve like this.
12262     if (!ovl.HasFormOfMemberPointer &&
12263         isa<CXXMethodDecl>(fn) &&
12264         cast<CXXMethodDecl>(fn)->isInstance()) {
12265       if (!complain) return false;
12266 
12267       Diag(ovl.Expression->getExprLoc(),
12268            diag::err_bound_member_function)
12269         << 0 << ovl.Expression->getSourceRange();
12270 
12271       // TODO: I believe we only end up here if there's a mix of
12272       // static and non-static candidates (otherwise the expression
12273       // would have 'bound member' type, not 'overload' type).
12274       // Ideally we would note which candidate was chosen and why
12275       // the static candidates were rejected.
12276       SrcExpr = ExprError();
12277       return true;
12278     }
12279 
12280     // Fix the expression to refer to 'fn'.
12281     SingleFunctionExpression =
12282         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12283 
12284     // If desired, do function-to-pointer decay.
12285     if (doFunctionPointerConverion) {
12286       SingleFunctionExpression =
12287         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12288       if (SingleFunctionExpression.isInvalid()) {
12289         SrcExpr = ExprError();
12290         return true;
12291       }
12292     }
12293   }
12294 
12295   if (!SingleFunctionExpression.isUsable()) {
12296     if (complain) {
12297       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12298         << ovl.Expression->getName()
12299         << DestTypeForComplaining
12300         << OpRangeForComplaining
12301         << ovl.Expression->getQualifierLoc().getSourceRange();
12302       NoteAllOverloadCandidates(SrcExpr.get());
12303 
12304       SrcExpr = ExprError();
12305       return true;
12306     }
12307 
12308     return false;
12309   }
12310 
12311   SrcExpr = SingleFunctionExpression;
12312   return true;
12313 }
12314 
12315 /// Add a single candidate to the overload set.
12316 static void AddOverloadedCallCandidate(Sema &S,
12317                                        DeclAccessPair FoundDecl,
12318                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12319                                        ArrayRef<Expr *> Args,
12320                                        OverloadCandidateSet &CandidateSet,
12321                                        bool PartialOverloading,
12322                                        bool KnownValid) {
12323   NamedDecl *Callee = FoundDecl.getDecl();
12324   if (isa<UsingShadowDecl>(Callee))
12325     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12326 
12327   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12328     if (ExplicitTemplateArgs) {
12329       assert(!KnownValid && "Explicit template arguments?");
12330       return;
12331     }
12332     // Prevent ill-formed function decls to be added as overload candidates.
12333     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12334       return;
12335 
12336     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12337                            /*SuppressUserConversions=*/false,
12338                            PartialOverloading);
12339     return;
12340   }
12341 
12342   if (FunctionTemplateDecl *FuncTemplate
12343       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12344     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12345                                    ExplicitTemplateArgs, Args, CandidateSet,
12346                                    /*SuppressUserConversions=*/false,
12347                                    PartialOverloading);
12348     return;
12349   }
12350 
12351   assert(!KnownValid && "unhandled case in overloaded call candidate");
12352 }
12353 
12354 /// Add the overload candidates named by callee and/or found by argument
12355 /// dependent lookup to the given overload set.
12356 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12357                                        ArrayRef<Expr *> Args,
12358                                        OverloadCandidateSet &CandidateSet,
12359                                        bool PartialOverloading) {
12360 
12361 #ifndef NDEBUG
12362   // Verify that ArgumentDependentLookup is consistent with the rules
12363   // in C++0x [basic.lookup.argdep]p3:
12364   //
12365   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12366   //   and let Y be the lookup set produced by argument dependent
12367   //   lookup (defined as follows). If X contains
12368   //
12369   //     -- a declaration of a class member, or
12370   //
12371   //     -- a block-scope function declaration that is not a
12372   //        using-declaration, or
12373   //
12374   //     -- a declaration that is neither a function or a function
12375   //        template
12376   //
12377   //   then Y is empty.
12378 
12379   if (ULE->requiresADL()) {
12380     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12381            E = ULE->decls_end(); I != E; ++I) {
12382       assert(!(*I)->getDeclContext()->isRecord());
12383       assert(isa<UsingShadowDecl>(*I) ||
12384              !(*I)->getDeclContext()->isFunctionOrMethod());
12385       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12386     }
12387   }
12388 #endif
12389 
12390   // It would be nice to avoid this copy.
12391   TemplateArgumentListInfo TABuffer;
12392   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12393   if (ULE->hasExplicitTemplateArgs()) {
12394     ULE->copyTemplateArgumentsInto(TABuffer);
12395     ExplicitTemplateArgs = &TABuffer;
12396   }
12397 
12398   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12399          E = ULE->decls_end(); I != E; ++I)
12400     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12401                                CandidateSet, PartialOverloading,
12402                                /*KnownValid*/ true);
12403 
12404   if (ULE->requiresADL())
12405     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12406                                          Args, ExplicitTemplateArgs,
12407                                          CandidateSet, PartialOverloading);
12408 }
12409 
12410 /// Determine whether a declaration with the specified name could be moved into
12411 /// a different namespace.
12412 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12413   switch (Name.getCXXOverloadedOperator()) {
12414   case OO_New: case OO_Array_New:
12415   case OO_Delete: case OO_Array_Delete:
12416     return false;
12417 
12418   default:
12419     return true;
12420   }
12421 }
12422 
12423 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12424 /// template, where the non-dependent name was declared after the template
12425 /// was defined. This is common in code written for a compilers which do not
12426 /// correctly implement two-stage name lookup.
12427 ///
12428 /// Returns true if a viable candidate was found and a diagnostic was issued.
12429 static bool
12430 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12431                        const CXXScopeSpec &SS, LookupResult &R,
12432                        OverloadCandidateSet::CandidateSetKind CSK,
12433                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12434                        ArrayRef<Expr *> Args,
12435                        bool *DoDiagnoseEmptyLookup = nullptr) {
12436   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12437     return false;
12438 
12439   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12440     if (DC->isTransparentContext())
12441       continue;
12442 
12443     SemaRef.LookupQualifiedName(R, DC);
12444 
12445     if (!R.empty()) {
12446       R.suppressDiagnostics();
12447 
12448       if (isa<CXXRecordDecl>(DC)) {
12449         // Don't diagnose names we find in classes; we get much better
12450         // diagnostics for these from DiagnoseEmptyLookup.
12451         R.clear();
12452         if (DoDiagnoseEmptyLookup)
12453           *DoDiagnoseEmptyLookup = true;
12454         return false;
12455       }
12456 
12457       OverloadCandidateSet Candidates(FnLoc, CSK);
12458       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12459         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12460                                    ExplicitTemplateArgs, Args,
12461                                    Candidates, false, /*KnownValid*/ false);
12462 
12463       OverloadCandidateSet::iterator Best;
12464       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12465         // No viable functions. Don't bother the user with notes for functions
12466         // which don't work and shouldn't be found anyway.
12467         R.clear();
12468         return false;
12469       }
12470 
12471       // Find the namespaces where ADL would have looked, and suggest
12472       // declaring the function there instead.
12473       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12474       Sema::AssociatedClassSet AssociatedClasses;
12475       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12476                                                  AssociatedNamespaces,
12477                                                  AssociatedClasses);
12478       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12479       if (canBeDeclaredInNamespace(R.getLookupName())) {
12480         DeclContext *Std = SemaRef.getStdNamespace();
12481         for (Sema::AssociatedNamespaceSet::iterator
12482                it = AssociatedNamespaces.begin(),
12483                end = AssociatedNamespaces.end(); it != end; ++it) {
12484           // Never suggest declaring a function within namespace 'std'.
12485           if (Std && Std->Encloses(*it))
12486             continue;
12487 
12488           // Never suggest declaring a function within a namespace with a
12489           // reserved name, like __gnu_cxx.
12490           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12491           if (NS &&
12492               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12493             continue;
12494 
12495           SuggestedNamespaces.insert(*it);
12496         }
12497       }
12498 
12499       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12500         << R.getLookupName();
12501       if (SuggestedNamespaces.empty()) {
12502         SemaRef.Diag(Best->Function->getLocation(),
12503                      diag::note_not_found_by_two_phase_lookup)
12504           << R.getLookupName() << 0;
12505       } else if (SuggestedNamespaces.size() == 1) {
12506         SemaRef.Diag(Best->Function->getLocation(),
12507                      diag::note_not_found_by_two_phase_lookup)
12508           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12509       } else {
12510         // FIXME: It would be useful to list the associated namespaces here,
12511         // but the diagnostics infrastructure doesn't provide a way to produce
12512         // a localized representation of a list of items.
12513         SemaRef.Diag(Best->Function->getLocation(),
12514                      diag::note_not_found_by_two_phase_lookup)
12515           << R.getLookupName() << 2;
12516       }
12517 
12518       // Try to recover by calling this function.
12519       return true;
12520     }
12521 
12522     R.clear();
12523   }
12524 
12525   return false;
12526 }
12527 
12528 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12529 /// template, where the non-dependent operator was declared after the template
12530 /// was defined.
12531 ///
12532 /// Returns true if a viable candidate was found and a diagnostic was issued.
12533 static bool
12534 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12535                                SourceLocation OpLoc,
12536                                ArrayRef<Expr *> Args) {
12537   DeclarationName OpName =
12538     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12539   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12540   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12541                                 OverloadCandidateSet::CSK_Operator,
12542                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12543 }
12544 
12545 namespace {
12546 class BuildRecoveryCallExprRAII {
12547   Sema &SemaRef;
12548 public:
12549   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12550     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12551     SemaRef.IsBuildingRecoveryCallExpr = true;
12552   }
12553 
12554   ~BuildRecoveryCallExprRAII() {
12555     SemaRef.IsBuildingRecoveryCallExpr = false;
12556   }
12557 };
12558 
12559 }
12560 
12561 /// Attempts to recover from a call where no functions were found.
12562 ///
12563 /// Returns true if new candidates were found.
12564 static ExprResult
12565 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12566                       UnresolvedLookupExpr *ULE,
12567                       SourceLocation LParenLoc,
12568                       MutableArrayRef<Expr *> Args,
12569                       SourceLocation RParenLoc,
12570                       bool EmptyLookup, bool AllowTypoCorrection) {
12571   // Do not try to recover if it is already building a recovery call.
12572   // This stops infinite loops for template instantiations like
12573   //
12574   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12575   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12576   //
12577   if (SemaRef.IsBuildingRecoveryCallExpr)
12578     return ExprError();
12579   BuildRecoveryCallExprRAII RCE(SemaRef);
12580 
12581   CXXScopeSpec SS;
12582   SS.Adopt(ULE->getQualifierLoc());
12583   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12584 
12585   TemplateArgumentListInfo TABuffer;
12586   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12587   if (ULE->hasExplicitTemplateArgs()) {
12588     ULE->copyTemplateArgumentsInto(TABuffer);
12589     ExplicitTemplateArgs = &TABuffer;
12590   }
12591 
12592   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12593                  Sema::LookupOrdinaryName);
12594   bool DoDiagnoseEmptyLookup = EmptyLookup;
12595   if (!DiagnoseTwoPhaseLookup(
12596           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12597           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12598     NoTypoCorrectionCCC NoTypoValidator{};
12599     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12600                                                 ExplicitTemplateArgs != nullptr,
12601                                                 dyn_cast<MemberExpr>(Fn));
12602     CorrectionCandidateCallback &Validator =
12603         AllowTypoCorrection
12604             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12605             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12606     if (!DoDiagnoseEmptyLookup ||
12607         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12608                                     Args))
12609       return ExprError();
12610   }
12611 
12612   assert(!R.empty() && "lookup results empty despite recovery");
12613 
12614   // If recovery created an ambiguity, just bail out.
12615   if (R.isAmbiguous()) {
12616     R.suppressDiagnostics();
12617     return ExprError();
12618   }
12619 
12620   // Build an implicit member call if appropriate.  Just drop the
12621   // casts and such from the call, we don't really care.
12622   ExprResult NewFn = ExprError();
12623   if ((*R.begin())->isCXXClassMember())
12624     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12625                                                     ExplicitTemplateArgs, S);
12626   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12627     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12628                                         ExplicitTemplateArgs);
12629   else
12630     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12631 
12632   if (NewFn.isInvalid())
12633     return ExprError();
12634 
12635   // This shouldn't cause an infinite loop because we're giving it
12636   // an expression with viable lookup results, which should never
12637   // end up here.
12638   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12639                                MultiExprArg(Args.data(), Args.size()),
12640                                RParenLoc);
12641 }
12642 
12643 /// Constructs and populates an OverloadedCandidateSet from
12644 /// the given function.
12645 /// \returns true when an the ExprResult output parameter has been set.
12646 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12647                                   UnresolvedLookupExpr *ULE,
12648                                   MultiExprArg Args,
12649                                   SourceLocation RParenLoc,
12650                                   OverloadCandidateSet *CandidateSet,
12651                                   ExprResult *Result) {
12652 #ifndef NDEBUG
12653   if (ULE->requiresADL()) {
12654     // To do ADL, we must have found an unqualified name.
12655     assert(!ULE->getQualifier() && "qualified name with ADL");
12656 
12657     // We don't perform ADL for implicit declarations of builtins.
12658     // Verify that this was correctly set up.
12659     FunctionDecl *F;
12660     if (ULE->decls_begin() != ULE->decls_end() &&
12661         ULE->decls_begin() + 1 == ULE->decls_end() &&
12662         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12663         F->getBuiltinID() && F->isImplicit())
12664       llvm_unreachable("performing ADL for builtin");
12665 
12666     // We don't perform ADL in C.
12667     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12668   }
12669 #endif
12670 
12671   UnbridgedCastsSet UnbridgedCasts;
12672   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12673     *Result = ExprError();
12674     return true;
12675   }
12676 
12677   // Add the functions denoted by the callee to the set of candidate
12678   // functions, including those from argument-dependent lookup.
12679   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12680 
12681   if (getLangOpts().MSVCCompat &&
12682       CurContext->isDependentContext() && !isSFINAEContext() &&
12683       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12684 
12685     OverloadCandidateSet::iterator Best;
12686     if (CandidateSet->empty() ||
12687         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12688             OR_No_Viable_Function) {
12689       // In Microsoft mode, if we are inside a template class member function
12690       // then create a type dependent CallExpr. The goal is to postpone name
12691       // lookup to instantiation time to be able to search into type dependent
12692       // base classes.
12693       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12694                                       VK_RValue, RParenLoc);
12695       CE->setTypeDependent(true);
12696       CE->setValueDependent(true);
12697       CE->setInstantiationDependent(true);
12698       *Result = CE;
12699       return true;
12700     }
12701   }
12702 
12703   if (CandidateSet->empty())
12704     return false;
12705 
12706   UnbridgedCasts.restore();
12707   return false;
12708 }
12709 
12710 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12711 /// the completed call expression. If overload resolution fails, emits
12712 /// diagnostics and returns ExprError()
12713 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12714                                            UnresolvedLookupExpr *ULE,
12715                                            SourceLocation LParenLoc,
12716                                            MultiExprArg Args,
12717                                            SourceLocation RParenLoc,
12718                                            Expr *ExecConfig,
12719                                            OverloadCandidateSet *CandidateSet,
12720                                            OverloadCandidateSet::iterator *Best,
12721                                            OverloadingResult OverloadResult,
12722                                            bool AllowTypoCorrection) {
12723   if (CandidateSet->empty())
12724     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12725                                  RParenLoc, /*EmptyLookup=*/true,
12726                                  AllowTypoCorrection);
12727 
12728   switch (OverloadResult) {
12729   case OR_Success: {
12730     FunctionDecl *FDecl = (*Best)->Function;
12731     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12732     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12733       return ExprError();
12734     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12735     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12736                                          ExecConfig, /*IsExecConfig=*/false,
12737                                          (*Best)->IsADLCandidate);
12738   }
12739 
12740   case OR_No_Viable_Function: {
12741     // Try to recover by looking for viable functions which the user might
12742     // have meant to call.
12743     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12744                                                 Args, RParenLoc,
12745                                                 /*EmptyLookup=*/false,
12746                                                 AllowTypoCorrection);
12747     if (!Recovery.isInvalid())
12748       return Recovery;
12749 
12750     // If the user passes in a function that we can't take the address of, we
12751     // generally end up emitting really bad error messages. Here, we attempt to
12752     // emit better ones.
12753     for (const Expr *Arg : Args) {
12754       if (!Arg->getType()->isFunctionType())
12755         continue;
12756       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12757         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12758         if (FD &&
12759             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12760                                                        Arg->getExprLoc()))
12761           return ExprError();
12762       }
12763     }
12764 
12765     CandidateSet->NoteCandidates(
12766         PartialDiagnosticAt(
12767             Fn->getBeginLoc(),
12768             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12769                 << ULE->getName() << Fn->getSourceRange()),
12770         SemaRef, OCD_AllCandidates, Args);
12771     break;
12772   }
12773 
12774   case OR_Ambiguous:
12775     CandidateSet->NoteCandidates(
12776         PartialDiagnosticAt(Fn->getBeginLoc(),
12777                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12778                                 << ULE->getName() << Fn->getSourceRange()),
12779         SemaRef, OCD_AmbiguousCandidates, Args);
12780     break;
12781 
12782   case OR_Deleted: {
12783     CandidateSet->NoteCandidates(
12784         PartialDiagnosticAt(Fn->getBeginLoc(),
12785                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12786                                 << ULE->getName() << Fn->getSourceRange()),
12787         SemaRef, OCD_AllCandidates, Args);
12788 
12789     // We emitted an error for the unavailable/deleted function call but keep
12790     // the call in the AST.
12791     FunctionDecl *FDecl = (*Best)->Function;
12792     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12793     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12794                                          ExecConfig, /*IsExecConfig=*/false,
12795                                          (*Best)->IsADLCandidate);
12796   }
12797   }
12798 
12799   // Overload resolution failed.
12800   return ExprError();
12801 }
12802 
12803 static void markUnaddressableCandidatesUnviable(Sema &S,
12804                                                 OverloadCandidateSet &CS) {
12805   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12806     if (I->Viable &&
12807         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12808       I->Viable = false;
12809       I->FailureKind = ovl_fail_addr_not_available;
12810     }
12811   }
12812 }
12813 
12814 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12815 /// (which eventually refers to the declaration Func) and the call
12816 /// arguments Args/NumArgs, attempt to resolve the function call down
12817 /// to a specific function. If overload resolution succeeds, returns
12818 /// the call expression produced by overload resolution.
12819 /// Otherwise, emits diagnostics and returns ExprError.
12820 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12821                                          UnresolvedLookupExpr *ULE,
12822                                          SourceLocation LParenLoc,
12823                                          MultiExprArg Args,
12824                                          SourceLocation RParenLoc,
12825                                          Expr *ExecConfig,
12826                                          bool AllowTypoCorrection,
12827                                          bool CalleesAddressIsTaken) {
12828   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12829                                     OverloadCandidateSet::CSK_Normal);
12830   ExprResult result;
12831 
12832   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12833                              &result))
12834     return result;
12835 
12836   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12837   // functions that aren't addressible are considered unviable.
12838   if (CalleesAddressIsTaken)
12839     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12840 
12841   OverloadCandidateSet::iterator Best;
12842   OverloadingResult OverloadResult =
12843       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12844 
12845   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12846                                   ExecConfig, &CandidateSet, &Best,
12847                                   OverloadResult, AllowTypoCorrection);
12848 }
12849 
12850 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12851   return Functions.size() > 1 ||
12852     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12853 }
12854 
12855 /// Create a unary operation that may resolve to an overloaded
12856 /// operator.
12857 ///
12858 /// \param OpLoc The location of the operator itself (e.g., '*').
12859 ///
12860 /// \param Opc The UnaryOperatorKind that describes this operator.
12861 ///
12862 /// \param Fns The set of non-member functions that will be
12863 /// considered by overload resolution. The caller needs to build this
12864 /// set based on the context using, e.g.,
12865 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12866 /// set should not contain any member functions; those will be added
12867 /// by CreateOverloadedUnaryOp().
12868 ///
12869 /// \param Input The input argument.
12870 ExprResult
12871 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12872                               const UnresolvedSetImpl &Fns,
12873                               Expr *Input, bool PerformADL) {
12874   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12875   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12876   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12877   // TODO: provide better source location info.
12878   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12879 
12880   if (checkPlaceholderForOverload(*this, Input))
12881     return ExprError();
12882 
12883   Expr *Args[2] = { Input, nullptr };
12884   unsigned NumArgs = 1;
12885 
12886   // For post-increment and post-decrement, add the implicit '0' as
12887   // the second argument, so that we know this is a post-increment or
12888   // post-decrement.
12889   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12890     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12891     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12892                                      SourceLocation());
12893     NumArgs = 2;
12894   }
12895 
12896   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12897 
12898   if (Input->isTypeDependent()) {
12899     if (Fns.empty())
12900       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12901                                          VK_RValue, OK_Ordinary, OpLoc, false);
12902 
12903     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12904     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12905         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12906         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12907     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12908                                        Context.DependentTy, VK_RValue, OpLoc,
12909                                        FPOptions());
12910   }
12911 
12912   // Build an empty overload set.
12913   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12914 
12915   // Add the candidates from the given function set.
12916   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12917 
12918   // Add operator candidates that are member functions.
12919   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12920 
12921   // Add candidates from ADL.
12922   if (PerformADL) {
12923     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12924                                          /*ExplicitTemplateArgs*/nullptr,
12925                                          CandidateSet);
12926   }
12927 
12928   // Add builtin operator candidates.
12929   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12930 
12931   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12932 
12933   // Perform overload resolution.
12934   OverloadCandidateSet::iterator Best;
12935   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12936   case OR_Success: {
12937     // We found a built-in operator or an overloaded operator.
12938     FunctionDecl *FnDecl = Best->Function;
12939 
12940     if (FnDecl) {
12941       Expr *Base = nullptr;
12942       // We matched an overloaded operator. Build a call to that
12943       // operator.
12944 
12945       // Convert the arguments.
12946       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12947         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12948 
12949         ExprResult InputRes =
12950           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12951                                               Best->FoundDecl, Method);
12952         if (InputRes.isInvalid())
12953           return ExprError();
12954         Base = Input = InputRes.get();
12955       } else {
12956         // Convert the arguments.
12957         ExprResult InputInit
12958           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12959                                                       Context,
12960                                                       FnDecl->getParamDecl(0)),
12961                                       SourceLocation(),
12962                                       Input);
12963         if (InputInit.isInvalid())
12964           return ExprError();
12965         Input = InputInit.get();
12966       }
12967 
12968       // Build the actual expression node.
12969       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12970                                                 Base, HadMultipleCandidates,
12971                                                 OpLoc);
12972       if (FnExpr.isInvalid())
12973         return ExprError();
12974 
12975       // Determine the result type.
12976       QualType ResultTy = FnDecl->getReturnType();
12977       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12978       ResultTy = ResultTy.getNonLValueExprType(Context);
12979 
12980       Args[0] = Input;
12981       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12982           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12983           FPOptions(), Best->IsADLCandidate);
12984 
12985       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12986         return ExprError();
12987 
12988       if (CheckFunctionCall(FnDecl, TheCall,
12989                             FnDecl->getType()->castAs<FunctionProtoType>()))
12990         return ExprError();
12991 
12992       return MaybeBindToTemporary(TheCall);
12993     } else {
12994       // We matched a built-in operator. Convert the arguments, then
12995       // break out so that we will build the appropriate built-in
12996       // operator node.
12997       ExprResult InputRes = PerformImplicitConversion(
12998           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12999           CCK_ForBuiltinOverloadedOp);
13000       if (InputRes.isInvalid())
13001         return ExprError();
13002       Input = InputRes.get();
13003       break;
13004     }
13005   }
13006 
13007   case OR_No_Viable_Function:
13008     // This is an erroneous use of an operator which can be overloaded by
13009     // a non-member function. Check for non-member operators which were
13010     // defined too late to be candidates.
13011     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13012       // FIXME: Recover by calling the found function.
13013       return ExprError();
13014 
13015     // No viable function; fall through to handling this as a
13016     // built-in operator, which will produce an error message for us.
13017     break;
13018 
13019   case OR_Ambiguous:
13020     CandidateSet.NoteCandidates(
13021         PartialDiagnosticAt(OpLoc,
13022                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13023                                 << UnaryOperator::getOpcodeStr(Opc)
13024                                 << Input->getType() << Input->getSourceRange()),
13025         *this, OCD_AmbiguousCandidates, ArgsArray,
13026         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13027     return ExprError();
13028 
13029   case OR_Deleted:
13030     CandidateSet.NoteCandidates(
13031         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13032                                        << UnaryOperator::getOpcodeStr(Opc)
13033                                        << Input->getSourceRange()),
13034         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13035         OpLoc);
13036     return ExprError();
13037   }
13038 
13039   // Either we found no viable overloaded operator or we matched a
13040   // built-in operator. In either case, fall through to trying to
13041   // build a built-in operation.
13042   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13043 }
13044 
13045 /// Perform lookup for an overloaded binary operator.
13046 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13047                                  OverloadedOperatorKind Op,
13048                                  const UnresolvedSetImpl &Fns,
13049                                  ArrayRef<Expr *> Args, bool PerformADL) {
13050   SourceLocation OpLoc = CandidateSet.getLocation();
13051 
13052   OverloadedOperatorKind ExtraOp =
13053       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13054           ? getRewrittenOverloadedOperator(Op)
13055           : OO_None;
13056 
13057   // Add the candidates from the given function set. This also adds the
13058   // rewritten candidates using these functions if necessary.
13059   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13060 
13061   // Add operator candidates that are member functions.
13062   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13063   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13064     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13065                                 OverloadCandidateParamOrder::Reversed);
13066 
13067   // In C++20, also add any rewritten member candidates.
13068   if (ExtraOp) {
13069     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13070     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13071       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13072                                   CandidateSet,
13073                                   OverloadCandidateParamOrder::Reversed);
13074   }
13075 
13076   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13077   // performed for an assignment operator (nor for operator[] nor operator->,
13078   // which don't get here).
13079   if (Op != OO_Equal && PerformADL) {
13080     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13081     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13082                                          /*ExplicitTemplateArgs*/ nullptr,
13083                                          CandidateSet);
13084     if (ExtraOp) {
13085       DeclarationName ExtraOpName =
13086           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13087       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13088                                            /*ExplicitTemplateArgs*/ nullptr,
13089                                            CandidateSet);
13090     }
13091   }
13092 
13093   // Add builtin operator candidates.
13094   //
13095   // FIXME: We don't add any rewritten candidates here. This is strictly
13096   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13097   // resulting in our selecting a rewritten builtin candidate. For example:
13098   //
13099   //   enum class E { e };
13100   //   bool operator!=(E, E) requires false;
13101   //   bool k = E::e != E::e;
13102   //
13103   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13104   // it seems unreasonable to consider rewritten builtin candidates. A core
13105   // issue has been filed proposing to removed this requirement.
13106   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13107 }
13108 
13109 /// Create a binary operation that may resolve to an overloaded
13110 /// operator.
13111 ///
13112 /// \param OpLoc The location of the operator itself (e.g., '+').
13113 ///
13114 /// \param Opc The BinaryOperatorKind that describes this operator.
13115 ///
13116 /// \param Fns The set of non-member functions that will be
13117 /// considered by overload resolution. The caller needs to build this
13118 /// set based on the context using, e.g.,
13119 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13120 /// set should not contain any member functions; those will be added
13121 /// by CreateOverloadedBinOp().
13122 ///
13123 /// \param LHS Left-hand argument.
13124 /// \param RHS Right-hand argument.
13125 /// \param PerformADL Whether to consider operator candidates found by ADL.
13126 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13127 ///        C++20 operator rewrites.
13128 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13129 ///        the function in question. Such a function is never a candidate in
13130 ///        our overload resolution. This also enables synthesizing a three-way
13131 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13132 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13133                                        BinaryOperatorKind Opc,
13134                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13135                                        Expr *RHS, bool PerformADL,
13136                                        bool AllowRewrittenCandidates,
13137                                        FunctionDecl *DefaultedFn) {
13138   Expr *Args[2] = { LHS, RHS };
13139   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13140 
13141   if (!getLangOpts().CPlusPlus2a)
13142     AllowRewrittenCandidates = false;
13143 
13144   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13145 
13146   // If either side is type-dependent, create an appropriate dependent
13147   // expression.
13148   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13149     if (Fns.empty()) {
13150       // If there are no functions to store, just build a dependent
13151       // BinaryOperator or CompoundAssignment.
13152       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13153         return new (Context) BinaryOperator(
13154             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13155             OpLoc, FPFeatures);
13156 
13157       return new (Context) CompoundAssignOperator(
13158           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13159           Context.DependentTy, Context.DependentTy, OpLoc,
13160           FPFeatures);
13161     }
13162 
13163     // FIXME: save results of ADL from here?
13164     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13165     // TODO: provide better source location info in DNLoc component.
13166     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13167     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13168     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13169         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13170         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13171     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13172                                        Context.DependentTy, VK_RValue, OpLoc,
13173                                        FPFeatures);
13174   }
13175 
13176   // Always do placeholder-like conversions on the RHS.
13177   if (checkPlaceholderForOverload(*this, Args[1]))
13178     return ExprError();
13179 
13180   // Do placeholder-like conversion on the LHS; note that we should
13181   // not get here with a PseudoObject LHS.
13182   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13183   if (checkPlaceholderForOverload(*this, Args[0]))
13184     return ExprError();
13185 
13186   // If this is the assignment operator, we only perform overload resolution
13187   // if the left-hand side is a class or enumeration type. This is actually
13188   // a hack. The standard requires that we do overload resolution between the
13189   // various built-in candidates, but as DR507 points out, this can lead to
13190   // problems. So we do it this way, which pretty much follows what GCC does.
13191   // Note that we go the traditional code path for compound assignment forms.
13192   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13193     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13194 
13195   // If this is the .* operator, which is not overloadable, just
13196   // create a built-in binary operator.
13197   if (Opc == BO_PtrMemD)
13198     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13199 
13200   // Build the overload set.
13201   OverloadCandidateSet CandidateSet(
13202       OpLoc, OverloadCandidateSet::CSK_Operator,
13203       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13204   if (DefaultedFn)
13205     CandidateSet.exclude(DefaultedFn);
13206   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13207 
13208   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13209 
13210   // Perform overload resolution.
13211   OverloadCandidateSet::iterator Best;
13212   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13213     case OR_Success: {
13214       // We found a built-in operator or an overloaded operator.
13215       FunctionDecl *FnDecl = Best->Function;
13216 
13217       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13218       if (IsReversed)
13219         std::swap(Args[0], Args[1]);
13220 
13221       if (FnDecl) {
13222         Expr *Base = nullptr;
13223         // We matched an overloaded operator. Build a call to that
13224         // operator.
13225 
13226         OverloadedOperatorKind ChosenOp =
13227             FnDecl->getDeclName().getCXXOverloadedOperator();
13228 
13229         // C++2a [over.match.oper]p9:
13230         //   If a rewritten operator== candidate is selected by overload
13231         //   resolution for an operator@, its return type shall be cv bool
13232         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13233             !FnDecl->getReturnType()->isBooleanType()) {
13234           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13235               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13236               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13237           Diag(FnDecl->getLocation(), diag::note_declared_at);
13238           return ExprError();
13239         }
13240 
13241         if (AllowRewrittenCandidates && !IsReversed &&
13242             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13243           // We could have reversed this operator, but didn't. Check if the
13244           // reversed form was a viable candidate, and if so, if it had a
13245           // better conversion for either parameter. If so, this call is
13246           // formally ambiguous, and allowing it is an extension.
13247           for (OverloadCandidate &Cand : CandidateSet) {
13248             if (Cand.Viable && Cand.Function == FnDecl &&
13249                 Cand.RewriteKind & CRK_Reversed) {
13250               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13251                 if (CompareImplicitConversionSequences(
13252                         *this, OpLoc, Cand.Conversions[ArgIdx],
13253                         Best->Conversions[ArgIdx]) ==
13254                     ImplicitConversionSequence::Better) {
13255                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13256                       << BinaryOperator::getOpcodeStr(Opc)
13257                       << Args[0]->getType() << Args[1]->getType()
13258                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13259                   Diag(FnDecl->getLocation(),
13260                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13261                 }
13262               }
13263               break;
13264             }
13265           }
13266         }
13267 
13268         // Convert the arguments.
13269         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13270           // Best->Access is only meaningful for class members.
13271           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13272 
13273           ExprResult Arg1 =
13274             PerformCopyInitialization(
13275               InitializedEntity::InitializeParameter(Context,
13276                                                      FnDecl->getParamDecl(0)),
13277               SourceLocation(), Args[1]);
13278           if (Arg1.isInvalid())
13279             return ExprError();
13280 
13281           ExprResult Arg0 =
13282             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13283                                                 Best->FoundDecl, Method);
13284           if (Arg0.isInvalid())
13285             return ExprError();
13286           Base = Args[0] = Arg0.getAs<Expr>();
13287           Args[1] = RHS = Arg1.getAs<Expr>();
13288         } else {
13289           // Convert the arguments.
13290           ExprResult Arg0 = PerformCopyInitialization(
13291             InitializedEntity::InitializeParameter(Context,
13292                                                    FnDecl->getParamDecl(0)),
13293             SourceLocation(), Args[0]);
13294           if (Arg0.isInvalid())
13295             return ExprError();
13296 
13297           ExprResult Arg1 =
13298             PerformCopyInitialization(
13299               InitializedEntity::InitializeParameter(Context,
13300                                                      FnDecl->getParamDecl(1)),
13301               SourceLocation(), Args[1]);
13302           if (Arg1.isInvalid())
13303             return ExprError();
13304           Args[0] = LHS = Arg0.getAs<Expr>();
13305           Args[1] = RHS = Arg1.getAs<Expr>();
13306         }
13307 
13308         // Build the actual expression node.
13309         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13310                                                   Best->FoundDecl, Base,
13311                                                   HadMultipleCandidates, OpLoc);
13312         if (FnExpr.isInvalid())
13313           return ExprError();
13314 
13315         // Determine the result type.
13316         QualType ResultTy = FnDecl->getReturnType();
13317         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13318         ResultTy = ResultTy.getNonLValueExprType(Context);
13319 
13320         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13321             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13322             FPFeatures, Best->IsADLCandidate);
13323 
13324         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13325                                 FnDecl))
13326           return ExprError();
13327 
13328         ArrayRef<const Expr *> ArgsArray(Args, 2);
13329         const Expr *ImplicitThis = nullptr;
13330         // Cut off the implicit 'this'.
13331         if (isa<CXXMethodDecl>(FnDecl)) {
13332           ImplicitThis = ArgsArray[0];
13333           ArgsArray = ArgsArray.slice(1);
13334         }
13335 
13336         // Check for a self move.
13337         if (Op == OO_Equal)
13338           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13339 
13340         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13341                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13342                   VariadicDoesNotApply);
13343 
13344         ExprResult R = MaybeBindToTemporary(TheCall);
13345         if (R.isInvalid())
13346           return ExprError();
13347 
13348         // For a rewritten candidate, we've already reversed the arguments
13349         // if needed. Perform the rest of the rewrite now.
13350         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13351             (Op == OO_Spaceship && IsReversed)) {
13352           if (Op == OO_ExclaimEqual) {
13353             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13354             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13355           } else {
13356             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13357             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13358             Expr *ZeroLiteral =
13359                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13360 
13361             Sema::CodeSynthesisContext Ctx;
13362             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13363             Ctx.Entity = FnDecl;
13364             pushCodeSynthesisContext(Ctx);
13365 
13366             R = CreateOverloadedBinOp(
13367                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13368                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13369                 /*AllowRewrittenCandidates=*/false);
13370 
13371             popCodeSynthesisContext();
13372           }
13373           if (R.isInvalid())
13374             return ExprError();
13375         } else {
13376           assert(ChosenOp == Op && "unexpected operator name");
13377         }
13378 
13379         // Make a note in the AST if we did any rewriting.
13380         if (Best->RewriteKind != CRK_None)
13381           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13382 
13383         return R;
13384       } else {
13385         // We matched a built-in operator. Convert the arguments, then
13386         // break out so that we will build the appropriate built-in
13387         // operator node.
13388         ExprResult ArgsRes0 = PerformImplicitConversion(
13389             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13390             AA_Passing, CCK_ForBuiltinOverloadedOp);
13391         if (ArgsRes0.isInvalid())
13392           return ExprError();
13393         Args[0] = ArgsRes0.get();
13394 
13395         ExprResult ArgsRes1 = PerformImplicitConversion(
13396             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13397             AA_Passing, CCK_ForBuiltinOverloadedOp);
13398         if (ArgsRes1.isInvalid())
13399           return ExprError();
13400         Args[1] = ArgsRes1.get();
13401         break;
13402       }
13403     }
13404 
13405     case OR_No_Viable_Function: {
13406       // C++ [over.match.oper]p9:
13407       //   If the operator is the operator , [...] and there are no
13408       //   viable functions, then the operator is assumed to be the
13409       //   built-in operator and interpreted according to clause 5.
13410       if (Opc == BO_Comma)
13411         break;
13412 
13413       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13414       // compare result using '==' and '<'.
13415       if (DefaultedFn && Opc == BO_Cmp) {
13416         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13417                                                           Args[1], DefaultedFn);
13418         if (E.isInvalid() || E.isUsable())
13419           return E;
13420       }
13421 
13422       // For class as left operand for assignment or compound assignment
13423       // operator do not fall through to handling in built-in, but report that
13424       // no overloaded assignment operator found
13425       ExprResult Result = ExprError();
13426       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13427       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13428                                                    Args, OpLoc);
13429       if (Args[0]->getType()->isRecordType() &&
13430           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13431         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13432              << BinaryOperator::getOpcodeStr(Opc)
13433              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13434         if (Args[0]->getType()->isIncompleteType()) {
13435           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13436             << Args[0]->getType()
13437             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13438         }
13439       } else {
13440         // This is an erroneous use of an operator which can be overloaded by
13441         // a non-member function. Check for non-member operators which were
13442         // defined too late to be candidates.
13443         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13444           // FIXME: Recover by calling the found function.
13445           return ExprError();
13446 
13447         // No viable function; try to create a built-in operation, which will
13448         // produce an error. Then, show the non-viable candidates.
13449         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13450       }
13451       assert(Result.isInvalid() &&
13452              "C++ binary operator overloading is missing candidates!");
13453       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13454       return Result;
13455     }
13456 
13457     case OR_Ambiguous:
13458       CandidateSet.NoteCandidates(
13459           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13460                                          << BinaryOperator::getOpcodeStr(Opc)
13461                                          << Args[0]->getType()
13462                                          << Args[1]->getType()
13463                                          << Args[0]->getSourceRange()
13464                                          << Args[1]->getSourceRange()),
13465           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13466           OpLoc);
13467       return ExprError();
13468 
13469     case OR_Deleted:
13470       if (isImplicitlyDeleted(Best->Function)) {
13471         FunctionDecl *DeletedFD = Best->Function;
13472         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13473         if (DFK.isSpecialMember()) {
13474           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13475             << Args[0]->getType() << DFK.asSpecialMember();
13476         } else {
13477           assert(DFK.isComparison());
13478           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13479             << Args[0]->getType() << DeletedFD;
13480         }
13481 
13482         // The user probably meant to call this special member. Just
13483         // explain why it's deleted.
13484         NoteDeletedFunction(DeletedFD);
13485         return ExprError();
13486       }
13487       CandidateSet.NoteCandidates(
13488           PartialDiagnosticAt(
13489               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13490                          << getOperatorSpelling(Best->Function->getDeclName()
13491                                                     .getCXXOverloadedOperator())
13492                          << Args[0]->getSourceRange()
13493                          << Args[1]->getSourceRange()),
13494           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13495           OpLoc);
13496       return ExprError();
13497   }
13498 
13499   // We matched a built-in operator; build it.
13500   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13501 }
13502 
13503 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13504     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13505     FunctionDecl *DefaultedFn) {
13506   const ComparisonCategoryInfo *Info =
13507       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13508   // If we're not producing a known comparison category type, we can't
13509   // synthesize a three-way comparison. Let the caller diagnose this.
13510   if (!Info)
13511     return ExprResult((Expr*)nullptr);
13512 
13513   // If we ever want to perform this synthesis more generally, we will need to
13514   // apply the temporary materialization conversion to the operands.
13515   assert(LHS->isGLValue() && RHS->isGLValue() &&
13516          "cannot use prvalue expressions more than once");
13517   Expr *OrigLHS = LHS;
13518   Expr *OrigRHS = RHS;
13519 
13520   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13521   // each of them multiple times below.
13522   LHS = new (Context)
13523       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13524                       LHS->getObjectKind(), LHS);
13525   RHS = new (Context)
13526       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13527                       RHS->getObjectKind(), RHS);
13528 
13529   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13530                                         DefaultedFn);
13531   if (Eq.isInvalid())
13532     return ExprError();
13533 
13534   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13535                                           true, DefaultedFn);
13536   if (Less.isInvalid())
13537     return ExprError();
13538 
13539   ExprResult Greater;
13540   if (Info->isPartial()) {
13541     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13542                                     DefaultedFn);
13543     if (Greater.isInvalid())
13544       return ExprError();
13545   }
13546 
13547   // Form the list of comparisons we're going to perform.
13548   struct Comparison {
13549     ExprResult Cmp;
13550     ComparisonCategoryResult Result;
13551   } Comparisons[4] =
13552   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13553                           : ComparisonCategoryResult::Equivalent},
13554     {Less, ComparisonCategoryResult::Less},
13555     {Greater, ComparisonCategoryResult::Greater},
13556     {ExprResult(), ComparisonCategoryResult::Unordered},
13557   };
13558 
13559   int I = Info->isPartial() ? 3 : 2;
13560 
13561   // Combine the comparisons with suitable conditional expressions.
13562   ExprResult Result;
13563   for (; I >= 0; --I) {
13564     // Build a reference to the comparison category constant.
13565     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13566     // FIXME: Missing a constant for a comparison category. Diagnose this?
13567     if (!VI)
13568       return ExprResult((Expr*)nullptr);
13569     ExprResult ThisResult =
13570         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13571     if (ThisResult.isInvalid())
13572       return ExprError();
13573 
13574     // Build a conditional unless this is the final case.
13575     if (Result.get()) {
13576       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13577                                   ThisResult.get(), Result.get());
13578       if (Result.isInvalid())
13579         return ExprError();
13580     } else {
13581       Result = ThisResult;
13582     }
13583   }
13584 
13585   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13586   // bind the OpaqueValueExprs before they're (repeatedly) used.
13587   Expr *SyntacticForm = new (Context)
13588       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13589                      Result.get()->getValueKind(),
13590                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13591   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13592   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13593 }
13594 
13595 ExprResult
13596 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13597                                          SourceLocation RLoc,
13598                                          Expr *Base, Expr *Idx) {
13599   Expr *Args[2] = { Base, Idx };
13600   DeclarationName OpName =
13601       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13602 
13603   // If either side is type-dependent, create an appropriate dependent
13604   // expression.
13605   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13606 
13607     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13608     // CHECKME: no 'operator' keyword?
13609     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13610     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13611     UnresolvedLookupExpr *Fn
13612       = UnresolvedLookupExpr::Create(Context, NamingClass,
13613                                      NestedNameSpecifierLoc(), OpNameInfo,
13614                                      /*ADL*/ true, /*Overloaded*/ false,
13615                                      UnresolvedSetIterator(),
13616                                      UnresolvedSetIterator());
13617     // Can't add any actual overloads yet
13618 
13619     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13620                                        Context.DependentTy, VK_RValue, RLoc,
13621                                        FPOptions());
13622   }
13623 
13624   // Handle placeholders on both operands.
13625   if (checkPlaceholderForOverload(*this, Args[0]))
13626     return ExprError();
13627   if (checkPlaceholderForOverload(*this, Args[1]))
13628     return ExprError();
13629 
13630   // Build an empty overload set.
13631   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13632 
13633   // Subscript can only be overloaded as a member function.
13634 
13635   // Add operator candidates that are member functions.
13636   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13637 
13638   // Add builtin operator candidates.
13639   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13640 
13641   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13642 
13643   // Perform overload resolution.
13644   OverloadCandidateSet::iterator Best;
13645   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13646     case OR_Success: {
13647       // We found a built-in operator or an overloaded operator.
13648       FunctionDecl *FnDecl = Best->Function;
13649 
13650       if (FnDecl) {
13651         // We matched an overloaded operator. Build a call to that
13652         // operator.
13653 
13654         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13655 
13656         // Convert the arguments.
13657         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13658         ExprResult Arg0 =
13659           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13660                                               Best->FoundDecl, Method);
13661         if (Arg0.isInvalid())
13662           return ExprError();
13663         Args[0] = Arg0.get();
13664 
13665         // Convert the arguments.
13666         ExprResult InputInit
13667           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13668                                                       Context,
13669                                                       FnDecl->getParamDecl(0)),
13670                                       SourceLocation(),
13671                                       Args[1]);
13672         if (InputInit.isInvalid())
13673           return ExprError();
13674 
13675         Args[1] = InputInit.getAs<Expr>();
13676 
13677         // Build the actual expression node.
13678         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13679         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13680         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13681                                                   Best->FoundDecl,
13682                                                   Base,
13683                                                   HadMultipleCandidates,
13684                                                   OpLocInfo.getLoc(),
13685                                                   OpLocInfo.getInfo());
13686         if (FnExpr.isInvalid())
13687           return ExprError();
13688 
13689         // Determine the result type
13690         QualType ResultTy = FnDecl->getReturnType();
13691         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13692         ResultTy = ResultTy.getNonLValueExprType(Context);
13693 
13694         CXXOperatorCallExpr *TheCall =
13695             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13696                                         Args, ResultTy, VK, RLoc, FPOptions());
13697 
13698         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13699           return ExprError();
13700 
13701         if (CheckFunctionCall(Method, TheCall,
13702                               Method->getType()->castAs<FunctionProtoType>()))
13703           return ExprError();
13704 
13705         return MaybeBindToTemporary(TheCall);
13706       } else {
13707         // We matched a built-in operator. Convert the arguments, then
13708         // break out so that we will build the appropriate built-in
13709         // operator node.
13710         ExprResult ArgsRes0 = PerformImplicitConversion(
13711             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13712             AA_Passing, CCK_ForBuiltinOverloadedOp);
13713         if (ArgsRes0.isInvalid())
13714           return ExprError();
13715         Args[0] = ArgsRes0.get();
13716 
13717         ExprResult ArgsRes1 = PerformImplicitConversion(
13718             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13719             AA_Passing, CCK_ForBuiltinOverloadedOp);
13720         if (ArgsRes1.isInvalid())
13721           return ExprError();
13722         Args[1] = ArgsRes1.get();
13723 
13724         break;
13725       }
13726     }
13727 
13728     case OR_No_Viable_Function: {
13729       PartialDiagnostic PD = CandidateSet.empty()
13730           ? (PDiag(diag::err_ovl_no_oper)
13731              << Args[0]->getType() << /*subscript*/ 0
13732              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13733           : (PDiag(diag::err_ovl_no_viable_subscript)
13734              << Args[0]->getType() << Args[0]->getSourceRange()
13735              << Args[1]->getSourceRange());
13736       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13737                                   OCD_AllCandidates, Args, "[]", LLoc);
13738       return ExprError();
13739     }
13740 
13741     case OR_Ambiguous:
13742       CandidateSet.NoteCandidates(
13743           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13744                                         << "[]" << Args[0]->getType()
13745                                         << Args[1]->getType()
13746                                         << Args[0]->getSourceRange()
13747                                         << Args[1]->getSourceRange()),
13748           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13749       return ExprError();
13750 
13751     case OR_Deleted:
13752       CandidateSet.NoteCandidates(
13753           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13754                                         << "[]" << Args[0]->getSourceRange()
13755                                         << Args[1]->getSourceRange()),
13756           *this, OCD_AllCandidates, Args, "[]", LLoc);
13757       return ExprError();
13758     }
13759 
13760   // We matched a built-in operator; build it.
13761   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13762 }
13763 
13764 /// BuildCallToMemberFunction - Build a call to a member
13765 /// function. MemExpr is the expression that refers to the member
13766 /// function (and includes the object parameter), Args/NumArgs are the
13767 /// arguments to the function call (not including the object
13768 /// parameter). The caller needs to validate that the member
13769 /// expression refers to a non-static member function or an overloaded
13770 /// member function.
13771 ExprResult
13772 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13773                                 SourceLocation LParenLoc,
13774                                 MultiExprArg Args,
13775                                 SourceLocation RParenLoc) {
13776   assert(MemExprE->getType() == Context.BoundMemberTy ||
13777          MemExprE->getType() == Context.OverloadTy);
13778 
13779   // Dig out the member expression. This holds both the object
13780   // argument and the member function we're referring to.
13781   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13782 
13783   // Determine whether this is a call to a pointer-to-member function.
13784   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13785     assert(op->getType() == Context.BoundMemberTy);
13786     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13787 
13788     QualType fnType =
13789       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13790 
13791     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13792     QualType resultType = proto->getCallResultType(Context);
13793     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13794 
13795     // Check that the object type isn't more qualified than the
13796     // member function we're calling.
13797     Qualifiers funcQuals = proto->getMethodQuals();
13798 
13799     QualType objectType = op->getLHS()->getType();
13800     if (op->getOpcode() == BO_PtrMemI)
13801       objectType = objectType->castAs<PointerType>()->getPointeeType();
13802     Qualifiers objectQuals = objectType.getQualifiers();
13803 
13804     Qualifiers difference = objectQuals - funcQuals;
13805     difference.removeObjCGCAttr();
13806     difference.removeAddressSpace();
13807     if (difference) {
13808       std::string qualsString = difference.getAsString();
13809       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13810         << fnType.getUnqualifiedType()
13811         << qualsString
13812         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13813     }
13814 
13815     CXXMemberCallExpr *call =
13816         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13817                                   valueKind, RParenLoc, proto->getNumParams());
13818 
13819     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13820                             call, nullptr))
13821       return ExprError();
13822 
13823     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13824       return ExprError();
13825 
13826     if (CheckOtherCall(call, proto))
13827       return ExprError();
13828 
13829     return MaybeBindToTemporary(call);
13830   }
13831 
13832   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13833     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13834                             RParenLoc);
13835 
13836   UnbridgedCastsSet UnbridgedCasts;
13837   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13838     return ExprError();
13839 
13840   MemberExpr *MemExpr;
13841   CXXMethodDecl *Method = nullptr;
13842   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13843   NestedNameSpecifier *Qualifier = nullptr;
13844   if (isa<MemberExpr>(NakedMemExpr)) {
13845     MemExpr = cast<MemberExpr>(NakedMemExpr);
13846     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13847     FoundDecl = MemExpr->getFoundDecl();
13848     Qualifier = MemExpr->getQualifier();
13849     UnbridgedCasts.restore();
13850   } else {
13851     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13852     Qualifier = UnresExpr->getQualifier();
13853 
13854     QualType ObjectType = UnresExpr->getBaseType();
13855     Expr::Classification ObjectClassification
13856       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13857                             : UnresExpr->getBase()->Classify(Context);
13858 
13859     // Add overload candidates
13860     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13861                                       OverloadCandidateSet::CSK_Normal);
13862 
13863     // FIXME: avoid copy.
13864     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13865     if (UnresExpr->hasExplicitTemplateArgs()) {
13866       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13867       TemplateArgs = &TemplateArgsBuffer;
13868     }
13869 
13870     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13871            E = UnresExpr->decls_end(); I != E; ++I) {
13872 
13873       NamedDecl *Func = *I;
13874       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13875       if (isa<UsingShadowDecl>(Func))
13876         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13877 
13878 
13879       // Microsoft supports direct constructor calls.
13880       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13881         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13882                              CandidateSet,
13883                              /*SuppressUserConversions*/ false);
13884       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13885         // If explicit template arguments were provided, we can't call a
13886         // non-template member function.
13887         if (TemplateArgs)
13888           continue;
13889 
13890         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13891                            ObjectClassification, Args, CandidateSet,
13892                            /*SuppressUserConversions=*/false);
13893       } else {
13894         AddMethodTemplateCandidate(
13895             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13896             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13897             /*SuppressUserConversions=*/false);
13898       }
13899     }
13900 
13901     DeclarationName DeclName = UnresExpr->getMemberName();
13902 
13903     UnbridgedCasts.restore();
13904 
13905     OverloadCandidateSet::iterator Best;
13906     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13907                                             Best)) {
13908     case OR_Success:
13909       Method = cast<CXXMethodDecl>(Best->Function);
13910       FoundDecl = Best->FoundDecl;
13911       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13912       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13913         return ExprError();
13914       // If FoundDecl is different from Method (such as if one is a template
13915       // and the other a specialization), make sure DiagnoseUseOfDecl is
13916       // called on both.
13917       // FIXME: This would be more comprehensively addressed by modifying
13918       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13919       // being used.
13920       if (Method != FoundDecl.getDecl() &&
13921                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13922         return ExprError();
13923       break;
13924 
13925     case OR_No_Viable_Function:
13926       CandidateSet.NoteCandidates(
13927           PartialDiagnosticAt(
13928               UnresExpr->getMemberLoc(),
13929               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13930                   << DeclName << MemExprE->getSourceRange()),
13931           *this, OCD_AllCandidates, Args);
13932       // FIXME: Leaking incoming expressions!
13933       return ExprError();
13934 
13935     case OR_Ambiguous:
13936       CandidateSet.NoteCandidates(
13937           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13938                               PDiag(diag::err_ovl_ambiguous_member_call)
13939                                   << DeclName << MemExprE->getSourceRange()),
13940           *this, OCD_AmbiguousCandidates, Args);
13941       // FIXME: Leaking incoming expressions!
13942       return ExprError();
13943 
13944     case OR_Deleted:
13945       CandidateSet.NoteCandidates(
13946           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13947                               PDiag(diag::err_ovl_deleted_member_call)
13948                                   << DeclName << MemExprE->getSourceRange()),
13949           *this, OCD_AllCandidates, Args);
13950       // FIXME: Leaking incoming expressions!
13951       return ExprError();
13952     }
13953 
13954     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13955 
13956     // If overload resolution picked a static member, build a
13957     // non-member call based on that function.
13958     if (Method->isStatic()) {
13959       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13960                                    RParenLoc);
13961     }
13962 
13963     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13964   }
13965 
13966   QualType ResultType = Method->getReturnType();
13967   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13968   ResultType = ResultType.getNonLValueExprType(Context);
13969 
13970   assert(Method && "Member call to something that isn't a method?");
13971   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13972   CXXMemberCallExpr *TheCall =
13973       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13974                                 RParenLoc, Proto->getNumParams());
13975 
13976   // Check for a valid return type.
13977   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13978                           TheCall, Method))
13979     return ExprError();
13980 
13981   // Convert the object argument (for a non-static member function call).
13982   // We only need to do this if there was actually an overload; otherwise
13983   // it was done at lookup.
13984   if (!Method->isStatic()) {
13985     ExprResult ObjectArg =
13986       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13987                                           FoundDecl, Method);
13988     if (ObjectArg.isInvalid())
13989       return ExprError();
13990     MemExpr->setBase(ObjectArg.get());
13991   }
13992 
13993   // Convert the rest of the arguments
13994   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13995                               RParenLoc))
13996     return ExprError();
13997 
13998   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13999 
14000   if (CheckFunctionCall(Method, TheCall, Proto))
14001     return ExprError();
14002 
14003   // In the case the method to call was not selected by the overloading
14004   // resolution process, we still need to handle the enable_if attribute. Do
14005   // that here, so it will not hide previous -- and more relevant -- errors.
14006   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14007     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14008       Diag(MemE->getMemberLoc(),
14009            diag::err_ovl_no_viable_member_function_in_call)
14010           << Method << Method->getSourceRange();
14011       Diag(Method->getLocation(),
14012            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14013           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14014       return ExprError();
14015     }
14016   }
14017 
14018   if ((isa<CXXConstructorDecl>(CurContext) ||
14019        isa<CXXDestructorDecl>(CurContext)) &&
14020       TheCall->getMethodDecl()->isPure()) {
14021     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14022 
14023     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14024         MemExpr->performsVirtualDispatch(getLangOpts())) {
14025       Diag(MemExpr->getBeginLoc(),
14026            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14027           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14028           << MD->getParent()->getDeclName();
14029 
14030       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14031       if (getLangOpts().AppleKext)
14032         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14033             << MD->getParent()->getDeclName() << MD->getDeclName();
14034     }
14035   }
14036 
14037   if (CXXDestructorDecl *DD =
14038           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14039     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14040     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14041     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14042                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14043                          MemExpr->getMemberLoc());
14044   }
14045 
14046   return MaybeBindToTemporary(TheCall);
14047 }
14048 
14049 /// BuildCallToObjectOfClassType - Build a call to an object of class
14050 /// type (C++ [over.call.object]), which can end up invoking an
14051 /// overloaded function call operator (@c operator()) or performing a
14052 /// user-defined conversion on the object argument.
14053 ExprResult
14054 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14055                                    SourceLocation LParenLoc,
14056                                    MultiExprArg Args,
14057                                    SourceLocation RParenLoc) {
14058   if (checkPlaceholderForOverload(*this, Obj))
14059     return ExprError();
14060   ExprResult Object = Obj;
14061 
14062   UnbridgedCastsSet UnbridgedCasts;
14063   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14064     return ExprError();
14065 
14066   assert(Object.get()->getType()->isRecordType() &&
14067          "Requires object type argument");
14068 
14069   // C++ [over.call.object]p1:
14070   //  If the primary-expression E in the function call syntax
14071   //  evaluates to a class object of type "cv T", then the set of
14072   //  candidate functions includes at least the function call
14073   //  operators of T. The function call operators of T are obtained by
14074   //  ordinary lookup of the name operator() in the context of
14075   //  (E).operator().
14076   OverloadCandidateSet CandidateSet(LParenLoc,
14077                                     OverloadCandidateSet::CSK_Operator);
14078   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14079 
14080   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14081                           diag::err_incomplete_object_call, Object.get()))
14082     return true;
14083 
14084   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14085   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14086   LookupQualifiedName(R, Record->getDecl());
14087   R.suppressDiagnostics();
14088 
14089   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14090        Oper != OperEnd; ++Oper) {
14091     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14092                        Object.get()->Classify(Context), Args, CandidateSet,
14093                        /*SuppressUserConversion=*/false);
14094   }
14095 
14096   // C++ [over.call.object]p2:
14097   //   In addition, for each (non-explicit in C++0x) conversion function
14098   //   declared in T of the form
14099   //
14100   //        operator conversion-type-id () cv-qualifier;
14101   //
14102   //   where cv-qualifier is the same cv-qualification as, or a
14103   //   greater cv-qualification than, cv, and where conversion-type-id
14104   //   denotes the type "pointer to function of (P1,...,Pn) returning
14105   //   R", or the type "reference to pointer to function of
14106   //   (P1,...,Pn) returning R", or the type "reference to function
14107   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14108   //   is also considered as a candidate function. Similarly,
14109   //   surrogate call functions are added to the set of candidate
14110   //   functions for each conversion function declared in an
14111   //   accessible base class provided the function is not hidden
14112   //   within T by another intervening declaration.
14113   const auto &Conversions =
14114       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14115   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14116     NamedDecl *D = *I;
14117     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14118     if (isa<UsingShadowDecl>(D))
14119       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14120 
14121     // Skip over templated conversion functions; they aren't
14122     // surrogates.
14123     if (isa<FunctionTemplateDecl>(D))
14124       continue;
14125 
14126     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14127     if (!Conv->isExplicit()) {
14128       // Strip the reference type (if any) and then the pointer type (if
14129       // any) to get down to what might be a function type.
14130       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14131       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14132         ConvType = ConvPtrType->getPointeeType();
14133 
14134       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14135       {
14136         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14137                               Object.get(), Args, CandidateSet);
14138       }
14139     }
14140   }
14141 
14142   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14143 
14144   // Perform overload resolution.
14145   OverloadCandidateSet::iterator Best;
14146   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14147                                           Best)) {
14148   case OR_Success:
14149     // Overload resolution succeeded; we'll build the appropriate call
14150     // below.
14151     break;
14152 
14153   case OR_No_Viable_Function: {
14154     PartialDiagnostic PD =
14155         CandidateSet.empty()
14156             ? (PDiag(diag::err_ovl_no_oper)
14157                << Object.get()->getType() << /*call*/ 1
14158                << Object.get()->getSourceRange())
14159             : (PDiag(diag::err_ovl_no_viable_object_call)
14160                << Object.get()->getType() << Object.get()->getSourceRange());
14161     CandidateSet.NoteCandidates(
14162         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14163         OCD_AllCandidates, Args);
14164     break;
14165   }
14166   case OR_Ambiguous:
14167     CandidateSet.NoteCandidates(
14168         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14169                             PDiag(diag::err_ovl_ambiguous_object_call)
14170                                 << Object.get()->getType()
14171                                 << Object.get()->getSourceRange()),
14172         *this, OCD_AmbiguousCandidates, Args);
14173     break;
14174 
14175   case OR_Deleted:
14176     CandidateSet.NoteCandidates(
14177         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14178                             PDiag(diag::err_ovl_deleted_object_call)
14179                                 << Object.get()->getType()
14180                                 << Object.get()->getSourceRange()),
14181         *this, OCD_AllCandidates, Args);
14182     break;
14183   }
14184 
14185   if (Best == CandidateSet.end())
14186     return true;
14187 
14188   UnbridgedCasts.restore();
14189 
14190   if (Best->Function == nullptr) {
14191     // Since there is no function declaration, this is one of the
14192     // surrogate candidates. Dig out the conversion function.
14193     CXXConversionDecl *Conv
14194       = cast<CXXConversionDecl>(
14195                          Best->Conversions[0].UserDefined.ConversionFunction);
14196 
14197     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14198                               Best->FoundDecl);
14199     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14200       return ExprError();
14201     assert(Conv == Best->FoundDecl.getDecl() &&
14202              "Found Decl & conversion-to-functionptr should be same, right?!");
14203     // We selected one of the surrogate functions that converts the
14204     // object parameter to a function pointer. Perform the conversion
14205     // on the object argument, then let BuildCallExpr finish the job.
14206 
14207     // Create an implicit member expr to refer to the conversion operator.
14208     // and then call it.
14209     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14210                                              Conv, HadMultipleCandidates);
14211     if (Call.isInvalid())
14212       return ExprError();
14213     // Record usage of conversion in an implicit cast.
14214     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14215                                     CK_UserDefinedConversion, Call.get(),
14216                                     nullptr, VK_RValue);
14217 
14218     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14219   }
14220 
14221   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14222 
14223   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14224   // that calls this method, using Object for the implicit object
14225   // parameter and passing along the remaining arguments.
14226   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14227 
14228   // An error diagnostic has already been printed when parsing the declaration.
14229   if (Method->isInvalidDecl())
14230     return ExprError();
14231 
14232   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14233   unsigned NumParams = Proto->getNumParams();
14234 
14235   DeclarationNameInfo OpLocInfo(
14236                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14237   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14238   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14239                                            Obj, HadMultipleCandidates,
14240                                            OpLocInfo.getLoc(),
14241                                            OpLocInfo.getInfo());
14242   if (NewFn.isInvalid())
14243     return true;
14244 
14245   // The number of argument slots to allocate in the call. If we have default
14246   // arguments we need to allocate space for them as well. We additionally
14247   // need one more slot for the object parameter.
14248   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14249 
14250   // Build the full argument list for the method call (the implicit object
14251   // parameter is placed at the beginning of the list).
14252   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14253 
14254   bool IsError = false;
14255 
14256   // Initialize the implicit object parameter.
14257   ExprResult ObjRes =
14258     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14259                                         Best->FoundDecl, Method);
14260   if (ObjRes.isInvalid())
14261     IsError = true;
14262   else
14263     Object = ObjRes;
14264   MethodArgs[0] = Object.get();
14265 
14266   // Check the argument types.
14267   for (unsigned i = 0; i != NumParams; i++) {
14268     Expr *Arg;
14269     if (i < Args.size()) {
14270       Arg = Args[i];
14271 
14272       // Pass the argument.
14273 
14274       ExprResult InputInit
14275         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14276                                                     Context,
14277                                                     Method->getParamDecl(i)),
14278                                     SourceLocation(), Arg);
14279 
14280       IsError |= InputInit.isInvalid();
14281       Arg = InputInit.getAs<Expr>();
14282     } else {
14283       ExprResult DefArg
14284         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14285       if (DefArg.isInvalid()) {
14286         IsError = true;
14287         break;
14288       }
14289 
14290       Arg = DefArg.getAs<Expr>();
14291     }
14292 
14293     MethodArgs[i + 1] = Arg;
14294   }
14295 
14296   // If this is a variadic call, handle args passed through "...".
14297   if (Proto->isVariadic()) {
14298     // Promote the arguments (C99 6.5.2.2p7).
14299     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14300       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14301                                                         nullptr);
14302       IsError |= Arg.isInvalid();
14303       MethodArgs[i + 1] = Arg.get();
14304     }
14305   }
14306 
14307   if (IsError)
14308     return true;
14309 
14310   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14311 
14312   // Once we've built TheCall, all of the expressions are properly owned.
14313   QualType ResultTy = Method->getReturnType();
14314   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14315   ResultTy = ResultTy.getNonLValueExprType(Context);
14316 
14317   CXXOperatorCallExpr *TheCall =
14318       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14319                                   ResultTy, VK, RParenLoc, FPOptions());
14320 
14321   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14322     return true;
14323 
14324   if (CheckFunctionCall(Method, TheCall, Proto))
14325     return true;
14326 
14327   return MaybeBindToTemporary(TheCall);
14328 }
14329 
14330 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14331 ///  (if one exists), where @c Base is an expression of class type and
14332 /// @c Member is the name of the member we're trying to find.
14333 ExprResult
14334 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14335                                bool *NoArrowOperatorFound) {
14336   assert(Base->getType()->isRecordType() &&
14337          "left-hand side must have class type");
14338 
14339   if (checkPlaceholderForOverload(*this, Base))
14340     return ExprError();
14341 
14342   SourceLocation Loc = Base->getExprLoc();
14343 
14344   // C++ [over.ref]p1:
14345   //
14346   //   [...] An expression x->m is interpreted as (x.operator->())->m
14347   //   for a class object x of type T if T::operator->() exists and if
14348   //   the operator is selected as the best match function by the
14349   //   overload resolution mechanism (13.3).
14350   DeclarationName OpName =
14351     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14352   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14353 
14354   if (RequireCompleteType(Loc, Base->getType(),
14355                           diag::err_typecheck_incomplete_tag, Base))
14356     return ExprError();
14357 
14358   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14359   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14360   R.suppressDiagnostics();
14361 
14362   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14363        Oper != OperEnd; ++Oper) {
14364     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14365                        None, CandidateSet, /*SuppressUserConversion=*/false);
14366   }
14367 
14368   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14369 
14370   // Perform overload resolution.
14371   OverloadCandidateSet::iterator Best;
14372   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14373   case OR_Success:
14374     // Overload resolution succeeded; we'll build the call below.
14375     break;
14376 
14377   case OR_No_Viable_Function: {
14378     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14379     if (CandidateSet.empty()) {
14380       QualType BaseType = Base->getType();
14381       if (NoArrowOperatorFound) {
14382         // Report this specific error to the caller instead of emitting a
14383         // diagnostic, as requested.
14384         *NoArrowOperatorFound = true;
14385         return ExprError();
14386       }
14387       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14388         << BaseType << Base->getSourceRange();
14389       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14390         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14391           << FixItHint::CreateReplacement(OpLoc, ".");
14392       }
14393     } else
14394       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14395         << "operator->" << Base->getSourceRange();
14396     CandidateSet.NoteCandidates(*this, Base, Cands);
14397     return ExprError();
14398   }
14399   case OR_Ambiguous:
14400     CandidateSet.NoteCandidates(
14401         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14402                                        << "->" << Base->getType()
14403                                        << Base->getSourceRange()),
14404         *this, OCD_AmbiguousCandidates, Base);
14405     return ExprError();
14406 
14407   case OR_Deleted:
14408     CandidateSet.NoteCandidates(
14409         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14410                                        << "->" << Base->getSourceRange()),
14411         *this, OCD_AllCandidates, Base);
14412     return ExprError();
14413   }
14414 
14415   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14416 
14417   // Convert the object parameter.
14418   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14419   ExprResult BaseResult =
14420     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14421                                         Best->FoundDecl, Method);
14422   if (BaseResult.isInvalid())
14423     return ExprError();
14424   Base = BaseResult.get();
14425 
14426   // Build the operator call.
14427   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14428                                             Base, HadMultipleCandidates, OpLoc);
14429   if (FnExpr.isInvalid())
14430     return ExprError();
14431 
14432   QualType ResultTy = Method->getReturnType();
14433   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14434   ResultTy = ResultTy.getNonLValueExprType(Context);
14435   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14436       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14437 
14438   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14439     return ExprError();
14440 
14441   if (CheckFunctionCall(Method, TheCall,
14442                         Method->getType()->castAs<FunctionProtoType>()))
14443     return ExprError();
14444 
14445   return MaybeBindToTemporary(TheCall);
14446 }
14447 
14448 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14449 /// a literal operator described by the provided lookup results.
14450 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14451                                           DeclarationNameInfo &SuffixInfo,
14452                                           ArrayRef<Expr*> Args,
14453                                           SourceLocation LitEndLoc,
14454                                        TemplateArgumentListInfo *TemplateArgs) {
14455   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14456 
14457   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14458                                     OverloadCandidateSet::CSK_Normal);
14459   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14460                                  TemplateArgs);
14461 
14462   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14463 
14464   // Perform overload resolution. This will usually be trivial, but might need
14465   // to perform substitutions for a literal operator template.
14466   OverloadCandidateSet::iterator Best;
14467   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14468   case OR_Success:
14469   case OR_Deleted:
14470     break;
14471 
14472   case OR_No_Viable_Function:
14473     CandidateSet.NoteCandidates(
14474         PartialDiagnosticAt(UDSuffixLoc,
14475                             PDiag(diag::err_ovl_no_viable_function_in_call)
14476                                 << R.getLookupName()),
14477         *this, OCD_AllCandidates, Args);
14478     return ExprError();
14479 
14480   case OR_Ambiguous:
14481     CandidateSet.NoteCandidates(
14482         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14483                                                 << R.getLookupName()),
14484         *this, OCD_AmbiguousCandidates, Args);
14485     return ExprError();
14486   }
14487 
14488   FunctionDecl *FD = Best->Function;
14489   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14490                                         nullptr, HadMultipleCandidates,
14491                                         SuffixInfo.getLoc(),
14492                                         SuffixInfo.getInfo());
14493   if (Fn.isInvalid())
14494     return true;
14495 
14496   // Check the argument types. This should almost always be a no-op, except
14497   // that array-to-pointer decay is applied to string literals.
14498   Expr *ConvArgs[2];
14499   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14500     ExprResult InputInit = PerformCopyInitialization(
14501       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14502       SourceLocation(), Args[ArgIdx]);
14503     if (InputInit.isInvalid())
14504       return true;
14505     ConvArgs[ArgIdx] = InputInit.get();
14506   }
14507 
14508   QualType ResultTy = FD->getReturnType();
14509   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14510   ResultTy = ResultTy.getNonLValueExprType(Context);
14511 
14512   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14513       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14514       VK, LitEndLoc, UDSuffixLoc);
14515 
14516   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14517     return ExprError();
14518 
14519   if (CheckFunctionCall(FD, UDL, nullptr))
14520     return ExprError();
14521 
14522   return MaybeBindToTemporary(UDL);
14523 }
14524 
14525 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14526 /// given LookupResult is non-empty, it is assumed to describe a member which
14527 /// will be invoked. Otherwise, the function will be found via argument
14528 /// dependent lookup.
14529 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14530 /// otherwise CallExpr is set to ExprError() and some non-success value
14531 /// is returned.
14532 Sema::ForRangeStatus
14533 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14534                                 SourceLocation RangeLoc,
14535                                 const DeclarationNameInfo &NameInfo,
14536                                 LookupResult &MemberLookup,
14537                                 OverloadCandidateSet *CandidateSet,
14538                                 Expr *Range, ExprResult *CallExpr) {
14539   Scope *S = nullptr;
14540 
14541   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14542   if (!MemberLookup.empty()) {
14543     ExprResult MemberRef =
14544         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14545                                  /*IsPtr=*/false, CXXScopeSpec(),
14546                                  /*TemplateKWLoc=*/SourceLocation(),
14547                                  /*FirstQualifierInScope=*/nullptr,
14548                                  MemberLookup,
14549                                  /*TemplateArgs=*/nullptr, S);
14550     if (MemberRef.isInvalid()) {
14551       *CallExpr = ExprError();
14552       return FRS_DiagnosticIssued;
14553     }
14554     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14555     if (CallExpr->isInvalid()) {
14556       *CallExpr = ExprError();
14557       return FRS_DiagnosticIssued;
14558     }
14559   } else {
14560     UnresolvedSet<0> FoundNames;
14561     UnresolvedLookupExpr *Fn =
14562       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14563                                    NestedNameSpecifierLoc(), NameInfo,
14564                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14565                                    FoundNames.begin(), FoundNames.end());
14566 
14567     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14568                                                     CandidateSet, CallExpr);
14569     if (CandidateSet->empty() || CandidateSetError) {
14570       *CallExpr = ExprError();
14571       return FRS_NoViableFunction;
14572     }
14573     OverloadCandidateSet::iterator Best;
14574     OverloadingResult OverloadResult =
14575         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14576 
14577     if (OverloadResult == OR_No_Viable_Function) {
14578       *CallExpr = ExprError();
14579       return FRS_NoViableFunction;
14580     }
14581     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14582                                          Loc, nullptr, CandidateSet, &Best,
14583                                          OverloadResult,
14584                                          /*AllowTypoCorrection=*/false);
14585     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14586       *CallExpr = ExprError();
14587       return FRS_DiagnosticIssued;
14588     }
14589   }
14590   return FRS_Success;
14591 }
14592 
14593 
14594 /// FixOverloadedFunctionReference - E is an expression that refers to
14595 /// a C++ overloaded function (possibly with some parentheses and
14596 /// perhaps a '&' around it). We have resolved the overloaded function
14597 /// to the function declaration Fn, so patch up the expression E to
14598 /// refer (possibly indirectly) to Fn. Returns the new expr.
14599 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14600                                            FunctionDecl *Fn) {
14601   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14602     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14603                                                    Found, Fn);
14604     if (SubExpr == PE->getSubExpr())
14605       return PE;
14606 
14607     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14608   }
14609 
14610   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14611     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14612                                                    Found, Fn);
14613     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14614                                SubExpr->getType()) &&
14615            "Implicit cast type cannot be determined from overload");
14616     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14617     if (SubExpr == ICE->getSubExpr())
14618       return ICE;
14619 
14620     return ImplicitCastExpr::Create(Context, ICE->getType(),
14621                                     ICE->getCastKind(),
14622                                     SubExpr, nullptr,
14623                                     ICE->getValueKind());
14624   }
14625 
14626   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14627     if (!GSE->isResultDependent()) {
14628       Expr *SubExpr =
14629           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14630       if (SubExpr == GSE->getResultExpr())
14631         return GSE;
14632 
14633       // Replace the resulting type information before rebuilding the generic
14634       // selection expression.
14635       ArrayRef<Expr *> A = GSE->getAssocExprs();
14636       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14637       unsigned ResultIdx = GSE->getResultIndex();
14638       AssocExprs[ResultIdx] = SubExpr;
14639 
14640       return GenericSelectionExpr::Create(
14641           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14642           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14643           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14644           ResultIdx);
14645     }
14646     // Rather than fall through to the unreachable, return the original generic
14647     // selection expression.
14648     return GSE;
14649   }
14650 
14651   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14652     assert(UnOp->getOpcode() == UO_AddrOf &&
14653            "Can only take the address of an overloaded function");
14654     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14655       if (Method->isStatic()) {
14656         // Do nothing: static member functions aren't any different
14657         // from non-member functions.
14658       } else {
14659         // Fix the subexpression, which really has to be an
14660         // UnresolvedLookupExpr holding an overloaded member function
14661         // or template.
14662         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14663                                                        Found, Fn);
14664         if (SubExpr == UnOp->getSubExpr())
14665           return UnOp;
14666 
14667         assert(isa<DeclRefExpr>(SubExpr)
14668                && "fixed to something other than a decl ref");
14669         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14670                && "fixed to a member ref with no nested name qualifier");
14671 
14672         // We have taken the address of a pointer to member
14673         // function. Perform the computation here so that we get the
14674         // appropriate pointer to member type.
14675         QualType ClassType
14676           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14677         QualType MemPtrType
14678           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14679         // Under the MS ABI, lock down the inheritance model now.
14680         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14681           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14682 
14683         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14684                                            VK_RValue, OK_Ordinary,
14685                                            UnOp->getOperatorLoc(), false);
14686       }
14687     }
14688     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14689                                                    Found, Fn);
14690     if (SubExpr == UnOp->getSubExpr())
14691       return UnOp;
14692 
14693     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14694                                      Context.getPointerType(SubExpr->getType()),
14695                                        VK_RValue, OK_Ordinary,
14696                                        UnOp->getOperatorLoc(), false);
14697   }
14698 
14699   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14700     // FIXME: avoid copy.
14701     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14702     if (ULE->hasExplicitTemplateArgs()) {
14703       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14704       TemplateArgs = &TemplateArgsBuffer;
14705     }
14706 
14707     DeclRefExpr *DRE =
14708         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14709                          ULE->getQualifierLoc(), Found.getDecl(),
14710                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14711     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14712     return DRE;
14713   }
14714 
14715   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14716     // FIXME: avoid copy.
14717     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14718     if (MemExpr->hasExplicitTemplateArgs()) {
14719       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14720       TemplateArgs = &TemplateArgsBuffer;
14721     }
14722 
14723     Expr *Base;
14724 
14725     // If we're filling in a static method where we used to have an
14726     // implicit member access, rewrite to a simple decl ref.
14727     if (MemExpr->isImplicitAccess()) {
14728       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14729         DeclRefExpr *DRE = BuildDeclRefExpr(
14730             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14731             MemExpr->getQualifierLoc(), Found.getDecl(),
14732             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14733         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14734         return DRE;
14735       } else {
14736         SourceLocation Loc = MemExpr->getMemberLoc();
14737         if (MemExpr->getQualifier())
14738           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14739         Base =
14740             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14741       }
14742     } else
14743       Base = MemExpr->getBase();
14744 
14745     ExprValueKind valueKind;
14746     QualType type;
14747     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14748       valueKind = VK_LValue;
14749       type = Fn->getType();
14750     } else {
14751       valueKind = VK_RValue;
14752       type = Context.BoundMemberTy;
14753     }
14754 
14755     return BuildMemberExpr(
14756         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14757         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14758         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14759         type, valueKind, OK_Ordinary, TemplateArgs);
14760   }
14761 
14762   llvm_unreachable("Invalid reference to overloaded function");
14763 }
14764 
14765 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14766                                                 DeclAccessPair Found,
14767                                                 FunctionDecl *Fn) {
14768   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14769 }
14770