1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/CXXInheritance.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DependenceFlags.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include <algorithm>
38 #include <cstdlib>
39 
40 using namespace clang;
41 using namespace sema;
42 
43 using AllowedExplicit = Sema::AllowedExplicit;
44 
45 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
46   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
47     return P->hasAttr<PassObjectSizeAttr>();
48   });
49 }
50 
51 /// A convenience routine for creating a decayed reference to a function.
52 static ExprResult
53 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
54                       const Expr *Base, bool HadMultipleCandidates,
55                       SourceLocation Loc = SourceLocation(),
56                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
57   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
58     return ExprError();
59   // If FoundDecl is different from Fn (such as if one is a template
60   // and the other a specialization), make sure DiagnoseUseOfDecl is
61   // called on both.
62   // FIXME: This would be more comprehensively addressed by modifying
63   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
64   // being used.
65   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
66     return ExprError();
67   DeclRefExpr *DRE = new (S.Context)
68       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
69   if (HadMultipleCandidates)
70     DRE->setHadMultipleCandidates(true);
71 
72   S.MarkDeclRefReferenced(DRE, Base);
73   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
74     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
75       S.ResolveExceptionSpec(Loc, FPT);
76       DRE->setType(Fn->getType());
77     }
78   }
79   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
80                              CK_FunctionToPointerDecay);
81 }
82 
83 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
84                                  bool InOverloadResolution,
85                                  StandardConversionSequence &SCS,
86                                  bool CStyle,
87                                  bool AllowObjCWritebackConversion);
88 
89 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
90                                                  QualType &ToType,
91                                                  bool InOverloadResolution,
92                                                  StandardConversionSequence &SCS,
93                                                  bool CStyle);
94 static OverloadingResult
95 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
96                         UserDefinedConversionSequence& User,
97                         OverloadCandidateSet& Conversions,
98                         AllowedExplicit AllowExplicit,
99                         bool AllowObjCConversionOnExplicit);
100 
101 static ImplicitConversionSequence::CompareKind
102 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
103                                    const StandardConversionSequence& SCS1,
104                                    const StandardConversionSequence& SCS2);
105 
106 static ImplicitConversionSequence::CompareKind
107 CompareQualificationConversions(Sema &S,
108                                 const StandardConversionSequence& SCS1,
109                                 const StandardConversionSequence& SCS2);
110 
111 static ImplicitConversionSequence::CompareKind
112 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
113                                 const StandardConversionSequence& SCS1,
114                                 const StandardConversionSequence& SCS2);
115 
116 /// GetConversionRank - Retrieve the implicit conversion rank
117 /// corresponding to the given implicit conversion kind.
118 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
119   static const ImplicitConversionRank
120     Rank[(int)ICK_Num_Conversion_Kinds] = {
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Exact_Match,
126     ICR_Exact_Match,
127     ICR_Promotion,
128     ICR_Promotion,
129     ICR_Promotion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_OCL_Scalar_Widening,
142     ICR_Complex_Real_Conversion,
143     ICR_Conversion,
144     ICR_Conversion,
145     ICR_Writeback_Conversion,
146     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
147                      // it was omitted by the patch that added
148                      // ICK_Zero_Event_Conversion
149     ICR_C_Conversion,
150     ICR_C_Conversion_Extension
151   };
152   return Rank[(int)Kind];
153 }
154 
155 /// GetImplicitConversionName - Return the name of this kind of
156 /// implicit conversion.
157 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
158   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
159     "No conversion",
160     "Lvalue-to-rvalue",
161     "Array-to-pointer",
162     "Function-to-pointer",
163     "Function pointer conversion",
164     "Qualification",
165     "Integral promotion",
166     "Floating point promotion",
167     "Complex promotion",
168     "Integral conversion",
169     "Floating conversion",
170     "Complex conversion",
171     "Floating-integral conversion",
172     "Pointer conversion",
173     "Pointer-to-member conversion",
174     "Boolean conversion",
175     "Compatible-types conversion",
176     "Derived-to-base conversion",
177     "Vector conversion",
178     "SVE Vector conversion",
179     "Vector splat",
180     "Complex-real conversion",
181     "Block Pointer conversion",
182     "Transparent Union Conversion",
183     "Writeback conversion",
184     "OpenCL Zero Event Conversion",
185     "C specific type conversion",
186     "Incompatible pointer conversion"
187   };
188   return Name[Kind];
189 }
190 
191 /// StandardConversionSequence - Set the standard conversion
192 /// sequence to the identity conversion.
193 void StandardConversionSequence::setAsIdentityConversion() {
194   First = ICK_Identity;
195   Second = ICK_Identity;
196   Third = ICK_Identity;
197   DeprecatedStringLiteralToCharPtr = false;
198   QualificationIncludesObjCLifetime = false;
199   ReferenceBinding = false;
200   DirectBinding = false;
201   IsLvalueReference = true;
202   BindsToFunctionLvalue = false;
203   BindsToRvalue = false;
204   BindsImplicitObjectArgumentWithoutRefQualifier = false;
205   ObjCLifetimeConversionBinding = false;
206   CopyConstructor = nullptr;
207 }
208 
209 /// getRank - Retrieve the rank of this standard conversion sequence
210 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
211 /// implicit conversions.
212 ImplicitConversionRank StandardConversionSequence::getRank() const {
213   ImplicitConversionRank Rank = ICR_Exact_Match;
214   if  (GetConversionRank(First) > Rank)
215     Rank = GetConversionRank(First);
216   if  (GetConversionRank(Second) > Rank)
217     Rank = GetConversionRank(Second);
218   if  (GetConversionRank(Third) > Rank)
219     Rank = GetConversionRank(Third);
220   return Rank;
221 }
222 
223 /// isPointerConversionToBool - Determines whether this conversion is
224 /// a conversion of a pointer or pointer-to-member to bool. This is
225 /// used as part of the ranking of standard conversion sequences
226 /// (C++ 13.3.3.2p4).
227 bool StandardConversionSequence::isPointerConversionToBool() const {
228   // Note that FromType has not necessarily been transformed by the
229   // array-to-pointer or function-to-pointer implicit conversions, so
230   // check for their presence as well as checking whether FromType is
231   // a pointer.
232   if (getToType(1)->isBooleanType() &&
233       (getFromType()->isPointerType() ||
234        getFromType()->isMemberPointerType() ||
235        getFromType()->isObjCObjectPointerType() ||
236        getFromType()->isBlockPointerType() ||
237        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
238     return true;
239 
240   return false;
241 }
242 
243 /// isPointerConversionToVoidPointer - Determines whether this
244 /// conversion is a conversion of a pointer to a void pointer. This is
245 /// used as part of the ranking of standard conversion sequences (C++
246 /// 13.3.3.2p4).
247 bool
248 StandardConversionSequence::
249 isPointerConversionToVoidPointer(ASTContext& Context) const {
250   QualType FromType = getFromType();
251   QualType ToType = getToType(1);
252 
253   // Note that FromType has not necessarily been transformed by the
254   // array-to-pointer implicit conversion, so check for its presence
255   // and redo the conversion to get a pointer.
256   if (First == ICK_Array_To_Pointer)
257     FromType = Context.getArrayDecayedType(FromType);
258 
259   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
260     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
261       return ToPtrType->getPointeeType()->isVoidType();
262 
263   return false;
264 }
265 
266 /// Skip any implicit casts which could be either part of a narrowing conversion
267 /// or after one in an implicit conversion.
268 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
269                                              const Expr *Converted) {
270   // We can have cleanups wrapping the converted expression; these need to be
271   // preserved so that destructors run if necessary.
272   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
273     Expr *Inner =
274         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
275     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
276                                     EWC->getObjects());
277   }
278 
279   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280     switch (ICE->getCastKind()) {
281     case CK_NoOp:
282     case CK_IntegralCast:
283     case CK_IntegralToBoolean:
284     case CK_IntegralToFloating:
285     case CK_BooleanToSignedIntegral:
286     case CK_FloatingToIntegral:
287     case CK_FloatingToBoolean:
288     case CK_FloatingCast:
289       Converted = ICE->getSubExpr();
290       continue;
291 
292     default:
293       return Converted;
294     }
295   }
296 
297   return Converted;
298 }
299 
300 /// Check if this standard conversion sequence represents a narrowing
301 /// conversion, according to C++11 [dcl.init.list]p7.
302 ///
303 /// \param Ctx  The AST context.
304 /// \param Converted  The result of applying this standard conversion sequence.
305 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
306 ///        value of the expression prior to the narrowing conversion.
307 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
308 ///        type of the expression prior to the narrowing conversion.
309 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
310 ///        from floating point types to integral types should be ignored.
311 NarrowingKind StandardConversionSequence::getNarrowingKind(
312     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
313     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
314   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
315 
316   // C++11 [dcl.init.list]p7:
317   //   A narrowing conversion is an implicit conversion ...
318   QualType FromType = getToType(0);
319   QualType ToType = getToType(1);
320 
321   // A conversion to an enumeration type is narrowing if the conversion to
322   // the underlying type is narrowing. This only arises for expressions of
323   // the form 'Enum{init}'.
324   if (auto *ET = ToType->getAs<EnumType>())
325     ToType = ET->getDecl()->getIntegerType();
326 
327   switch (Second) {
328   // 'bool' is an integral type; dispatch to the right place to handle it.
329   case ICK_Boolean_Conversion:
330     if (FromType->isRealFloatingType())
331       goto FloatingIntegralConversion;
332     if (FromType->isIntegralOrUnscopedEnumerationType())
333       goto IntegralConversion;
334     // -- from a pointer type or pointer-to-member type to bool, or
335     return NK_Type_Narrowing;
336 
337   // -- from a floating-point type to an integer type, or
338   //
339   // -- from an integer type or unscoped enumeration type to a floating-point
340   //    type, except where the source is a constant expression and the actual
341   //    value after conversion will fit into the target type and will produce
342   //    the original value when converted back to the original type, or
343   case ICK_Floating_Integral:
344   FloatingIntegralConversion:
345     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
346       return NK_Type_Narrowing;
347     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
348                ToType->isRealFloatingType()) {
349       if (IgnoreFloatToIntegralConversion)
350         return NK_Not_Narrowing;
351       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
352       assert(Initializer && "Unknown conversion expression");
353 
354       // If it's value-dependent, we can't tell whether it's narrowing.
355       if (Initializer->isValueDependent())
356         return NK_Dependent_Narrowing;
357 
358       if (Optional<llvm::APSInt> IntConstantValue =
359               Initializer->getIntegerConstantExpr(Ctx)) {
360         // Convert the integer to the floating type.
361         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
362         Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
363                                 llvm::APFloat::rmNearestTiesToEven);
364         // And back.
365         llvm::APSInt ConvertedValue = *IntConstantValue;
366         bool ignored;
367         Result.convertToInteger(ConvertedValue,
368                                 llvm::APFloat::rmTowardZero, &ignored);
369         // If the resulting value is different, this was a narrowing conversion.
370         if (*IntConstantValue != ConvertedValue) {
371           ConstantValue = APValue(*IntConstantValue);
372           ConstantType = Initializer->getType();
373           return NK_Constant_Narrowing;
374         }
375       } else {
376         // Variables are always narrowings.
377         return NK_Variable_Narrowing;
378       }
379     }
380     return NK_Not_Narrowing;
381 
382   // -- from long double to double or float, or from double to float, except
383   //    where the source is a constant expression and the actual value after
384   //    conversion is within the range of values that can be represented (even
385   //    if it cannot be represented exactly), or
386   case ICK_Floating_Conversion:
387     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
388         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
389       // FromType is larger than ToType.
390       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
391 
392       // If it's value-dependent, we can't tell whether it's narrowing.
393       if (Initializer->isValueDependent())
394         return NK_Dependent_Narrowing;
395 
396       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
397         // Constant!
398         assert(ConstantValue.isFloat());
399         llvm::APFloat FloatVal = ConstantValue.getFloat();
400         // Convert the source value into the target type.
401         bool ignored;
402         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
403           Ctx.getFloatTypeSemantics(ToType),
404           llvm::APFloat::rmNearestTiesToEven, &ignored);
405         // If there was no overflow, the source value is within the range of
406         // values that can be represented.
407         if (ConvertStatus & llvm::APFloat::opOverflow) {
408           ConstantType = Initializer->getType();
409           return NK_Constant_Narrowing;
410         }
411       } else {
412         return NK_Variable_Narrowing;
413       }
414     }
415     return NK_Not_Narrowing;
416 
417   // -- from an integer type or unscoped enumeration type to an integer type
418   //    that cannot represent all the values of the original type, except where
419   //    the source is a constant expression and the actual value after
420   //    conversion will fit into the target type and will produce the original
421   //    value when converted back to the original type.
422   case ICK_Integral_Conversion:
423   IntegralConversion: {
424     assert(FromType->isIntegralOrUnscopedEnumerationType());
425     assert(ToType->isIntegralOrUnscopedEnumerationType());
426     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
427     const unsigned FromWidth = Ctx.getIntWidth(FromType);
428     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
429     const unsigned ToWidth = Ctx.getIntWidth(ToType);
430 
431     if (FromWidth > ToWidth ||
432         (FromWidth == ToWidth && FromSigned != ToSigned) ||
433         (FromSigned && !ToSigned)) {
434       // Not all values of FromType can be represented in ToType.
435       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
436 
437       // If it's value-dependent, we can't tell whether it's narrowing.
438       if (Initializer->isValueDependent())
439         return NK_Dependent_Narrowing;
440 
441       Optional<llvm::APSInt> OptInitializerValue;
442       if (!(OptInitializerValue = Initializer->getIntegerConstantExpr(Ctx))) {
443         // Such conversions on variables are always narrowing.
444         return NK_Variable_Narrowing;
445       }
446       llvm::APSInt &InitializerValue = *OptInitializerValue;
447       bool Narrowing = false;
448       if (FromWidth < ToWidth) {
449         // Negative -> unsigned is narrowing. Otherwise, more bits is never
450         // narrowing.
451         if (InitializerValue.isSigned() && InitializerValue.isNegative())
452           Narrowing = true;
453       } else {
454         // Add a bit to the InitializerValue so we don't have to worry about
455         // signed vs. unsigned comparisons.
456         InitializerValue = InitializerValue.extend(
457           InitializerValue.getBitWidth() + 1);
458         // Convert the initializer to and from the target width and signed-ness.
459         llvm::APSInt ConvertedValue = InitializerValue;
460         ConvertedValue = ConvertedValue.trunc(ToWidth);
461         ConvertedValue.setIsSigned(ToSigned);
462         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
463         ConvertedValue.setIsSigned(InitializerValue.isSigned());
464         // If the result is different, this was a narrowing conversion.
465         if (ConvertedValue != InitializerValue)
466           Narrowing = true;
467       }
468       if (Narrowing) {
469         ConstantType = Initializer->getType();
470         ConstantValue = APValue(InitializerValue);
471         return NK_Constant_Narrowing;
472       }
473     }
474     return NK_Not_Narrowing;
475   }
476 
477   default:
478     // Other kinds of conversions are not narrowings.
479     return NK_Not_Narrowing;
480   }
481 }
482 
483 /// dump - Print this standard conversion sequence to standard
484 /// error. Useful for debugging overloading issues.
485 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
486   raw_ostream &OS = llvm::errs();
487   bool PrintedSomething = false;
488   if (First != ICK_Identity) {
489     OS << GetImplicitConversionName(First);
490     PrintedSomething = true;
491   }
492 
493   if (Second != ICK_Identity) {
494     if (PrintedSomething) {
495       OS << " -> ";
496     }
497     OS << GetImplicitConversionName(Second);
498 
499     if (CopyConstructor) {
500       OS << " (by copy constructor)";
501     } else if (DirectBinding) {
502       OS << " (direct reference binding)";
503     } else if (ReferenceBinding) {
504       OS << " (reference binding)";
505     }
506     PrintedSomething = true;
507   }
508 
509   if (Third != ICK_Identity) {
510     if (PrintedSomething) {
511       OS << " -> ";
512     }
513     OS << GetImplicitConversionName(Third);
514     PrintedSomething = true;
515   }
516 
517   if (!PrintedSomething) {
518     OS << "No conversions required";
519   }
520 }
521 
522 /// dump - Print this user-defined conversion sequence to standard
523 /// error. Useful for debugging overloading issues.
524 void UserDefinedConversionSequence::dump() const {
525   raw_ostream &OS = llvm::errs();
526   if (Before.First || Before.Second || Before.Third) {
527     Before.dump();
528     OS << " -> ";
529   }
530   if (ConversionFunction)
531     OS << '\'' << *ConversionFunction << '\'';
532   else
533     OS << "aggregate initialization";
534   if (After.First || After.Second || After.Third) {
535     OS << " -> ";
536     After.dump();
537   }
538 }
539 
540 /// dump - Print this implicit conversion sequence to standard
541 /// error. Useful for debugging overloading issues.
542 void ImplicitConversionSequence::dump() const {
543   raw_ostream &OS = llvm::errs();
544   if (isStdInitializerListElement())
545     OS << "Worst std::initializer_list element conversion: ";
546   switch (ConversionKind) {
547   case StandardConversion:
548     OS << "Standard conversion: ";
549     Standard.dump();
550     break;
551   case UserDefinedConversion:
552     OS << "User-defined conversion: ";
553     UserDefined.dump();
554     break;
555   case EllipsisConversion:
556     OS << "Ellipsis conversion";
557     break;
558   case AmbiguousConversion:
559     OS << "Ambiguous conversion";
560     break;
561   case BadConversion:
562     OS << "Bad conversion";
563     break;
564   }
565 
566   OS << "\n";
567 }
568 
569 void AmbiguousConversionSequence::construct() {
570   new (&conversions()) ConversionSet();
571 }
572 
573 void AmbiguousConversionSequence::destruct() {
574   conversions().~ConversionSet();
575 }
576 
577 void
578 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
579   FromTypePtr = O.FromTypePtr;
580   ToTypePtr = O.ToTypePtr;
581   new (&conversions()) ConversionSet(O.conversions());
582 }
583 
584 namespace {
585   // Structure used by DeductionFailureInfo to store
586   // template argument information.
587   struct DFIArguments {
588     TemplateArgument FirstArg;
589     TemplateArgument SecondArg;
590   };
591   // Structure used by DeductionFailureInfo to store
592   // template parameter and template argument information.
593   struct DFIParamWithArguments : DFIArguments {
594     TemplateParameter Param;
595   };
596   // Structure used by DeductionFailureInfo to store template argument
597   // information and the index of the problematic call argument.
598   struct DFIDeducedMismatchArgs : DFIArguments {
599     TemplateArgumentList *TemplateArgs;
600     unsigned CallArgIndex;
601   };
602   // Structure used by DeductionFailureInfo to store information about
603   // unsatisfied constraints.
604   struct CNSInfo {
605     TemplateArgumentList *TemplateArgs;
606     ConstraintSatisfaction Satisfaction;
607   };
608 }
609 
610 /// Convert from Sema's representation of template deduction information
611 /// to the form used in overload-candidate information.
612 DeductionFailureInfo
613 clang::MakeDeductionFailureInfo(ASTContext &Context,
614                                 Sema::TemplateDeductionResult TDK,
615                                 TemplateDeductionInfo &Info) {
616   DeductionFailureInfo Result;
617   Result.Result = static_cast<unsigned>(TDK);
618   Result.HasDiagnostic = false;
619   switch (TDK) {
620   case Sema::TDK_Invalid:
621   case Sema::TDK_InstantiationDepth:
622   case Sema::TDK_TooManyArguments:
623   case Sema::TDK_TooFewArguments:
624   case Sema::TDK_MiscellaneousDeductionFailure:
625   case Sema::TDK_CUDATargetMismatch:
626     Result.Data = nullptr;
627     break;
628 
629   case Sema::TDK_Incomplete:
630   case Sema::TDK_InvalidExplicitArguments:
631     Result.Data = Info.Param.getOpaqueValue();
632     break;
633 
634   case Sema::TDK_DeducedMismatch:
635   case Sema::TDK_DeducedMismatchNested: {
636     // FIXME: Should allocate from normal heap so that we can free this later.
637     auto *Saved = new (Context) DFIDeducedMismatchArgs;
638     Saved->FirstArg = Info.FirstArg;
639     Saved->SecondArg = Info.SecondArg;
640     Saved->TemplateArgs = Info.take();
641     Saved->CallArgIndex = Info.CallArgIndex;
642     Result.Data = Saved;
643     break;
644   }
645 
646   case Sema::TDK_NonDeducedMismatch: {
647     // FIXME: Should allocate from normal heap so that we can free this later.
648     DFIArguments *Saved = new (Context) DFIArguments;
649     Saved->FirstArg = Info.FirstArg;
650     Saved->SecondArg = Info.SecondArg;
651     Result.Data = Saved;
652     break;
653   }
654 
655   case Sema::TDK_IncompletePack:
656     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
657   case Sema::TDK_Inconsistent:
658   case Sema::TDK_Underqualified: {
659     // FIXME: Should allocate from normal heap so that we can free this later.
660     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
661     Saved->Param = Info.Param;
662     Saved->FirstArg = Info.FirstArg;
663     Saved->SecondArg = Info.SecondArg;
664     Result.Data = Saved;
665     break;
666   }
667 
668   case Sema::TDK_SubstitutionFailure:
669     Result.Data = Info.take();
670     if (Info.hasSFINAEDiagnostic()) {
671       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
672           SourceLocation(), PartialDiagnostic::NullDiagnostic());
673       Info.takeSFINAEDiagnostic(*Diag);
674       Result.HasDiagnostic = true;
675     }
676     break;
677 
678   case Sema::TDK_ConstraintsNotSatisfied: {
679     CNSInfo *Saved = new (Context) CNSInfo;
680     Saved->TemplateArgs = Info.take();
681     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682     Result.Data = Saved;
683     break;
684   }
685 
686   case Sema::TDK_Success:
687   case Sema::TDK_NonDependentConversionFailure:
688     llvm_unreachable("not a deduction failure");
689   }
690 
691   return Result;
692 }
693 
694 void DeductionFailureInfo::Destroy() {
695   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
696   case Sema::TDK_Success:
697   case Sema::TDK_Invalid:
698   case Sema::TDK_InstantiationDepth:
699   case Sema::TDK_Incomplete:
700   case Sema::TDK_TooManyArguments:
701   case Sema::TDK_TooFewArguments:
702   case Sema::TDK_InvalidExplicitArguments:
703   case Sema::TDK_CUDATargetMismatch:
704   case Sema::TDK_NonDependentConversionFailure:
705     break;
706 
707   case Sema::TDK_IncompletePack:
708   case Sema::TDK_Inconsistent:
709   case Sema::TDK_Underqualified:
710   case Sema::TDK_DeducedMismatch:
711   case Sema::TDK_DeducedMismatchNested:
712   case Sema::TDK_NonDeducedMismatch:
713     // FIXME: Destroy the data?
714     Data = nullptr;
715     break;
716 
717   case Sema::TDK_SubstitutionFailure:
718     // FIXME: Destroy the template argument list?
719     Data = nullptr;
720     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
721       Diag->~PartialDiagnosticAt();
722       HasDiagnostic = false;
723     }
724     break;
725 
726   case Sema::TDK_ConstraintsNotSatisfied:
727     // FIXME: Destroy the template argument list?
728     Data = nullptr;
729     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
730       Diag->~PartialDiagnosticAt();
731       HasDiagnostic = false;
732     }
733     break;
734 
735   // Unhandled
736   case Sema::TDK_MiscellaneousDeductionFailure:
737     break;
738   }
739 }
740 
741 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
742   if (HasDiagnostic)
743     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
744   return nullptr;
745 }
746 
747 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
748   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749   case Sema::TDK_Success:
750   case Sema::TDK_Invalid:
751   case Sema::TDK_InstantiationDepth:
752   case Sema::TDK_TooManyArguments:
753   case Sema::TDK_TooFewArguments:
754   case Sema::TDK_SubstitutionFailure:
755   case Sema::TDK_DeducedMismatch:
756   case Sema::TDK_DeducedMismatchNested:
757   case Sema::TDK_NonDeducedMismatch:
758   case Sema::TDK_CUDATargetMismatch:
759   case Sema::TDK_NonDependentConversionFailure:
760   case Sema::TDK_ConstraintsNotSatisfied:
761     return TemplateParameter();
762 
763   case Sema::TDK_Incomplete:
764   case Sema::TDK_InvalidExplicitArguments:
765     return TemplateParameter::getFromOpaqueValue(Data);
766 
767   case Sema::TDK_IncompletePack:
768   case Sema::TDK_Inconsistent:
769   case Sema::TDK_Underqualified:
770     return static_cast<DFIParamWithArguments*>(Data)->Param;
771 
772   // Unhandled
773   case Sema::TDK_MiscellaneousDeductionFailure:
774     break;
775   }
776 
777   return TemplateParameter();
778 }
779 
780 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
781   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
782   case Sema::TDK_Success:
783   case Sema::TDK_Invalid:
784   case Sema::TDK_InstantiationDepth:
785   case Sema::TDK_TooManyArguments:
786   case Sema::TDK_TooFewArguments:
787   case Sema::TDK_Incomplete:
788   case Sema::TDK_IncompletePack:
789   case Sema::TDK_InvalidExplicitArguments:
790   case Sema::TDK_Inconsistent:
791   case Sema::TDK_Underqualified:
792   case Sema::TDK_NonDeducedMismatch:
793   case Sema::TDK_CUDATargetMismatch:
794   case Sema::TDK_NonDependentConversionFailure:
795     return nullptr;
796 
797   case Sema::TDK_DeducedMismatch:
798   case Sema::TDK_DeducedMismatchNested:
799     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
800 
801   case Sema::TDK_SubstitutionFailure:
802     return static_cast<TemplateArgumentList*>(Data);
803 
804   case Sema::TDK_ConstraintsNotSatisfied:
805     return static_cast<CNSInfo*>(Data)->TemplateArgs;
806 
807   // Unhandled
808   case Sema::TDK_MiscellaneousDeductionFailure:
809     break;
810   }
811 
812   return nullptr;
813 }
814 
815 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
816   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
817   case Sema::TDK_Success:
818   case Sema::TDK_Invalid:
819   case Sema::TDK_InstantiationDepth:
820   case Sema::TDK_Incomplete:
821   case Sema::TDK_TooManyArguments:
822   case Sema::TDK_TooFewArguments:
823   case Sema::TDK_InvalidExplicitArguments:
824   case Sema::TDK_SubstitutionFailure:
825   case Sema::TDK_CUDATargetMismatch:
826   case Sema::TDK_NonDependentConversionFailure:
827   case Sema::TDK_ConstraintsNotSatisfied:
828     return nullptr;
829 
830   case Sema::TDK_IncompletePack:
831   case Sema::TDK_Inconsistent:
832   case Sema::TDK_Underqualified:
833   case Sema::TDK_DeducedMismatch:
834   case Sema::TDK_DeducedMismatchNested:
835   case Sema::TDK_NonDeducedMismatch:
836     return &static_cast<DFIArguments*>(Data)->FirstArg;
837 
838   // Unhandled
839   case Sema::TDK_MiscellaneousDeductionFailure:
840     break;
841   }
842 
843   return nullptr;
844 }
845 
846 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
847   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
848   case Sema::TDK_Success:
849   case Sema::TDK_Invalid:
850   case Sema::TDK_InstantiationDepth:
851   case Sema::TDK_Incomplete:
852   case Sema::TDK_IncompletePack:
853   case Sema::TDK_TooManyArguments:
854   case Sema::TDK_TooFewArguments:
855   case Sema::TDK_InvalidExplicitArguments:
856   case Sema::TDK_SubstitutionFailure:
857   case Sema::TDK_CUDATargetMismatch:
858   case Sema::TDK_NonDependentConversionFailure:
859   case Sema::TDK_ConstraintsNotSatisfied:
860     return nullptr;
861 
862   case Sema::TDK_Inconsistent:
863   case Sema::TDK_Underqualified:
864   case Sema::TDK_DeducedMismatch:
865   case Sema::TDK_DeducedMismatchNested:
866   case Sema::TDK_NonDeducedMismatch:
867     return &static_cast<DFIArguments*>(Data)->SecondArg;
868 
869   // Unhandled
870   case Sema::TDK_MiscellaneousDeductionFailure:
871     break;
872   }
873 
874   return nullptr;
875 }
876 
877 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
878   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
879   case Sema::TDK_DeducedMismatch:
880   case Sema::TDK_DeducedMismatchNested:
881     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
882 
883   default:
884     return llvm::None;
885   }
886 }
887 
888 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
889     OverloadedOperatorKind Op) {
890   if (!AllowRewrittenCandidates)
891     return false;
892   return Op == OO_EqualEqual || Op == OO_Spaceship;
893 }
894 
895 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
896     ASTContext &Ctx, const FunctionDecl *FD) {
897   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
898     return false;
899   // Don't bother adding a reversed candidate that can never be a better
900   // match than the non-reversed version.
901   return FD->getNumParams() != 2 ||
902          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
903                                      FD->getParamDecl(1)->getType()) ||
904          FD->hasAttr<EnableIfAttr>();
905 }
906 
907 void OverloadCandidateSet::destroyCandidates() {
908   for (iterator i = begin(), e = end(); i != e; ++i) {
909     for (auto &C : i->Conversions)
910       C.~ImplicitConversionSequence();
911     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
912       i->DeductionFailure.Destroy();
913   }
914 }
915 
916 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
917   destroyCandidates();
918   SlabAllocator.Reset();
919   NumInlineBytesUsed = 0;
920   Candidates.clear();
921   Functions.clear();
922   Kind = CSK;
923 }
924 
925 namespace {
926   class UnbridgedCastsSet {
927     struct Entry {
928       Expr **Addr;
929       Expr *Saved;
930     };
931     SmallVector<Entry, 2> Entries;
932 
933   public:
934     void save(Sema &S, Expr *&E) {
935       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
936       Entry entry = { &E, E };
937       Entries.push_back(entry);
938       E = S.stripARCUnbridgedCast(E);
939     }
940 
941     void restore() {
942       for (SmallVectorImpl<Entry>::iterator
943              i = Entries.begin(), e = Entries.end(); i != e; ++i)
944         *i->Addr = i->Saved;
945     }
946   };
947 }
948 
949 /// checkPlaceholderForOverload - Do any interesting placeholder-like
950 /// preprocessing on the given expression.
951 ///
952 /// \param unbridgedCasts a collection to which to add unbridged casts;
953 ///   without this, they will be immediately diagnosed as errors
954 ///
955 /// Return true on unrecoverable error.
956 static bool
957 checkPlaceholderForOverload(Sema &S, Expr *&E,
958                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
959   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
960     // We can't handle overloaded expressions here because overload
961     // resolution might reasonably tweak them.
962     if (placeholder->getKind() == BuiltinType::Overload) return false;
963 
964     // If the context potentially accepts unbridged ARC casts, strip
965     // the unbridged cast and add it to the collection for later restoration.
966     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
967         unbridgedCasts) {
968       unbridgedCasts->save(S, E);
969       return false;
970     }
971 
972     // Go ahead and check everything else.
973     ExprResult result = S.CheckPlaceholderExpr(E);
974     if (result.isInvalid())
975       return true;
976 
977     E = result.get();
978     return false;
979   }
980 
981   // Nothing to do.
982   return false;
983 }
984 
985 /// checkArgPlaceholdersForOverload - Check a set of call operands for
986 /// placeholders.
987 static bool checkArgPlaceholdersForOverload(Sema &S,
988                                             MultiExprArg Args,
989                                             UnbridgedCastsSet &unbridged) {
990   for (unsigned i = 0, e = Args.size(); i != e; ++i)
991     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
992       return true;
993 
994   return false;
995 }
996 
997 /// Determine whether the given New declaration is an overload of the
998 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
999 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1000 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1001 /// functions (or function templates) at all. When it does return Ovl_Match or
1002 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1003 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1004 /// declaration.
1005 ///
1006 /// Example: Given the following input:
1007 ///
1008 ///   void f(int, float); // #1
1009 ///   void f(int, int); // #2
1010 ///   int f(int, int); // #3
1011 ///
1012 /// When we process #1, there is no previous declaration of "f", so IsOverload
1013 /// will not be used.
1014 ///
1015 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1016 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1017 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1018 /// unchanged.
1019 ///
1020 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1021 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1022 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1023 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1024 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1025 ///
1026 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1027 /// by a using declaration. The rules for whether to hide shadow declarations
1028 /// ignore some properties which otherwise figure into a function template's
1029 /// signature.
1030 Sema::OverloadKind
1031 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1032                     NamedDecl *&Match, bool NewIsUsingDecl) {
1033   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1034          I != E; ++I) {
1035     NamedDecl *OldD = *I;
1036 
1037     bool OldIsUsingDecl = false;
1038     if (isa<UsingShadowDecl>(OldD)) {
1039       OldIsUsingDecl = true;
1040 
1041       // We can always introduce two using declarations into the same
1042       // context, even if they have identical signatures.
1043       if (NewIsUsingDecl) continue;
1044 
1045       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1046     }
1047 
1048     // A using-declaration does not conflict with another declaration
1049     // if one of them is hidden.
1050     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1051       continue;
1052 
1053     // If either declaration was introduced by a using declaration,
1054     // we'll need to use slightly different rules for matching.
1055     // Essentially, these rules are the normal rules, except that
1056     // function templates hide function templates with different
1057     // return types or template parameter lists.
1058     bool UseMemberUsingDeclRules =
1059       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1060       !New->getFriendObjectKind();
1061 
1062     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1063       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1064         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1065           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1066           continue;
1067         }
1068 
1069         if (!isa<FunctionTemplateDecl>(OldD) &&
1070             !shouldLinkPossiblyHiddenDecl(*I, New))
1071           continue;
1072 
1073         Match = *I;
1074         return Ovl_Match;
1075       }
1076 
1077       // Builtins that have custom typechecking or have a reference should
1078       // not be overloadable or redeclarable.
1079       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1080         Match = *I;
1081         return Ovl_NonFunction;
1082       }
1083     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1084       // We can overload with these, which can show up when doing
1085       // redeclaration checks for UsingDecls.
1086       assert(Old.getLookupKind() == LookupUsingDeclName);
1087     } else if (isa<TagDecl>(OldD)) {
1088       // We can always overload with tags by hiding them.
1089     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1090       // Optimistically assume that an unresolved using decl will
1091       // overload; if it doesn't, we'll have to diagnose during
1092       // template instantiation.
1093       //
1094       // Exception: if the scope is dependent and this is not a class
1095       // member, the using declaration can only introduce an enumerator.
1096       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1097         Match = *I;
1098         return Ovl_NonFunction;
1099       }
1100     } else {
1101       // (C++ 13p1):
1102       //   Only function declarations can be overloaded; object and type
1103       //   declarations cannot be overloaded.
1104       Match = *I;
1105       return Ovl_NonFunction;
1106     }
1107   }
1108 
1109   // C++ [temp.friend]p1:
1110   //   For a friend function declaration that is not a template declaration:
1111   //    -- if the name of the friend is a qualified or unqualified template-id,
1112   //       [...], otherwise
1113   //    -- if the name of the friend is a qualified-id and a matching
1114   //       non-template function is found in the specified class or namespace,
1115   //       the friend declaration refers to that function, otherwise,
1116   //    -- if the name of the friend is a qualified-id and a matching function
1117   //       template is found in the specified class or namespace, the friend
1118   //       declaration refers to the deduced specialization of that function
1119   //       template, otherwise
1120   //    -- the name shall be an unqualified-id [...]
1121   // If we get here for a qualified friend declaration, we've just reached the
1122   // third bullet. If the type of the friend is dependent, skip this lookup
1123   // until instantiation.
1124   if (New->getFriendObjectKind() && New->getQualifier() &&
1125       !New->getDescribedFunctionTemplate() &&
1126       !New->getDependentSpecializationInfo() &&
1127       !New->getType()->isDependentType()) {
1128     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1129     TemplateSpecResult.addAllDecls(Old);
1130     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1131                                             /*QualifiedFriend*/true)) {
1132       New->setInvalidDecl();
1133       return Ovl_Overload;
1134     }
1135 
1136     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1137     return Ovl_Match;
1138   }
1139 
1140   return Ovl_Overload;
1141 }
1142 
1143 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1144                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1145                       bool ConsiderRequiresClauses) {
1146   // C++ [basic.start.main]p2: This function shall not be overloaded.
1147   if (New->isMain())
1148     return false;
1149 
1150   // MSVCRT user defined entry points cannot be overloaded.
1151   if (New->isMSVCRTEntryPoint())
1152     return false;
1153 
1154   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1155   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1156 
1157   // C++ [temp.fct]p2:
1158   //   A function template can be overloaded with other function templates
1159   //   and with normal (non-template) functions.
1160   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1161     return true;
1162 
1163   // Is the function New an overload of the function Old?
1164   QualType OldQType = Context.getCanonicalType(Old->getType());
1165   QualType NewQType = Context.getCanonicalType(New->getType());
1166 
1167   // Compare the signatures (C++ 1.3.10) of the two functions to
1168   // determine whether they are overloads. If we find any mismatch
1169   // in the signature, they are overloads.
1170 
1171   // If either of these functions is a K&R-style function (no
1172   // prototype), then we consider them to have matching signatures.
1173   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1174       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1175     return false;
1176 
1177   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1178   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1179 
1180   // The signature of a function includes the types of its
1181   // parameters (C++ 1.3.10), which includes the presence or absence
1182   // of the ellipsis; see C++ DR 357).
1183   if (OldQType != NewQType &&
1184       (OldType->getNumParams() != NewType->getNumParams() ||
1185        OldType->isVariadic() != NewType->isVariadic() ||
1186        !FunctionParamTypesAreEqual(OldType, NewType)))
1187     return true;
1188 
1189   // C++ [temp.over.link]p4:
1190   //   The signature of a function template consists of its function
1191   //   signature, its return type and its template parameter list. The names
1192   //   of the template parameters are significant only for establishing the
1193   //   relationship between the template parameters and the rest of the
1194   //   signature.
1195   //
1196   // We check the return type and template parameter lists for function
1197   // templates first; the remaining checks follow.
1198   //
1199   // However, we don't consider either of these when deciding whether
1200   // a member introduced by a shadow declaration is hidden.
1201   if (!UseMemberUsingDeclRules && NewTemplate &&
1202       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1203                                        OldTemplate->getTemplateParameters(),
1204                                        false, TPL_TemplateMatch) ||
1205        !Context.hasSameType(Old->getDeclaredReturnType(),
1206                             New->getDeclaredReturnType())))
1207     return true;
1208 
1209   // If the function is a class member, its signature includes the
1210   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1211   //
1212   // As part of this, also check whether one of the member functions
1213   // is static, in which case they are not overloads (C++
1214   // 13.1p2). While not part of the definition of the signature,
1215   // this check is important to determine whether these functions
1216   // can be overloaded.
1217   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1218   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1219   if (OldMethod && NewMethod &&
1220       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1221     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1222       if (!UseMemberUsingDeclRules &&
1223           (OldMethod->getRefQualifier() == RQ_None ||
1224            NewMethod->getRefQualifier() == RQ_None)) {
1225         // C++0x [over.load]p2:
1226         //   - Member function declarations with the same name and the same
1227         //     parameter-type-list as well as member function template
1228         //     declarations with the same name, the same parameter-type-list, and
1229         //     the same template parameter lists cannot be overloaded if any of
1230         //     them, but not all, have a ref-qualifier (8.3.5).
1231         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1232           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1233         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234       }
1235       return true;
1236     }
1237 
1238     // We may not have applied the implicit const for a constexpr member
1239     // function yet (because we haven't yet resolved whether this is a static
1240     // or non-static member function). Add it now, on the assumption that this
1241     // is a redeclaration of OldMethod.
1242     auto OldQuals = OldMethod->getMethodQualifiers();
1243     auto NewQuals = NewMethod->getMethodQualifiers();
1244     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1245         !isa<CXXConstructorDecl>(NewMethod))
1246       NewQuals.addConst();
1247     // We do not allow overloading based off of '__restrict'.
1248     OldQuals.removeRestrict();
1249     NewQuals.removeRestrict();
1250     if (OldQuals != NewQuals)
1251       return true;
1252   }
1253 
1254   // Though pass_object_size is placed on parameters and takes an argument, we
1255   // consider it to be a function-level modifier for the sake of function
1256   // identity. Either the function has one or more parameters with
1257   // pass_object_size or it doesn't.
1258   if (functionHasPassObjectSizeParams(New) !=
1259       functionHasPassObjectSizeParams(Old))
1260     return true;
1261 
1262   // enable_if attributes are an order-sensitive part of the signature.
1263   for (specific_attr_iterator<EnableIfAttr>
1264          NewI = New->specific_attr_begin<EnableIfAttr>(),
1265          NewE = New->specific_attr_end<EnableIfAttr>(),
1266          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1267          OldE = Old->specific_attr_end<EnableIfAttr>();
1268        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1269     if (NewI == NewE || OldI == OldE)
1270       return true;
1271     llvm::FoldingSetNodeID NewID, OldID;
1272     NewI->getCond()->Profile(NewID, Context, true);
1273     OldI->getCond()->Profile(OldID, Context, true);
1274     if (NewID != OldID)
1275       return true;
1276   }
1277 
1278   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1279     // Don't allow overloading of destructors.  (In theory we could, but it
1280     // would be a giant change to clang.)
1281     if (!isa<CXXDestructorDecl>(New)) {
1282       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1283                          OldTarget = IdentifyCUDATarget(Old);
1284       if (NewTarget != CFT_InvalidTarget) {
1285         assert((OldTarget != CFT_InvalidTarget) &&
1286                "Unexpected invalid target.");
1287 
1288         // Allow overloading of functions with same signature and different CUDA
1289         // target attributes.
1290         if (NewTarget != OldTarget)
1291           return true;
1292       }
1293     }
1294   }
1295 
1296   if (ConsiderRequiresClauses) {
1297     Expr *NewRC = New->getTrailingRequiresClause(),
1298          *OldRC = Old->getTrailingRequiresClause();
1299     if ((NewRC != nullptr) != (OldRC != nullptr))
1300       // RC are most certainly different - these are overloads.
1301       return true;
1302 
1303     if (NewRC) {
1304       llvm::FoldingSetNodeID NewID, OldID;
1305       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1306       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1307       if (NewID != OldID)
1308         // RCs are not equivalent - these are overloads.
1309         return true;
1310     }
1311   }
1312 
1313   // The signatures match; this is not an overload.
1314   return false;
1315 }
1316 
1317 /// Tries a user-defined conversion from From to ToType.
1318 ///
1319 /// Produces an implicit conversion sequence for when a standard conversion
1320 /// is not an option. See TryImplicitConversion for more information.
1321 static ImplicitConversionSequence
1322 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1323                          bool SuppressUserConversions,
1324                          AllowedExplicit AllowExplicit,
1325                          bool InOverloadResolution,
1326                          bool CStyle,
1327                          bool AllowObjCWritebackConversion,
1328                          bool AllowObjCConversionOnExplicit) {
1329   ImplicitConversionSequence ICS;
1330 
1331   if (SuppressUserConversions) {
1332     // We're not in the case above, so there is no conversion that
1333     // we can perform.
1334     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1335     return ICS;
1336   }
1337 
1338   // Attempt user-defined conversion.
1339   OverloadCandidateSet Conversions(From->getExprLoc(),
1340                                    OverloadCandidateSet::CSK_Normal);
1341   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1342                                   Conversions, AllowExplicit,
1343                                   AllowObjCConversionOnExplicit)) {
1344   case OR_Success:
1345   case OR_Deleted:
1346     ICS.setUserDefined();
1347     // C++ [over.ics.user]p4:
1348     //   A conversion of an expression of class type to the same class
1349     //   type is given Exact Match rank, and a conversion of an
1350     //   expression of class type to a base class of that type is
1351     //   given Conversion rank, in spite of the fact that a copy
1352     //   constructor (i.e., a user-defined conversion function) is
1353     //   called for those cases.
1354     if (CXXConstructorDecl *Constructor
1355           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1356       QualType FromCanon
1357         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1358       QualType ToCanon
1359         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1360       if (Constructor->isCopyConstructor() &&
1361           (FromCanon == ToCanon ||
1362            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1363         // Turn this into a "standard" conversion sequence, so that it
1364         // gets ranked with standard conversion sequences.
1365         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1366         ICS.setStandard();
1367         ICS.Standard.setAsIdentityConversion();
1368         ICS.Standard.setFromType(From->getType());
1369         ICS.Standard.setAllToTypes(ToType);
1370         ICS.Standard.CopyConstructor = Constructor;
1371         ICS.Standard.FoundCopyConstructor = Found;
1372         if (ToCanon != FromCanon)
1373           ICS.Standard.Second = ICK_Derived_To_Base;
1374       }
1375     }
1376     break;
1377 
1378   case OR_Ambiguous:
1379     ICS.setAmbiguous();
1380     ICS.Ambiguous.setFromType(From->getType());
1381     ICS.Ambiguous.setToType(ToType);
1382     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1383          Cand != Conversions.end(); ++Cand)
1384       if (Cand->Best)
1385         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1386     break;
1387 
1388     // Fall through.
1389   case OR_No_Viable_Function:
1390     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1391     break;
1392   }
1393 
1394   return ICS;
1395 }
1396 
1397 /// TryImplicitConversion - Attempt to perform an implicit conversion
1398 /// from the given expression (Expr) to the given type (ToType). This
1399 /// function returns an implicit conversion sequence that can be used
1400 /// to perform the initialization. Given
1401 ///
1402 ///   void f(float f);
1403 ///   void g(int i) { f(i); }
1404 ///
1405 /// this routine would produce an implicit conversion sequence to
1406 /// describe the initialization of f from i, which will be a standard
1407 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1408 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1409 //
1410 /// Note that this routine only determines how the conversion can be
1411 /// performed; it does not actually perform the conversion. As such,
1412 /// it will not produce any diagnostics if no conversion is available,
1413 /// but will instead return an implicit conversion sequence of kind
1414 /// "BadConversion".
1415 ///
1416 /// If @p SuppressUserConversions, then user-defined conversions are
1417 /// not permitted.
1418 /// If @p AllowExplicit, then explicit user-defined conversions are
1419 /// permitted.
1420 ///
1421 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1422 /// writeback conversion, which allows __autoreleasing id* parameters to
1423 /// be initialized with __strong id* or __weak id* arguments.
1424 static ImplicitConversionSequence
1425 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1426                       bool SuppressUserConversions,
1427                       AllowedExplicit AllowExplicit,
1428                       bool InOverloadResolution,
1429                       bool CStyle,
1430                       bool AllowObjCWritebackConversion,
1431                       bool AllowObjCConversionOnExplicit) {
1432   ImplicitConversionSequence ICS;
1433   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1434                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435     ICS.setStandard();
1436     return ICS;
1437   }
1438 
1439   if (!S.getLangOpts().CPlusPlus) {
1440     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1441     return ICS;
1442   }
1443 
1444   // C++ [over.ics.user]p4:
1445   //   A conversion of an expression of class type to the same class
1446   //   type is given Exact Match rank, and a conversion of an
1447   //   expression of class type to a base class of that type is
1448   //   given Conversion rank, in spite of the fact that a copy/move
1449   //   constructor (i.e., a user-defined conversion function) is
1450   //   called for those cases.
1451   QualType FromType = From->getType();
1452   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1453       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1454        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1455     ICS.setStandard();
1456     ICS.Standard.setAsIdentityConversion();
1457     ICS.Standard.setFromType(FromType);
1458     ICS.Standard.setAllToTypes(ToType);
1459 
1460     // We don't actually check at this point whether there is a valid
1461     // copy/move constructor, since overloading just assumes that it
1462     // exists. When we actually perform initialization, we'll find the
1463     // appropriate constructor to copy the returned object, if needed.
1464     ICS.Standard.CopyConstructor = nullptr;
1465 
1466     // Determine whether this is considered a derived-to-base conversion.
1467     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1468       ICS.Standard.Second = ICK_Derived_To_Base;
1469 
1470     return ICS;
1471   }
1472 
1473   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1474                                   AllowExplicit, InOverloadResolution, CStyle,
1475                                   AllowObjCWritebackConversion,
1476                                   AllowObjCConversionOnExplicit);
1477 }
1478 
1479 ImplicitConversionSequence
1480 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1481                             bool SuppressUserConversions,
1482                             AllowedExplicit AllowExplicit,
1483                             bool InOverloadResolution,
1484                             bool CStyle,
1485                             bool AllowObjCWritebackConversion) {
1486   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1487                                  AllowExplicit, InOverloadResolution, CStyle,
1488                                  AllowObjCWritebackConversion,
1489                                  /*AllowObjCConversionOnExplicit=*/false);
1490 }
1491 
1492 /// PerformImplicitConversion - Perform an implicit conversion of the
1493 /// expression From to the type ToType. Returns the
1494 /// converted expression. Flavor is the kind of conversion we're
1495 /// performing, used in the error message. If @p AllowExplicit,
1496 /// explicit user-defined conversions are permitted.
1497 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1498                                            AssignmentAction Action,
1499                                            bool AllowExplicit) {
1500   if (checkPlaceholderForOverload(*this, From))
1501     return ExprError();
1502 
1503   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1504   bool AllowObjCWritebackConversion
1505     = getLangOpts().ObjCAutoRefCount &&
1506       (Action == AA_Passing || Action == AA_Sending);
1507   if (getLangOpts().ObjC)
1508     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1509                                       From->getType(), From);
1510   ImplicitConversionSequence ICS = ::TryImplicitConversion(
1511       *this, From, ToType,
1512       /*SuppressUserConversions=*/false,
1513       AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1514       /*InOverloadResolution=*/false,
1515       /*CStyle=*/false, AllowObjCWritebackConversion,
1516       /*AllowObjCConversionOnExplicit=*/false);
1517   return PerformImplicitConversion(From, ToType, ICS, Action);
1518 }
1519 
1520 /// Determine whether the conversion from FromType to ToType is a valid
1521 /// conversion that strips "noexcept" or "noreturn" off the nested function
1522 /// type.
1523 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1524                                 QualType &ResultTy) {
1525   if (Context.hasSameUnqualifiedType(FromType, ToType))
1526     return false;
1527 
1528   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1529   //                    or F(t noexcept) -> F(t)
1530   // where F adds one of the following at most once:
1531   //   - a pointer
1532   //   - a member pointer
1533   //   - a block pointer
1534   // Changes here need matching changes in FindCompositePointerType.
1535   CanQualType CanTo = Context.getCanonicalType(ToType);
1536   CanQualType CanFrom = Context.getCanonicalType(FromType);
1537   Type::TypeClass TyClass = CanTo->getTypeClass();
1538   if (TyClass != CanFrom->getTypeClass()) return false;
1539   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1540     if (TyClass == Type::Pointer) {
1541       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1542       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1543     } else if (TyClass == Type::BlockPointer) {
1544       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1545       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1546     } else if (TyClass == Type::MemberPointer) {
1547       auto ToMPT = CanTo.castAs<MemberPointerType>();
1548       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1549       // A function pointer conversion cannot change the class of the function.
1550       if (ToMPT->getClass() != FromMPT->getClass())
1551         return false;
1552       CanTo = ToMPT->getPointeeType();
1553       CanFrom = FromMPT->getPointeeType();
1554     } else {
1555       return false;
1556     }
1557 
1558     TyClass = CanTo->getTypeClass();
1559     if (TyClass != CanFrom->getTypeClass()) return false;
1560     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1561       return false;
1562   }
1563 
1564   const auto *FromFn = cast<FunctionType>(CanFrom);
1565   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1566 
1567   const auto *ToFn = cast<FunctionType>(CanTo);
1568   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1569 
1570   bool Changed = false;
1571 
1572   // Drop 'noreturn' if not present in target type.
1573   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1574     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1575     Changed = true;
1576   }
1577 
1578   // Drop 'noexcept' if not present in target type.
1579   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1580     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1581     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1582       FromFn = cast<FunctionType>(
1583           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1584                                                    EST_None)
1585                  .getTypePtr());
1586       Changed = true;
1587     }
1588 
1589     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1590     // only if the ExtParameterInfo lists of the two function prototypes can be
1591     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1592     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1593     bool CanUseToFPT, CanUseFromFPT;
1594     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1595                                       CanUseFromFPT, NewParamInfos) &&
1596         CanUseToFPT && !CanUseFromFPT) {
1597       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1598       ExtInfo.ExtParameterInfos =
1599           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1600       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1601                                             FromFPT->getParamTypes(), ExtInfo);
1602       FromFn = QT->getAs<FunctionType>();
1603       Changed = true;
1604     }
1605   }
1606 
1607   if (!Changed)
1608     return false;
1609 
1610   assert(QualType(FromFn, 0).isCanonical());
1611   if (QualType(FromFn, 0) != CanTo) return false;
1612 
1613   ResultTy = ToType;
1614   return true;
1615 }
1616 
1617 /// Determine whether the conversion from FromType to ToType is a valid
1618 /// vector conversion.
1619 ///
1620 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1621 /// conversion.
1622 static bool IsVectorConversion(Sema &S, QualType FromType,
1623                                QualType ToType, ImplicitConversionKind &ICK) {
1624   // We need at least one of these types to be a vector type to have a vector
1625   // conversion.
1626   if (!ToType->isVectorType() && !FromType->isVectorType())
1627     return false;
1628 
1629   // Identical types require no conversions.
1630   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1631     return false;
1632 
1633   // There are no conversions between extended vector types, only identity.
1634   if (ToType->isExtVectorType()) {
1635     // There are no conversions between extended vector types other than the
1636     // identity conversion.
1637     if (FromType->isExtVectorType())
1638       return false;
1639 
1640     // Vector splat from any arithmetic type to a vector.
1641     if (FromType->isArithmeticType()) {
1642       ICK = ICK_Vector_Splat;
1643       return true;
1644     }
1645   }
1646 
1647   if ((ToType->isSizelessBuiltinType() || FromType->isSizelessBuiltinType()) &&
1648       S.Context.areCompatibleSveTypes(FromType, ToType)) {
1649     ICK = ICK_SVE_Vector_Conversion;
1650     return true;
1651   }
1652 
1653   // We can perform the conversion between vector types in the following cases:
1654   // 1)vector types are equivalent AltiVec and GCC vector types
1655   // 2)lax vector conversions are permitted and the vector types are of the
1656   //   same size
1657   // 3)the destination type does not have the ARM MVE strict-polymorphism
1658   //   attribute, which inhibits lax vector conversion for overload resolution
1659   //   only
1660   if (ToType->isVectorType() && FromType->isVectorType()) {
1661     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1662         (S.isLaxVectorConversion(FromType, ToType) &&
1663          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1664       ICK = ICK_Vector_Conversion;
1665       return true;
1666     }
1667   }
1668 
1669   return false;
1670 }
1671 
1672 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1673                                 bool InOverloadResolution,
1674                                 StandardConversionSequence &SCS,
1675                                 bool CStyle);
1676 
1677 /// IsStandardConversion - Determines whether there is a standard
1678 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1679 /// expression From to the type ToType. Standard conversion sequences
1680 /// only consider non-class types; for conversions that involve class
1681 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1682 /// contain the standard conversion sequence required to perform this
1683 /// conversion and this routine will return true. Otherwise, this
1684 /// routine will return false and the value of SCS is unspecified.
1685 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1686                                  bool InOverloadResolution,
1687                                  StandardConversionSequence &SCS,
1688                                  bool CStyle,
1689                                  bool AllowObjCWritebackConversion) {
1690   QualType FromType = From->getType();
1691 
1692   // Standard conversions (C++ [conv])
1693   SCS.setAsIdentityConversion();
1694   SCS.IncompatibleObjC = false;
1695   SCS.setFromType(FromType);
1696   SCS.CopyConstructor = nullptr;
1697 
1698   // There are no standard conversions for class types in C++, so
1699   // abort early. When overloading in C, however, we do permit them.
1700   if (S.getLangOpts().CPlusPlus &&
1701       (FromType->isRecordType() || ToType->isRecordType()))
1702     return false;
1703 
1704   // The first conversion can be an lvalue-to-rvalue conversion,
1705   // array-to-pointer conversion, or function-to-pointer conversion
1706   // (C++ 4p1).
1707 
1708   if (FromType == S.Context.OverloadTy) {
1709     DeclAccessPair AccessPair;
1710     if (FunctionDecl *Fn
1711           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1712                                                  AccessPair)) {
1713       // We were able to resolve the address of the overloaded function,
1714       // so we can convert to the type of that function.
1715       FromType = Fn->getType();
1716       SCS.setFromType(FromType);
1717 
1718       // we can sometimes resolve &foo<int> regardless of ToType, so check
1719       // if the type matches (identity) or we are converting to bool
1720       if (!S.Context.hasSameUnqualifiedType(
1721                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1722         QualType resultTy;
1723         // if the function type matches except for [[noreturn]], it's ok
1724         if (!S.IsFunctionConversion(FromType,
1725               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1726           // otherwise, only a boolean conversion is standard
1727           if (!ToType->isBooleanType())
1728             return false;
1729       }
1730 
1731       // Check if the "from" expression is taking the address of an overloaded
1732       // function and recompute the FromType accordingly. Take advantage of the
1733       // fact that non-static member functions *must* have such an address-of
1734       // expression.
1735       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1736       if (Method && !Method->isStatic()) {
1737         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1738                "Non-unary operator on non-static member address");
1739         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1740                == UO_AddrOf &&
1741                "Non-address-of operator on non-static member address");
1742         const Type *ClassType
1743           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1744         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1745       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1746         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1747                UO_AddrOf &&
1748                "Non-address-of operator for overloaded function expression");
1749         FromType = S.Context.getPointerType(FromType);
1750       }
1751 
1752       // Check that we've computed the proper type after overload resolution.
1753       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1754       // be calling it from within an NDEBUG block.
1755       assert(S.Context.hasSameType(
1756         FromType,
1757         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1758     } else {
1759       return false;
1760     }
1761   }
1762   // Lvalue-to-rvalue conversion (C++11 4.1):
1763   //   A glvalue (3.10) of a non-function, non-array type T can
1764   //   be converted to a prvalue.
1765   bool argIsLValue = From->isGLValue();
1766   if (argIsLValue &&
1767       !FromType->isFunctionType() && !FromType->isArrayType() &&
1768       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1769     SCS.First = ICK_Lvalue_To_Rvalue;
1770 
1771     // C11 6.3.2.1p2:
1772     //   ... if the lvalue has atomic type, the value has the non-atomic version
1773     //   of the type of the lvalue ...
1774     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1775       FromType = Atomic->getValueType();
1776 
1777     // If T is a non-class type, the type of the rvalue is the
1778     // cv-unqualified version of T. Otherwise, the type of the rvalue
1779     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1780     // just strip the qualifiers because they don't matter.
1781     FromType = FromType.getUnqualifiedType();
1782   } else if (FromType->isArrayType()) {
1783     // Array-to-pointer conversion (C++ 4.2)
1784     SCS.First = ICK_Array_To_Pointer;
1785 
1786     // An lvalue or rvalue of type "array of N T" or "array of unknown
1787     // bound of T" can be converted to an rvalue of type "pointer to
1788     // T" (C++ 4.2p1).
1789     FromType = S.Context.getArrayDecayedType(FromType);
1790 
1791     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1792       // This conversion is deprecated in C++03 (D.4)
1793       SCS.DeprecatedStringLiteralToCharPtr = true;
1794 
1795       // For the purpose of ranking in overload resolution
1796       // (13.3.3.1.1), this conversion is considered an
1797       // array-to-pointer conversion followed by a qualification
1798       // conversion (4.4). (C++ 4.2p2)
1799       SCS.Second = ICK_Identity;
1800       SCS.Third = ICK_Qualification;
1801       SCS.QualificationIncludesObjCLifetime = false;
1802       SCS.setAllToTypes(FromType);
1803       return true;
1804     }
1805   } else if (FromType->isFunctionType() && argIsLValue) {
1806     // Function-to-pointer conversion (C++ 4.3).
1807     SCS.First = ICK_Function_To_Pointer;
1808 
1809     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1810       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1811         if (!S.checkAddressOfFunctionIsAvailable(FD))
1812           return false;
1813 
1814     // An lvalue of function type T can be converted to an rvalue of
1815     // type "pointer to T." The result is a pointer to the
1816     // function. (C++ 4.3p1).
1817     FromType = S.Context.getPointerType(FromType);
1818   } else {
1819     // We don't require any conversions for the first step.
1820     SCS.First = ICK_Identity;
1821   }
1822   SCS.setToType(0, FromType);
1823 
1824   // The second conversion can be an integral promotion, floating
1825   // point promotion, integral conversion, floating point conversion,
1826   // floating-integral conversion, pointer conversion,
1827   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1828   // For overloading in C, this can also be a "compatible-type"
1829   // conversion.
1830   bool IncompatibleObjC = false;
1831   ImplicitConversionKind SecondICK = ICK_Identity;
1832   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1833     // The unqualified versions of the types are the same: there's no
1834     // conversion to do.
1835     SCS.Second = ICK_Identity;
1836   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1837     // Integral promotion (C++ 4.5).
1838     SCS.Second = ICK_Integral_Promotion;
1839     FromType = ToType.getUnqualifiedType();
1840   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1841     // Floating point promotion (C++ 4.6).
1842     SCS.Second = ICK_Floating_Promotion;
1843     FromType = ToType.getUnqualifiedType();
1844   } else if (S.IsComplexPromotion(FromType, ToType)) {
1845     // Complex promotion (Clang extension)
1846     SCS.Second = ICK_Complex_Promotion;
1847     FromType = ToType.getUnqualifiedType();
1848   } else if (ToType->isBooleanType() &&
1849              (FromType->isArithmeticType() ||
1850               FromType->isAnyPointerType() ||
1851               FromType->isBlockPointerType() ||
1852               FromType->isMemberPointerType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double 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 
1875     // Conversions between bfloat and other floats are not permitted.
1876     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1877       return false;
1878     if (&S.Context.getFloatTypeSemantics(FromType) !=
1879         &S.Context.getFloatTypeSemantics(ToType)) {
1880       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1881                                     ToType == S.Context.LongDoubleTy) ||
1882                                    (FromType == S.Context.LongDoubleTy &&
1883                                     ToType == S.Context.Float128Ty));
1884       if (Float128AndLongDouble &&
1885           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1886            &llvm::APFloat::PPCDoubleDouble()))
1887         return false;
1888     }
1889     // Floating point conversions (C++ 4.8).
1890     SCS.Second = ICK_Floating_Conversion;
1891     FromType = ToType.getUnqualifiedType();
1892   } else if ((FromType->isRealFloatingType() &&
1893               ToType->isIntegralType(S.Context)) ||
1894              (FromType->isIntegralOrUnscopedEnumerationType() &&
1895               ToType->isRealFloatingType())) {
1896     // Conversions between bfloat and int are not permitted.
1897     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1898       return false;
1899 
1900     // Floating-integral conversions (C++ 4.9).
1901     SCS.Second = ICK_Floating_Integral;
1902     FromType = ToType.getUnqualifiedType();
1903   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1904     SCS.Second = ICK_Block_Pointer_Conversion;
1905   } else if (AllowObjCWritebackConversion &&
1906              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1907     SCS.Second = ICK_Writeback_Conversion;
1908   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1909                                    FromType, IncompatibleObjC)) {
1910     // Pointer conversions (C++ 4.10).
1911     SCS.Second = ICK_Pointer_Conversion;
1912     SCS.IncompatibleObjC = IncompatibleObjC;
1913     FromType = FromType.getUnqualifiedType();
1914   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1915                                          InOverloadResolution, FromType)) {
1916     // Pointer to member conversions (4.11).
1917     SCS.Second = ICK_Pointer_Member;
1918   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1919     SCS.Second = SecondICK;
1920     FromType = ToType.getUnqualifiedType();
1921   } else if (!S.getLangOpts().CPlusPlus &&
1922              S.Context.typesAreCompatible(ToType, FromType)) {
1923     // Compatible conversions (Clang extension for C function overloading)
1924     SCS.Second = ICK_Compatible_Conversion;
1925     FromType = ToType.getUnqualifiedType();
1926   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1927                                              InOverloadResolution,
1928                                              SCS, CStyle)) {
1929     SCS.Second = ICK_TransparentUnionConversion;
1930     FromType = ToType;
1931   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1932                                  CStyle)) {
1933     // tryAtomicConversion has updated the standard conversion sequence
1934     // appropriately.
1935     return true;
1936   } else if (ToType->isEventT() &&
1937              From->isIntegerConstantExpr(S.getASTContext()) &&
1938              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1939     SCS.Second = ICK_Zero_Event_Conversion;
1940     FromType = ToType;
1941   } else if (ToType->isQueueT() &&
1942              From->isIntegerConstantExpr(S.getASTContext()) &&
1943              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1944     SCS.Second = ICK_Zero_Queue_Conversion;
1945     FromType = ToType;
1946   } else if (ToType->isSamplerT() &&
1947              From->isIntegerConstantExpr(S.getASTContext())) {
1948     SCS.Second = ICK_Compatible_Conversion;
1949     FromType = ToType;
1950   } else {
1951     // No second conversion required.
1952     SCS.Second = ICK_Identity;
1953   }
1954   SCS.setToType(1, FromType);
1955 
1956   // The third conversion can be a function pointer conversion or a
1957   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1958   bool ObjCLifetimeConversion;
1959   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1960     // Function pointer conversions (removing 'noexcept') including removal of
1961     // 'noreturn' (Clang extension).
1962     SCS.Third = ICK_Function_Conversion;
1963   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1964                                          ObjCLifetimeConversion)) {
1965     SCS.Third = ICK_Qualification;
1966     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1967     FromType = ToType;
1968   } else {
1969     // No conversion required
1970     SCS.Third = ICK_Identity;
1971   }
1972 
1973   // C++ [over.best.ics]p6:
1974   //   [...] Any difference in top-level cv-qualification is
1975   //   subsumed by the initialization itself and does not constitute
1976   //   a conversion. [...]
1977   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1978   QualType CanonTo = S.Context.getCanonicalType(ToType);
1979   if (CanonFrom.getLocalUnqualifiedType()
1980                                      == CanonTo.getLocalUnqualifiedType() &&
1981       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1982     FromType = ToType;
1983     CanonFrom = CanonTo;
1984   }
1985 
1986   SCS.setToType(2, FromType);
1987 
1988   if (CanonFrom == CanonTo)
1989     return true;
1990 
1991   // If we have not converted the argument type to the parameter type,
1992   // this is a bad conversion sequence, unless we're resolving an overload in C.
1993   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1994     return false;
1995 
1996   ExprResult ER = ExprResult{From};
1997   Sema::AssignConvertType Conv =
1998       S.CheckSingleAssignmentConstraints(ToType, ER,
1999                                          /*Diagnose=*/false,
2000                                          /*DiagnoseCFAudited=*/false,
2001                                          /*ConvertRHS=*/false);
2002   ImplicitConversionKind SecondConv;
2003   switch (Conv) {
2004   case Sema::Compatible:
2005     SecondConv = ICK_C_Only_Conversion;
2006     break;
2007   // For our purposes, discarding qualifiers is just as bad as using an
2008   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2009   // qualifiers, as well.
2010   case Sema::CompatiblePointerDiscardsQualifiers:
2011   case Sema::IncompatiblePointer:
2012   case Sema::IncompatiblePointerSign:
2013     SecondConv = ICK_Incompatible_Pointer_Conversion;
2014     break;
2015   default:
2016     return false;
2017   }
2018 
2019   // First can only be an lvalue conversion, so we pretend that this was the
2020   // second conversion. First should already be valid from earlier in the
2021   // function.
2022   SCS.Second = SecondConv;
2023   SCS.setToType(1, ToType);
2024 
2025   // Third is Identity, because Second should rank us worse than any other
2026   // conversion. This could also be ICK_Qualification, but it's simpler to just
2027   // lump everything in with the second conversion, and we don't gain anything
2028   // from making this ICK_Qualification.
2029   SCS.Third = ICK_Identity;
2030   SCS.setToType(2, ToType);
2031   return true;
2032 }
2033 
2034 static bool
2035 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2036                                      QualType &ToType,
2037                                      bool InOverloadResolution,
2038                                      StandardConversionSequence &SCS,
2039                                      bool CStyle) {
2040 
2041   const RecordType *UT = ToType->getAsUnionType();
2042   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2043     return false;
2044   // The field to initialize within the transparent union.
2045   RecordDecl *UD = UT->getDecl();
2046   // It's compatible if the expression matches any of the fields.
2047   for (const auto *it : UD->fields()) {
2048     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2049                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2050       ToType = it->getType();
2051       return true;
2052     }
2053   }
2054   return false;
2055 }
2056 
2057 /// IsIntegralPromotion - Determines whether the conversion from the
2058 /// expression From (whose potentially-adjusted type is FromType) to
2059 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2060 /// sets PromotedType to the promoted type.
2061 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2062   const BuiltinType *To = ToType->getAs<BuiltinType>();
2063   // All integers are built-in.
2064   if (!To) {
2065     return false;
2066   }
2067 
2068   // An rvalue of type char, signed char, unsigned char, short int, or
2069   // unsigned short int can be converted to an rvalue of type int if
2070   // int can represent all the values of the source type; otherwise,
2071   // the source rvalue can be converted to an rvalue of type unsigned
2072   // int (C++ 4.5p1).
2073   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2074       !FromType->isEnumeralType()) {
2075     if (// We can promote any signed, promotable integer type to an int
2076         (FromType->isSignedIntegerType() ||
2077          // We can promote any unsigned integer type whose size is
2078          // less than int to an int.
2079          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2080       return To->getKind() == BuiltinType::Int;
2081     }
2082 
2083     return To->getKind() == BuiltinType::UInt;
2084   }
2085 
2086   // C++11 [conv.prom]p3:
2087   //   A prvalue of an unscoped enumeration type whose underlying type is not
2088   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2089   //   following types that can represent all the values of the enumeration
2090   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2091   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2092   //   long long int. If none of the types in that list can represent all the
2093   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2094   //   type can be converted to an rvalue a prvalue of the extended integer type
2095   //   with lowest integer conversion rank (4.13) greater than the rank of long
2096   //   long in which all the values of the enumeration can be represented. If
2097   //   there are two such extended types, the signed one is chosen.
2098   // C++11 [conv.prom]p4:
2099   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2100   //   can be converted to a prvalue of its underlying type. Moreover, if
2101   //   integral promotion can be applied to its underlying type, a prvalue of an
2102   //   unscoped enumeration type whose underlying type is fixed can also be
2103   //   converted to a prvalue of the promoted underlying type.
2104   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2105     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2106     // provided for a scoped enumeration.
2107     if (FromEnumType->getDecl()->isScoped())
2108       return false;
2109 
2110     // We can perform an integral promotion to the underlying type of the enum,
2111     // even if that's not the promoted type. Note that the check for promoting
2112     // the underlying type is based on the type alone, and does not consider
2113     // the bitfield-ness of the actual source expression.
2114     if (FromEnumType->getDecl()->isFixed()) {
2115       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2116       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2117              IsIntegralPromotion(nullptr, Underlying, ToType);
2118     }
2119 
2120     // We have already pre-calculated the promotion type, so this is trivial.
2121     if (ToType->isIntegerType() &&
2122         isCompleteType(From->getBeginLoc(), FromType))
2123       return Context.hasSameUnqualifiedType(
2124           ToType, FromEnumType->getDecl()->getPromotionType());
2125 
2126     // C++ [conv.prom]p5:
2127     //   If the bit-field has an enumerated type, it is treated as any other
2128     //   value of that type for promotion purposes.
2129     //
2130     // ... so do not fall through into the bit-field checks below in C++.
2131     if (getLangOpts().CPlusPlus)
2132       return false;
2133   }
2134 
2135   // C++0x [conv.prom]p2:
2136   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2137   //   to an rvalue a prvalue of the first of the following types that can
2138   //   represent all the values of its underlying type: int, unsigned int,
2139   //   long int, unsigned long int, long long int, or unsigned long long int.
2140   //   If none of the types in that list can represent all the values of its
2141   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2142   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2143   //   type.
2144   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2145       ToType->isIntegerType()) {
2146     // Determine whether the type we're converting from is signed or
2147     // unsigned.
2148     bool FromIsSigned = FromType->isSignedIntegerType();
2149     uint64_t FromSize = Context.getTypeSize(FromType);
2150 
2151     // The types we'll try to promote to, in the appropriate
2152     // order. Try each of these types.
2153     QualType PromoteTypes[6] = {
2154       Context.IntTy, Context.UnsignedIntTy,
2155       Context.LongTy, Context.UnsignedLongTy ,
2156       Context.LongLongTy, Context.UnsignedLongLongTy
2157     };
2158     for (int Idx = 0; Idx < 6; ++Idx) {
2159       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2160       if (FromSize < ToSize ||
2161           (FromSize == ToSize &&
2162            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2163         // We found the type that we can promote to. If this is the
2164         // type we wanted, we have a promotion. Otherwise, no
2165         // promotion.
2166         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2167       }
2168     }
2169   }
2170 
2171   // An rvalue for an integral bit-field (9.6) can be converted to an
2172   // rvalue of type int if int can represent all the values of the
2173   // bit-field; otherwise, it can be converted to unsigned int if
2174   // unsigned int can represent all the values of the bit-field. If
2175   // the bit-field is larger yet, no integral promotion applies to
2176   // it. If the bit-field has an enumerated type, it is treated as any
2177   // other value of that type for promotion purposes (C++ 4.5p3).
2178   // FIXME: We should delay checking of bit-fields until we actually perform the
2179   // conversion.
2180   //
2181   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2182   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2183   // bit-fields and those whose underlying type is larger than int) for GCC
2184   // compatibility.
2185   if (From) {
2186     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2187       Optional<llvm::APSInt> BitWidth;
2188       if (FromType->isIntegralType(Context) &&
2189           (BitWidth =
2190                MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2191         llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2192         ToSize = Context.getTypeSize(ToType);
2193 
2194         // Are we promoting to an int from a bitfield that fits in an int?
2195         if (*BitWidth < ToSize ||
2196             (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2197           return To->getKind() == BuiltinType::Int;
2198         }
2199 
2200         // Are we promoting to an unsigned int from an unsigned bitfield
2201         // that fits into an unsigned int?
2202         if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2203           return To->getKind() == BuiltinType::UInt;
2204         }
2205 
2206         return false;
2207       }
2208     }
2209   }
2210 
2211   // An rvalue of type bool can be converted to an rvalue of type int,
2212   // with false becoming zero and true becoming one (C++ 4.5p4).
2213   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2214     return true;
2215   }
2216 
2217   return false;
2218 }
2219 
2220 /// IsFloatingPointPromotion - Determines whether the conversion from
2221 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2222 /// returns true and sets PromotedType to the promoted type.
2223 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2224   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2225     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2226       /// An rvalue of type float can be converted to an rvalue of type
2227       /// double. (C++ 4.6p1).
2228       if (FromBuiltin->getKind() == BuiltinType::Float &&
2229           ToBuiltin->getKind() == BuiltinType::Double)
2230         return true;
2231 
2232       // C99 6.3.1.5p1:
2233       //   When a float is promoted to double or long double, or a
2234       //   double is promoted to long double [...].
2235       if (!getLangOpts().CPlusPlus &&
2236           (FromBuiltin->getKind() == BuiltinType::Float ||
2237            FromBuiltin->getKind() == BuiltinType::Double) &&
2238           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2239            ToBuiltin->getKind() == BuiltinType::Float128))
2240         return true;
2241 
2242       // Half can be promoted to float.
2243       if (!getLangOpts().NativeHalfType &&
2244            FromBuiltin->getKind() == BuiltinType::Half &&
2245           ToBuiltin->getKind() == BuiltinType::Float)
2246         return true;
2247     }
2248 
2249   return false;
2250 }
2251 
2252 /// Determine if a conversion is a complex promotion.
2253 ///
2254 /// A complex promotion is defined as a complex -> complex conversion
2255 /// where the conversion between the underlying real types is a
2256 /// floating-point or integral promotion.
2257 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2258   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2259   if (!FromComplex)
2260     return false;
2261 
2262   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2263   if (!ToComplex)
2264     return false;
2265 
2266   return IsFloatingPointPromotion(FromComplex->getElementType(),
2267                                   ToComplex->getElementType()) ||
2268     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2269                         ToComplex->getElementType());
2270 }
2271 
2272 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2273 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2274 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2275 /// if non-empty, will be a pointer to ToType that may or may not have
2276 /// the right set of qualifiers on its pointee.
2277 ///
2278 static QualType
2279 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2280                                    QualType ToPointee, QualType ToType,
2281                                    ASTContext &Context,
2282                                    bool StripObjCLifetime = false) {
2283   assert((FromPtr->getTypeClass() == Type::Pointer ||
2284           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2285          "Invalid similarly-qualified pointer type");
2286 
2287   /// Conversions to 'id' subsume cv-qualifier conversions.
2288   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2289     return ToType.getUnqualifiedType();
2290 
2291   QualType CanonFromPointee
2292     = Context.getCanonicalType(FromPtr->getPointeeType());
2293   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2294   Qualifiers Quals = CanonFromPointee.getQualifiers();
2295 
2296   if (StripObjCLifetime)
2297     Quals.removeObjCLifetime();
2298 
2299   // Exact qualifier match -> return the pointer type we're converting to.
2300   if (CanonToPointee.getLocalQualifiers() == Quals) {
2301     // ToType is exactly what we need. Return it.
2302     if (!ToType.isNull())
2303       return ToType.getUnqualifiedType();
2304 
2305     // Build a pointer to ToPointee. It has the right qualifiers
2306     // already.
2307     if (isa<ObjCObjectPointerType>(ToType))
2308       return Context.getObjCObjectPointerType(ToPointee);
2309     return Context.getPointerType(ToPointee);
2310   }
2311 
2312   // Just build a canonical type that has the right qualifiers.
2313   QualType QualifiedCanonToPointee
2314     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2315 
2316   if (isa<ObjCObjectPointerType>(ToType))
2317     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2318   return Context.getPointerType(QualifiedCanonToPointee);
2319 }
2320 
2321 static bool isNullPointerConstantForConversion(Expr *Expr,
2322                                                bool InOverloadResolution,
2323                                                ASTContext &Context) {
2324   // Handle value-dependent integral null pointer constants correctly.
2325   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2326   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2327       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2328     return !InOverloadResolution;
2329 
2330   return Expr->isNullPointerConstant(Context,
2331                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2332                                         : Expr::NPC_ValueDependentIsNull);
2333 }
2334 
2335 /// IsPointerConversion - Determines whether the conversion of the
2336 /// expression From, which has the (possibly adjusted) type FromType,
2337 /// can be converted to the type ToType via a pointer conversion (C++
2338 /// 4.10). If so, returns true and places the converted type (that
2339 /// might differ from ToType in its cv-qualifiers at some level) into
2340 /// ConvertedType.
2341 ///
2342 /// This routine also supports conversions to and from block pointers
2343 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2344 /// pointers to interfaces. FIXME: Once we've determined the
2345 /// appropriate overloading rules for Objective-C, we may want to
2346 /// split the Objective-C checks into a different routine; however,
2347 /// GCC seems to consider all of these conversions to be pointer
2348 /// conversions, so for now they live here. IncompatibleObjC will be
2349 /// set if the conversion is an allowed Objective-C conversion that
2350 /// should result in a warning.
2351 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2352                                bool InOverloadResolution,
2353                                QualType& ConvertedType,
2354                                bool &IncompatibleObjC) {
2355   IncompatibleObjC = false;
2356   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2357                               IncompatibleObjC))
2358     return true;
2359 
2360   // Conversion from a null pointer constant to any Objective-C pointer type.
2361   if (ToType->isObjCObjectPointerType() &&
2362       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2363     ConvertedType = ToType;
2364     return true;
2365   }
2366 
2367   // Blocks: Block pointers can be converted to void*.
2368   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2369       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2370     ConvertedType = ToType;
2371     return true;
2372   }
2373   // Blocks: A null pointer constant can be converted to a block
2374   // pointer type.
2375   if (ToType->isBlockPointerType() &&
2376       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2377     ConvertedType = ToType;
2378     return true;
2379   }
2380 
2381   // If the left-hand-side is nullptr_t, the right side can be a null
2382   // pointer constant.
2383   if (ToType->isNullPtrType() &&
2384       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385     ConvertedType = ToType;
2386     return true;
2387   }
2388 
2389   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2390   if (!ToTypePtr)
2391     return false;
2392 
2393   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2394   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2395     ConvertedType = ToType;
2396     return true;
2397   }
2398 
2399   // Beyond this point, both types need to be pointers
2400   // , including objective-c pointers.
2401   QualType ToPointeeType = ToTypePtr->getPointeeType();
2402   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2403       !getLangOpts().ObjCAutoRefCount) {
2404     ConvertedType = BuildSimilarlyQualifiedPointerType(
2405                                       FromType->getAs<ObjCObjectPointerType>(),
2406                                                        ToPointeeType,
2407                                                        ToType, Context);
2408     return true;
2409   }
2410   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2411   if (!FromTypePtr)
2412     return false;
2413 
2414   QualType FromPointeeType = FromTypePtr->getPointeeType();
2415 
2416   // If the unqualified pointee types are the same, this can't be a
2417   // pointer conversion, so don't do all of the work below.
2418   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2419     return false;
2420 
2421   // An rvalue of type "pointer to cv T," where T is an object type,
2422   // can be converted to an rvalue of type "pointer to cv void" (C++
2423   // 4.10p2).
2424   if (FromPointeeType->isIncompleteOrObjectType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context,
2429                                                    /*StripObjCLifetime=*/true);
2430     return true;
2431   }
2432 
2433   // MSVC allows implicit function to void* type conversion.
2434   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2435       ToPointeeType->isVoidType()) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // When we're overloading in C, we allow a special kind of pointer
2443   // conversion for compatible-but-not-identical pointee types.
2444   if (!getLangOpts().CPlusPlus &&
2445       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2446     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2447                                                        ToPointeeType,
2448                                                        ToType, Context);
2449     return true;
2450   }
2451 
2452   // C++ [conv.ptr]p3:
2453   //
2454   //   An rvalue of type "pointer to cv D," where D is a class type,
2455   //   can be converted to an rvalue of type "pointer to cv B," where
2456   //   B is a base class (clause 10) of D. If B is an inaccessible
2457   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2458   //   necessitates this conversion is ill-formed. The result of the
2459   //   conversion is a pointer to the base class sub-object of the
2460   //   derived class object. The null pointer value is converted to
2461   //   the null pointer value of the destination type.
2462   //
2463   // Note that we do not check for ambiguity or inaccessibility
2464   // here. That is handled by CheckPointerConversion.
2465   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2466       ToPointeeType->isRecordType() &&
2467       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2468       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2469     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2470                                                        ToPointeeType,
2471                                                        ToType, Context);
2472     return true;
2473   }
2474 
2475   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2476       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2477     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2478                                                        ToPointeeType,
2479                                                        ToType, Context);
2480     return true;
2481   }
2482 
2483   return false;
2484 }
2485 
2486 /// Adopt the given qualifiers for the given type.
2487 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2488   Qualifiers TQs = T.getQualifiers();
2489 
2490   // Check whether qualifiers already match.
2491   if (TQs == Qs)
2492     return T;
2493 
2494   if (Qs.compatiblyIncludes(TQs))
2495     return Context.getQualifiedType(T, Qs);
2496 
2497   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2498 }
2499 
2500 /// isObjCPointerConversion - Determines whether this is an
2501 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2502 /// with the same arguments and return values.
2503 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2504                                    QualType& ConvertedType,
2505                                    bool &IncompatibleObjC) {
2506   if (!getLangOpts().ObjC)
2507     return false;
2508 
2509   // The set of qualifiers on the type we're converting from.
2510   Qualifiers FromQualifiers = FromType.getQualifiers();
2511 
2512   // First, we handle all conversions on ObjC object pointer types.
2513   const ObjCObjectPointerType* ToObjCPtr =
2514     ToType->getAs<ObjCObjectPointerType>();
2515   const ObjCObjectPointerType *FromObjCPtr =
2516     FromType->getAs<ObjCObjectPointerType>();
2517 
2518   if (ToObjCPtr && FromObjCPtr) {
2519     // If the pointee types are the same (ignoring qualifications),
2520     // then this is not a pointer conversion.
2521     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2522                                        FromObjCPtr->getPointeeType()))
2523       return false;
2524 
2525     // Conversion between Objective-C pointers.
2526     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2527       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2528       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2529       if (getLangOpts().CPlusPlus && LHS && RHS &&
2530           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2531                                                 FromObjCPtr->getPointeeType()))
2532         return false;
2533       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2534                                                    ToObjCPtr->getPointeeType(),
2535                                                          ToType, Context);
2536       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2537       return true;
2538     }
2539 
2540     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2541       // Okay: this is some kind of implicit downcast of Objective-C
2542       // interfaces, which is permitted. However, we're going to
2543       // complain about it.
2544       IncompatibleObjC = true;
2545       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2546                                                    ToObjCPtr->getPointeeType(),
2547                                                          ToType, Context);
2548       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2549       return true;
2550     }
2551   }
2552   // Beyond this point, both types need to be C pointers or block pointers.
2553   QualType ToPointeeType;
2554   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2555     ToPointeeType = ToCPtr->getPointeeType();
2556   else if (const BlockPointerType *ToBlockPtr =
2557             ToType->getAs<BlockPointerType>()) {
2558     // Objective C++: We're able to convert from a pointer to any object
2559     // to a block pointer type.
2560     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2561       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562       return true;
2563     }
2564     ToPointeeType = ToBlockPtr->getPointeeType();
2565   }
2566   else if (FromType->getAs<BlockPointerType>() &&
2567            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2568     // Objective C++: We're able to convert from a block pointer type to a
2569     // pointer to any object.
2570     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2571     return true;
2572   }
2573   else
2574     return false;
2575 
2576   QualType FromPointeeType;
2577   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2578     FromPointeeType = FromCPtr->getPointeeType();
2579   else if (const BlockPointerType *FromBlockPtr =
2580            FromType->getAs<BlockPointerType>())
2581     FromPointeeType = FromBlockPtr->getPointeeType();
2582   else
2583     return false;
2584 
2585   // If we have pointers to pointers, recursively check whether this
2586   // is an Objective-C conversion.
2587   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2588       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2589                               IncompatibleObjC)) {
2590     // We always complain about this conversion.
2591     IncompatibleObjC = true;
2592     ConvertedType = Context.getPointerType(ConvertedType);
2593     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2594     return true;
2595   }
2596   // Allow conversion of pointee being objective-c pointer to another one;
2597   // as in I* to id.
2598   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2599       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2600       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2601                               IncompatibleObjC)) {
2602 
2603     ConvertedType = Context.getPointerType(ConvertedType);
2604     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2605     return true;
2606   }
2607 
2608   // If we have pointers to functions or blocks, check whether the only
2609   // differences in the argument and result types are in Objective-C
2610   // pointer conversions. If so, we permit the conversion (but
2611   // complain about it).
2612   const FunctionProtoType *FromFunctionType
2613     = FromPointeeType->getAs<FunctionProtoType>();
2614   const FunctionProtoType *ToFunctionType
2615     = ToPointeeType->getAs<FunctionProtoType>();
2616   if (FromFunctionType && ToFunctionType) {
2617     // If the function types are exactly the same, this isn't an
2618     // Objective-C pointer conversion.
2619     if (Context.getCanonicalType(FromPointeeType)
2620           == Context.getCanonicalType(ToPointeeType))
2621       return false;
2622 
2623     // Perform the quick checks that will tell us whether these
2624     // function types are obviously different.
2625     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2626         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2627         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2628       return false;
2629 
2630     bool HasObjCConversion = false;
2631     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2632         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2633       // Okay, the types match exactly. Nothing to do.
2634     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2635                                        ToFunctionType->getReturnType(),
2636                                        ConvertedType, IncompatibleObjC)) {
2637       // Okay, we have an Objective-C pointer conversion.
2638       HasObjCConversion = true;
2639     } else {
2640       // Function types are too different. Abort.
2641       return false;
2642     }
2643 
2644     // Check argument types.
2645     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2646          ArgIdx != NumArgs; ++ArgIdx) {
2647       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2648       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2649       if (Context.getCanonicalType(FromArgType)
2650             == Context.getCanonicalType(ToArgType)) {
2651         // Okay, the types match exactly. Nothing to do.
2652       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2653                                          ConvertedType, IncompatibleObjC)) {
2654         // Okay, we have an Objective-C pointer conversion.
2655         HasObjCConversion = true;
2656       } else {
2657         // Argument types are too different. Abort.
2658         return false;
2659       }
2660     }
2661 
2662     if (HasObjCConversion) {
2663       // We had an Objective-C conversion. Allow this pointer
2664       // conversion, but complain about it.
2665       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2666       IncompatibleObjC = true;
2667       return true;
2668     }
2669   }
2670 
2671   return false;
2672 }
2673 
2674 /// Determine whether this is an Objective-C writeback conversion,
2675 /// used for parameter passing when performing automatic reference counting.
2676 ///
2677 /// \param FromType The type we're converting form.
2678 ///
2679 /// \param ToType The type we're converting to.
2680 ///
2681 /// \param ConvertedType The type that will be produced after applying
2682 /// this conversion.
2683 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2684                                      QualType &ConvertedType) {
2685   if (!getLangOpts().ObjCAutoRefCount ||
2686       Context.hasSameUnqualifiedType(FromType, ToType))
2687     return false;
2688 
2689   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2690   QualType ToPointee;
2691   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2692     ToPointee = ToPointer->getPointeeType();
2693   else
2694     return false;
2695 
2696   Qualifiers ToQuals = ToPointee.getQualifiers();
2697   if (!ToPointee->isObjCLifetimeType() ||
2698       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2699       !ToQuals.withoutObjCLifetime().empty())
2700     return false;
2701 
2702   // Argument must be a pointer to __strong to __weak.
2703   QualType FromPointee;
2704   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2705     FromPointee = FromPointer->getPointeeType();
2706   else
2707     return false;
2708 
2709   Qualifiers FromQuals = FromPointee.getQualifiers();
2710   if (!FromPointee->isObjCLifetimeType() ||
2711       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2712        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2713     return false;
2714 
2715   // Make sure that we have compatible qualifiers.
2716   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2717   if (!ToQuals.compatiblyIncludes(FromQuals))
2718     return false;
2719 
2720   // Remove qualifiers from the pointee type we're converting from; they
2721   // aren't used in the compatibility check belong, and we'll be adding back
2722   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2723   FromPointee = FromPointee.getUnqualifiedType();
2724 
2725   // The unqualified form of the pointee types must be compatible.
2726   ToPointee = ToPointee.getUnqualifiedType();
2727   bool IncompatibleObjC;
2728   if (Context.typesAreCompatible(FromPointee, ToPointee))
2729     FromPointee = ToPointee;
2730   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2731                                     IncompatibleObjC))
2732     return false;
2733 
2734   /// Construct the type we're converting to, which is a pointer to
2735   /// __autoreleasing pointee.
2736   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2737   ConvertedType = Context.getPointerType(FromPointee);
2738   return true;
2739 }
2740 
2741 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2742                                     QualType& ConvertedType) {
2743   QualType ToPointeeType;
2744   if (const BlockPointerType *ToBlockPtr =
2745         ToType->getAs<BlockPointerType>())
2746     ToPointeeType = ToBlockPtr->getPointeeType();
2747   else
2748     return false;
2749 
2750   QualType FromPointeeType;
2751   if (const BlockPointerType *FromBlockPtr =
2752       FromType->getAs<BlockPointerType>())
2753     FromPointeeType = FromBlockPtr->getPointeeType();
2754   else
2755     return false;
2756   // We have pointer to blocks, check whether the only
2757   // differences in the argument and result types are in Objective-C
2758   // pointer conversions. If so, we permit the conversion.
2759 
2760   const FunctionProtoType *FromFunctionType
2761     = FromPointeeType->getAs<FunctionProtoType>();
2762   const FunctionProtoType *ToFunctionType
2763     = ToPointeeType->getAs<FunctionProtoType>();
2764 
2765   if (!FromFunctionType || !ToFunctionType)
2766     return false;
2767 
2768   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2769     return true;
2770 
2771   // Perform the quick checks that will tell us whether these
2772   // function types are obviously different.
2773   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2774       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2775     return false;
2776 
2777   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2778   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2779   if (FromEInfo != ToEInfo)
2780     return false;
2781 
2782   bool IncompatibleObjC = false;
2783   if (Context.hasSameType(FromFunctionType->getReturnType(),
2784                           ToFunctionType->getReturnType())) {
2785     // Okay, the types match exactly. Nothing to do.
2786   } else {
2787     QualType RHS = FromFunctionType->getReturnType();
2788     QualType LHS = ToFunctionType->getReturnType();
2789     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2790         !RHS.hasQualifiers() && LHS.hasQualifiers())
2791        LHS = LHS.getUnqualifiedType();
2792 
2793      if (Context.hasSameType(RHS,LHS)) {
2794        // OK exact match.
2795      } else if (isObjCPointerConversion(RHS, LHS,
2796                                         ConvertedType, IncompatibleObjC)) {
2797      if (IncompatibleObjC)
2798        return false;
2799      // Okay, we have an Objective-C pointer conversion.
2800      }
2801      else
2802        return false;
2803    }
2804 
2805    // Check argument types.
2806    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2807         ArgIdx != NumArgs; ++ArgIdx) {
2808      IncompatibleObjC = false;
2809      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2810      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2811      if (Context.hasSameType(FromArgType, ToArgType)) {
2812        // Okay, the types match exactly. Nothing to do.
2813      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2814                                         ConvertedType, IncompatibleObjC)) {
2815        if (IncompatibleObjC)
2816          return false;
2817        // Okay, we have an Objective-C pointer conversion.
2818      } else
2819        // Argument types are too different. Abort.
2820        return false;
2821    }
2822 
2823    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2824    bool CanUseToFPT, CanUseFromFPT;
2825    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2826                                       CanUseToFPT, CanUseFromFPT,
2827                                       NewParamInfos))
2828      return false;
2829 
2830    ConvertedType = ToType;
2831    return true;
2832 }
2833 
2834 enum {
2835   ft_default,
2836   ft_different_class,
2837   ft_parameter_arity,
2838   ft_parameter_mismatch,
2839   ft_return_type,
2840   ft_qualifer_mismatch,
2841   ft_noexcept
2842 };
2843 
2844 /// Attempts to get the FunctionProtoType from a Type. Handles
2845 /// MemberFunctionPointers properly.
2846 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2847   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2848     return FPT;
2849 
2850   if (auto *MPT = FromType->getAs<MemberPointerType>())
2851     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2852 
2853   return nullptr;
2854 }
2855 
2856 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2857 /// function types.  Catches different number of parameter, mismatch in
2858 /// parameter types, and different return types.
2859 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2860                                       QualType FromType, QualType ToType) {
2861   // If either type is not valid, include no extra info.
2862   if (FromType.isNull() || ToType.isNull()) {
2863     PDiag << ft_default;
2864     return;
2865   }
2866 
2867   // Get the function type from the pointers.
2868   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2869     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2870                *ToMember = ToType->castAs<MemberPointerType>();
2871     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2872       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2873             << QualType(FromMember->getClass(), 0);
2874       return;
2875     }
2876     FromType = FromMember->getPointeeType();
2877     ToType = ToMember->getPointeeType();
2878   }
2879 
2880   if (FromType->isPointerType())
2881     FromType = FromType->getPointeeType();
2882   if (ToType->isPointerType())
2883     ToType = ToType->getPointeeType();
2884 
2885   // Remove references.
2886   FromType = FromType.getNonReferenceType();
2887   ToType = ToType.getNonReferenceType();
2888 
2889   // Don't print extra info for non-specialized template functions.
2890   if (FromType->isInstantiationDependentType() &&
2891       !FromType->getAs<TemplateSpecializationType>()) {
2892     PDiag << ft_default;
2893     return;
2894   }
2895 
2896   // No extra info for same types.
2897   if (Context.hasSameType(FromType, ToType)) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2903                           *ToFunction = tryGetFunctionProtoType(ToType);
2904 
2905   // Both types need to be function types.
2906   if (!FromFunction || !ToFunction) {
2907     PDiag << ft_default;
2908     return;
2909   }
2910 
2911   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2912     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2913           << FromFunction->getNumParams();
2914     return;
2915   }
2916 
2917   // Handle different parameter types.
2918   unsigned ArgPos;
2919   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2920     PDiag << ft_parameter_mismatch << ArgPos + 1
2921           << ToFunction->getParamType(ArgPos)
2922           << FromFunction->getParamType(ArgPos);
2923     return;
2924   }
2925 
2926   // Handle different return type.
2927   if (!Context.hasSameType(FromFunction->getReturnType(),
2928                            ToFunction->getReturnType())) {
2929     PDiag << ft_return_type << ToFunction->getReturnType()
2930           << FromFunction->getReturnType();
2931     return;
2932   }
2933 
2934   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2935     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2936           << FromFunction->getMethodQuals();
2937     return;
2938   }
2939 
2940   // Handle exception specification differences on canonical type (in C++17
2941   // onwards).
2942   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2943           ->isNothrow() !=
2944       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2945           ->isNothrow()) {
2946     PDiag << ft_noexcept;
2947     return;
2948   }
2949 
2950   // Unable to find a difference, so add no extra info.
2951   PDiag << ft_default;
2952 }
2953 
2954 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2955 /// for equality of their argument types. Caller has already checked that
2956 /// they have same number of arguments.  If the parameters are different,
2957 /// ArgPos will have the parameter index of the first different parameter.
2958 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2959                                       const FunctionProtoType *NewType,
2960                                       unsigned *ArgPos) {
2961   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2962                                               N = NewType->param_type_begin(),
2963                                               E = OldType->param_type_end();
2964        O && (O != E); ++O, ++N) {
2965     // Ignore address spaces in pointee type. This is to disallow overloading
2966     // on __ptr32/__ptr64 address spaces.
2967     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2968     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2969 
2970     if (!Context.hasSameType(Old, New)) {
2971       if (ArgPos)
2972         *ArgPos = O - OldType->param_type_begin();
2973       return false;
2974     }
2975   }
2976   return true;
2977 }
2978 
2979 /// CheckPointerConversion - Check the pointer conversion from the
2980 /// expression From to the type ToType. This routine checks for
2981 /// ambiguous or inaccessible derived-to-base pointer
2982 /// conversions for which IsPointerConversion has already returned
2983 /// true. It returns true and produces a diagnostic if there was an
2984 /// error, or returns false otherwise.
2985 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2986                                   CastKind &Kind,
2987                                   CXXCastPath& BasePath,
2988                                   bool IgnoreBaseAccess,
2989                                   bool Diagnose) {
2990   QualType FromType = From->getType();
2991   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2992 
2993   Kind = CK_BitCast;
2994 
2995   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2996       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2997           Expr::NPCK_ZeroExpression) {
2998     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2999       DiagRuntimeBehavior(From->getExprLoc(), From,
3000                           PDiag(diag::warn_impcast_bool_to_null_pointer)
3001                             << ToType << From->getSourceRange());
3002     else if (!isUnevaluatedContext())
3003       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3004         << ToType << From->getSourceRange();
3005   }
3006   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3007     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3008       QualType FromPointeeType = FromPtrType->getPointeeType(),
3009                ToPointeeType   = ToPtrType->getPointeeType();
3010 
3011       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3012           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3013         // We must have a derived-to-base conversion. Check an
3014         // ambiguous or inaccessible conversion.
3015         unsigned InaccessibleID = 0;
3016         unsigned AmbiguousID = 0;
3017         if (Diagnose) {
3018           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3019           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3020         }
3021         if (CheckDerivedToBaseConversion(
3022                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3023                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3024                 &BasePath, IgnoreBaseAccess))
3025           return true;
3026 
3027         // The conversion was successful.
3028         Kind = CK_DerivedToBase;
3029       }
3030 
3031       if (Diagnose && !IsCStyleOrFunctionalCast &&
3032           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3033         assert(getLangOpts().MSVCCompat &&
3034                "this should only be possible with MSVCCompat!");
3035         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3036             << From->getSourceRange();
3037       }
3038     }
3039   } else if (const ObjCObjectPointerType *ToPtrType =
3040                ToType->getAs<ObjCObjectPointerType>()) {
3041     if (const ObjCObjectPointerType *FromPtrType =
3042           FromType->getAs<ObjCObjectPointerType>()) {
3043       // Objective-C++ conversions are always okay.
3044       // FIXME: We should have a different class of conversions for the
3045       // Objective-C++ implicit conversions.
3046       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3047         return false;
3048     } else if (FromType->isBlockPointerType()) {
3049       Kind = CK_BlockPointerToObjCPointerCast;
3050     } else {
3051       Kind = CK_CPointerToObjCPointerCast;
3052     }
3053   } else if (ToType->isBlockPointerType()) {
3054     if (!FromType->isBlockPointerType())
3055       Kind = CK_AnyPointerToBlockPointerCast;
3056   }
3057 
3058   // We shouldn't fall into this case unless it's valid for other
3059   // reasons.
3060   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3061     Kind = CK_NullToPointer;
3062 
3063   return false;
3064 }
3065 
3066 /// IsMemberPointerConversion - Determines whether the conversion of the
3067 /// expression From, which has the (possibly adjusted) type FromType, can be
3068 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3069 /// If so, returns true and places the converted type (that might differ from
3070 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3071 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3072                                      QualType ToType,
3073                                      bool InOverloadResolution,
3074                                      QualType &ConvertedType) {
3075   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3076   if (!ToTypePtr)
3077     return false;
3078 
3079   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3080   if (From->isNullPointerConstant(Context,
3081                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3082                                         : Expr::NPC_ValueDependentIsNull)) {
3083     ConvertedType = ToType;
3084     return true;
3085   }
3086 
3087   // Otherwise, both types have to be member pointers.
3088   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3089   if (!FromTypePtr)
3090     return false;
3091 
3092   // A pointer to member of B can be converted to a pointer to member of D,
3093   // where D is derived from B (C++ 4.11p2).
3094   QualType FromClass(FromTypePtr->getClass(), 0);
3095   QualType ToClass(ToTypePtr->getClass(), 0);
3096 
3097   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3098       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3099     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3100                                                  ToClass.getTypePtr());
3101     return true;
3102   }
3103 
3104   return false;
3105 }
3106 
3107 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3108 /// expression From to the type ToType. This routine checks for ambiguous or
3109 /// virtual or inaccessible base-to-derived member pointer conversions
3110 /// for which IsMemberPointerConversion has already returned true. It returns
3111 /// true and produces a diagnostic if there was an error, or returns false
3112 /// otherwise.
3113 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3114                                         CastKind &Kind,
3115                                         CXXCastPath &BasePath,
3116                                         bool IgnoreBaseAccess) {
3117   QualType FromType = From->getType();
3118   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3119   if (!FromPtrType) {
3120     // This must be a null pointer to member pointer conversion
3121     assert(From->isNullPointerConstant(Context,
3122                                        Expr::NPC_ValueDependentIsNull) &&
3123            "Expr must be null pointer constant!");
3124     Kind = CK_NullToMemberPointer;
3125     return false;
3126   }
3127 
3128   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3129   assert(ToPtrType && "No member pointer cast has a target type "
3130                       "that is not a member pointer.");
3131 
3132   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3133   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3134 
3135   // FIXME: What about dependent types?
3136   assert(FromClass->isRecordType() && "Pointer into non-class.");
3137   assert(ToClass->isRecordType() && "Pointer into non-class.");
3138 
3139   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3140                      /*DetectVirtual=*/true);
3141   bool DerivationOkay =
3142       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3143   assert(DerivationOkay &&
3144          "Should not have been called if derivation isn't OK.");
3145   (void)DerivationOkay;
3146 
3147   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3148                                   getUnqualifiedType())) {
3149     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3150     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3151       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3152     return true;
3153   }
3154 
3155   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3156     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3157       << FromClass << ToClass << QualType(VBase, 0)
3158       << From->getSourceRange();
3159     return true;
3160   }
3161 
3162   if (!IgnoreBaseAccess)
3163     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3164                          Paths.front(),
3165                          diag::err_downcast_from_inaccessible_base);
3166 
3167   // Must be a base to derived member conversion.
3168   BuildBasePathArray(Paths, BasePath);
3169   Kind = CK_BaseToDerivedMemberPointer;
3170   return false;
3171 }
3172 
3173 /// Determine whether the lifetime conversion between the two given
3174 /// qualifiers sets is nontrivial.
3175 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3176                                                Qualifiers ToQuals) {
3177   // Converting anything to const __unsafe_unretained is trivial.
3178   if (ToQuals.hasConst() &&
3179       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3180     return false;
3181 
3182   return true;
3183 }
3184 
3185 /// Perform a single iteration of the loop for checking if a qualification
3186 /// conversion is valid.
3187 ///
3188 /// Specifically, check whether any change between the qualifiers of \p
3189 /// FromType and \p ToType is permissible, given knowledge about whether every
3190 /// outer layer is const-qualified.
3191 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3192                                           bool CStyle, bool IsTopLevel,
3193                                           bool &PreviousToQualsIncludeConst,
3194                                           bool &ObjCLifetimeConversion) {
3195   Qualifiers FromQuals = FromType.getQualifiers();
3196   Qualifiers ToQuals = ToType.getQualifiers();
3197 
3198   // Ignore __unaligned qualifier if this type is void.
3199   if (ToType.getUnqualifiedType()->isVoidType())
3200     FromQuals.removeUnaligned();
3201 
3202   // Objective-C ARC:
3203   //   Check Objective-C lifetime conversions.
3204   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3205     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3206       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3207         ObjCLifetimeConversion = true;
3208       FromQuals.removeObjCLifetime();
3209       ToQuals.removeObjCLifetime();
3210     } else {
3211       // Qualification conversions cannot cast between different
3212       // Objective-C lifetime qualifiers.
3213       return false;
3214     }
3215   }
3216 
3217   // Allow addition/removal of GC attributes but not changing GC attributes.
3218   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3219       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3220     FromQuals.removeObjCGCAttr();
3221     ToQuals.removeObjCGCAttr();
3222   }
3223 
3224   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3225   //      2,j, and similarly for volatile.
3226   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3227     return false;
3228 
3229   // If address spaces mismatch:
3230   //  - in top level it is only valid to convert to addr space that is a
3231   //    superset in all cases apart from C-style casts where we allow
3232   //    conversions between overlapping address spaces.
3233   //  - in non-top levels it is not a valid conversion.
3234   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3235       (!IsTopLevel ||
3236        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3237          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3238     return false;
3239 
3240   //   -- if the cv 1,j and cv 2,j are different, then const is in
3241   //      every cv for 0 < k < j.
3242   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3243       !PreviousToQualsIncludeConst)
3244     return false;
3245 
3246   // Keep track of whether all prior cv-qualifiers in the "to" type
3247   // include const.
3248   PreviousToQualsIncludeConst =
3249       PreviousToQualsIncludeConst && ToQuals.hasConst();
3250   return true;
3251 }
3252 
3253 /// IsQualificationConversion - Determines whether the conversion from
3254 /// an rvalue of type FromType to ToType is a qualification conversion
3255 /// (C++ 4.4).
3256 ///
3257 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3258 /// when the qualification conversion involves a change in the Objective-C
3259 /// object lifetime.
3260 bool
3261 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3262                                 bool CStyle, bool &ObjCLifetimeConversion) {
3263   FromType = Context.getCanonicalType(FromType);
3264   ToType = Context.getCanonicalType(ToType);
3265   ObjCLifetimeConversion = false;
3266 
3267   // If FromType and ToType are the same type, this is not a
3268   // qualification conversion.
3269   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3270     return false;
3271 
3272   // (C++ 4.4p4):
3273   //   A conversion can add cv-qualifiers at levels other than the first
3274   //   in multi-level pointers, subject to the following rules: [...]
3275   bool PreviousToQualsIncludeConst = true;
3276   bool UnwrappedAnyPointer = false;
3277   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3278     if (!isQualificationConversionStep(
3279             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3280             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3281       return false;
3282     UnwrappedAnyPointer = true;
3283   }
3284 
3285   // We are left with FromType and ToType being the pointee types
3286   // after unwrapping the original FromType and ToType the same number
3287   // of times. If we unwrapped any pointers, and if FromType and
3288   // ToType have the same unqualified type (since we checked
3289   // qualifiers above), then this is a qualification conversion.
3290   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3291 }
3292 
3293 /// - Determine whether this is a conversion from a scalar type to an
3294 /// atomic type.
3295 ///
3296 /// If successful, updates \c SCS's second and third steps in the conversion
3297 /// sequence to finish the conversion.
3298 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3299                                 bool InOverloadResolution,
3300                                 StandardConversionSequence &SCS,
3301                                 bool CStyle) {
3302   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3303   if (!ToAtomic)
3304     return false;
3305 
3306   StandardConversionSequence InnerSCS;
3307   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3308                             InOverloadResolution, InnerSCS,
3309                             CStyle, /*AllowObjCWritebackConversion=*/false))
3310     return false;
3311 
3312   SCS.Second = InnerSCS.Second;
3313   SCS.setToType(1, InnerSCS.getToType(1));
3314   SCS.Third = InnerSCS.Third;
3315   SCS.QualificationIncludesObjCLifetime
3316     = InnerSCS.QualificationIncludesObjCLifetime;
3317   SCS.setToType(2, InnerSCS.getToType(2));
3318   return true;
3319 }
3320 
3321 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3322                                               CXXConstructorDecl *Constructor,
3323                                               QualType Type) {
3324   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3325   if (CtorType->getNumParams() > 0) {
3326     QualType FirstArg = CtorType->getParamType(0);
3327     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3328       return true;
3329   }
3330   return false;
3331 }
3332 
3333 static OverloadingResult
3334 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3335                                        CXXRecordDecl *To,
3336                                        UserDefinedConversionSequence &User,
3337                                        OverloadCandidateSet &CandidateSet,
3338                                        bool AllowExplicit) {
3339   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3340   for (auto *D : S.LookupConstructors(To)) {
3341     auto Info = getConstructorInfo(D);
3342     if (!Info)
3343       continue;
3344 
3345     bool Usable = !Info.Constructor->isInvalidDecl() &&
3346                   S.isInitListConstructor(Info.Constructor);
3347     if (Usable) {
3348       // If the first argument is (a reference to) the target type,
3349       // suppress conversions.
3350       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3351           S.Context, Info.Constructor, ToType);
3352       if (Info.ConstructorTmpl)
3353         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3354                                        /*ExplicitArgs*/ nullptr, From,
3355                                        CandidateSet, SuppressUserConversions,
3356                                        /*PartialOverloading*/ false,
3357                                        AllowExplicit);
3358       else
3359         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3360                                CandidateSet, SuppressUserConversions,
3361                                /*PartialOverloading*/ false, AllowExplicit);
3362     }
3363   }
3364 
3365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3366 
3367   OverloadCandidateSet::iterator Best;
3368   switch (auto Result =
3369               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3370   case OR_Deleted:
3371   case OR_Success: {
3372     // Record the standard conversion we used and the conversion function.
3373     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3374     QualType ThisType = Constructor->getThisType();
3375     // Initializer lists don't have conversions as such.
3376     User.Before.setAsIdentityConversion();
3377     User.HadMultipleCandidates = HadMultipleCandidates;
3378     User.ConversionFunction = Constructor;
3379     User.FoundConversionFunction = Best->FoundDecl;
3380     User.After.setAsIdentityConversion();
3381     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3382     User.After.setAllToTypes(ToType);
3383     return Result;
3384   }
3385 
3386   case OR_No_Viable_Function:
3387     return OR_No_Viable_Function;
3388   case OR_Ambiguous:
3389     return OR_Ambiguous;
3390   }
3391 
3392   llvm_unreachable("Invalid OverloadResult!");
3393 }
3394 
3395 /// Determines whether there is a user-defined conversion sequence
3396 /// (C++ [over.ics.user]) that converts expression From to the type
3397 /// ToType. If such a conversion exists, User will contain the
3398 /// user-defined conversion sequence that performs such a conversion
3399 /// and this routine will return true. Otherwise, this routine returns
3400 /// false and User is unspecified.
3401 ///
3402 /// \param AllowExplicit  true if the conversion should consider C++0x
3403 /// "explicit" conversion functions as well as non-explicit conversion
3404 /// functions (C++0x [class.conv.fct]p2).
3405 ///
3406 /// \param AllowObjCConversionOnExplicit true if the conversion should
3407 /// allow an extra Objective-C pointer conversion on uses of explicit
3408 /// constructors. Requires \c AllowExplicit to also be set.
3409 static OverloadingResult
3410 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3411                         UserDefinedConversionSequence &User,
3412                         OverloadCandidateSet &CandidateSet,
3413                         AllowedExplicit AllowExplicit,
3414                         bool AllowObjCConversionOnExplicit) {
3415   assert(AllowExplicit != AllowedExplicit::None ||
3416          !AllowObjCConversionOnExplicit);
3417   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3418 
3419   // Whether we will only visit constructors.
3420   bool ConstructorsOnly = false;
3421 
3422   // If the type we are conversion to is a class type, enumerate its
3423   // constructors.
3424   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3425     // C++ [over.match.ctor]p1:
3426     //   When objects of class type are direct-initialized (8.5), or
3427     //   copy-initialized from an expression of the same or a
3428     //   derived class type (8.5), overload resolution selects the
3429     //   constructor. [...] For copy-initialization, the candidate
3430     //   functions are all the converting constructors (12.3.1) of
3431     //   that class. The argument list is the expression-list within
3432     //   the parentheses of the initializer.
3433     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3434         (From->getType()->getAs<RecordType>() &&
3435          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3436       ConstructorsOnly = true;
3437 
3438     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3439       // We're not going to find any constructors.
3440     } else if (CXXRecordDecl *ToRecordDecl
3441                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3442 
3443       Expr **Args = &From;
3444       unsigned NumArgs = 1;
3445       bool ListInitializing = false;
3446       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3447         // But first, see if there is an init-list-constructor that will work.
3448         OverloadingResult Result = IsInitializerListConstructorConversion(
3449             S, From, ToType, ToRecordDecl, User, CandidateSet,
3450             AllowExplicit == AllowedExplicit::All);
3451         if (Result != OR_No_Viable_Function)
3452           return Result;
3453         // Never mind.
3454         CandidateSet.clear(
3455             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3456 
3457         // If we're list-initializing, we pass the individual elements as
3458         // arguments, not the entire list.
3459         Args = InitList->getInits();
3460         NumArgs = InitList->getNumInits();
3461         ListInitializing = true;
3462       }
3463 
3464       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3465         auto Info = getConstructorInfo(D);
3466         if (!Info)
3467           continue;
3468 
3469         bool Usable = !Info.Constructor->isInvalidDecl();
3470         if (!ListInitializing)
3471           Usable = Usable && Info.Constructor->isConvertingConstructor(
3472                                  /*AllowExplicit*/ true);
3473         if (Usable) {
3474           bool SuppressUserConversions = !ConstructorsOnly;
3475           if (SuppressUserConversions && ListInitializing) {
3476             SuppressUserConversions = false;
3477             if (NumArgs == 1) {
3478               // If the first argument is (a reference to) the target type,
3479               // suppress conversions.
3480               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3481                   S.Context, Info.Constructor, ToType);
3482             }
3483           }
3484           if (Info.ConstructorTmpl)
3485             S.AddTemplateOverloadCandidate(
3486                 Info.ConstructorTmpl, Info.FoundDecl,
3487                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3488                 CandidateSet, SuppressUserConversions,
3489                 /*PartialOverloading*/ false,
3490                 AllowExplicit == AllowedExplicit::All);
3491           else
3492             // Allow one user-defined conversion when user specifies a
3493             // From->ToType conversion via an static cast (c-style, etc).
3494             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3495                                    llvm::makeArrayRef(Args, NumArgs),
3496                                    CandidateSet, SuppressUserConversions,
3497                                    /*PartialOverloading*/ false,
3498                                    AllowExplicit == AllowedExplicit::All);
3499         }
3500       }
3501     }
3502   }
3503 
3504   // Enumerate conversion functions, if we're allowed to.
3505   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3506   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3507     // No conversion functions from incomplete types.
3508   } else if (const RecordType *FromRecordType =
3509                  From->getType()->getAs<RecordType>()) {
3510     if (CXXRecordDecl *FromRecordDecl
3511          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3512       // Add all of the conversion functions as candidates.
3513       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3514       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3515         DeclAccessPair FoundDecl = I.getPair();
3516         NamedDecl *D = FoundDecl.getDecl();
3517         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3518         if (isa<UsingShadowDecl>(D))
3519           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3520 
3521         CXXConversionDecl *Conv;
3522         FunctionTemplateDecl *ConvTemplate;
3523         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3524           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3525         else
3526           Conv = cast<CXXConversionDecl>(D);
3527 
3528         if (ConvTemplate)
3529           S.AddTemplateConversionCandidate(
3530               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3531               CandidateSet, AllowObjCConversionOnExplicit,
3532               AllowExplicit != AllowedExplicit::None);
3533         else
3534           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3535                                    CandidateSet, AllowObjCConversionOnExplicit,
3536                                    AllowExplicit != AllowedExplicit::None);
3537       }
3538     }
3539   }
3540 
3541   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3542 
3543   OverloadCandidateSet::iterator Best;
3544   switch (auto Result =
3545               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3546   case OR_Success:
3547   case OR_Deleted:
3548     // Record the standard conversion we used and the conversion function.
3549     if (CXXConstructorDecl *Constructor
3550           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3551       // C++ [over.ics.user]p1:
3552       //   If the user-defined conversion is specified by a
3553       //   constructor (12.3.1), the initial standard conversion
3554       //   sequence converts the source type to the type required by
3555       //   the argument of the constructor.
3556       //
3557       QualType ThisType = Constructor->getThisType();
3558       if (isa<InitListExpr>(From)) {
3559         // Initializer lists don't have conversions as such.
3560         User.Before.setAsIdentityConversion();
3561       } else {
3562         if (Best->Conversions[0].isEllipsis())
3563           User.EllipsisConversion = true;
3564         else {
3565           User.Before = Best->Conversions[0].Standard;
3566           User.EllipsisConversion = false;
3567         }
3568       }
3569       User.HadMultipleCandidates = HadMultipleCandidates;
3570       User.ConversionFunction = Constructor;
3571       User.FoundConversionFunction = Best->FoundDecl;
3572       User.After.setAsIdentityConversion();
3573       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3574       User.After.setAllToTypes(ToType);
3575       return Result;
3576     }
3577     if (CXXConversionDecl *Conversion
3578                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3579       // C++ [over.ics.user]p1:
3580       //
3581       //   [...] If the user-defined conversion is specified by a
3582       //   conversion function (12.3.2), the initial standard
3583       //   conversion sequence converts the source type to the
3584       //   implicit object parameter of the conversion function.
3585       User.Before = Best->Conversions[0].Standard;
3586       User.HadMultipleCandidates = HadMultipleCandidates;
3587       User.ConversionFunction = Conversion;
3588       User.FoundConversionFunction = Best->FoundDecl;
3589       User.EllipsisConversion = false;
3590 
3591       // C++ [over.ics.user]p2:
3592       //   The second standard conversion sequence converts the
3593       //   result of the user-defined conversion to the target type
3594       //   for the sequence. Since an implicit conversion sequence
3595       //   is an initialization, the special rules for
3596       //   initialization by user-defined conversion apply when
3597       //   selecting the best user-defined conversion for a
3598       //   user-defined conversion sequence (see 13.3.3 and
3599       //   13.3.3.1).
3600       User.After = Best->FinalConversion;
3601       return Result;
3602     }
3603     llvm_unreachable("Not a constructor or conversion function?");
3604 
3605   case OR_No_Viable_Function:
3606     return OR_No_Viable_Function;
3607 
3608   case OR_Ambiguous:
3609     return OR_Ambiguous;
3610   }
3611 
3612   llvm_unreachable("Invalid OverloadResult!");
3613 }
3614 
3615 bool
3616 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3617   ImplicitConversionSequence ICS;
3618   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3619                                     OverloadCandidateSet::CSK_Normal);
3620   OverloadingResult OvResult =
3621     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3622                             CandidateSet, AllowedExplicit::None, false);
3623 
3624   if (!(OvResult == OR_Ambiguous ||
3625         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3626     return false;
3627 
3628   auto Cands = CandidateSet.CompleteCandidates(
3629       *this,
3630       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3631       From);
3632   if (OvResult == OR_Ambiguous)
3633     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3634         << From->getType() << ToType << From->getSourceRange();
3635   else { // OR_No_Viable_Function && !CandidateSet.empty()
3636     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3637                              diag::err_typecheck_nonviable_condition_incomplete,
3638                              From->getType(), From->getSourceRange()))
3639       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3640           << false << From->getType() << From->getSourceRange() << ToType;
3641   }
3642 
3643   CandidateSet.NoteCandidates(
3644                               *this, From, Cands);
3645   return true;
3646 }
3647 
3648 /// Compare the user-defined conversion functions or constructors
3649 /// of two user-defined conversion sequences to determine whether any ordering
3650 /// is possible.
3651 static ImplicitConversionSequence::CompareKind
3652 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3653                            FunctionDecl *Function2) {
3654   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   // Objective-C++:
3658   //   If both conversion functions are implicitly-declared conversions from
3659   //   a lambda closure type to a function pointer and a block pointer,
3660   //   respectively, always prefer the conversion to a function pointer,
3661   //   because the function pointer is more lightweight and is more likely
3662   //   to keep code working.
3663   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3664   if (!Conv1)
3665     return ImplicitConversionSequence::Indistinguishable;
3666 
3667   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3668   if (!Conv2)
3669     return ImplicitConversionSequence::Indistinguishable;
3670 
3671   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3672     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3673     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3674     if (Block1 != Block2)
3675       return Block1 ? ImplicitConversionSequence::Worse
3676                     : ImplicitConversionSequence::Better;
3677   }
3678 
3679   return ImplicitConversionSequence::Indistinguishable;
3680 }
3681 
3682 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3683     const ImplicitConversionSequence &ICS) {
3684   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3685          (ICS.isUserDefined() &&
3686           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3687 }
3688 
3689 /// CompareImplicitConversionSequences - Compare two implicit
3690 /// conversion sequences to determine whether one is better than the
3691 /// other or if they are indistinguishable (C++ 13.3.3.2).
3692 static ImplicitConversionSequence::CompareKind
3693 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3694                                    const ImplicitConversionSequence& ICS1,
3695                                    const ImplicitConversionSequence& ICS2)
3696 {
3697   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3698   // conversion sequences (as defined in 13.3.3.1)
3699   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3700   //      conversion sequence than a user-defined conversion sequence or
3701   //      an ellipsis conversion sequence, and
3702   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3703   //      conversion sequence than an ellipsis conversion sequence
3704   //      (13.3.3.1.3).
3705   //
3706   // C++0x [over.best.ics]p10:
3707   //   For the purpose of ranking implicit conversion sequences as
3708   //   described in 13.3.3.2, the ambiguous conversion sequence is
3709   //   treated as a user-defined sequence that is indistinguishable
3710   //   from any other user-defined conversion sequence.
3711 
3712   // String literal to 'char *' conversion has been deprecated in C++03. It has
3713   // been removed from C++11. We still accept this conversion, if it happens at
3714   // the best viable function. Otherwise, this conversion is considered worse
3715   // than ellipsis conversion. Consider this as an extension; this is not in the
3716   // standard. For example:
3717   //
3718   // int &f(...);    // #1
3719   // void f(char*);  // #2
3720   // void g() { int &r = f("foo"); }
3721   //
3722   // In C++03, we pick #2 as the best viable function.
3723   // In C++11, we pick #1 as the best viable function, because ellipsis
3724   // conversion is better than string-literal to char* conversion (since there
3725   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3726   // convert arguments, #2 would be the best viable function in C++11.
3727   // If the best viable function has this conversion, a warning will be issued
3728   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3729 
3730   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3731       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3732       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3733     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3734                ? ImplicitConversionSequence::Worse
3735                : ImplicitConversionSequence::Better;
3736 
3737   if (ICS1.getKindRank() < ICS2.getKindRank())
3738     return ImplicitConversionSequence::Better;
3739   if (ICS2.getKindRank() < ICS1.getKindRank())
3740     return ImplicitConversionSequence::Worse;
3741 
3742   // The following checks require both conversion sequences to be of
3743   // the same kind.
3744   if (ICS1.getKind() != ICS2.getKind())
3745     return ImplicitConversionSequence::Indistinguishable;
3746 
3747   ImplicitConversionSequence::CompareKind Result =
3748       ImplicitConversionSequence::Indistinguishable;
3749 
3750   // Two implicit conversion sequences of the same form are
3751   // indistinguishable conversion sequences unless one of the
3752   // following rules apply: (C++ 13.3.3.2p3):
3753 
3754   // List-initialization sequence L1 is a better conversion sequence than
3755   // list-initialization sequence L2 if:
3756   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3757   //   if not that,
3758   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3759   //   and N1 is smaller than N2.,
3760   // even if one of the other rules in this paragraph would otherwise apply.
3761   if (!ICS1.isBad()) {
3762     if (ICS1.isStdInitializerListElement() &&
3763         !ICS2.isStdInitializerListElement())
3764       return ImplicitConversionSequence::Better;
3765     if (!ICS1.isStdInitializerListElement() &&
3766         ICS2.isStdInitializerListElement())
3767       return ImplicitConversionSequence::Worse;
3768   }
3769 
3770   if (ICS1.isStandard())
3771     // Standard conversion sequence S1 is a better conversion sequence than
3772     // standard conversion sequence S2 if [...]
3773     Result = CompareStandardConversionSequences(S, Loc,
3774                                                 ICS1.Standard, ICS2.Standard);
3775   else if (ICS1.isUserDefined()) {
3776     // User-defined conversion sequence U1 is a better conversion
3777     // sequence than another user-defined conversion sequence U2 if
3778     // they contain the same user-defined conversion function or
3779     // constructor and if the second standard conversion sequence of
3780     // U1 is better than the second standard conversion sequence of
3781     // U2 (C++ 13.3.3.2p3).
3782     if (ICS1.UserDefined.ConversionFunction ==
3783           ICS2.UserDefined.ConversionFunction)
3784       Result = CompareStandardConversionSequences(S, Loc,
3785                                                   ICS1.UserDefined.After,
3786                                                   ICS2.UserDefined.After);
3787     else
3788       Result = compareConversionFunctions(S,
3789                                           ICS1.UserDefined.ConversionFunction,
3790                                           ICS2.UserDefined.ConversionFunction);
3791   }
3792 
3793   return Result;
3794 }
3795 
3796 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3797 // determine if one is a proper subset of the other.
3798 static ImplicitConversionSequence::CompareKind
3799 compareStandardConversionSubsets(ASTContext &Context,
3800                                  const StandardConversionSequence& SCS1,
3801                                  const StandardConversionSequence& SCS2) {
3802   ImplicitConversionSequence::CompareKind Result
3803     = ImplicitConversionSequence::Indistinguishable;
3804 
3805   // the identity conversion sequence is considered to be a subsequence of
3806   // any non-identity conversion sequence
3807   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3808     return ImplicitConversionSequence::Better;
3809   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3810     return ImplicitConversionSequence::Worse;
3811 
3812   if (SCS1.Second != SCS2.Second) {
3813     if (SCS1.Second == ICK_Identity)
3814       Result = ImplicitConversionSequence::Better;
3815     else if (SCS2.Second == ICK_Identity)
3816       Result = ImplicitConversionSequence::Worse;
3817     else
3818       return ImplicitConversionSequence::Indistinguishable;
3819   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3820     return ImplicitConversionSequence::Indistinguishable;
3821 
3822   if (SCS1.Third == SCS2.Third) {
3823     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3824                              : ImplicitConversionSequence::Indistinguishable;
3825   }
3826 
3827   if (SCS1.Third == ICK_Identity)
3828     return Result == ImplicitConversionSequence::Worse
3829              ? ImplicitConversionSequence::Indistinguishable
3830              : ImplicitConversionSequence::Better;
3831 
3832   if (SCS2.Third == ICK_Identity)
3833     return Result == ImplicitConversionSequence::Better
3834              ? ImplicitConversionSequence::Indistinguishable
3835              : ImplicitConversionSequence::Worse;
3836 
3837   return ImplicitConversionSequence::Indistinguishable;
3838 }
3839 
3840 /// Determine whether one of the given reference bindings is better
3841 /// than the other based on what kind of bindings they are.
3842 static bool
3843 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3844                              const StandardConversionSequence &SCS2) {
3845   // C++0x [over.ics.rank]p3b4:
3846   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3847   //      implicit object parameter of a non-static member function declared
3848   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3849   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3850   //      lvalue reference to a function lvalue and S2 binds an rvalue
3851   //      reference*.
3852   //
3853   // FIXME: Rvalue references. We're going rogue with the above edits,
3854   // because the semantics in the current C++0x working paper (N3225 at the
3855   // time of this writing) break the standard definition of std::forward
3856   // and std::reference_wrapper when dealing with references to functions.
3857   // Proposed wording changes submitted to CWG for consideration.
3858   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3859       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3860     return false;
3861 
3862   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3863           SCS2.IsLvalueReference) ||
3864          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3865           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3866 }
3867 
3868 enum class FixedEnumPromotion {
3869   None,
3870   ToUnderlyingType,
3871   ToPromotedUnderlyingType
3872 };
3873 
3874 /// Returns kind of fixed enum promotion the \a SCS uses.
3875 static FixedEnumPromotion
3876 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3877 
3878   if (SCS.Second != ICK_Integral_Promotion)
3879     return FixedEnumPromotion::None;
3880 
3881   QualType FromType = SCS.getFromType();
3882   if (!FromType->isEnumeralType())
3883     return FixedEnumPromotion::None;
3884 
3885   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3886   if (!Enum->isFixed())
3887     return FixedEnumPromotion::None;
3888 
3889   QualType UnderlyingType = Enum->getIntegerType();
3890   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3891     return FixedEnumPromotion::ToUnderlyingType;
3892 
3893   return FixedEnumPromotion::ToPromotedUnderlyingType;
3894 }
3895 
3896 /// CompareStandardConversionSequences - Compare two standard
3897 /// conversion sequences to determine whether one is better than the
3898 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3899 static ImplicitConversionSequence::CompareKind
3900 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3901                                    const StandardConversionSequence& SCS1,
3902                                    const StandardConversionSequence& SCS2)
3903 {
3904   // Standard conversion sequence S1 is a better conversion sequence
3905   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3906 
3907   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3908   //     sequences in the canonical form defined by 13.3.3.1.1,
3909   //     excluding any Lvalue Transformation; the identity conversion
3910   //     sequence is considered to be a subsequence of any
3911   //     non-identity conversion sequence) or, if not that,
3912   if (ImplicitConversionSequence::CompareKind CK
3913         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3914     return CK;
3915 
3916   //  -- the rank of S1 is better than the rank of S2 (by the rules
3917   //     defined below), or, if not that,
3918   ImplicitConversionRank Rank1 = SCS1.getRank();
3919   ImplicitConversionRank Rank2 = SCS2.getRank();
3920   if (Rank1 < Rank2)
3921     return ImplicitConversionSequence::Better;
3922   else if (Rank2 < Rank1)
3923     return ImplicitConversionSequence::Worse;
3924 
3925   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3926   // are indistinguishable unless one of the following rules
3927   // applies:
3928 
3929   //   A conversion that is not a conversion of a pointer, or
3930   //   pointer to member, to bool is better than another conversion
3931   //   that is such a conversion.
3932   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3933     return SCS2.isPointerConversionToBool()
3934              ? ImplicitConversionSequence::Better
3935              : ImplicitConversionSequence::Worse;
3936 
3937   // C++14 [over.ics.rank]p4b2:
3938   // This is retroactively applied to C++11 by CWG 1601.
3939   //
3940   //   A conversion that promotes an enumeration whose underlying type is fixed
3941   //   to its underlying type is better than one that promotes to the promoted
3942   //   underlying type, if the two are different.
3943   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3944   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3945   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3946       FEP1 != FEP2)
3947     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3948                ? ImplicitConversionSequence::Better
3949                : ImplicitConversionSequence::Worse;
3950 
3951   // C++ [over.ics.rank]p4b2:
3952   //
3953   //   If class B is derived directly or indirectly from class A,
3954   //   conversion of B* to A* is better than conversion of B* to
3955   //   void*, and conversion of A* to void* is better than conversion
3956   //   of B* to void*.
3957   bool SCS1ConvertsToVoid
3958     = SCS1.isPointerConversionToVoidPointer(S.Context);
3959   bool SCS2ConvertsToVoid
3960     = SCS2.isPointerConversionToVoidPointer(S.Context);
3961   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3962     // Exactly one of the conversion sequences is a conversion to
3963     // a void pointer; it's the worse conversion.
3964     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3965                               : ImplicitConversionSequence::Worse;
3966   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3967     // Neither conversion sequence converts to a void pointer; compare
3968     // their derived-to-base conversions.
3969     if (ImplicitConversionSequence::CompareKind DerivedCK
3970           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3971       return DerivedCK;
3972   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3973              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3974     // Both conversion sequences are conversions to void
3975     // pointers. Compare the source types to determine if there's an
3976     // inheritance relationship in their sources.
3977     QualType FromType1 = SCS1.getFromType();
3978     QualType FromType2 = SCS2.getFromType();
3979 
3980     // Adjust the types we're converting from via the array-to-pointer
3981     // conversion, if we need to.
3982     if (SCS1.First == ICK_Array_To_Pointer)
3983       FromType1 = S.Context.getArrayDecayedType(FromType1);
3984     if (SCS2.First == ICK_Array_To_Pointer)
3985       FromType2 = S.Context.getArrayDecayedType(FromType2);
3986 
3987     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3988     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3989 
3990     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3991       return ImplicitConversionSequence::Better;
3992     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3993       return ImplicitConversionSequence::Worse;
3994 
3995     // Objective-C++: If one interface is more specific than the
3996     // other, it is the better one.
3997     const ObjCObjectPointerType* FromObjCPtr1
3998       = FromType1->getAs<ObjCObjectPointerType>();
3999     const ObjCObjectPointerType* FromObjCPtr2
4000       = FromType2->getAs<ObjCObjectPointerType>();
4001     if (FromObjCPtr1 && FromObjCPtr2) {
4002       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4003                                                           FromObjCPtr2);
4004       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4005                                                            FromObjCPtr1);
4006       if (AssignLeft != AssignRight) {
4007         return AssignLeft? ImplicitConversionSequence::Better
4008                          : ImplicitConversionSequence::Worse;
4009       }
4010     }
4011   }
4012 
4013   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4014     // Check for a better reference binding based on the kind of bindings.
4015     if (isBetterReferenceBindingKind(SCS1, SCS2))
4016       return ImplicitConversionSequence::Better;
4017     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4018       return ImplicitConversionSequence::Worse;
4019   }
4020 
4021   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4022   // bullet 3).
4023   if (ImplicitConversionSequence::CompareKind QualCK
4024         = CompareQualificationConversions(S, SCS1, SCS2))
4025     return QualCK;
4026 
4027   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4028     // C++ [over.ics.rank]p3b4:
4029     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4030     //      which the references refer are the same type except for
4031     //      top-level cv-qualifiers, and the type to which the reference
4032     //      initialized by S2 refers is more cv-qualified than the type
4033     //      to which the reference initialized by S1 refers.
4034     QualType T1 = SCS1.getToType(2);
4035     QualType T2 = SCS2.getToType(2);
4036     T1 = S.Context.getCanonicalType(T1);
4037     T2 = S.Context.getCanonicalType(T2);
4038     Qualifiers T1Quals, T2Quals;
4039     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4040     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4041     if (UnqualT1 == UnqualT2) {
4042       // Objective-C++ ARC: If the references refer to objects with different
4043       // lifetimes, prefer bindings that don't change lifetime.
4044       if (SCS1.ObjCLifetimeConversionBinding !=
4045                                           SCS2.ObjCLifetimeConversionBinding) {
4046         return SCS1.ObjCLifetimeConversionBinding
4047                                            ? ImplicitConversionSequence::Worse
4048                                            : ImplicitConversionSequence::Better;
4049       }
4050 
4051       // If the type is an array type, promote the element qualifiers to the
4052       // type for comparison.
4053       if (isa<ArrayType>(T1) && T1Quals)
4054         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4055       if (isa<ArrayType>(T2) && T2Quals)
4056         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4057       if (T2.isMoreQualifiedThan(T1))
4058         return ImplicitConversionSequence::Better;
4059       if (T1.isMoreQualifiedThan(T2))
4060         return ImplicitConversionSequence::Worse;
4061     }
4062   }
4063 
4064   // In Microsoft mode, prefer an integral conversion to a
4065   // floating-to-integral conversion if the integral conversion
4066   // is between types of the same size.
4067   // For example:
4068   // void f(float);
4069   // void f(int);
4070   // int main {
4071   //    long a;
4072   //    f(a);
4073   // }
4074   // Here, MSVC will call f(int) instead of generating a compile error
4075   // as clang will do in standard mode.
4076   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4077       SCS2.Second == ICK_Floating_Integral &&
4078       S.Context.getTypeSize(SCS1.getFromType()) ==
4079           S.Context.getTypeSize(SCS1.getToType(2)))
4080     return ImplicitConversionSequence::Better;
4081 
4082   // Prefer a compatible vector conversion over a lax vector conversion
4083   // For example:
4084   //
4085   // typedef float __v4sf __attribute__((__vector_size__(16)));
4086   // void f(vector float);
4087   // void f(vector signed int);
4088   // int main() {
4089   //   __v4sf a;
4090   //   f(a);
4091   // }
4092   // Here, we'd like to choose f(vector float) and not
4093   // report an ambiguous call error
4094   if (SCS1.Second == ICK_Vector_Conversion &&
4095       SCS2.Second == ICK_Vector_Conversion) {
4096     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4097         SCS1.getFromType(), SCS1.getToType(2));
4098     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4099         SCS2.getFromType(), SCS2.getToType(2));
4100 
4101     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4102       return SCS1IsCompatibleVectorConversion
4103                  ? ImplicitConversionSequence::Better
4104                  : ImplicitConversionSequence::Worse;
4105   }
4106 
4107   if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4108       SCS2.Second == ICK_SVE_Vector_Conversion) {
4109     bool SCS1IsCompatibleSVEVectorConversion =
4110         S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4111     bool SCS2IsCompatibleSVEVectorConversion =
4112         S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4113 
4114     if (SCS1IsCompatibleSVEVectorConversion !=
4115         SCS2IsCompatibleSVEVectorConversion)
4116       return SCS1IsCompatibleSVEVectorConversion
4117                  ? ImplicitConversionSequence::Better
4118                  : ImplicitConversionSequence::Worse;
4119   }
4120 
4121   return ImplicitConversionSequence::Indistinguishable;
4122 }
4123 
4124 /// CompareQualificationConversions - Compares two standard conversion
4125 /// sequences to determine whether they can be ranked based on their
4126 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4127 static ImplicitConversionSequence::CompareKind
4128 CompareQualificationConversions(Sema &S,
4129                                 const StandardConversionSequence& SCS1,
4130                                 const StandardConversionSequence& SCS2) {
4131   // C++ 13.3.3.2p3:
4132   //  -- S1 and S2 differ only in their qualification conversion and
4133   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4134   //     cv-qualification signature of type T1 is a proper subset of
4135   //     the cv-qualification signature of type T2, and S1 is not the
4136   //     deprecated string literal array-to-pointer conversion (4.2).
4137   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4138       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4139     return ImplicitConversionSequence::Indistinguishable;
4140 
4141   // FIXME: the example in the standard doesn't use a qualification
4142   // conversion (!)
4143   QualType T1 = SCS1.getToType(2);
4144   QualType T2 = SCS2.getToType(2);
4145   T1 = S.Context.getCanonicalType(T1);
4146   T2 = S.Context.getCanonicalType(T2);
4147   assert(!T1->isReferenceType() && !T2->isReferenceType());
4148   Qualifiers T1Quals, T2Quals;
4149   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4150   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4151 
4152   // If the types are the same, we won't learn anything by unwrapping
4153   // them.
4154   if (UnqualT1 == UnqualT2)
4155     return ImplicitConversionSequence::Indistinguishable;
4156 
4157   ImplicitConversionSequence::CompareKind Result
4158     = ImplicitConversionSequence::Indistinguishable;
4159 
4160   // Objective-C++ ARC:
4161   //   Prefer qualification conversions not involving a change in lifetime
4162   //   to qualification conversions that do not change lifetime.
4163   if (SCS1.QualificationIncludesObjCLifetime !=
4164                                       SCS2.QualificationIncludesObjCLifetime) {
4165     Result = SCS1.QualificationIncludesObjCLifetime
4166                ? ImplicitConversionSequence::Worse
4167                : ImplicitConversionSequence::Better;
4168   }
4169 
4170   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4171     // Within each iteration of the loop, we check the qualifiers to
4172     // determine if this still looks like a qualification
4173     // conversion. Then, if all is well, we unwrap one more level of
4174     // pointers or pointers-to-members and do it all again
4175     // until there are no more pointers or pointers-to-members left
4176     // to unwrap. This essentially mimics what
4177     // IsQualificationConversion does, but here we're checking for a
4178     // strict subset of qualifiers.
4179     if (T1.getQualifiers().withoutObjCLifetime() ==
4180         T2.getQualifiers().withoutObjCLifetime())
4181       // The qualifiers are the same, so this doesn't tell us anything
4182       // about how the sequences rank.
4183       // ObjC ownership quals are omitted above as they interfere with
4184       // the ARC overload rule.
4185       ;
4186     else if (T2.isMoreQualifiedThan(T1)) {
4187       // T1 has fewer qualifiers, so it could be the better sequence.
4188       if (Result == ImplicitConversionSequence::Worse)
4189         // Neither has qualifiers that are a subset of the other's
4190         // qualifiers.
4191         return ImplicitConversionSequence::Indistinguishable;
4192 
4193       Result = ImplicitConversionSequence::Better;
4194     } else if (T1.isMoreQualifiedThan(T2)) {
4195       // T2 has fewer qualifiers, so it could be the better sequence.
4196       if (Result == ImplicitConversionSequence::Better)
4197         // Neither has qualifiers that are a subset of the other's
4198         // qualifiers.
4199         return ImplicitConversionSequence::Indistinguishable;
4200 
4201       Result = ImplicitConversionSequence::Worse;
4202     } else {
4203       // Qualifiers are disjoint.
4204       return ImplicitConversionSequence::Indistinguishable;
4205     }
4206 
4207     // If the types after this point are equivalent, we're done.
4208     if (S.Context.hasSameUnqualifiedType(T1, T2))
4209       break;
4210   }
4211 
4212   // Check that the winning standard conversion sequence isn't using
4213   // the deprecated string literal array to pointer conversion.
4214   switch (Result) {
4215   case ImplicitConversionSequence::Better:
4216     if (SCS1.DeprecatedStringLiteralToCharPtr)
4217       Result = ImplicitConversionSequence::Indistinguishable;
4218     break;
4219 
4220   case ImplicitConversionSequence::Indistinguishable:
4221     break;
4222 
4223   case ImplicitConversionSequence::Worse:
4224     if (SCS2.DeprecatedStringLiteralToCharPtr)
4225       Result = ImplicitConversionSequence::Indistinguishable;
4226     break;
4227   }
4228 
4229   return Result;
4230 }
4231 
4232 /// CompareDerivedToBaseConversions - Compares two standard conversion
4233 /// sequences to determine whether they can be ranked based on their
4234 /// various kinds of derived-to-base conversions (C++
4235 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4236 /// conversions between Objective-C interface types.
4237 static ImplicitConversionSequence::CompareKind
4238 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4239                                 const StandardConversionSequence& SCS1,
4240                                 const StandardConversionSequence& SCS2) {
4241   QualType FromType1 = SCS1.getFromType();
4242   QualType ToType1 = SCS1.getToType(1);
4243   QualType FromType2 = SCS2.getFromType();
4244   QualType ToType2 = SCS2.getToType(1);
4245 
4246   // Adjust the types we're converting from via the array-to-pointer
4247   // conversion, if we need to.
4248   if (SCS1.First == ICK_Array_To_Pointer)
4249     FromType1 = S.Context.getArrayDecayedType(FromType1);
4250   if (SCS2.First == ICK_Array_To_Pointer)
4251     FromType2 = S.Context.getArrayDecayedType(FromType2);
4252 
4253   // Canonicalize all of the types.
4254   FromType1 = S.Context.getCanonicalType(FromType1);
4255   ToType1 = S.Context.getCanonicalType(ToType1);
4256   FromType2 = S.Context.getCanonicalType(FromType2);
4257   ToType2 = S.Context.getCanonicalType(ToType2);
4258 
4259   // C++ [over.ics.rank]p4b3:
4260   //
4261   //   If class B is derived directly or indirectly from class A and
4262   //   class C is derived directly or indirectly from B,
4263   //
4264   // Compare based on pointer conversions.
4265   if (SCS1.Second == ICK_Pointer_Conversion &&
4266       SCS2.Second == ICK_Pointer_Conversion &&
4267       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4268       FromType1->isPointerType() && FromType2->isPointerType() &&
4269       ToType1->isPointerType() && ToType2->isPointerType()) {
4270     QualType FromPointee1 =
4271         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4272     QualType ToPointee1 =
4273         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4274     QualType FromPointee2 =
4275         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4276     QualType ToPointee2 =
4277         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4278 
4279     //   -- conversion of C* to B* is better than conversion of C* to A*,
4280     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4281       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4282         return ImplicitConversionSequence::Better;
4283       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4284         return ImplicitConversionSequence::Worse;
4285     }
4286 
4287     //   -- conversion of B* to A* is better than conversion of C* to A*,
4288     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4289       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4290         return ImplicitConversionSequence::Better;
4291       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4292         return ImplicitConversionSequence::Worse;
4293     }
4294   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4295              SCS2.Second == ICK_Pointer_Conversion) {
4296     const ObjCObjectPointerType *FromPtr1
4297       = FromType1->getAs<ObjCObjectPointerType>();
4298     const ObjCObjectPointerType *FromPtr2
4299       = FromType2->getAs<ObjCObjectPointerType>();
4300     const ObjCObjectPointerType *ToPtr1
4301       = ToType1->getAs<ObjCObjectPointerType>();
4302     const ObjCObjectPointerType *ToPtr2
4303       = ToType2->getAs<ObjCObjectPointerType>();
4304 
4305     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4306       // Apply the same conversion ranking rules for Objective-C pointer types
4307       // that we do for C++ pointers to class types. However, we employ the
4308       // Objective-C pseudo-subtyping relationship used for assignment of
4309       // Objective-C pointer types.
4310       bool FromAssignLeft
4311         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4312       bool FromAssignRight
4313         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4314       bool ToAssignLeft
4315         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4316       bool ToAssignRight
4317         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4318 
4319       // A conversion to an a non-id object pointer type or qualified 'id'
4320       // type is better than a conversion to 'id'.
4321       if (ToPtr1->isObjCIdType() &&
4322           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4323         return ImplicitConversionSequence::Worse;
4324       if (ToPtr2->isObjCIdType() &&
4325           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4326         return ImplicitConversionSequence::Better;
4327 
4328       // A conversion to a non-id object pointer type is better than a
4329       // conversion to a qualified 'id' type
4330       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4331         return ImplicitConversionSequence::Worse;
4332       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4333         return ImplicitConversionSequence::Better;
4334 
4335       // A conversion to an a non-Class object pointer type or qualified 'Class'
4336       // type is better than a conversion to 'Class'.
4337       if (ToPtr1->isObjCClassType() &&
4338           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4339         return ImplicitConversionSequence::Worse;
4340       if (ToPtr2->isObjCClassType() &&
4341           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4342         return ImplicitConversionSequence::Better;
4343 
4344       // A conversion to a non-Class object pointer type is better than a
4345       // conversion to a qualified 'Class' type.
4346       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4347         return ImplicitConversionSequence::Worse;
4348       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4349         return ImplicitConversionSequence::Better;
4350 
4351       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4352       if (S.Context.hasSameType(FromType1, FromType2) &&
4353           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4354           (ToAssignLeft != ToAssignRight)) {
4355         if (FromPtr1->isSpecialized()) {
4356           // "conversion of B<A> * to B * is better than conversion of B * to
4357           // C *.
4358           bool IsFirstSame =
4359               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4360           bool IsSecondSame =
4361               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4362           if (IsFirstSame) {
4363             if (!IsSecondSame)
4364               return ImplicitConversionSequence::Better;
4365           } else if (IsSecondSame)
4366             return ImplicitConversionSequence::Worse;
4367         }
4368         return ToAssignLeft? ImplicitConversionSequence::Worse
4369                            : ImplicitConversionSequence::Better;
4370       }
4371 
4372       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4373       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4374           (FromAssignLeft != FromAssignRight))
4375         return FromAssignLeft? ImplicitConversionSequence::Better
4376         : ImplicitConversionSequence::Worse;
4377     }
4378   }
4379 
4380   // Ranking of member-pointer types.
4381   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4382       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4383       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4384     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4385     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4386     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4387     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4388     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4389     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4390     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4391     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4392     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4393     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4394     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4395     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4396     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4397     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4398       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4399         return ImplicitConversionSequence::Worse;
4400       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4401         return ImplicitConversionSequence::Better;
4402     }
4403     // conversion of B::* to C::* is better than conversion of A::* to C::*
4404     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4405       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4406         return ImplicitConversionSequence::Better;
4407       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4408         return ImplicitConversionSequence::Worse;
4409     }
4410   }
4411 
4412   if (SCS1.Second == ICK_Derived_To_Base) {
4413     //   -- conversion of C to B is better than conversion of C to A,
4414     //   -- binding of an expression of type C to a reference of type
4415     //      B& is better than binding an expression of type C to a
4416     //      reference of type A&,
4417     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4418         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4419       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4420         return ImplicitConversionSequence::Better;
4421       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4422         return ImplicitConversionSequence::Worse;
4423     }
4424 
4425     //   -- conversion of B to A is better than conversion of C to A.
4426     //   -- binding of an expression of type B to a reference of type
4427     //      A& is better than binding an expression of type C to a
4428     //      reference of type A&,
4429     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4430         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4431       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4432         return ImplicitConversionSequence::Better;
4433       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4434         return ImplicitConversionSequence::Worse;
4435     }
4436   }
4437 
4438   return ImplicitConversionSequence::Indistinguishable;
4439 }
4440 
4441 /// Determine whether the given type is valid, e.g., it is not an invalid
4442 /// C++ class.
4443 static bool isTypeValid(QualType T) {
4444   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4445     return !Record->isInvalidDecl();
4446 
4447   return true;
4448 }
4449 
4450 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4451   if (!T.getQualifiers().hasUnaligned())
4452     return T;
4453 
4454   Qualifiers Q;
4455   T = Ctx.getUnqualifiedArrayType(T, Q);
4456   Q.removeUnaligned();
4457   return Ctx.getQualifiedType(T, Q);
4458 }
4459 
4460 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4461 /// determine whether they are reference-compatible,
4462 /// reference-related, or incompatible, for use in C++ initialization by
4463 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4464 /// type, and the first type (T1) is the pointee type of the reference
4465 /// type being initialized.
4466 Sema::ReferenceCompareResult
4467 Sema::CompareReferenceRelationship(SourceLocation Loc,
4468                                    QualType OrigT1, QualType OrigT2,
4469                                    ReferenceConversions *ConvOut) {
4470   assert(!OrigT1->isReferenceType() &&
4471     "T1 must be the pointee type of the reference type");
4472   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4473 
4474   QualType T1 = Context.getCanonicalType(OrigT1);
4475   QualType T2 = Context.getCanonicalType(OrigT2);
4476   Qualifiers T1Quals, T2Quals;
4477   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4478   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4479 
4480   ReferenceConversions ConvTmp;
4481   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4482   Conv = ReferenceConversions();
4483 
4484   // C++2a [dcl.init.ref]p4:
4485   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4486   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4487   //   T1 is a base class of T2.
4488   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4489   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4490   //   "pointer to cv1 T1" via a standard conversion sequence.
4491 
4492   // Check for standard conversions we can apply to pointers: derived-to-base
4493   // conversions, ObjC pointer conversions, and function pointer conversions.
4494   // (Qualification conversions are checked last.)
4495   QualType ConvertedT2;
4496   if (UnqualT1 == UnqualT2) {
4497     // Nothing to do.
4498   } else if (isCompleteType(Loc, OrigT2) &&
4499              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4500              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4501     Conv |= ReferenceConversions::DerivedToBase;
4502   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4503            UnqualT2->isObjCObjectOrInterfaceType() &&
4504            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4505     Conv |= ReferenceConversions::ObjC;
4506   else if (UnqualT2->isFunctionType() &&
4507            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4508     Conv |= ReferenceConversions::Function;
4509     // No need to check qualifiers; function types don't have them.
4510     return Ref_Compatible;
4511   }
4512   bool ConvertedReferent = Conv != 0;
4513 
4514   // We can have a qualification conversion. Compute whether the types are
4515   // similar at the same time.
4516   bool PreviousToQualsIncludeConst = true;
4517   bool TopLevel = true;
4518   do {
4519     if (T1 == T2)
4520       break;
4521 
4522     // We will need a qualification conversion.
4523     Conv |= ReferenceConversions::Qualification;
4524 
4525     // Track whether we performed a qualification conversion anywhere other
4526     // than the top level. This matters for ranking reference bindings in
4527     // overload resolution.
4528     if (!TopLevel)
4529       Conv |= ReferenceConversions::NestedQualification;
4530 
4531     // MS compiler ignores __unaligned qualifier for references; do the same.
4532     T1 = withoutUnaligned(Context, T1);
4533     T2 = withoutUnaligned(Context, T2);
4534 
4535     // If we find a qualifier mismatch, the types are not reference-compatible,
4536     // but are still be reference-related if they're similar.
4537     bool ObjCLifetimeConversion = false;
4538     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4539                                        PreviousToQualsIncludeConst,
4540                                        ObjCLifetimeConversion))
4541       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4542                  ? Ref_Related
4543                  : Ref_Incompatible;
4544 
4545     // FIXME: Should we track this for any level other than the first?
4546     if (ObjCLifetimeConversion)
4547       Conv |= ReferenceConversions::ObjCLifetime;
4548 
4549     TopLevel = false;
4550   } while (Context.UnwrapSimilarTypes(T1, T2));
4551 
4552   // At this point, if the types are reference-related, we must either have the
4553   // same inner type (ignoring qualifiers), or must have already worked out how
4554   // to convert the referent.
4555   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4556              ? Ref_Compatible
4557              : Ref_Incompatible;
4558 }
4559 
4560 /// Look for a user-defined conversion to a value reference-compatible
4561 ///        with DeclType. Return true if something definite is found.
4562 static bool
4563 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4564                          QualType DeclType, SourceLocation DeclLoc,
4565                          Expr *Init, QualType T2, bool AllowRvalues,
4566                          bool AllowExplicit) {
4567   assert(T2->isRecordType() && "Can only find conversions of record types.");
4568   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4569 
4570   OverloadCandidateSet CandidateSet(
4571       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4572   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4573   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4574     NamedDecl *D = *I;
4575     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4576     if (isa<UsingShadowDecl>(D))
4577       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4578 
4579     FunctionTemplateDecl *ConvTemplate
4580       = dyn_cast<FunctionTemplateDecl>(D);
4581     CXXConversionDecl *Conv;
4582     if (ConvTemplate)
4583       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4584     else
4585       Conv = cast<CXXConversionDecl>(D);
4586 
4587     if (AllowRvalues) {
4588       // If we are initializing an rvalue reference, don't permit conversion
4589       // functions that return lvalues.
4590       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4591         const ReferenceType *RefType
4592           = Conv->getConversionType()->getAs<LValueReferenceType>();
4593         if (RefType && !RefType->getPointeeType()->isFunctionType())
4594           continue;
4595       }
4596 
4597       if (!ConvTemplate &&
4598           S.CompareReferenceRelationship(
4599               DeclLoc,
4600               Conv->getConversionType()
4601                   .getNonReferenceType()
4602                   .getUnqualifiedType(),
4603               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4604               Sema::Ref_Incompatible)
4605         continue;
4606     } else {
4607       // If the conversion function doesn't return a reference type,
4608       // it can't be considered for this conversion. An rvalue reference
4609       // is only acceptable if its referencee is a function type.
4610 
4611       const ReferenceType *RefType =
4612         Conv->getConversionType()->getAs<ReferenceType>();
4613       if (!RefType ||
4614           (!RefType->isLValueReferenceType() &&
4615            !RefType->getPointeeType()->isFunctionType()))
4616         continue;
4617     }
4618 
4619     if (ConvTemplate)
4620       S.AddTemplateConversionCandidate(
4621           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4622           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4623     else
4624       S.AddConversionCandidate(
4625           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4626           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4627   }
4628 
4629   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4630 
4631   OverloadCandidateSet::iterator Best;
4632   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4633   case OR_Success:
4634     // C++ [over.ics.ref]p1:
4635     //
4636     //   [...] If the parameter binds directly to the result of
4637     //   applying a conversion function to the argument
4638     //   expression, the implicit conversion sequence is a
4639     //   user-defined conversion sequence (13.3.3.1.2), with the
4640     //   second standard conversion sequence either an identity
4641     //   conversion or, if the conversion function returns an
4642     //   entity of a type that is a derived class of the parameter
4643     //   type, a derived-to-base Conversion.
4644     if (!Best->FinalConversion.DirectBinding)
4645       return false;
4646 
4647     ICS.setUserDefined();
4648     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4649     ICS.UserDefined.After = Best->FinalConversion;
4650     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4651     ICS.UserDefined.ConversionFunction = Best->Function;
4652     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4653     ICS.UserDefined.EllipsisConversion = false;
4654     assert(ICS.UserDefined.After.ReferenceBinding &&
4655            ICS.UserDefined.After.DirectBinding &&
4656            "Expected a direct reference binding!");
4657     return true;
4658 
4659   case OR_Ambiguous:
4660     ICS.setAmbiguous();
4661     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4662          Cand != CandidateSet.end(); ++Cand)
4663       if (Cand->Best)
4664         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4665     return true;
4666 
4667   case OR_No_Viable_Function:
4668   case OR_Deleted:
4669     // There was no suitable conversion, or we found a deleted
4670     // conversion; continue with other checks.
4671     return false;
4672   }
4673 
4674   llvm_unreachable("Invalid OverloadResult!");
4675 }
4676 
4677 /// Compute an implicit conversion sequence for reference
4678 /// initialization.
4679 static ImplicitConversionSequence
4680 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4681                  SourceLocation DeclLoc,
4682                  bool SuppressUserConversions,
4683                  bool AllowExplicit) {
4684   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4685 
4686   // Most paths end in a failed conversion.
4687   ImplicitConversionSequence ICS;
4688   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4689 
4690   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4691   QualType T2 = Init->getType();
4692 
4693   // If the initializer is the address of an overloaded function, try
4694   // to resolve the overloaded function. If all goes well, T2 is the
4695   // type of the resulting function.
4696   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4697     DeclAccessPair Found;
4698     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4699                                                                 false, Found))
4700       T2 = Fn->getType();
4701   }
4702 
4703   // Compute some basic properties of the types and the initializer.
4704   bool isRValRef = DeclType->isRValueReferenceType();
4705   Expr::Classification InitCategory = Init->Classify(S.Context);
4706 
4707   Sema::ReferenceConversions RefConv;
4708   Sema::ReferenceCompareResult RefRelationship =
4709       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4710 
4711   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4712     ICS.setStandard();
4713     ICS.Standard.First = ICK_Identity;
4714     // FIXME: A reference binding can be a function conversion too. We should
4715     // consider that when ordering reference-to-function bindings.
4716     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4717                               ? ICK_Derived_To_Base
4718                               : (RefConv & Sema::ReferenceConversions::ObjC)
4719                                     ? ICK_Compatible_Conversion
4720                                     : ICK_Identity;
4721     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4722     // a reference binding that performs a non-top-level qualification
4723     // conversion as a qualification conversion, not as an identity conversion.
4724     ICS.Standard.Third = (RefConv &
4725                               Sema::ReferenceConversions::NestedQualification)
4726                              ? ICK_Qualification
4727                              : ICK_Identity;
4728     ICS.Standard.setFromType(T2);
4729     ICS.Standard.setToType(0, T2);
4730     ICS.Standard.setToType(1, T1);
4731     ICS.Standard.setToType(2, T1);
4732     ICS.Standard.ReferenceBinding = true;
4733     ICS.Standard.DirectBinding = BindsDirectly;
4734     ICS.Standard.IsLvalueReference = !isRValRef;
4735     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4736     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4737     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4738     ICS.Standard.ObjCLifetimeConversionBinding =
4739         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4740     ICS.Standard.CopyConstructor = nullptr;
4741     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4742   };
4743 
4744   // C++0x [dcl.init.ref]p5:
4745   //   A reference to type "cv1 T1" is initialized by an expression
4746   //   of type "cv2 T2" as follows:
4747 
4748   //     -- If reference is an lvalue reference and the initializer expression
4749   if (!isRValRef) {
4750     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4751     //        reference-compatible with "cv2 T2," or
4752     //
4753     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4754     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4755       // C++ [over.ics.ref]p1:
4756       //   When a parameter of reference type binds directly (8.5.3)
4757       //   to an argument expression, the implicit conversion sequence
4758       //   is the identity conversion, unless the argument expression
4759       //   has a type that is a derived class of the parameter type,
4760       //   in which case the implicit conversion sequence is a
4761       //   derived-to-base Conversion (13.3.3.1).
4762       SetAsReferenceBinding(/*BindsDirectly=*/true);
4763 
4764       // Nothing more to do: the inaccessibility/ambiguity check for
4765       // derived-to-base conversions is suppressed when we're
4766       // computing the implicit conversion sequence (C++
4767       // [over.best.ics]p2).
4768       return ICS;
4769     }
4770 
4771     //       -- has a class type (i.e., T2 is a class type), where T1 is
4772     //          not reference-related to T2, and can be implicitly
4773     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4774     //          is reference-compatible with "cv3 T3" 92) (this
4775     //          conversion is selected by enumerating the applicable
4776     //          conversion functions (13.3.1.6) and choosing the best
4777     //          one through overload resolution (13.3)),
4778     if (!SuppressUserConversions && T2->isRecordType() &&
4779         S.isCompleteType(DeclLoc, T2) &&
4780         RefRelationship == Sema::Ref_Incompatible) {
4781       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4782                                    Init, T2, /*AllowRvalues=*/false,
4783                                    AllowExplicit))
4784         return ICS;
4785     }
4786   }
4787 
4788   //     -- Otherwise, the reference shall be an lvalue reference to a
4789   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4790   //        shall be an rvalue reference.
4791   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4792     return ICS;
4793 
4794   //       -- If the initializer expression
4795   //
4796   //            -- is an xvalue, class prvalue, array prvalue or function
4797   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4798   if (RefRelationship == Sema::Ref_Compatible &&
4799       (InitCategory.isXValue() ||
4800        (InitCategory.isPRValue() &&
4801           (T2->isRecordType() || T2->isArrayType())) ||
4802        (InitCategory.isLValue() && T2->isFunctionType()))) {
4803     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4804     // binding unless we're binding to a class prvalue.
4805     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4806     // allow the use of rvalue references in C++98/03 for the benefit of
4807     // standard library implementors; therefore, we need the xvalue check here.
4808     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4809                           !(InitCategory.isPRValue() || T2->isRecordType()));
4810     return ICS;
4811   }
4812 
4813   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4814   //               reference-related to T2, and can be implicitly converted to
4815   //               an xvalue, class prvalue, or function lvalue of type
4816   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4817   //               "cv3 T3",
4818   //
4819   //          then the reference is bound to the value of the initializer
4820   //          expression in the first case and to the result of the conversion
4821   //          in the second case (or, in either case, to an appropriate base
4822   //          class subobject).
4823   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4824       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4825       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4826                                Init, T2, /*AllowRvalues=*/true,
4827                                AllowExplicit)) {
4828     // In the second case, if the reference is an rvalue reference
4829     // and the second standard conversion sequence of the
4830     // user-defined conversion sequence includes an lvalue-to-rvalue
4831     // conversion, the program is ill-formed.
4832     if (ICS.isUserDefined() && isRValRef &&
4833         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4834       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4835 
4836     return ICS;
4837   }
4838 
4839   // A temporary of function type cannot be created; don't even try.
4840   if (T1->isFunctionType())
4841     return ICS;
4842 
4843   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4844   //          initialized from the initializer expression using the
4845   //          rules for a non-reference copy initialization (8.5). The
4846   //          reference is then bound to the temporary. If T1 is
4847   //          reference-related to T2, cv1 must be the same
4848   //          cv-qualification as, or greater cv-qualification than,
4849   //          cv2; otherwise, the program is ill-formed.
4850   if (RefRelationship == Sema::Ref_Related) {
4851     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4852     // we would be reference-compatible or reference-compatible with
4853     // added qualification. But that wasn't the case, so the reference
4854     // initialization fails.
4855     //
4856     // Note that we only want to check address spaces and cvr-qualifiers here.
4857     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4858     Qualifiers T1Quals = T1.getQualifiers();
4859     Qualifiers T2Quals = T2.getQualifiers();
4860     T1Quals.removeObjCGCAttr();
4861     T1Quals.removeObjCLifetime();
4862     T2Quals.removeObjCGCAttr();
4863     T2Quals.removeObjCLifetime();
4864     // MS compiler ignores __unaligned qualifier for references; do the same.
4865     T1Quals.removeUnaligned();
4866     T2Quals.removeUnaligned();
4867     if (!T1Quals.compatiblyIncludes(T2Quals))
4868       return ICS;
4869   }
4870 
4871   // If at least one of the types is a class type, the types are not
4872   // related, and we aren't allowed any user conversions, the
4873   // reference binding fails. This case is important for breaking
4874   // recursion, since TryImplicitConversion below will attempt to
4875   // create a temporary through the use of a copy constructor.
4876   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4877       (T1->isRecordType() || T2->isRecordType()))
4878     return ICS;
4879 
4880   // If T1 is reference-related to T2 and the reference is an rvalue
4881   // reference, the initializer expression shall not be an lvalue.
4882   if (RefRelationship >= Sema::Ref_Related &&
4883       isRValRef && Init->Classify(S.Context).isLValue())
4884     return ICS;
4885 
4886   // C++ [over.ics.ref]p2:
4887   //   When a parameter of reference type is not bound directly to
4888   //   an argument expression, the conversion sequence is the one
4889   //   required to convert the argument expression to the
4890   //   underlying type of the reference according to
4891   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4892   //   to copy-initializing a temporary of the underlying type with
4893   //   the argument expression. Any difference in top-level
4894   //   cv-qualification is subsumed by the initialization itself
4895   //   and does not constitute a conversion.
4896   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4897                               AllowedExplicit::None,
4898                               /*InOverloadResolution=*/false,
4899                               /*CStyle=*/false,
4900                               /*AllowObjCWritebackConversion=*/false,
4901                               /*AllowObjCConversionOnExplicit=*/false);
4902 
4903   // Of course, that's still a reference binding.
4904   if (ICS.isStandard()) {
4905     ICS.Standard.ReferenceBinding = true;
4906     ICS.Standard.IsLvalueReference = !isRValRef;
4907     ICS.Standard.BindsToFunctionLvalue = false;
4908     ICS.Standard.BindsToRvalue = true;
4909     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4910     ICS.Standard.ObjCLifetimeConversionBinding = false;
4911   } else if (ICS.isUserDefined()) {
4912     const ReferenceType *LValRefType =
4913         ICS.UserDefined.ConversionFunction->getReturnType()
4914             ->getAs<LValueReferenceType>();
4915 
4916     // C++ [over.ics.ref]p3:
4917     //   Except for an implicit object parameter, for which see 13.3.1, a
4918     //   standard conversion sequence cannot be formed if it requires [...]
4919     //   binding an rvalue reference to an lvalue other than a function
4920     //   lvalue.
4921     // Note that the function case is not possible here.
4922     if (DeclType->isRValueReferenceType() && LValRefType) {
4923       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4924       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4925       // reference to an rvalue!
4926       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4927       return ICS;
4928     }
4929 
4930     ICS.UserDefined.After.ReferenceBinding = true;
4931     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4932     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4933     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4934     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4935     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4936   }
4937 
4938   return ICS;
4939 }
4940 
4941 static ImplicitConversionSequence
4942 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4943                       bool SuppressUserConversions,
4944                       bool InOverloadResolution,
4945                       bool AllowObjCWritebackConversion,
4946                       bool AllowExplicit = false);
4947 
4948 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4949 /// initializer list From.
4950 static ImplicitConversionSequence
4951 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4952                   bool SuppressUserConversions,
4953                   bool InOverloadResolution,
4954                   bool AllowObjCWritebackConversion) {
4955   // C++11 [over.ics.list]p1:
4956   //   When an argument is an initializer list, it is not an expression and
4957   //   special rules apply for converting it to a parameter type.
4958 
4959   ImplicitConversionSequence Result;
4960   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4961 
4962   // We need a complete type for what follows. Incomplete types can never be
4963   // initialized from init lists.
4964   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4965     return Result;
4966 
4967   // Per DR1467:
4968   //   If the parameter type is a class X and the initializer list has a single
4969   //   element of type cv U, where U is X or a class derived from X, the
4970   //   implicit conversion sequence is the one required to convert the element
4971   //   to the parameter type.
4972   //
4973   //   Otherwise, if the parameter type is a character array [... ]
4974   //   and the initializer list has a single element that is an
4975   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4976   //   implicit conversion sequence is the identity conversion.
4977   if (From->getNumInits() == 1) {
4978     if (ToType->isRecordType()) {
4979       QualType InitType = From->getInit(0)->getType();
4980       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4981           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4982         return TryCopyInitialization(S, From->getInit(0), ToType,
4983                                      SuppressUserConversions,
4984                                      InOverloadResolution,
4985                                      AllowObjCWritebackConversion);
4986     }
4987     // FIXME: Check the other conditions here: array of character type,
4988     // initializer is a string literal.
4989     if (ToType->isArrayType()) {
4990       InitializedEntity Entity =
4991         InitializedEntity::InitializeParameter(S.Context, ToType,
4992                                                /*Consumed=*/false);
4993       if (S.CanPerformCopyInitialization(Entity, From)) {
4994         Result.setStandard();
4995         Result.Standard.setAsIdentityConversion();
4996         Result.Standard.setFromType(ToType);
4997         Result.Standard.setAllToTypes(ToType);
4998         return Result;
4999       }
5000     }
5001   }
5002 
5003   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5004   // C++11 [over.ics.list]p2:
5005   //   If the parameter type is std::initializer_list<X> or "array of X" and
5006   //   all the elements can be implicitly converted to X, the implicit
5007   //   conversion sequence is the worst conversion necessary to convert an
5008   //   element of the list to X.
5009   //
5010   // C++14 [over.ics.list]p3:
5011   //   Otherwise, if the parameter type is "array of N X", if the initializer
5012   //   list has exactly N elements or if it has fewer than N elements and X is
5013   //   default-constructible, and if all the elements of the initializer list
5014   //   can be implicitly converted to X, the implicit conversion sequence is
5015   //   the worst conversion necessary to convert an element of the list to X.
5016   //
5017   // FIXME: We're missing a lot of these checks.
5018   bool toStdInitializerList = false;
5019   QualType X;
5020   if (ToType->isArrayType())
5021     X = S.Context.getAsArrayType(ToType)->getElementType();
5022   else
5023     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5024   if (!X.isNull()) {
5025     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5026       Expr *Init = From->getInit(i);
5027       ImplicitConversionSequence ICS =
5028           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5029                                 InOverloadResolution,
5030                                 AllowObjCWritebackConversion);
5031       // If a single element isn't convertible, fail.
5032       if (ICS.isBad()) {
5033         Result = ICS;
5034         break;
5035       }
5036       // Otherwise, look for the worst conversion.
5037       if (Result.isBad() || CompareImplicitConversionSequences(
5038                                 S, From->getBeginLoc(), ICS, Result) ==
5039                                 ImplicitConversionSequence::Worse)
5040         Result = ICS;
5041     }
5042 
5043     // For an empty list, we won't have computed any conversion sequence.
5044     // Introduce the identity conversion sequence.
5045     if (From->getNumInits() == 0) {
5046       Result.setStandard();
5047       Result.Standard.setAsIdentityConversion();
5048       Result.Standard.setFromType(ToType);
5049       Result.Standard.setAllToTypes(ToType);
5050     }
5051 
5052     Result.setStdInitializerListElement(toStdInitializerList);
5053     return Result;
5054   }
5055 
5056   // C++14 [over.ics.list]p4:
5057   // C++11 [over.ics.list]p3:
5058   //   Otherwise, if the parameter is a non-aggregate class X and overload
5059   //   resolution chooses a single best constructor [...] the implicit
5060   //   conversion sequence is a user-defined conversion sequence. If multiple
5061   //   constructors are viable but none is better than the others, the
5062   //   implicit conversion sequence is a user-defined conversion sequence.
5063   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5064     // This function can deal with initializer lists.
5065     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5066                                     AllowedExplicit::None,
5067                                     InOverloadResolution, /*CStyle=*/false,
5068                                     AllowObjCWritebackConversion,
5069                                     /*AllowObjCConversionOnExplicit=*/false);
5070   }
5071 
5072   // C++14 [over.ics.list]p5:
5073   // C++11 [over.ics.list]p4:
5074   //   Otherwise, if the parameter has an aggregate type which can be
5075   //   initialized from the initializer list [...] the implicit conversion
5076   //   sequence is a user-defined conversion sequence.
5077   if (ToType->isAggregateType()) {
5078     // Type is an aggregate, argument is an init list. At this point it comes
5079     // down to checking whether the initialization works.
5080     // FIXME: Find out whether this parameter is consumed or not.
5081     InitializedEntity Entity =
5082         InitializedEntity::InitializeParameter(S.Context, ToType,
5083                                                /*Consumed=*/false);
5084     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5085                                                                  From)) {
5086       Result.setUserDefined();
5087       Result.UserDefined.Before.setAsIdentityConversion();
5088       // Initializer lists don't have a type.
5089       Result.UserDefined.Before.setFromType(QualType());
5090       Result.UserDefined.Before.setAllToTypes(QualType());
5091 
5092       Result.UserDefined.After.setAsIdentityConversion();
5093       Result.UserDefined.After.setFromType(ToType);
5094       Result.UserDefined.After.setAllToTypes(ToType);
5095       Result.UserDefined.ConversionFunction = nullptr;
5096     }
5097     return Result;
5098   }
5099 
5100   // C++14 [over.ics.list]p6:
5101   // C++11 [over.ics.list]p5:
5102   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5103   if (ToType->isReferenceType()) {
5104     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5105     // mention initializer lists in any way. So we go by what list-
5106     // initialization would do and try to extrapolate from that.
5107 
5108     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5109 
5110     // If the initializer list has a single element that is reference-related
5111     // to the parameter type, we initialize the reference from that.
5112     if (From->getNumInits() == 1) {
5113       Expr *Init = From->getInit(0);
5114 
5115       QualType T2 = Init->getType();
5116 
5117       // If the initializer is the address of an overloaded function, try
5118       // to resolve the overloaded function. If all goes well, T2 is the
5119       // type of the resulting function.
5120       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5121         DeclAccessPair Found;
5122         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5123                                    Init, ToType, false, Found))
5124           T2 = Fn->getType();
5125       }
5126 
5127       // Compute some basic properties of the types and the initializer.
5128       Sema::ReferenceCompareResult RefRelationship =
5129           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5130 
5131       if (RefRelationship >= Sema::Ref_Related) {
5132         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5133                                 SuppressUserConversions,
5134                                 /*AllowExplicit=*/false);
5135       }
5136     }
5137 
5138     // Otherwise, we bind the reference to a temporary created from the
5139     // initializer list.
5140     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5141                                InOverloadResolution,
5142                                AllowObjCWritebackConversion);
5143     if (Result.isFailure())
5144       return Result;
5145     assert(!Result.isEllipsis() &&
5146            "Sub-initialization cannot result in ellipsis conversion.");
5147 
5148     // Can we even bind to a temporary?
5149     if (ToType->isRValueReferenceType() ||
5150         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5151       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5152                                             Result.UserDefined.After;
5153       SCS.ReferenceBinding = true;
5154       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5155       SCS.BindsToRvalue = true;
5156       SCS.BindsToFunctionLvalue = false;
5157       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5158       SCS.ObjCLifetimeConversionBinding = false;
5159     } else
5160       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5161                     From, ToType);
5162     return Result;
5163   }
5164 
5165   // C++14 [over.ics.list]p7:
5166   // C++11 [over.ics.list]p6:
5167   //   Otherwise, if the parameter type is not a class:
5168   if (!ToType->isRecordType()) {
5169     //    - if the initializer list has one element that is not itself an
5170     //      initializer list, the implicit conversion sequence is the one
5171     //      required to convert the element to the parameter type.
5172     unsigned NumInits = From->getNumInits();
5173     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5174       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5175                                      SuppressUserConversions,
5176                                      InOverloadResolution,
5177                                      AllowObjCWritebackConversion);
5178     //    - if the initializer list has no elements, the implicit conversion
5179     //      sequence is the identity conversion.
5180     else if (NumInits == 0) {
5181       Result.setStandard();
5182       Result.Standard.setAsIdentityConversion();
5183       Result.Standard.setFromType(ToType);
5184       Result.Standard.setAllToTypes(ToType);
5185     }
5186     return Result;
5187   }
5188 
5189   // C++14 [over.ics.list]p8:
5190   // C++11 [over.ics.list]p7:
5191   //   In all cases other than those enumerated above, no conversion is possible
5192   return Result;
5193 }
5194 
5195 /// TryCopyInitialization - Try to copy-initialize a value of type
5196 /// ToType from the expression From. Return the implicit conversion
5197 /// sequence required to pass this argument, which may be a bad
5198 /// conversion sequence (meaning that the argument cannot be passed to
5199 /// a parameter of this type). If @p SuppressUserConversions, then we
5200 /// do not permit any user-defined conversion sequences.
5201 static ImplicitConversionSequence
5202 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5203                       bool SuppressUserConversions,
5204                       bool InOverloadResolution,
5205                       bool AllowObjCWritebackConversion,
5206                       bool AllowExplicit) {
5207   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5208     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5209                              InOverloadResolution,AllowObjCWritebackConversion);
5210 
5211   if (ToType->isReferenceType())
5212     return TryReferenceInit(S, From, ToType,
5213                             /*FIXME:*/ From->getBeginLoc(),
5214                             SuppressUserConversions, AllowExplicit);
5215 
5216   return TryImplicitConversion(S, From, ToType,
5217                                SuppressUserConversions,
5218                                AllowedExplicit::None,
5219                                InOverloadResolution,
5220                                /*CStyle=*/false,
5221                                AllowObjCWritebackConversion,
5222                                /*AllowObjCConversionOnExplicit=*/false);
5223 }
5224 
5225 static bool TryCopyInitialization(const CanQualType FromQTy,
5226                                   const CanQualType ToQTy,
5227                                   Sema &S,
5228                                   SourceLocation Loc,
5229                                   ExprValueKind FromVK) {
5230   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5231   ImplicitConversionSequence ICS =
5232     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5233 
5234   return !ICS.isBad();
5235 }
5236 
5237 /// TryObjectArgumentInitialization - Try to initialize the object
5238 /// parameter of the given member function (@c Method) from the
5239 /// expression @p From.
5240 static ImplicitConversionSequence
5241 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5242                                 Expr::Classification FromClassification,
5243                                 CXXMethodDecl *Method,
5244                                 CXXRecordDecl *ActingContext) {
5245   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5246   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5247   //                 const volatile object.
5248   Qualifiers Quals = Method->getMethodQualifiers();
5249   if (isa<CXXDestructorDecl>(Method)) {
5250     Quals.addConst();
5251     Quals.addVolatile();
5252   }
5253 
5254   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5255 
5256   // Set up the conversion sequence as a "bad" conversion, to allow us
5257   // to exit early.
5258   ImplicitConversionSequence ICS;
5259 
5260   // We need to have an object of class type.
5261   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5262     FromType = PT->getPointeeType();
5263 
5264     // When we had a pointer, it's implicitly dereferenced, so we
5265     // better have an lvalue.
5266     assert(FromClassification.isLValue());
5267   }
5268 
5269   assert(FromType->isRecordType());
5270 
5271   // C++0x [over.match.funcs]p4:
5272   //   For non-static member functions, the type of the implicit object
5273   //   parameter is
5274   //
5275   //     - "lvalue reference to cv X" for functions declared without a
5276   //        ref-qualifier or with the & ref-qualifier
5277   //     - "rvalue reference to cv X" for functions declared with the &&
5278   //        ref-qualifier
5279   //
5280   // where X is the class of which the function is a member and cv is the
5281   // cv-qualification on the member function declaration.
5282   //
5283   // However, when finding an implicit conversion sequence for the argument, we
5284   // are not allowed to perform user-defined conversions
5285   // (C++ [over.match.funcs]p5). We perform a simplified version of
5286   // reference binding here, that allows class rvalues to bind to
5287   // non-constant references.
5288 
5289   // First check the qualifiers.
5290   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5291   if (ImplicitParamType.getCVRQualifiers()
5292                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5293       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5294     ICS.setBad(BadConversionSequence::bad_qualifiers,
5295                FromType, ImplicitParamType);
5296     return ICS;
5297   }
5298 
5299   if (FromTypeCanon.hasAddressSpace()) {
5300     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5301     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5302     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5303       ICS.setBad(BadConversionSequence::bad_qualifiers,
5304                  FromType, ImplicitParamType);
5305       return ICS;
5306     }
5307   }
5308 
5309   // Check that we have either the same type or a derived type. It
5310   // affects the conversion rank.
5311   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5312   ImplicitConversionKind SecondKind;
5313   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5314     SecondKind = ICK_Identity;
5315   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5316     SecondKind = ICK_Derived_To_Base;
5317   else {
5318     ICS.setBad(BadConversionSequence::unrelated_class,
5319                FromType, ImplicitParamType);
5320     return ICS;
5321   }
5322 
5323   // Check the ref-qualifier.
5324   switch (Method->getRefQualifier()) {
5325   case RQ_None:
5326     // Do nothing; we don't care about lvalueness or rvalueness.
5327     break;
5328 
5329   case RQ_LValue:
5330     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5331       // non-const lvalue reference cannot bind to an rvalue
5332       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5333                  ImplicitParamType);
5334       return ICS;
5335     }
5336     break;
5337 
5338   case RQ_RValue:
5339     if (!FromClassification.isRValue()) {
5340       // rvalue reference cannot bind to an lvalue
5341       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5342                  ImplicitParamType);
5343       return ICS;
5344     }
5345     break;
5346   }
5347 
5348   // Success. Mark this as a reference binding.
5349   ICS.setStandard();
5350   ICS.Standard.setAsIdentityConversion();
5351   ICS.Standard.Second = SecondKind;
5352   ICS.Standard.setFromType(FromType);
5353   ICS.Standard.setAllToTypes(ImplicitParamType);
5354   ICS.Standard.ReferenceBinding = true;
5355   ICS.Standard.DirectBinding = true;
5356   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5357   ICS.Standard.BindsToFunctionLvalue = false;
5358   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5359   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5360     = (Method->getRefQualifier() == RQ_None);
5361   return ICS;
5362 }
5363 
5364 /// PerformObjectArgumentInitialization - Perform initialization of
5365 /// the implicit object parameter for the given Method with the given
5366 /// expression.
5367 ExprResult
5368 Sema::PerformObjectArgumentInitialization(Expr *From,
5369                                           NestedNameSpecifier *Qualifier,
5370                                           NamedDecl *FoundDecl,
5371                                           CXXMethodDecl *Method) {
5372   QualType FromRecordType, DestType;
5373   QualType ImplicitParamRecordType  =
5374     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5375 
5376   Expr::Classification FromClassification;
5377   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5378     FromRecordType = PT->getPointeeType();
5379     DestType = Method->getThisType();
5380     FromClassification = Expr::Classification::makeSimpleLValue();
5381   } else {
5382     FromRecordType = From->getType();
5383     DestType = ImplicitParamRecordType;
5384     FromClassification = From->Classify(Context);
5385 
5386     // When performing member access on an rvalue, materialize a temporary.
5387     if (From->isRValue()) {
5388       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5389                                             Method->getRefQualifier() !=
5390                                                 RefQualifierKind::RQ_RValue);
5391     }
5392   }
5393 
5394   // Note that we always use the true parent context when performing
5395   // the actual argument initialization.
5396   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5397       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5398       Method->getParent());
5399   if (ICS.isBad()) {
5400     switch (ICS.Bad.Kind) {
5401     case BadConversionSequence::bad_qualifiers: {
5402       Qualifiers FromQs = FromRecordType.getQualifiers();
5403       Qualifiers ToQs = DestType.getQualifiers();
5404       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5405       if (CVR) {
5406         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5407             << Method->getDeclName() << FromRecordType << (CVR - 1)
5408             << From->getSourceRange();
5409         Diag(Method->getLocation(), diag::note_previous_decl)
5410           << Method->getDeclName();
5411         return ExprError();
5412       }
5413       break;
5414     }
5415 
5416     case BadConversionSequence::lvalue_ref_to_rvalue:
5417     case BadConversionSequence::rvalue_ref_to_lvalue: {
5418       bool IsRValueQualified =
5419         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5420       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5421           << Method->getDeclName() << FromClassification.isRValue()
5422           << IsRValueQualified;
5423       Diag(Method->getLocation(), diag::note_previous_decl)
5424         << Method->getDeclName();
5425       return ExprError();
5426     }
5427 
5428     case BadConversionSequence::no_conversion:
5429     case BadConversionSequence::unrelated_class:
5430       break;
5431     }
5432 
5433     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5434            << ImplicitParamRecordType << FromRecordType
5435            << From->getSourceRange();
5436   }
5437 
5438   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5439     ExprResult FromRes =
5440       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5441     if (FromRes.isInvalid())
5442       return ExprError();
5443     From = FromRes.get();
5444   }
5445 
5446   if (!Context.hasSameType(From->getType(), DestType)) {
5447     CastKind CK;
5448     QualType PteeTy = DestType->getPointeeType();
5449     LangAS DestAS =
5450         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5451     if (FromRecordType.getAddressSpace() != DestAS)
5452       CK = CK_AddressSpaceConversion;
5453     else
5454       CK = CK_NoOp;
5455     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5456   }
5457   return From;
5458 }
5459 
5460 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5461 /// expression From to bool (C++0x [conv]p3).
5462 static ImplicitConversionSequence
5463 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5464   // C++ [dcl.init]/17.8:
5465   //   - Otherwise, if the initialization is direct-initialization, the source
5466   //     type is std::nullptr_t, and the destination type is bool, the initial
5467   //     value of the object being initialized is false.
5468   if (From->getType()->isNullPtrType())
5469     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5470                                                         S.Context.BoolTy,
5471                                                         From->isGLValue());
5472 
5473   // All other direct-initialization of bool is equivalent to an implicit
5474   // conversion to bool in which explicit conversions are permitted.
5475   return TryImplicitConversion(S, From, S.Context.BoolTy,
5476                                /*SuppressUserConversions=*/false,
5477                                AllowedExplicit::Conversions,
5478                                /*InOverloadResolution=*/false,
5479                                /*CStyle=*/false,
5480                                /*AllowObjCWritebackConversion=*/false,
5481                                /*AllowObjCConversionOnExplicit=*/false);
5482 }
5483 
5484 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5485 /// of the expression From to bool (C++0x [conv]p3).
5486 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5487   if (checkPlaceholderForOverload(*this, From))
5488     return ExprError();
5489 
5490   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5491   if (!ICS.isBad())
5492     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5493 
5494   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5495     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5496            << From->getType() << From->getSourceRange();
5497   return ExprError();
5498 }
5499 
5500 /// Check that the specified conversion is permitted in a converted constant
5501 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5502 /// is acceptable.
5503 static bool CheckConvertedConstantConversions(Sema &S,
5504                                               StandardConversionSequence &SCS) {
5505   // Since we know that the target type is an integral or unscoped enumeration
5506   // type, most conversion kinds are impossible. All possible First and Third
5507   // conversions are fine.
5508   switch (SCS.Second) {
5509   case ICK_Identity:
5510   case ICK_Integral_Promotion:
5511   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5512   case ICK_Zero_Queue_Conversion:
5513     return true;
5514 
5515   case ICK_Boolean_Conversion:
5516     // Conversion from an integral or unscoped enumeration type to bool is
5517     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5518     // conversion, so we allow it in a converted constant expression.
5519     //
5520     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5521     // a lot of popular code. We should at least add a warning for this
5522     // (non-conforming) extension.
5523     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5524            SCS.getToType(2)->isBooleanType();
5525 
5526   case ICK_Pointer_Conversion:
5527   case ICK_Pointer_Member:
5528     // C++1z: null pointer conversions and null member pointer conversions are
5529     // only permitted if the source type is std::nullptr_t.
5530     return SCS.getFromType()->isNullPtrType();
5531 
5532   case ICK_Floating_Promotion:
5533   case ICK_Complex_Promotion:
5534   case ICK_Floating_Conversion:
5535   case ICK_Complex_Conversion:
5536   case ICK_Floating_Integral:
5537   case ICK_Compatible_Conversion:
5538   case ICK_Derived_To_Base:
5539   case ICK_Vector_Conversion:
5540   case ICK_SVE_Vector_Conversion:
5541   case ICK_Vector_Splat:
5542   case ICK_Complex_Real:
5543   case ICK_Block_Pointer_Conversion:
5544   case ICK_TransparentUnionConversion:
5545   case ICK_Writeback_Conversion:
5546   case ICK_Zero_Event_Conversion:
5547   case ICK_C_Only_Conversion:
5548   case ICK_Incompatible_Pointer_Conversion:
5549     return false;
5550 
5551   case ICK_Lvalue_To_Rvalue:
5552   case ICK_Array_To_Pointer:
5553   case ICK_Function_To_Pointer:
5554     llvm_unreachable("found a first conversion kind in Second");
5555 
5556   case ICK_Function_Conversion:
5557   case ICK_Qualification:
5558     llvm_unreachable("found a third conversion kind in Second");
5559 
5560   case ICK_Num_Conversion_Kinds:
5561     break;
5562   }
5563 
5564   llvm_unreachable("unknown conversion kind");
5565 }
5566 
5567 /// CheckConvertedConstantExpression - Check that the expression From is a
5568 /// converted constant expression of type T, perform the conversion and produce
5569 /// the converted expression, per C++11 [expr.const]p3.
5570 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5571                                                    QualType T, APValue &Value,
5572                                                    Sema::CCEKind CCE,
5573                                                    bool RequireInt) {
5574   assert(S.getLangOpts().CPlusPlus11 &&
5575          "converted constant expression outside C++11");
5576 
5577   if (checkPlaceholderForOverload(S, From))
5578     return ExprError();
5579 
5580   // C++1z [expr.const]p3:
5581   //  A converted constant expression of type T is an expression,
5582   //  implicitly converted to type T, where the converted
5583   //  expression is a constant expression and the implicit conversion
5584   //  sequence contains only [... list of conversions ...].
5585   // C++1z [stmt.if]p2:
5586   //  If the if statement is of the form if constexpr, the value of the
5587   //  condition shall be a contextually converted constant expression of type
5588   //  bool.
5589   ImplicitConversionSequence ICS =
5590       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5591           ? TryContextuallyConvertToBool(S, From)
5592           : TryCopyInitialization(S, From, T,
5593                                   /*SuppressUserConversions=*/false,
5594                                   /*InOverloadResolution=*/false,
5595                                   /*AllowObjCWritebackConversion=*/false,
5596                                   /*AllowExplicit=*/false);
5597   StandardConversionSequence *SCS = nullptr;
5598   switch (ICS.getKind()) {
5599   case ImplicitConversionSequence::StandardConversion:
5600     SCS = &ICS.Standard;
5601     break;
5602   case ImplicitConversionSequence::UserDefinedConversion:
5603     // We are converting to a non-class type, so the Before sequence
5604     // must be trivial.
5605     SCS = &ICS.UserDefined.After;
5606     break;
5607   case ImplicitConversionSequence::AmbiguousConversion:
5608   case ImplicitConversionSequence::BadConversion:
5609     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5610       return S.Diag(From->getBeginLoc(),
5611                     diag::err_typecheck_converted_constant_expression)
5612              << From->getType() << From->getSourceRange() << T;
5613     return ExprError();
5614 
5615   case ImplicitConversionSequence::EllipsisConversion:
5616     llvm_unreachable("ellipsis conversion in converted constant expression");
5617   }
5618 
5619   // Check that we would only use permitted conversions.
5620   if (!CheckConvertedConstantConversions(S, *SCS)) {
5621     return S.Diag(From->getBeginLoc(),
5622                   diag::err_typecheck_converted_constant_expression_disallowed)
5623            << From->getType() << From->getSourceRange() << T;
5624   }
5625   // [...] and where the reference binding (if any) binds directly.
5626   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5627     return S.Diag(From->getBeginLoc(),
5628                   diag::err_typecheck_converted_constant_expression_indirect)
5629            << From->getType() << From->getSourceRange() << T;
5630   }
5631 
5632   ExprResult Result =
5633       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5634   if (Result.isInvalid())
5635     return Result;
5636 
5637   // C++2a [intro.execution]p5:
5638   //   A full-expression is [...] a constant-expression [...]
5639   Result =
5640       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5641                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5642   if (Result.isInvalid())
5643     return Result;
5644 
5645   // Check for a narrowing implicit conversion.
5646   bool ReturnPreNarrowingValue = false;
5647   APValue PreNarrowingValue;
5648   QualType PreNarrowingType;
5649   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5650                                 PreNarrowingType)) {
5651   case NK_Dependent_Narrowing:
5652     // Implicit conversion to a narrower type, but the expression is
5653     // value-dependent so we can't tell whether it's actually narrowing.
5654   case NK_Variable_Narrowing:
5655     // Implicit conversion to a narrower type, and the value is not a constant
5656     // expression. We'll diagnose this in a moment.
5657   case NK_Not_Narrowing:
5658     break;
5659 
5660   case NK_Constant_Narrowing:
5661     if (CCE == Sema::CCEK_ArrayBound &&
5662         PreNarrowingType->isIntegralOrEnumerationType() &&
5663         PreNarrowingValue.isInt()) {
5664       // Don't diagnose array bound narrowing here; we produce more precise
5665       // errors by allowing the un-narrowed value through.
5666       ReturnPreNarrowingValue = true;
5667       break;
5668     }
5669     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5670         << CCE << /*Constant*/ 1
5671         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5672     break;
5673 
5674   case NK_Type_Narrowing:
5675     // FIXME: It would be better to diagnose that the expression is not a
5676     // constant expression.
5677     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5678         << CCE << /*Constant*/ 0 << From->getType() << T;
5679     break;
5680   }
5681 
5682   if (Result.get()->isValueDependent()) {
5683     Value = APValue();
5684     return Result;
5685   }
5686 
5687   // Check the expression is a constant expression.
5688   SmallVector<PartialDiagnosticAt, 8> Notes;
5689   Expr::EvalResult Eval;
5690   Eval.Diag = &Notes;
5691   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5692                                    ? Expr::EvaluateForMangling
5693                                    : Expr::EvaluateForCodeGen;
5694 
5695   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5696       (RequireInt && !Eval.Val.isInt())) {
5697     // The expression can't be folded, so we can't keep it at this position in
5698     // the AST.
5699     Result = ExprError();
5700   } else {
5701     Value = Eval.Val;
5702 
5703     if (Notes.empty()) {
5704       // It's a constant expression.
5705       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5706       if (ReturnPreNarrowingValue)
5707         Value = std::move(PreNarrowingValue);
5708       return E;
5709     }
5710   }
5711 
5712   // It's not a constant expression. Produce an appropriate diagnostic.
5713   if (Notes.size() == 1 &&
5714       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5715     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5716   else {
5717     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5718         << CCE << From->getSourceRange();
5719     for (unsigned I = 0; I < Notes.size(); ++I)
5720       S.Diag(Notes[I].first, Notes[I].second);
5721   }
5722   return ExprError();
5723 }
5724 
5725 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5726                                                   APValue &Value, CCEKind CCE) {
5727   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5728 }
5729 
5730 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5731                                                   llvm::APSInt &Value,
5732                                                   CCEKind CCE) {
5733   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5734 
5735   APValue V;
5736   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5737   if (!R.isInvalid() && !R.get()->isValueDependent())
5738     Value = V.getInt();
5739   return R;
5740 }
5741 
5742 
5743 /// dropPointerConversions - If the given standard conversion sequence
5744 /// involves any pointer conversions, remove them.  This may change
5745 /// the result type of the conversion sequence.
5746 static void dropPointerConversion(StandardConversionSequence &SCS) {
5747   if (SCS.Second == ICK_Pointer_Conversion) {
5748     SCS.Second = ICK_Identity;
5749     SCS.Third = ICK_Identity;
5750     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5751   }
5752 }
5753 
5754 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5755 /// convert the expression From to an Objective-C pointer type.
5756 static ImplicitConversionSequence
5757 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5758   // Do an implicit conversion to 'id'.
5759   QualType Ty = S.Context.getObjCIdType();
5760   ImplicitConversionSequence ICS
5761     = TryImplicitConversion(S, From, Ty,
5762                             // FIXME: Are these flags correct?
5763                             /*SuppressUserConversions=*/false,
5764                             AllowedExplicit::Conversions,
5765                             /*InOverloadResolution=*/false,
5766                             /*CStyle=*/false,
5767                             /*AllowObjCWritebackConversion=*/false,
5768                             /*AllowObjCConversionOnExplicit=*/true);
5769 
5770   // Strip off any final conversions to 'id'.
5771   switch (ICS.getKind()) {
5772   case ImplicitConversionSequence::BadConversion:
5773   case ImplicitConversionSequence::AmbiguousConversion:
5774   case ImplicitConversionSequence::EllipsisConversion:
5775     break;
5776 
5777   case ImplicitConversionSequence::UserDefinedConversion:
5778     dropPointerConversion(ICS.UserDefined.After);
5779     break;
5780 
5781   case ImplicitConversionSequence::StandardConversion:
5782     dropPointerConversion(ICS.Standard);
5783     break;
5784   }
5785 
5786   return ICS;
5787 }
5788 
5789 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5790 /// conversion of the expression From to an Objective-C pointer type.
5791 /// Returns a valid but null ExprResult if no conversion sequence exists.
5792 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5793   if (checkPlaceholderForOverload(*this, From))
5794     return ExprError();
5795 
5796   QualType Ty = Context.getObjCIdType();
5797   ImplicitConversionSequence ICS =
5798     TryContextuallyConvertToObjCPointer(*this, From);
5799   if (!ICS.isBad())
5800     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5801   return ExprResult();
5802 }
5803 
5804 /// Determine whether the provided type is an integral type, or an enumeration
5805 /// type of a permitted flavor.
5806 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5807   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5808                                  : T->isIntegralOrUnscopedEnumerationType();
5809 }
5810 
5811 static ExprResult
5812 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5813                             Sema::ContextualImplicitConverter &Converter,
5814                             QualType T, UnresolvedSetImpl &ViableConversions) {
5815 
5816   if (Converter.Suppress)
5817     return ExprError();
5818 
5819   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5820   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5821     CXXConversionDecl *Conv =
5822         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5823     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5824     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5825   }
5826   return From;
5827 }
5828 
5829 static bool
5830 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5831                            Sema::ContextualImplicitConverter &Converter,
5832                            QualType T, bool HadMultipleCandidates,
5833                            UnresolvedSetImpl &ExplicitConversions) {
5834   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5835     DeclAccessPair Found = ExplicitConversions[0];
5836     CXXConversionDecl *Conversion =
5837         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5838 
5839     // The user probably meant to invoke the given explicit
5840     // conversion; use it.
5841     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5842     std::string TypeStr;
5843     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5844 
5845     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5846         << FixItHint::CreateInsertion(From->getBeginLoc(),
5847                                       "static_cast<" + TypeStr + ">(")
5848         << FixItHint::CreateInsertion(
5849                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5850     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5851 
5852     // If we aren't in a SFINAE context, build a call to the
5853     // explicit conversion function.
5854     if (SemaRef.isSFINAEContext())
5855       return true;
5856 
5857     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5858     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5859                                                        HadMultipleCandidates);
5860     if (Result.isInvalid())
5861       return true;
5862     // Record usage of conversion in an implicit cast.
5863     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5864                                     CK_UserDefinedConversion, Result.get(),
5865                                     nullptr, Result.get()->getValueKind());
5866   }
5867   return false;
5868 }
5869 
5870 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5871                              Sema::ContextualImplicitConverter &Converter,
5872                              QualType T, bool HadMultipleCandidates,
5873                              DeclAccessPair &Found) {
5874   CXXConversionDecl *Conversion =
5875       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5876   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5877 
5878   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5879   if (!Converter.SuppressConversion) {
5880     if (SemaRef.isSFINAEContext())
5881       return true;
5882 
5883     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5884         << From->getSourceRange();
5885   }
5886 
5887   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5888                                                      HadMultipleCandidates);
5889   if (Result.isInvalid())
5890     return true;
5891   // Record usage of conversion in an implicit cast.
5892   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5893                                   CK_UserDefinedConversion, Result.get(),
5894                                   nullptr, Result.get()->getValueKind());
5895   return false;
5896 }
5897 
5898 static ExprResult finishContextualImplicitConversion(
5899     Sema &SemaRef, SourceLocation Loc, Expr *From,
5900     Sema::ContextualImplicitConverter &Converter) {
5901   if (!Converter.match(From->getType()) && !Converter.Suppress)
5902     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5903         << From->getSourceRange();
5904 
5905   return SemaRef.DefaultLvalueConversion(From);
5906 }
5907 
5908 static void
5909 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5910                                   UnresolvedSetImpl &ViableConversions,
5911                                   OverloadCandidateSet &CandidateSet) {
5912   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5913     DeclAccessPair FoundDecl = ViableConversions[I];
5914     NamedDecl *D = FoundDecl.getDecl();
5915     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5916     if (isa<UsingShadowDecl>(D))
5917       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5918 
5919     CXXConversionDecl *Conv;
5920     FunctionTemplateDecl *ConvTemplate;
5921     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5922       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5923     else
5924       Conv = cast<CXXConversionDecl>(D);
5925 
5926     if (ConvTemplate)
5927       SemaRef.AddTemplateConversionCandidate(
5928           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5929           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5930     else
5931       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5932                                      ToType, CandidateSet,
5933                                      /*AllowObjCConversionOnExplicit=*/false,
5934                                      /*AllowExplicit*/ true);
5935   }
5936 }
5937 
5938 /// Attempt to convert the given expression to a type which is accepted
5939 /// by the given converter.
5940 ///
5941 /// This routine will attempt to convert an expression of class type to a
5942 /// type accepted by the specified converter. In C++11 and before, the class
5943 /// must have a single non-explicit conversion function converting to a matching
5944 /// type. In C++1y, there can be multiple such conversion functions, but only
5945 /// one target type.
5946 ///
5947 /// \param Loc The source location of the construct that requires the
5948 /// conversion.
5949 ///
5950 /// \param From The expression we're converting from.
5951 ///
5952 /// \param Converter Used to control and diagnose the conversion process.
5953 ///
5954 /// \returns The expression, converted to an integral or enumeration type if
5955 /// successful.
5956 ExprResult Sema::PerformContextualImplicitConversion(
5957     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5958   // We can't perform any more checking for type-dependent expressions.
5959   if (From->isTypeDependent())
5960     return From;
5961 
5962   // Process placeholders immediately.
5963   if (From->hasPlaceholderType()) {
5964     ExprResult result = CheckPlaceholderExpr(From);
5965     if (result.isInvalid())
5966       return result;
5967     From = result.get();
5968   }
5969 
5970   // If the expression already has a matching type, we're golden.
5971   QualType T = From->getType();
5972   if (Converter.match(T))
5973     return DefaultLvalueConversion(From);
5974 
5975   // FIXME: Check for missing '()' if T is a function type?
5976 
5977   // We can only perform contextual implicit conversions on objects of class
5978   // type.
5979   const RecordType *RecordTy = T->getAs<RecordType>();
5980   if (!RecordTy || !getLangOpts().CPlusPlus) {
5981     if (!Converter.Suppress)
5982       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5983     return From;
5984   }
5985 
5986   // We must have a complete class type.
5987   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5988     ContextualImplicitConverter &Converter;
5989     Expr *From;
5990 
5991     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5992         : Converter(Converter), From(From) {}
5993 
5994     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5995       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5996     }
5997   } IncompleteDiagnoser(Converter, From);
5998 
5999   if (Converter.Suppress ? !isCompleteType(Loc, T)
6000                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6001     return From;
6002 
6003   // Look for a conversion to an integral or enumeration type.
6004   UnresolvedSet<4>
6005       ViableConversions; // These are *potentially* viable in C++1y.
6006   UnresolvedSet<4> ExplicitConversions;
6007   const auto &Conversions =
6008       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6009 
6010   bool HadMultipleCandidates =
6011       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6012 
6013   // To check that there is only one target type, in C++1y:
6014   QualType ToType;
6015   bool HasUniqueTargetType = true;
6016 
6017   // Collect explicit or viable (potentially in C++1y) conversions.
6018   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6019     NamedDecl *D = (*I)->getUnderlyingDecl();
6020     CXXConversionDecl *Conversion;
6021     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6022     if (ConvTemplate) {
6023       if (getLangOpts().CPlusPlus14)
6024         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6025       else
6026         continue; // C++11 does not consider conversion operator templates(?).
6027     } else
6028       Conversion = cast<CXXConversionDecl>(D);
6029 
6030     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6031            "Conversion operator templates are considered potentially "
6032            "viable in C++1y");
6033 
6034     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6035     if (Converter.match(CurToType) || ConvTemplate) {
6036 
6037       if (Conversion->isExplicit()) {
6038         // FIXME: For C++1y, do we need this restriction?
6039         // cf. diagnoseNoViableConversion()
6040         if (!ConvTemplate)
6041           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6042       } else {
6043         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6044           if (ToType.isNull())
6045             ToType = CurToType.getUnqualifiedType();
6046           else if (HasUniqueTargetType &&
6047                    (CurToType.getUnqualifiedType() != ToType))
6048             HasUniqueTargetType = false;
6049         }
6050         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6051       }
6052     }
6053   }
6054 
6055   if (getLangOpts().CPlusPlus14) {
6056     // C++1y [conv]p6:
6057     // ... An expression e of class type E appearing in such a context
6058     // is said to be contextually implicitly converted to a specified
6059     // type T and is well-formed if and only if e can be implicitly
6060     // converted to a type T that is determined as follows: E is searched
6061     // for conversion functions whose return type is cv T or reference to
6062     // cv T such that T is allowed by the context. There shall be
6063     // exactly one such T.
6064 
6065     // If no unique T is found:
6066     if (ToType.isNull()) {
6067       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6068                                      HadMultipleCandidates,
6069                                      ExplicitConversions))
6070         return ExprError();
6071       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6072     }
6073 
6074     // If more than one unique Ts are found:
6075     if (!HasUniqueTargetType)
6076       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6077                                          ViableConversions);
6078 
6079     // If one unique T is found:
6080     // First, build a candidate set from the previously recorded
6081     // potentially viable conversions.
6082     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6083     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6084                                       CandidateSet);
6085 
6086     // Then, perform overload resolution over the candidate set.
6087     OverloadCandidateSet::iterator Best;
6088     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6089     case OR_Success: {
6090       // Apply this conversion.
6091       DeclAccessPair Found =
6092           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6093       if (recordConversion(*this, Loc, From, Converter, T,
6094                            HadMultipleCandidates, Found))
6095         return ExprError();
6096       break;
6097     }
6098     case OR_Ambiguous:
6099       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6100                                          ViableConversions);
6101     case OR_No_Viable_Function:
6102       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6103                                      HadMultipleCandidates,
6104                                      ExplicitConversions))
6105         return ExprError();
6106       LLVM_FALLTHROUGH;
6107     case OR_Deleted:
6108       // We'll complain below about a non-integral condition type.
6109       break;
6110     }
6111   } else {
6112     switch (ViableConversions.size()) {
6113     case 0: {
6114       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6115                                      HadMultipleCandidates,
6116                                      ExplicitConversions))
6117         return ExprError();
6118 
6119       // We'll complain below about a non-integral condition type.
6120       break;
6121     }
6122     case 1: {
6123       // Apply this conversion.
6124       DeclAccessPair Found = ViableConversions[0];
6125       if (recordConversion(*this, Loc, From, Converter, T,
6126                            HadMultipleCandidates, Found))
6127         return ExprError();
6128       break;
6129     }
6130     default:
6131       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6132                                          ViableConversions);
6133     }
6134   }
6135 
6136   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6137 }
6138 
6139 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6140 /// an acceptable non-member overloaded operator for a call whose
6141 /// arguments have types T1 (and, if non-empty, T2). This routine
6142 /// implements the check in C++ [over.match.oper]p3b2 concerning
6143 /// enumeration types.
6144 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6145                                                    FunctionDecl *Fn,
6146                                                    ArrayRef<Expr *> Args) {
6147   QualType T1 = Args[0]->getType();
6148   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6149 
6150   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6151     return true;
6152 
6153   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6154     return true;
6155 
6156   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6157   if (Proto->getNumParams() < 1)
6158     return false;
6159 
6160   if (T1->isEnumeralType()) {
6161     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6162     if (Context.hasSameUnqualifiedType(T1, ArgType))
6163       return true;
6164   }
6165 
6166   if (Proto->getNumParams() < 2)
6167     return false;
6168 
6169   if (!T2.isNull() && T2->isEnumeralType()) {
6170     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6171     if (Context.hasSameUnqualifiedType(T2, ArgType))
6172       return true;
6173   }
6174 
6175   return false;
6176 }
6177 
6178 /// AddOverloadCandidate - Adds the given function to the set of
6179 /// candidate functions, using the given function call arguments.  If
6180 /// @p SuppressUserConversions, then don't allow user-defined
6181 /// conversions via constructors or conversion operators.
6182 ///
6183 /// \param PartialOverloading true if we are performing "partial" overloading
6184 /// based on an incomplete set of function arguments. This feature is used by
6185 /// code completion.
6186 void Sema::AddOverloadCandidate(
6187     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6188     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6189     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6190     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6191     OverloadCandidateParamOrder PO) {
6192   const FunctionProtoType *Proto
6193     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6194   assert(Proto && "Functions without a prototype cannot be overloaded");
6195   assert(!Function->getDescribedFunctionTemplate() &&
6196          "Use AddTemplateOverloadCandidate for function templates");
6197 
6198   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6199     if (!isa<CXXConstructorDecl>(Method)) {
6200       // If we get here, it's because we're calling a member function
6201       // that is named without a member access expression (e.g.,
6202       // "this->f") that was either written explicitly or created
6203       // implicitly. This can happen with a qualified call to a member
6204       // function, e.g., X::f(). We use an empty type for the implied
6205       // object argument (C++ [over.call.func]p3), and the acting context
6206       // is irrelevant.
6207       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6208                          Expr::Classification::makeSimpleLValue(), Args,
6209                          CandidateSet, SuppressUserConversions,
6210                          PartialOverloading, EarlyConversions, PO);
6211       return;
6212     }
6213     // We treat a constructor like a non-member function, since its object
6214     // argument doesn't participate in overload resolution.
6215   }
6216 
6217   if (!CandidateSet.isNewCandidate(Function, PO))
6218     return;
6219 
6220   // C++11 [class.copy]p11: [DR1402]
6221   //   A defaulted move constructor that is defined as deleted is ignored by
6222   //   overload resolution.
6223   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6224   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6225       Constructor->isMoveConstructor())
6226     return;
6227 
6228   // Overload resolution is always an unevaluated context.
6229   EnterExpressionEvaluationContext Unevaluated(
6230       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6231 
6232   // C++ [over.match.oper]p3:
6233   //   if no operand has a class type, only those non-member functions in the
6234   //   lookup set that have a first parameter of type T1 or "reference to
6235   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6236   //   is a right operand) a second parameter of type T2 or "reference to
6237   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6238   //   candidate functions.
6239   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6240       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6241     return;
6242 
6243   // Add this candidate
6244   OverloadCandidate &Candidate =
6245       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6246   Candidate.FoundDecl = FoundDecl;
6247   Candidate.Function = Function;
6248   Candidate.Viable = true;
6249   Candidate.RewriteKind =
6250       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6251   Candidate.IsSurrogate = false;
6252   Candidate.IsADLCandidate = IsADLCandidate;
6253   Candidate.IgnoreObjectArgument = false;
6254   Candidate.ExplicitCallArguments = Args.size();
6255 
6256   // Explicit functions are not actually candidates at all if we're not
6257   // allowing them in this context, but keep them around so we can point
6258   // to them in diagnostics.
6259   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6260     Candidate.Viable = false;
6261     Candidate.FailureKind = ovl_fail_explicit;
6262     return;
6263   }
6264 
6265   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6266       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6267     Candidate.Viable = false;
6268     Candidate.FailureKind = ovl_non_default_multiversion_function;
6269     return;
6270   }
6271 
6272   if (Constructor) {
6273     // C++ [class.copy]p3:
6274     //   A member function template is never instantiated to perform the copy
6275     //   of a class object to an object of its class type.
6276     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6277     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6278         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6279          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6280                        ClassType))) {
6281       Candidate.Viable = false;
6282       Candidate.FailureKind = ovl_fail_illegal_constructor;
6283       return;
6284     }
6285 
6286     // C++ [over.match.funcs]p8: (proposed DR resolution)
6287     //   A constructor inherited from class type C that has a first parameter
6288     //   of type "reference to P" (including such a constructor instantiated
6289     //   from a template) is excluded from the set of candidate functions when
6290     //   constructing an object of type cv D if the argument list has exactly
6291     //   one argument and D is reference-related to P and P is reference-related
6292     //   to C.
6293     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6294     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6295         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6296       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6297       QualType C = Context.getRecordType(Constructor->getParent());
6298       QualType D = Context.getRecordType(Shadow->getParent());
6299       SourceLocation Loc = Args.front()->getExprLoc();
6300       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6301           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6302         Candidate.Viable = false;
6303         Candidate.FailureKind = ovl_fail_inhctor_slice;
6304         return;
6305       }
6306     }
6307 
6308     // Check that the constructor is capable of constructing an object in the
6309     // destination address space.
6310     if (!Qualifiers::isAddressSpaceSupersetOf(
6311             Constructor->getMethodQualifiers().getAddressSpace(),
6312             CandidateSet.getDestAS())) {
6313       Candidate.Viable = false;
6314       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6315     }
6316   }
6317 
6318   unsigned NumParams = Proto->getNumParams();
6319 
6320   // (C++ 13.3.2p2): A candidate function having fewer than m
6321   // parameters is viable only if it has an ellipsis in its parameter
6322   // list (8.3.5).
6323   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6324       !Proto->isVariadic()) {
6325     Candidate.Viable = false;
6326     Candidate.FailureKind = ovl_fail_too_many_arguments;
6327     return;
6328   }
6329 
6330   // (C++ 13.3.2p2): A candidate function having more than m parameters
6331   // is viable only if the (m+1)st parameter has a default argument
6332   // (8.3.6). For the purposes of overload resolution, the
6333   // parameter list is truncated on the right, so that there are
6334   // exactly m parameters.
6335   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6336   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6337     // Not enough arguments.
6338     Candidate.Viable = false;
6339     Candidate.FailureKind = ovl_fail_too_few_arguments;
6340     return;
6341   }
6342 
6343   // (CUDA B.1): Check for invalid calls between targets.
6344   if (getLangOpts().CUDA)
6345     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6346       // Skip the check for callers that are implicit members, because in this
6347       // case we may not yet know what the member's target is; the target is
6348       // inferred for the member automatically, based on the bases and fields of
6349       // the class.
6350       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6351         Candidate.Viable = false;
6352         Candidate.FailureKind = ovl_fail_bad_target;
6353         return;
6354       }
6355 
6356   if (Function->getTrailingRequiresClause()) {
6357     ConstraintSatisfaction Satisfaction;
6358     if (CheckFunctionConstraints(Function, Satisfaction) ||
6359         !Satisfaction.IsSatisfied) {
6360       Candidate.Viable = false;
6361       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6362       return;
6363     }
6364   }
6365 
6366   // Determine the implicit conversion sequences for each of the
6367   // arguments.
6368   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6369     unsigned ConvIdx =
6370         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6371     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6372       // We already formed a conversion sequence for this parameter during
6373       // template argument deduction.
6374     } else if (ArgIdx < NumParams) {
6375       // (C++ 13.3.2p3): for F to be a viable function, there shall
6376       // exist for each argument an implicit conversion sequence
6377       // (13.3.3.1) that converts that argument to the corresponding
6378       // parameter of F.
6379       QualType ParamType = Proto->getParamType(ArgIdx);
6380       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6381           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6382           /*InOverloadResolution=*/true,
6383           /*AllowObjCWritebackConversion=*/
6384           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6385       if (Candidate.Conversions[ConvIdx].isBad()) {
6386         Candidate.Viable = false;
6387         Candidate.FailureKind = ovl_fail_bad_conversion;
6388         return;
6389       }
6390     } else {
6391       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6392       // argument for which there is no corresponding parameter is
6393       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6394       Candidate.Conversions[ConvIdx].setEllipsis();
6395     }
6396   }
6397 
6398   if (EnableIfAttr *FailedAttr =
6399           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6400     Candidate.Viable = false;
6401     Candidate.FailureKind = ovl_fail_enable_if;
6402     Candidate.DeductionFailure.Data = FailedAttr;
6403     return;
6404   }
6405 
6406   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6407     Candidate.Viable = false;
6408     Candidate.FailureKind = ovl_fail_ext_disabled;
6409     return;
6410   }
6411 }
6412 
6413 ObjCMethodDecl *
6414 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6415                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6416   if (Methods.size() <= 1)
6417     return nullptr;
6418 
6419   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6420     bool Match = true;
6421     ObjCMethodDecl *Method = Methods[b];
6422     unsigned NumNamedArgs = Sel.getNumArgs();
6423     // Method might have more arguments than selector indicates. This is due
6424     // to addition of c-style arguments in method.
6425     if (Method->param_size() > NumNamedArgs)
6426       NumNamedArgs = Method->param_size();
6427     if (Args.size() < NumNamedArgs)
6428       continue;
6429 
6430     for (unsigned i = 0; i < NumNamedArgs; i++) {
6431       // We can't do any type-checking on a type-dependent argument.
6432       if (Args[i]->isTypeDependent()) {
6433         Match = false;
6434         break;
6435       }
6436 
6437       ParmVarDecl *param = Method->parameters()[i];
6438       Expr *argExpr = Args[i];
6439       assert(argExpr && "SelectBestMethod(): missing expression");
6440 
6441       // Strip the unbridged-cast placeholder expression off unless it's
6442       // a consumed argument.
6443       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6444           !param->hasAttr<CFConsumedAttr>())
6445         argExpr = stripARCUnbridgedCast(argExpr);
6446 
6447       // If the parameter is __unknown_anytype, move on to the next method.
6448       if (param->getType() == Context.UnknownAnyTy) {
6449         Match = false;
6450         break;
6451       }
6452 
6453       ImplicitConversionSequence ConversionState
6454         = TryCopyInitialization(*this, argExpr, param->getType(),
6455                                 /*SuppressUserConversions*/false,
6456                                 /*InOverloadResolution=*/true,
6457                                 /*AllowObjCWritebackConversion=*/
6458                                 getLangOpts().ObjCAutoRefCount,
6459                                 /*AllowExplicit*/false);
6460       // This function looks for a reasonably-exact match, so we consider
6461       // incompatible pointer conversions to be a failure here.
6462       if (ConversionState.isBad() ||
6463           (ConversionState.isStandard() &&
6464            ConversionState.Standard.Second ==
6465                ICK_Incompatible_Pointer_Conversion)) {
6466         Match = false;
6467         break;
6468       }
6469     }
6470     // Promote additional arguments to variadic methods.
6471     if (Match && Method->isVariadic()) {
6472       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6473         if (Args[i]->isTypeDependent()) {
6474           Match = false;
6475           break;
6476         }
6477         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6478                                                           nullptr);
6479         if (Arg.isInvalid()) {
6480           Match = false;
6481           break;
6482         }
6483       }
6484     } else {
6485       // Check for extra arguments to non-variadic methods.
6486       if (Args.size() != NumNamedArgs)
6487         Match = false;
6488       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6489         // Special case when selectors have no argument. In this case, select
6490         // one with the most general result type of 'id'.
6491         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6492           QualType ReturnT = Methods[b]->getReturnType();
6493           if (ReturnT->isObjCIdType())
6494             return Methods[b];
6495         }
6496       }
6497     }
6498 
6499     if (Match)
6500       return Method;
6501   }
6502   return nullptr;
6503 }
6504 
6505 static bool convertArgsForAvailabilityChecks(
6506     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6507     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6508     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6509   if (ThisArg) {
6510     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6511     assert(!isa<CXXConstructorDecl>(Method) &&
6512            "Shouldn't have `this` for ctors!");
6513     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6514     ExprResult R = S.PerformObjectArgumentInitialization(
6515         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6516     if (R.isInvalid())
6517       return false;
6518     ConvertedThis = R.get();
6519   } else {
6520     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6521       (void)MD;
6522       assert((MissingImplicitThis || MD->isStatic() ||
6523               isa<CXXConstructorDecl>(MD)) &&
6524              "Expected `this` for non-ctor instance methods");
6525     }
6526     ConvertedThis = nullptr;
6527   }
6528 
6529   // Ignore any variadic arguments. Converting them is pointless, since the
6530   // user can't refer to them in the function condition.
6531   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6532 
6533   // Convert the arguments.
6534   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6535     ExprResult R;
6536     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6537                                         S.Context, Function->getParamDecl(I)),
6538                                     SourceLocation(), Args[I]);
6539 
6540     if (R.isInvalid())
6541       return false;
6542 
6543     ConvertedArgs.push_back(R.get());
6544   }
6545 
6546   if (Trap.hasErrorOccurred())
6547     return false;
6548 
6549   // Push default arguments if needed.
6550   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6551     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6552       ParmVarDecl *P = Function->getParamDecl(i);
6553       if (!P->hasDefaultArg())
6554         return false;
6555       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6556       if (R.isInvalid())
6557         return false;
6558       ConvertedArgs.push_back(R.get());
6559     }
6560 
6561     if (Trap.hasErrorOccurred())
6562       return false;
6563   }
6564   return true;
6565 }
6566 
6567 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6568                                   SourceLocation CallLoc,
6569                                   ArrayRef<Expr *> Args,
6570                                   bool MissingImplicitThis) {
6571   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6572   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6573     return nullptr;
6574 
6575   SFINAETrap Trap(*this);
6576   SmallVector<Expr *, 16> ConvertedArgs;
6577   // FIXME: We should look into making enable_if late-parsed.
6578   Expr *DiscardedThis;
6579   if (!convertArgsForAvailabilityChecks(
6580           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6581           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6582     return *EnableIfAttrs.begin();
6583 
6584   for (auto *EIA : EnableIfAttrs) {
6585     APValue Result;
6586     // FIXME: This doesn't consider value-dependent cases, because doing so is
6587     // very difficult. Ideally, we should handle them more gracefully.
6588     if (EIA->getCond()->isValueDependent() ||
6589         !EIA->getCond()->EvaluateWithSubstitution(
6590             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6591       return EIA;
6592 
6593     if (!Result.isInt() || !Result.getInt().getBoolValue())
6594       return EIA;
6595   }
6596   return nullptr;
6597 }
6598 
6599 template <typename CheckFn>
6600 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6601                                         bool ArgDependent, SourceLocation Loc,
6602                                         CheckFn &&IsSuccessful) {
6603   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6604   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6605     if (ArgDependent == DIA->getArgDependent())
6606       Attrs.push_back(DIA);
6607   }
6608 
6609   // Common case: No diagnose_if attributes, so we can quit early.
6610   if (Attrs.empty())
6611     return false;
6612 
6613   auto WarningBegin = std::stable_partition(
6614       Attrs.begin(), Attrs.end(),
6615       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6616 
6617   // Note that diagnose_if attributes are late-parsed, so they appear in the
6618   // correct order (unlike enable_if attributes).
6619   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6620                                IsSuccessful);
6621   if (ErrAttr != WarningBegin) {
6622     const DiagnoseIfAttr *DIA = *ErrAttr;
6623     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6624     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6625         << DIA->getParent() << DIA->getCond()->getSourceRange();
6626     return true;
6627   }
6628 
6629   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6630     if (IsSuccessful(DIA)) {
6631       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6632       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6633           << DIA->getParent() << DIA->getCond()->getSourceRange();
6634     }
6635 
6636   return false;
6637 }
6638 
6639 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6640                                                const Expr *ThisArg,
6641                                                ArrayRef<const Expr *> Args,
6642                                                SourceLocation Loc) {
6643   return diagnoseDiagnoseIfAttrsWith(
6644       *this, Function, /*ArgDependent=*/true, Loc,
6645       [&](const DiagnoseIfAttr *DIA) {
6646         APValue Result;
6647         // It's sane to use the same Args for any redecl of this function, since
6648         // EvaluateWithSubstitution only cares about the position of each
6649         // argument in the arg list, not the ParmVarDecl* it maps to.
6650         if (!DIA->getCond()->EvaluateWithSubstitution(
6651                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6652           return false;
6653         return Result.isInt() && Result.getInt().getBoolValue();
6654       });
6655 }
6656 
6657 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6658                                                  SourceLocation Loc) {
6659   return diagnoseDiagnoseIfAttrsWith(
6660       *this, ND, /*ArgDependent=*/false, Loc,
6661       [&](const DiagnoseIfAttr *DIA) {
6662         bool Result;
6663         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6664                Result;
6665       });
6666 }
6667 
6668 /// Add all of the function declarations in the given function set to
6669 /// the overload candidate set.
6670 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6671                                  ArrayRef<Expr *> Args,
6672                                  OverloadCandidateSet &CandidateSet,
6673                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6674                                  bool SuppressUserConversions,
6675                                  bool PartialOverloading,
6676                                  bool FirstArgumentIsBase) {
6677   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6678     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6679     ArrayRef<Expr *> FunctionArgs = Args;
6680 
6681     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6682     FunctionDecl *FD =
6683         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6684 
6685     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6686       QualType ObjectType;
6687       Expr::Classification ObjectClassification;
6688       if (Args.size() > 0) {
6689         if (Expr *E = Args[0]) {
6690           // Use the explicit base to restrict the lookup:
6691           ObjectType = E->getType();
6692           // Pointers in the object arguments are implicitly dereferenced, so we
6693           // always classify them as l-values.
6694           if (!ObjectType.isNull() && ObjectType->isPointerType())
6695             ObjectClassification = Expr::Classification::makeSimpleLValue();
6696           else
6697             ObjectClassification = E->Classify(Context);
6698         } // .. else there is an implicit base.
6699         FunctionArgs = Args.slice(1);
6700       }
6701       if (FunTmpl) {
6702         AddMethodTemplateCandidate(
6703             FunTmpl, F.getPair(),
6704             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6705             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6706             FunctionArgs, CandidateSet, SuppressUserConversions,
6707             PartialOverloading);
6708       } else {
6709         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6710                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6711                            ObjectClassification, FunctionArgs, CandidateSet,
6712                            SuppressUserConversions, PartialOverloading);
6713       }
6714     } else {
6715       // This branch handles both standalone functions and static methods.
6716 
6717       // Slice the first argument (which is the base) when we access
6718       // static method as non-static.
6719       if (Args.size() > 0 &&
6720           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6721                         !isa<CXXConstructorDecl>(FD)))) {
6722         assert(cast<CXXMethodDecl>(FD)->isStatic());
6723         FunctionArgs = Args.slice(1);
6724       }
6725       if (FunTmpl) {
6726         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6727                                      ExplicitTemplateArgs, FunctionArgs,
6728                                      CandidateSet, SuppressUserConversions,
6729                                      PartialOverloading);
6730       } else {
6731         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6732                              SuppressUserConversions, PartialOverloading);
6733       }
6734     }
6735   }
6736 }
6737 
6738 /// AddMethodCandidate - Adds a named decl (which is some kind of
6739 /// method) as a method candidate to the given overload set.
6740 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6741                               Expr::Classification ObjectClassification,
6742                               ArrayRef<Expr *> Args,
6743                               OverloadCandidateSet &CandidateSet,
6744                               bool SuppressUserConversions,
6745                               OverloadCandidateParamOrder PO) {
6746   NamedDecl *Decl = FoundDecl.getDecl();
6747   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6748 
6749   if (isa<UsingShadowDecl>(Decl))
6750     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6751 
6752   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6753     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6754            "Expected a member function template");
6755     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6756                                /*ExplicitArgs*/ nullptr, ObjectType,
6757                                ObjectClassification, Args, CandidateSet,
6758                                SuppressUserConversions, false, PO);
6759   } else {
6760     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6761                        ObjectType, ObjectClassification, Args, CandidateSet,
6762                        SuppressUserConversions, false, None, PO);
6763   }
6764 }
6765 
6766 /// AddMethodCandidate - Adds the given C++ member function to the set
6767 /// of candidate functions, using the given function call arguments
6768 /// and the object argument (@c Object). For example, in a call
6769 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6770 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6771 /// allow user-defined conversions via constructors or conversion
6772 /// operators.
6773 void
6774 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6775                          CXXRecordDecl *ActingContext, QualType ObjectType,
6776                          Expr::Classification ObjectClassification,
6777                          ArrayRef<Expr *> Args,
6778                          OverloadCandidateSet &CandidateSet,
6779                          bool SuppressUserConversions,
6780                          bool PartialOverloading,
6781                          ConversionSequenceList EarlyConversions,
6782                          OverloadCandidateParamOrder PO) {
6783   const FunctionProtoType *Proto
6784     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6785   assert(Proto && "Methods without a prototype cannot be overloaded");
6786   assert(!isa<CXXConstructorDecl>(Method) &&
6787          "Use AddOverloadCandidate for constructors");
6788 
6789   if (!CandidateSet.isNewCandidate(Method, PO))
6790     return;
6791 
6792   // C++11 [class.copy]p23: [DR1402]
6793   //   A defaulted move assignment operator that is defined as deleted is
6794   //   ignored by overload resolution.
6795   if (Method->isDefaulted() && Method->isDeleted() &&
6796       Method->isMoveAssignmentOperator())
6797     return;
6798 
6799   // Overload resolution is always an unevaluated context.
6800   EnterExpressionEvaluationContext Unevaluated(
6801       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6802 
6803   // Add this candidate
6804   OverloadCandidate &Candidate =
6805       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6806   Candidate.FoundDecl = FoundDecl;
6807   Candidate.Function = Method;
6808   Candidate.RewriteKind =
6809       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6810   Candidate.IsSurrogate = false;
6811   Candidate.IgnoreObjectArgument = false;
6812   Candidate.ExplicitCallArguments = Args.size();
6813 
6814   unsigned NumParams = Proto->getNumParams();
6815 
6816   // (C++ 13.3.2p2): A candidate function having fewer than m
6817   // parameters is viable only if it has an ellipsis in its parameter
6818   // list (8.3.5).
6819   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6820       !Proto->isVariadic()) {
6821     Candidate.Viable = false;
6822     Candidate.FailureKind = ovl_fail_too_many_arguments;
6823     return;
6824   }
6825 
6826   // (C++ 13.3.2p2): A candidate function having more than m parameters
6827   // is viable only if the (m+1)st parameter has a default argument
6828   // (8.3.6). For the purposes of overload resolution, the
6829   // parameter list is truncated on the right, so that there are
6830   // exactly m parameters.
6831   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6832   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6833     // Not enough arguments.
6834     Candidate.Viable = false;
6835     Candidate.FailureKind = ovl_fail_too_few_arguments;
6836     return;
6837   }
6838 
6839   Candidate.Viable = true;
6840 
6841   if (Method->isStatic() || ObjectType.isNull())
6842     // The implicit object argument is ignored.
6843     Candidate.IgnoreObjectArgument = true;
6844   else {
6845     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6846     // Determine the implicit conversion sequence for the object
6847     // parameter.
6848     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6849         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6850         Method, ActingContext);
6851     if (Candidate.Conversions[ConvIdx].isBad()) {
6852       Candidate.Viable = false;
6853       Candidate.FailureKind = ovl_fail_bad_conversion;
6854       return;
6855     }
6856   }
6857 
6858   // (CUDA B.1): Check for invalid calls between targets.
6859   if (getLangOpts().CUDA)
6860     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6861       if (!IsAllowedCUDACall(Caller, Method)) {
6862         Candidate.Viable = false;
6863         Candidate.FailureKind = ovl_fail_bad_target;
6864         return;
6865       }
6866 
6867   if (Method->getTrailingRequiresClause()) {
6868     ConstraintSatisfaction Satisfaction;
6869     if (CheckFunctionConstraints(Method, Satisfaction) ||
6870         !Satisfaction.IsSatisfied) {
6871       Candidate.Viable = false;
6872       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6873       return;
6874     }
6875   }
6876 
6877   // Determine the implicit conversion sequences for each of the
6878   // arguments.
6879   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6880     unsigned ConvIdx =
6881         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6882     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6883       // We already formed a conversion sequence for this parameter during
6884       // template argument deduction.
6885     } else if (ArgIdx < NumParams) {
6886       // (C++ 13.3.2p3): for F to be a viable function, there shall
6887       // exist for each argument an implicit conversion sequence
6888       // (13.3.3.1) that converts that argument to the corresponding
6889       // parameter of F.
6890       QualType ParamType = Proto->getParamType(ArgIdx);
6891       Candidate.Conversions[ConvIdx]
6892         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6893                                 SuppressUserConversions,
6894                                 /*InOverloadResolution=*/true,
6895                                 /*AllowObjCWritebackConversion=*/
6896                                   getLangOpts().ObjCAutoRefCount);
6897       if (Candidate.Conversions[ConvIdx].isBad()) {
6898         Candidate.Viable = false;
6899         Candidate.FailureKind = ovl_fail_bad_conversion;
6900         return;
6901       }
6902     } else {
6903       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6904       // argument for which there is no corresponding parameter is
6905       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6906       Candidate.Conversions[ConvIdx].setEllipsis();
6907     }
6908   }
6909 
6910   if (EnableIfAttr *FailedAttr =
6911           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6912     Candidate.Viable = false;
6913     Candidate.FailureKind = ovl_fail_enable_if;
6914     Candidate.DeductionFailure.Data = FailedAttr;
6915     return;
6916   }
6917 
6918   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6919       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6920     Candidate.Viable = false;
6921     Candidate.FailureKind = ovl_non_default_multiversion_function;
6922   }
6923 }
6924 
6925 /// Add a C++ member function template as a candidate to the candidate
6926 /// set, using template argument deduction to produce an appropriate member
6927 /// function template specialization.
6928 void Sema::AddMethodTemplateCandidate(
6929     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6930     CXXRecordDecl *ActingContext,
6931     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6932     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6933     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6934     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6935   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6936     return;
6937 
6938   // C++ [over.match.funcs]p7:
6939   //   In each case where a candidate is a function template, candidate
6940   //   function template specializations are generated using template argument
6941   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6942   //   candidate functions in the usual way.113) A given name can refer to one
6943   //   or more function templates and also to a set of overloaded non-template
6944   //   functions. In such a case, the candidate functions generated from each
6945   //   function template are combined with the set of non-template candidate
6946   //   functions.
6947   TemplateDeductionInfo Info(CandidateSet.getLocation());
6948   FunctionDecl *Specialization = nullptr;
6949   ConversionSequenceList Conversions;
6950   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6951           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6952           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6953             return CheckNonDependentConversions(
6954                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6955                 SuppressUserConversions, ActingContext, ObjectType,
6956                 ObjectClassification, PO);
6957           })) {
6958     OverloadCandidate &Candidate =
6959         CandidateSet.addCandidate(Conversions.size(), Conversions);
6960     Candidate.FoundDecl = FoundDecl;
6961     Candidate.Function = MethodTmpl->getTemplatedDecl();
6962     Candidate.Viable = false;
6963     Candidate.RewriteKind =
6964       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6965     Candidate.IsSurrogate = false;
6966     Candidate.IgnoreObjectArgument =
6967         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6968         ObjectType.isNull();
6969     Candidate.ExplicitCallArguments = Args.size();
6970     if (Result == TDK_NonDependentConversionFailure)
6971       Candidate.FailureKind = ovl_fail_bad_conversion;
6972     else {
6973       Candidate.FailureKind = ovl_fail_bad_deduction;
6974       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6975                                                             Info);
6976     }
6977     return;
6978   }
6979 
6980   // Add the function template specialization produced by template argument
6981   // deduction as a candidate.
6982   assert(Specialization && "Missing member function template specialization?");
6983   assert(isa<CXXMethodDecl>(Specialization) &&
6984          "Specialization is not a member function?");
6985   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6986                      ActingContext, ObjectType, ObjectClassification, Args,
6987                      CandidateSet, SuppressUserConversions, PartialOverloading,
6988                      Conversions, PO);
6989 }
6990 
6991 /// Determine whether a given function template has a simple explicit specifier
6992 /// or a non-value-dependent explicit-specification that evaluates to true.
6993 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6994   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6995 }
6996 
6997 /// Add a C++ function template specialization as a candidate
6998 /// in the candidate set, using template argument deduction to produce
6999 /// an appropriate function template specialization.
7000 void Sema::AddTemplateOverloadCandidate(
7001     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7002     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7003     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7004     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7005     OverloadCandidateParamOrder PO) {
7006   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7007     return;
7008 
7009   // If the function template has a non-dependent explicit specification,
7010   // exclude it now if appropriate; we are not permitted to perform deduction
7011   // and substitution in this case.
7012   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7013     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7014     Candidate.FoundDecl = FoundDecl;
7015     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7016     Candidate.Viable = false;
7017     Candidate.FailureKind = ovl_fail_explicit;
7018     return;
7019   }
7020 
7021   // C++ [over.match.funcs]p7:
7022   //   In each case where a candidate is a function template, candidate
7023   //   function template specializations are generated using template argument
7024   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7025   //   candidate functions in the usual way.113) A given name can refer to one
7026   //   or more function templates and also to a set of overloaded non-template
7027   //   functions. In such a case, the candidate functions generated from each
7028   //   function template are combined with the set of non-template candidate
7029   //   functions.
7030   TemplateDeductionInfo Info(CandidateSet.getLocation());
7031   FunctionDecl *Specialization = nullptr;
7032   ConversionSequenceList Conversions;
7033   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7034           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7035           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7036             return CheckNonDependentConversions(
7037                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7038                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7039           })) {
7040     OverloadCandidate &Candidate =
7041         CandidateSet.addCandidate(Conversions.size(), Conversions);
7042     Candidate.FoundDecl = FoundDecl;
7043     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7044     Candidate.Viable = false;
7045     Candidate.RewriteKind =
7046       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7047     Candidate.IsSurrogate = false;
7048     Candidate.IsADLCandidate = IsADLCandidate;
7049     // Ignore the object argument if there is one, since we don't have an object
7050     // type.
7051     Candidate.IgnoreObjectArgument =
7052         isa<CXXMethodDecl>(Candidate.Function) &&
7053         !isa<CXXConstructorDecl>(Candidate.Function);
7054     Candidate.ExplicitCallArguments = Args.size();
7055     if (Result == TDK_NonDependentConversionFailure)
7056       Candidate.FailureKind = ovl_fail_bad_conversion;
7057     else {
7058       Candidate.FailureKind = ovl_fail_bad_deduction;
7059       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7060                                                             Info);
7061     }
7062     return;
7063   }
7064 
7065   // Add the function template specialization produced by template argument
7066   // deduction as a candidate.
7067   assert(Specialization && "Missing function template specialization?");
7068   AddOverloadCandidate(
7069       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7070       PartialOverloading, AllowExplicit,
7071       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7072 }
7073 
7074 /// Check that implicit conversion sequences can be formed for each argument
7075 /// whose corresponding parameter has a non-dependent type, per DR1391's
7076 /// [temp.deduct.call]p10.
7077 bool Sema::CheckNonDependentConversions(
7078     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7079     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7080     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7081     CXXRecordDecl *ActingContext, QualType ObjectType,
7082     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7083   // FIXME: The cases in which we allow explicit conversions for constructor
7084   // arguments never consider calling a constructor template. It's not clear
7085   // that is correct.
7086   const bool AllowExplicit = false;
7087 
7088   auto *FD = FunctionTemplate->getTemplatedDecl();
7089   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7090   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7091   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7092 
7093   Conversions =
7094       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7095 
7096   // Overload resolution is always an unevaluated context.
7097   EnterExpressionEvaluationContext Unevaluated(
7098       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7099 
7100   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7101   // require that, but this check should never result in a hard error, and
7102   // overload resolution is permitted to sidestep instantiations.
7103   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7104       !ObjectType.isNull()) {
7105     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7106     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7107         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7108         Method, ActingContext);
7109     if (Conversions[ConvIdx].isBad())
7110       return true;
7111   }
7112 
7113   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7114        ++I) {
7115     QualType ParamType = ParamTypes[I];
7116     if (!ParamType->isDependentType()) {
7117       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7118                              ? 0
7119                              : (ThisConversions + I);
7120       Conversions[ConvIdx]
7121         = TryCopyInitialization(*this, Args[I], ParamType,
7122                                 SuppressUserConversions,
7123                                 /*InOverloadResolution=*/true,
7124                                 /*AllowObjCWritebackConversion=*/
7125                                   getLangOpts().ObjCAutoRefCount,
7126                                 AllowExplicit);
7127       if (Conversions[ConvIdx].isBad())
7128         return true;
7129     }
7130   }
7131 
7132   return false;
7133 }
7134 
7135 /// Determine whether this is an allowable conversion from the result
7136 /// of an explicit conversion operator to the expected type, per C++
7137 /// [over.match.conv]p1 and [over.match.ref]p1.
7138 ///
7139 /// \param ConvType The return type of the conversion function.
7140 ///
7141 /// \param ToType The type we are converting to.
7142 ///
7143 /// \param AllowObjCPointerConversion Allow a conversion from one
7144 /// Objective-C pointer to another.
7145 ///
7146 /// \returns true if the conversion is allowable, false otherwise.
7147 static bool isAllowableExplicitConversion(Sema &S,
7148                                           QualType ConvType, QualType ToType,
7149                                           bool AllowObjCPointerConversion) {
7150   QualType ToNonRefType = ToType.getNonReferenceType();
7151 
7152   // Easy case: the types are the same.
7153   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7154     return true;
7155 
7156   // Allow qualification conversions.
7157   bool ObjCLifetimeConversion;
7158   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7159                                   ObjCLifetimeConversion))
7160     return true;
7161 
7162   // If we're not allowed to consider Objective-C pointer conversions,
7163   // we're done.
7164   if (!AllowObjCPointerConversion)
7165     return false;
7166 
7167   // Is this an Objective-C pointer conversion?
7168   bool IncompatibleObjC = false;
7169   QualType ConvertedType;
7170   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7171                                    IncompatibleObjC);
7172 }
7173 
7174 /// AddConversionCandidate - Add a C++ conversion function as a
7175 /// candidate in the candidate set (C++ [over.match.conv],
7176 /// C++ [over.match.copy]). From is the expression we're converting from,
7177 /// and ToType is the type that we're eventually trying to convert to
7178 /// (which may or may not be the same type as the type that the
7179 /// conversion function produces).
7180 void Sema::AddConversionCandidate(
7181     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7182     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7183     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7184     bool AllowExplicit, bool AllowResultConversion) {
7185   assert(!Conversion->getDescribedFunctionTemplate() &&
7186          "Conversion function templates use AddTemplateConversionCandidate");
7187   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7188   if (!CandidateSet.isNewCandidate(Conversion))
7189     return;
7190 
7191   // If the conversion function has an undeduced return type, trigger its
7192   // deduction now.
7193   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7194     if (DeduceReturnType(Conversion, From->getExprLoc()))
7195       return;
7196     ConvType = Conversion->getConversionType().getNonReferenceType();
7197   }
7198 
7199   // If we don't allow any conversion of the result type, ignore conversion
7200   // functions that don't convert to exactly (possibly cv-qualified) T.
7201   if (!AllowResultConversion &&
7202       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7203     return;
7204 
7205   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7206   // operator is only a candidate if its return type is the target type or
7207   // can be converted to the target type with a qualification conversion.
7208   //
7209   // FIXME: Include such functions in the candidate list and explain why we
7210   // can't select them.
7211   if (Conversion->isExplicit() &&
7212       !isAllowableExplicitConversion(*this, ConvType, ToType,
7213                                      AllowObjCConversionOnExplicit))
7214     return;
7215 
7216   // Overload resolution is always an unevaluated context.
7217   EnterExpressionEvaluationContext Unevaluated(
7218       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7219 
7220   // Add this candidate
7221   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7222   Candidate.FoundDecl = FoundDecl;
7223   Candidate.Function = Conversion;
7224   Candidate.IsSurrogate = false;
7225   Candidate.IgnoreObjectArgument = false;
7226   Candidate.FinalConversion.setAsIdentityConversion();
7227   Candidate.FinalConversion.setFromType(ConvType);
7228   Candidate.FinalConversion.setAllToTypes(ToType);
7229   Candidate.Viable = true;
7230   Candidate.ExplicitCallArguments = 1;
7231 
7232   // Explicit functions are not actually candidates at all if we're not
7233   // allowing them in this context, but keep them around so we can point
7234   // to them in diagnostics.
7235   if (!AllowExplicit && Conversion->isExplicit()) {
7236     Candidate.Viable = false;
7237     Candidate.FailureKind = ovl_fail_explicit;
7238     return;
7239   }
7240 
7241   // C++ [over.match.funcs]p4:
7242   //   For conversion functions, the function is considered to be a member of
7243   //   the class of the implicit implied object argument for the purpose of
7244   //   defining the type of the implicit object parameter.
7245   //
7246   // Determine the implicit conversion sequence for the implicit
7247   // object parameter.
7248   QualType ImplicitParamType = From->getType();
7249   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7250     ImplicitParamType = FromPtrType->getPointeeType();
7251   CXXRecordDecl *ConversionContext
7252     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7253 
7254   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7255       *this, CandidateSet.getLocation(), From->getType(),
7256       From->Classify(Context), Conversion, ConversionContext);
7257 
7258   if (Candidate.Conversions[0].isBad()) {
7259     Candidate.Viable = false;
7260     Candidate.FailureKind = ovl_fail_bad_conversion;
7261     return;
7262   }
7263 
7264   if (Conversion->getTrailingRequiresClause()) {
7265     ConstraintSatisfaction Satisfaction;
7266     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7267         !Satisfaction.IsSatisfied) {
7268       Candidate.Viable = false;
7269       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7270       return;
7271     }
7272   }
7273 
7274   // We won't go through a user-defined type conversion function to convert a
7275   // derived to base as such conversions are given Conversion Rank. They only
7276   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7277   QualType FromCanon
7278     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7279   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7280   if (FromCanon == ToCanon ||
7281       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7282     Candidate.Viable = false;
7283     Candidate.FailureKind = ovl_fail_trivial_conversion;
7284     return;
7285   }
7286 
7287   // To determine what the conversion from the result of calling the
7288   // conversion function to the type we're eventually trying to
7289   // convert to (ToType), we need to synthesize a call to the
7290   // conversion function and attempt copy initialization from it. This
7291   // makes sure that we get the right semantics with respect to
7292   // lvalues/rvalues and the type. Fortunately, we can allocate this
7293   // call on the stack and we don't need its arguments to be
7294   // well-formed.
7295   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7296                             VK_LValue, From->getBeginLoc());
7297   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7298                                 Context.getPointerType(Conversion->getType()),
7299                                 CK_FunctionToPointerDecay,
7300                                 &ConversionRef, VK_RValue);
7301 
7302   QualType ConversionType = Conversion->getConversionType();
7303   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7304     Candidate.Viable = false;
7305     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7306     return;
7307   }
7308 
7309   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7310 
7311   // Note that it is safe to allocate CallExpr on the stack here because
7312   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7313   // allocator).
7314   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7315 
7316   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7317   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7318       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7319 
7320   ImplicitConversionSequence ICS =
7321       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7322                             /*SuppressUserConversions=*/true,
7323                             /*InOverloadResolution=*/false,
7324                             /*AllowObjCWritebackConversion=*/false);
7325 
7326   switch (ICS.getKind()) {
7327   case ImplicitConversionSequence::StandardConversion:
7328     Candidate.FinalConversion = ICS.Standard;
7329 
7330     // C++ [over.ics.user]p3:
7331     //   If the user-defined conversion is specified by a specialization of a
7332     //   conversion function template, the second standard conversion sequence
7333     //   shall have exact match rank.
7334     if (Conversion->getPrimaryTemplate() &&
7335         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7336       Candidate.Viable = false;
7337       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7338       return;
7339     }
7340 
7341     // C++0x [dcl.init.ref]p5:
7342     //    In the second case, if the reference is an rvalue reference and
7343     //    the second standard conversion sequence of the user-defined
7344     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7345     //    program is ill-formed.
7346     if (ToType->isRValueReferenceType() &&
7347         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7348       Candidate.Viable = false;
7349       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7350       return;
7351     }
7352     break;
7353 
7354   case ImplicitConversionSequence::BadConversion:
7355     Candidate.Viable = false;
7356     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7357     return;
7358 
7359   default:
7360     llvm_unreachable(
7361            "Can only end up with a standard conversion sequence or failure");
7362   }
7363 
7364   if (EnableIfAttr *FailedAttr =
7365           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7366     Candidate.Viable = false;
7367     Candidate.FailureKind = ovl_fail_enable_if;
7368     Candidate.DeductionFailure.Data = FailedAttr;
7369     return;
7370   }
7371 
7372   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7373       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7374     Candidate.Viable = false;
7375     Candidate.FailureKind = ovl_non_default_multiversion_function;
7376   }
7377 }
7378 
7379 /// Adds a conversion function template specialization
7380 /// candidate to the overload set, using template argument deduction
7381 /// to deduce the template arguments of the conversion function
7382 /// template from the type that we are converting to (C++
7383 /// [temp.deduct.conv]).
7384 void Sema::AddTemplateConversionCandidate(
7385     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7386     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7387     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7388     bool AllowExplicit, bool AllowResultConversion) {
7389   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7390          "Only conversion function templates permitted here");
7391 
7392   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7393     return;
7394 
7395   // If the function template has a non-dependent explicit specification,
7396   // exclude it now if appropriate; we are not permitted to perform deduction
7397   // and substitution in this case.
7398   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7399     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7400     Candidate.FoundDecl = FoundDecl;
7401     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7402     Candidate.Viable = false;
7403     Candidate.FailureKind = ovl_fail_explicit;
7404     return;
7405   }
7406 
7407   TemplateDeductionInfo Info(CandidateSet.getLocation());
7408   CXXConversionDecl *Specialization = nullptr;
7409   if (TemplateDeductionResult Result
7410         = DeduceTemplateArguments(FunctionTemplate, ToType,
7411                                   Specialization, Info)) {
7412     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7413     Candidate.FoundDecl = FoundDecl;
7414     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7415     Candidate.Viable = false;
7416     Candidate.FailureKind = ovl_fail_bad_deduction;
7417     Candidate.IsSurrogate = false;
7418     Candidate.IgnoreObjectArgument = false;
7419     Candidate.ExplicitCallArguments = 1;
7420     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7421                                                           Info);
7422     return;
7423   }
7424 
7425   // Add the conversion function template specialization produced by
7426   // template argument deduction as a candidate.
7427   assert(Specialization && "Missing function template specialization?");
7428   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7429                          CandidateSet, AllowObjCConversionOnExplicit,
7430                          AllowExplicit, AllowResultConversion);
7431 }
7432 
7433 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7434 /// converts the given @c Object to a function pointer via the
7435 /// conversion function @c Conversion, and then attempts to call it
7436 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7437 /// the type of function that we'll eventually be calling.
7438 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7439                                  DeclAccessPair FoundDecl,
7440                                  CXXRecordDecl *ActingContext,
7441                                  const FunctionProtoType *Proto,
7442                                  Expr *Object,
7443                                  ArrayRef<Expr *> Args,
7444                                  OverloadCandidateSet& CandidateSet) {
7445   if (!CandidateSet.isNewCandidate(Conversion))
7446     return;
7447 
7448   // Overload resolution is always an unevaluated context.
7449   EnterExpressionEvaluationContext Unevaluated(
7450       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7451 
7452   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7453   Candidate.FoundDecl = FoundDecl;
7454   Candidate.Function = nullptr;
7455   Candidate.Surrogate = Conversion;
7456   Candidate.Viable = true;
7457   Candidate.IsSurrogate = true;
7458   Candidate.IgnoreObjectArgument = false;
7459   Candidate.ExplicitCallArguments = Args.size();
7460 
7461   // Determine the implicit conversion sequence for the implicit
7462   // object parameter.
7463   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7464       *this, CandidateSet.getLocation(), Object->getType(),
7465       Object->Classify(Context), Conversion, ActingContext);
7466   if (ObjectInit.isBad()) {
7467     Candidate.Viable = false;
7468     Candidate.FailureKind = ovl_fail_bad_conversion;
7469     Candidate.Conversions[0] = ObjectInit;
7470     return;
7471   }
7472 
7473   // The first conversion is actually a user-defined conversion whose
7474   // first conversion is ObjectInit's standard conversion (which is
7475   // effectively a reference binding). Record it as such.
7476   Candidate.Conversions[0].setUserDefined();
7477   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7478   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7479   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7480   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7481   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7482   Candidate.Conversions[0].UserDefined.After
7483     = Candidate.Conversions[0].UserDefined.Before;
7484   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7485 
7486   // Find the
7487   unsigned NumParams = Proto->getNumParams();
7488 
7489   // (C++ 13.3.2p2): A candidate function having fewer than m
7490   // parameters is viable only if it has an ellipsis in its parameter
7491   // list (8.3.5).
7492   if (Args.size() > NumParams && !Proto->isVariadic()) {
7493     Candidate.Viable = false;
7494     Candidate.FailureKind = ovl_fail_too_many_arguments;
7495     return;
7496   }
7497 
7498   // Function types don't have any default arguments, so just check if
7499   // we have enough arguments.
7500   if (Args.size() < NumParams) {
7501     // Not enough arguments.
7502     Candidate.Viable = false;
7503     Candidate.FailureKind = ovl_fail_too_few_arguments;
7504     return;
7505   }
7506 
7507   // Determine the implicit conversion sequences for each of the
7508   // arguments.
7509   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7510     if (ArgIdx < NumParams) {
7511       // (C++ 13.3.2p3): for F to be a viable function, there shall
7512       // exist for each argument an implicit conversion sequence
7513       // (13.3.3.1) that converts that argument to the corresponding
7514       // parameter of F.
7515       QualType ParamType = Proto->getParamType(ArgIdx);
7516       Candidate.Conversions[ArgIdx + 1]
7517         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7518                                 /*SuppressUserConversions=*/false,
7519                                 /*InOverloadResolution=*/false,
7520                                 /*AllowObjCWritebackConversion=*/
7521                                   getLangOpts().ObjCAutoRefCount);
7522       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7523         Candidate.Viable = false;
7524         Candidate.FailureKind = ovl_fail_bad_conversion;
7525         return;
7526       }
7527     } else {
7528       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7529       // argument for which there is no corresponding parameter is
7530       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7531       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7532     }
7533   }
7534 
7535   if (EnableIfAttr *FailedAttr =
7536           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7537     Candidate.Viable = false;
7538     Candidate.FailureKind = ovl_fail_enable_if;
7539     Candidate.DeductionFailure.Data = FailedAttr;
7540     return;
7541   }
7542 }
7543 
7544 /// Add all of the non-member operator function declarations in the given
7545 /// function set to the overload candidate set.
7546 void Sema::AddNonMemberOperatorCandidates(
7547     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7548     OverloadCandidateSet &CandidateSet,
7549     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7550   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7551     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7552     ArrayRef<Expr *> FunctionArgs = Args;
7553 
7554     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7555     FunctionDecl *FD =
7556         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7557 
7558     // Don't consider rewritten functions if we're not rewriting.
7559     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7560       continue;
7561 
7562     assert(!isa<CXXMethodDecl>(FD) &&
7563            "unqualified operator lookup found a member function");
7564 
7565     if (FunTmpl) {
7566       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7567                                    FunctionArgs, CandidateSet);
7568       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7569         AddTemplateOverloadCandidate(
7570             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7571             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7572             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7573     } else {
7574       if (ExplicitTemplateArgs)
7575         continue;
7576       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7577       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7578         AddOverloadCandidate(FD, F.getPair(),
7579                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7580                              false, false, true, false, ADLCallKind::NotADL,
7581                              None, OverloadCandidateParamOrder::Reversed);
7582     }
7583   }
7584 }
7585 
7586 /// Add overload candidates for overloaded operators that are
7587 /// member functions.
7588 ///
7589 /// Add the overloaded operator candidates that are member functions
7590 /// for the operator Op that was used in an operator expression such
7591 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7592 /// CandidateSet will store the added overload candidates. (C++
7593 /// [over.match.oper]).
7594 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7595                                        SourceLocation OpLoc,
7596                                        ArrayRef<Expr *> Args,
7597                                        OverloadCandidateSet &CandidateSet,
7598                                        OverloadCandidateParamOrder PO) {
7599   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7600 
7601   // C++ [over.match.oper]p3:
7602   //   For a unary operator @ with an operand of a type whose
7603   //   cv-unqualified version is T1, and for a binary operator @ with
7604   //   a left operand of a type whose cv-unqualified version is T1 and
7605   //   a right operand of a type whose cv-unqualified version is T2,
7606   //   three sets of candidate functions, designated member
7607   //   candidates, non-member candidates and built-in candidates, are
7608   //   constructed as follows:
7609   QualType T1 = Args[0]->getType();
7610 
7611   //     -- If T1 is a complete class type or a class currently being
7612   //        defined, the set of member candidates is the result of the
7613   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7614   //        the set of member candidates is empty.
7615   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7616     // Complete the type if it can be completed.
7617     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7618       return;
7619     // If the type is neither complete nor being defined, bail out now.
7620     if (!T1Rec->getDecl()->getDefinition())
7621       return;
7622 
7623     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7624     LookupQualifiedName(Operators, T1Rec->getDecl());
7625     Operators.suppressDiagnostics();
7626 
7627     for (LookupResult::iterator Oper = Operators.begin(),
7628                              OperEnd = Operators.end();
7629          Oper != OperEnd;
7630          ++Oper)
7631       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7632                          Args[0]->Classify(Context), Args.slice(1),
7633                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7634   }
7635 }
7636 
7637 /// AddBuiltinCandidate - Add a candidate for a built-in
7638 /// operator. ResultTy and ParamTys are the result and parameter types
7639 /// of the built-in candidate, respectively. Args and NumArgs are the
7640 /// arguments being passed to the candidate. IsAssignmentOperator
7641 /// should be true when this built-in candidate is an assignment
7642 /// operator. NumContextualBoolArguments is the number of arguments
7643 /// (at the beginning of the argument list) that will be contextually
7644 /// converted to bool.
7645 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7646                                OverloadCandidateSet& CandidateSet,
7647                                bool IsAssignmentOperator,
7648                                unsigned NumContextualBoolArguments) {
7649   // Overload resolution is always an unevaluated context.
7650   EnterExpressionEvaluationContext Unevaluated(
7651       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7652 
7653   // Add this candidate
7654   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7655   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7656   Candidate.Function = nullptr;
7657   Candidate.IsSurrogate = false;
7658   Candidate.IgnoreObjectArgument = false;
7659   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7660 
7661   // Determine the implicit conversion sequences for each of the
7662   // arguments.
7663   Candidate.Viable = true;
7664   Candidate.ExplicitCallArguments = Args.size();
7665   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7666     // C++ [over.match.oper]p4:
7667     //   For the built-in assignment operators, conversions of the
7668     //   left operand are restricted as follows:
7669     //     -- no temporaries are introduced to hold the left operand, and
7670     //     -- no user-defined conversions are applied to the left
7671     //        operand to achieve a type match with the left-most
7672     //        parameter of a built-in candidate.
7673     //
7674     // We block these conversions by turning off user-defined
7675     // conversions, since that is the only way that initialization of
7676     // a reference to a non-class type can occur from something that
7677     // is not of the same type.
7678     if (ArgIdx < NumContextualBoolArguments) {
7679       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7680              "Contextual conversion to bool requires bool type");
7681       Candidate.Conversions[ArgIdx]
7682         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7683     } else {
7684       Candidate.Conversions[ArgIdx]
7685         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7686                                 ArgIdx == 0 && IsAssignmentOperator,
7687                                 /*InOverloadResolution=*/false,
7688                                 /*AllowObjCWritebackConversion=*/
7689                                   getLangOpts().ObjCAutoRefCount);
7690     }
7691     if (Candidate.Conversions[ArgIdx].isBad()) {
7692       Candidate.Viable = false;
7693       Candidate.FailureKind = ovl_fail_bad_conversion;
7694       break;
7695     }
7696   }
7697 }
7698 
7699 namespace {
7700 
7701 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7702 /// candidate operator functions for built-in operators (C++
7703 /// [over.built]). The types are separated into pointer types and
7704 /// enumeration types.
7705 class BuiltinCandidateTypeSet  {
7706   /// TypeSet - A set of types.
7707   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7708                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7709 
7710   /// PointerTypes - The set of pointer types that will be used in the
7711   /// built-in candidates.
7712   TypeSet PointerTypes;
7713 
7714   /// MemberPointerTypes - The set of member pointer types that will be
7715   /// used in the built-in candidates.
7716   TypeSet MemberPointerTypes;
7717 
7718   /// EnumerationTypes - The set of enumeration types that will be
7719   /// used in the built-in candidates.
7720   TypeSet EnumerationTypes;
7721 
7722   /// The set of vector types that will be used in the built-in
7723   /// candidates.
7724   TypeSet VectorTypes;
7725 
7726   /// The set of matrix types that will be used in the built-in
7727   /// candidates.
7728   TypeSet MatrixTypes;
7729 
7730   /// A flag indicating non-record types are viable candidates
7731   bool HasNonRecordTypes;
7732 
7733   /// A flag indicating whether either arithmetic or enumeration types
7734   /// were present in the candidate set.
7735   bool HasArithmeticOrEnumeralTypes;
7736 
7737   /// A flag indicating whether the nullptr type was present in the
7738   /// candidate set.
7739   bool HasNullPtrType;
7740 
7741   /// Sema - The semantic analysis instance where we are building the
7742   /// candidate type set.
7743   Sema &SemaRef;
7744 
7745   /// Context - The AST context in which we will build the type sets.
7746   ASTContext &Context;
7747 
7748   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7749                                                const Qualifiers &VisibleQuals);
7750   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7751 
7752 public:
7753   /// iterator - Iterates through the types that are part of the set.
7754   typedef TypeSet::iterator iterator;
7755 
7756   BuiltinCandidateTypeSet(Sema &SemaRef)
7757     : HasNonRecordTypes(false),
7758       HasArithmeticOrEnumeralTypes(false),
7759       HasNullPtrType(false),
7760       SemaRef(SemaRef),
7761       Context(SemaRef.Context) { }
7762 
7763   void AddTypesConvertedFrom(QualType Ty,
7764                              SourceLocation Loc,
7765                              bool AllowUserConversions,
7766                              bool AllowExplicitConversions,
7767                              const Qualifiers &VisibleTypeConversionsQuals);
7768 
7769   /// pointer_begin - First pointer type found;
7770   iterator pointer_begin() { return PointerTypes.begin(); }
7771 
7772   /// pointer_end - Past the last pointer type found;
7773   iterator pointer_end() { return PointerTypes.end(); }
7774 
7775   /// member_pointer_begin - First member pointer type found;
7776   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7777 
7778   /// member_pointer_end - Past the last member pointer type found;
7779   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7780 
7781   /// enumeration_begin - First enumeration type found;
7782   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7783 
7784   /// enumeration_end - Past the last enumeration type found;
7785   iterator enumeration_end() { return EnumerationTypes.end(); }
7786 
7787   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7788 
7789   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7790 
7791   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7792   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7793   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7794   bool hasNullPtrType() const { return HasNullPtrType; }
7795 };
7796 
7797 } // end anonymous namespace
7798 
7799 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7800 /// the set of pointer types along with any more-qualified variants of
7801 /// that type. For example, if @p Ty is "int const *", this routine
7802 /// will add "int const *", "int const volatile *", "int const
7803 /// restrict *", and "int const volatile restrict *" to the set of
7804 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7805 /// false otherwise.
7806 ///
7807 /// FIXME: what to do about extended qualifiers?
7808 bool
7809 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7810                                              const Qualifiers &VisibleQuals) {
7811 
7812   // Insert this type.
7813   if (!PointerTypes.insert(Ty))
7814     return false;
7815 
7816   QualType PointeeTy;
7817   const PointerType *PointerTy = Ty->getAs<PointerType>();
7818   bool buildObjCPtr = false;
7819   if (!PointerTy) {
7820     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7821     PointeeTy = PTy->getPointeeType();
7822     buildObjCPtr = true;
7823   } else {
7824     PointeeTy = PointerTy->getPointeeType();
7825   }
7826 
7827   // Don't add qualified variants of arrays. For one, they're not allowed
7828   // (the qualifier would sink to the element type), and for another, the
7829   // only overload situation where it matters is subscript or pointer +- int,
7830   // and those shouldn't have qualifier variants anyway.
7831   if (PointeeTy->isArrayType())
7832     return true;
7833 
7834   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7835   bool hasVolatile = VisibleQuals.hasVolatile();
7836   bool hasRestrict = VisibleQuals.hasRestrict();
7837 
7838   // Iterate through all strict supersets of BaseCVR.
7839   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7840     if ((CVR | BaseCVR) != CVR) continue;
7841     // Skip over volatile if no volatile found anywhere in the types.
7842     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7843 
7844     // Skip over restrict if no restrict found anywhere in the types, or if
7845     // the type cannot be restrict-qualified.
7846     if ((CVR & Qualifiers::Restrict) &&
7847         (!hasRestrict ||
7848          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7849       continue;
7850 
7851     // Build qualified pointee type.
7852     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7853 
7854     // Build qualified pointer type.
7855     QualType QPointerTy;
7856     if (!buildObjCPtr)
7857       QPointerTy = Context.getPointerType(QPointeeTy);
7858     else
7859       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7860 
7861     // Insert qualified pointer type.
7862     PointerTypes.insert(QPointerTy);
7863   }
7864 
7865   return true;
7866 }
7867 
7868 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7869 /// to the set of pointer types along with any more-qualified variants of
7870 /// that type. For example, if @p Ty is "int const *", this routine
7871 /// will add "int const *", "int const volatile *", "int const
7872 /// restrict *", and "int const volatile restrict *" to the set of
7873 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7874 /// false otherwise.
7875 ///
7876 /// FIXME: what to do about extended qualifiers?
7877 bool
7878 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7879     QualType Ty) {
7880   // Insert this type.
7881   if (!MemberPointerTypes.insert(Ty))
7882     return false;
7883 
7884   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7885   assert(PointerTy && "type was not a member pointer type!");
7886 
7887   QualType PointeeTy = PointerTy->getPointeeType();
7888   // Don't add qualified variants of arrays. For one, they're not allowed
7889   // (the qualifier would sink to the element type), and for another, the
7890   // only overload situation where it matters is subscript or pointer +- int,
7891   // and those shouldn't have qualifier variants anyway.
7892   if (PointeeTy->isArrayType())
7893     return true;
7894   const Type *ClassTy = PointerTy->getClass();
7895 
7896   // Iterate through all strict supersets of the pointee type's CVR
7897   // qualifiers.
7898   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7899   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7900     if ((CVR | BaseCVR) != CVR) continue;
7901 
7902     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7903     MemberPointerTypes.insert(
7904       Context.getMemberPointerType(QPointeeTy, ClassTy));
7905   }
7906 
7907   return true;
7908 }
7909 
7910 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7911 /// Ty can be implicit converted to the given set of @p Types. We're
7912 /// primarily interested in pointer types and enumeration types. We also
7913 /// take member pointer types, for the conditional operator.
7914 /// AllowUserConversions is true if we should look at the conversion
7915 /// functions of a class type, and AllowExplicitConversions if we
7916 /// should also include the explicit conversion functions of a class
7917 /// type.
7918 void
7919 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7920                                                SourceLocation Loc,
7921                                                bool AllowUserConversions,
7922                                                bool AllowExplicitConversions,
7923                                                const Qualifiers &VisibleQuals) {
7924   // Only deal with canonical types.
7925   Ty = Context.getCanonicalType(Ty);
7926 
7927   // Look through reference types; they aren't part of the type of an
7928   // expression for the purposes of conversions.
7929   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7930     Ty = RefTy->getPointeeType();
7931 
7932   // If we're dealing with an array type, decay to the pointer.
7933   if (Ty->isArrayType())
7934     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7935 
7936   // Otherwise, we don't care about qualifiers on the type.
7937   Ty = Ty.getLocalUnqualifiedType();
7938 
7939   // Flag if we ever add a non-record type.
7940   const RecordType *TyRec = Ty->getAs<RecordType>();
7941   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7942 
7943   // Flag if we encounter an arithmetic type.
7944   HasArithmeticOrEnumeralTypes =
7945     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7946 
7947   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7948     PointerTypes.insert(Ty);
7949   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7950     // Insert our type, and its more-qualified variants, into the set
7951     // of types.
7952     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7953       return;
7954   } else if (Ty->isMemberPointerType()) {
7955     // Member pointers are far easier, since the pointee can't be converted.
7956     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7957       return;
7958   } else if (Ty->isEnumeralType()) {
7959     HasArithmeticOrEnumeralTypes = true;
7960     EnumerationTypes.insert(Ty);
7961   } else if (Ty->isVectorType()) {
7962     // We treat vector types as arithmetic types in many contexts as an
7963     // extension.
7964     HasArithmeticOrEnumeralTypes = true;
7965     VectorTypes.insert(Ty);
7966   } else if (Ty->isMatrixType()) {
7967     // Similar to vector types, we treat vector types as arithmetic types in
7968     // many contexts as an extension.
7969     HasArithmeticOrEnumeralTypes = true;
7970     MatrixTypes.insert(Ty);
7971   } else if (Ty->isNullPtrType()) {
7972     HasNullPtrType = true;
7973   } else if (AllowUserConversions && TyRec) {
7974     // No conversion functions in incomplete types.
7975     if (!SemaRef.isCompleteType(Loc, Ty))
7976       return;
7977 
7978     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7979     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7980       if (isa<UsingShadowDecl>(D))
7981         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7982 
7983       // Skip conversion function templates; they don't tell us anything
7984       // about which builtin types we can convert to.
7985       if (isa<FunctionTemplateDecl>(D))
7986         continue;
7987 
7988       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7989       if (AllowExplicitConversions || !Conv->isExplicit()) {
7990         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7991                               VisibleQuals);
7992       }
7993     }
7994   }
7995 }
7996 /// Helper function for adjusting address spaces for the pointer or reference
7997 /// operands of builtin operators depending on the argument.
7998 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7999                                                         Expr *Arg) {
8000   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8001 }
8002 
8003 /// Helper function for AddBuiltinOperatorCandidates() that adds
8004 /// the volatile- and non-volatile-qualified assignment operators for the
8005 /// given type to the candidate set.
8006 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8007                                                    QualType T,
8008                                                    ArrayRef<Expr *> Args,
8009                                     OverloadCandidateSet &CandidateSet) {
8010   QualType ParamTypes[2];
8011 
8012   // T& operator=(T&, T)
8013   ParamTypes[0] = S.Context.getLValueReferenceType(
8014       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8015   ParamTypes[1] = T;
8016   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8017                         /*IsAssignmentOperator=*/true);
8018 
8019   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8020     // volatile T& operator=(volatile T&, T)
8021     ParamTypes[0] = S.Context.getLValueReferenceType(
8022         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8023                                                 Args[0]));
8024     ParamTypes[1] = T;
8025     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8026                           /*IsAssignmentOperator=*/true);
8027   }
8028 }
8029 
8030 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8031 /// if any, found in visible type conversion functions found in ArgExpr's type.
8032 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8033     Qualifiers VRQuals;
8034     const RecordType *TyRec;
8035     if (const MemberPointerType *RHSMPType =
8036         ArgExpr->getType()->getAs<MemberPointerType>())
8037       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8038     else
8039       TyRec = ArgExpr->getType()->getAs<RecordType>();
8040     if (!TyRec) {
8041       // Just to be safe, assume the worst case.
8042       VRQuals.addVolatile();
8043       VRQuals.addRestrict();
8044       return VRQuals;
8045     }
8046 
8047     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8048     if (!ClassDecl->hasDefinition())
8049       return VRQuals;
8050 
8051     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8052       if (isa<UsingShadowDecl>(D))
8053         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8054       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8055         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8056         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8057           CanTy = ResTypeRef->getPointeeType();
8058         // Need to go down the pointer/mempointer chain and add qualifiers
8059         // as see them.
8060         bool done = false;
8061         while (!done) {
8062           if (CanTy.isRestrictQualified())
8063             VRQuals.addRestrict();
8064           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8065             CanTy = ResTypePtr->getPointeeType();
8066           else if (const MemberPointerType *ResTypeMPtr =
8067                 CanTy->getAs<MemberPointerType>())
8068             CanTy = ResTypeMPtr->getPointeeType();
8069           else
8070             done = true;
8071           if (CanTy.isVolatileQualified())
8072             VRQuals.addVolatile();
8073           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8074             return VRQuals;
8075         }
8076       }
8077     }
8078     return VRQuals;
8079 }
8080 
8081 namespace {
8082 
8083 /// Helper class to manage the addition of builtin operator overload
8084 /// candidates. It provides shared state and utility methods used throughout
8085 /// the process, as well as a helper method to add each group of builtin
8086 /// operator overloads from the standard to a candidate set.
8087 class BuiltinOperatorOverloadBuilder {
8088   // Common instance state available to all overload candidate addition methods.
8089   Sema &S;
8090   ArrayRef<Expr *> Args;
8091   Qualifiers VisibleTypeConversionsQuals;
8092   bool HasArithmeticOrEnumeralCandidateType;
8093   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8094   OverloadCandidateSet &CandidateSet;
8095 
8096   static constexpr int ArithmeticTypesCap = 24;
8097   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8098 
8099   // Define some indices used to iterate over the arithmetic types in
8100   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8101   // types are that preserved by promotion (C++ [over.built]p2).
8102   unsigned FirstIntegralType,
8103            LastIntegralType;
8104   unsigned FirstPromotedIntegralType,
8105            LastPromotedIntegralType;
8106   unsigned FirstPromotedArithmeticType,
8107            LastPromotedArithmeticType;
8108   unsigned NumArithmeticTypes;
8109 
8110   void InitArithmeticTypes() {
8111     // Start of promoted types.
8112     FirstPromotedArithmeticType = 0;
8113     ArithmeticTypes.push_back(S.Context.FloatTy);
8114     ArithmeticTypes.push_back(S.Context.DoubleTy);
8115     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8116     if (S.Context.getTargetInfo().hasFloat128Type())
8117       ArithmeticTypes.push_back(S.Context.Float128Ty);
8118 
8119     // Start of integral types.
8120     FirstIntegralType = ArithmeticTypes.size();
8121     FirstPromotedIntegralType = ArithmeticTypes.size();
8122     ArithmeticTypes.push_back(S.Context.IntTy);
8123     ArithmeticTypes.push_back(S.Context.LongTy);
8124     ArithmeticTypes.push_back(S.Context.LongLongTy);
8125     if (S.Context.getTargetInfo().hasInt128Type())
8126       ArithmeticTypes.push_back(S.Context.Int128Ty);
8127     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8128     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8129     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8130     if (S.Context.getTargetInfo().hasInt128Type())
8131       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8132     LastPromotedIntegralType = ArithmeticTypes.size();
8133     LastPromotedArithmeticType = ArithmeticTypes.size();
8134     // End of promoted types.
8135 
8136     ArithmeticTypes.push_back(S.Context.BoolTy);
8137     ArithmeticTypes.push_back(S.Context.CharTy);
8138     ArithmeticTypes.push_back(S.Context.WCharTy);
8139     if (S.Context.getLangOpts().Char8)
8140       ArithmeticTypes.push_back(S.Context.Char8Ty);
8141     ArithmeticTypes.push_back(S.Context.Char16Ty);
8142     ArithmeticTypes.push_back(S.Context.Char32Ty);
8143     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8144     ArithmeticTypes.push_back(S.Context.ShortTy);
8145     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8146     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8147     LastIntegralType = ArithmeticTypes.size();
8148     NumArithmeticTypes = ArithmeticTypes.size();
8149     // End of integral types.
8150     // FIXME: What about complex? What about half?
8151 
8152     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8153            "Enough inline storage for all arithmetic types.");
8154   }
8155 
8156   /// Helper method to factor out the common pattern of adding overloads
8157   /// for '++' and '--' builtin operators.
8158   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8159                                            bool HasVolatile,
8160                                            bool HasRestrict) {
8161     QualType ParamTypes[2] = {
8162       S.Context.getLValueReferenceType(CandidateTy),
8163       S.Context.IntTy
8164     };
8165 
8166     // Non-volatile version.
8167     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8168 
8169     // Use a heuristic to reduce number of builtin candidates in the set:
8170     // add volatile version only if there are conversions to a volatile type.
8171     if (HasVolatile) {
8172       ParamTypes[0] =
8173         S.Context.getLValueReferenceType(
8174           S.Context.getVolatileType(CandidateTy));
8175       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8176     }
8177 
8178     // Add restrict version only if there are conversions to a restrict type
8179     // and our candidate type is a non-restrict-qualified pointer.
8180     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8181         !CandidateTy.isRestrictQualified()) {
8182       ParamTypes[0]
8183         = S.Context.getLValueReferenceType(
8184             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8185       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8186 
8187       if (HasVolatile) {
8188         ParamTypes[0]
8189           = S.Context.getLValueReferenceType(
8190               S.Context.getCVRQualifiedType(CandidateTy,
8191                                             (Qualifiers::Volatile |
8192                                              Qualifiers::Restrict)));
8193         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8194       }
8195     }
8196 
8197   }
8198 
8199   /// Helper to add an overload candidate for a binary builtin with types \p L
8200   /// and \p R.
8201   void AddCandidate(QualType L, QualType R) {
8202     QualType LandR[2] = {L, R};
8203     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8204   }
8205 
8206 public:
8207   BuiltinOperatorOverloadBuilder(
8208     Sema &S, ArrayRef<Expr *> Args,
8209     Qualifiers VisibleTypeConversionsQuals,
8210     bool HasArithmeticOrEnumeralCandidateType,
8211     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8212     OverloadCandidateSet &CandidateSet)
8213     : S(S), Args(Args),
8214       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8215       HasArithmeticOrEnumeralCandidateType(
8216         HasArithmeticOrEnumeralCandidateType),
8217       CandidateTypes(CandidateTypes),
8218       CandidateSet(CandidateSet) {
8219 
8220     InitArithmeticTypes();
8221   }
8222 
8223   // Increment is deprecated for bool since C++17.
8224   //
8225   // C++ [over.built]p3:
8226   //
8227   //   For every pair (T, VQ), where T is an arithmetic type other
8228   //   than bool, and VQ is either volatile or empty, there exist
8229   //   candidate operator functions of the form
8230   //
8231   //       VQ T&      operator++(VQ T&);
8232   //       T          operator++(VQ T&, int);
8233   //
8234   // C++ [over.built]p4:
8235   //
8236   //   For every pair (T, VQ), where T is an arithmetic type other
8237   //   than bool, and VQ is either volatile or empty, there exist
8238   //   candidate operator functions of the form
8239   //
8240   //       VQ T&      operator--(VQ T&);
8241   //       T          operator--(VQ T&, int);
8242   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8243     if (!HasArithmeticOrEnumeralCandidateType)
8244       return;
8245 
8246     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8247       const auto TypeOfT = ArithmeticTypes[Arith];
8248       if (TypeOfT == S.Context.BoolTy) {
8249         if (Op == OO_MinusMinus)
8250           continue;
8251         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8252           continue;
8253       }
8254       addPlusPlusMinusMinusStyleOverloads(
8255         TypeOfT,
8256         VisibleTypeConversionsQuals.hasVolatile(),
8257         VisibleTypeConversionsQuals.hasRestrict());
8258     }
8259   }
8260 
8261   // C++ [over.built]p5:
8262   //
8263   //   For every pair (T, VQ), where T is a cv-qualified or
8264   //   cv-unqualified object type, and VQ is either volatile or
8265   //   empty, there exist candidate operator functions of the form
8266   //
8267   //       T*VQ&      operator++(T*VQ&);
8268   //       T*VQ&      operator--(T*VQ&);
8269   //       T*         operator++(T*VQ&, int);
8270   //       T*         operator--(T*VQ&, int);
8271   void addPlusPlusMinusMinusPointerOverloads() {
8272     for (BuiltinCandidateTypeSet::iterator
8273               Ptr = CandidateTypes[0].pointer_begin(),
8274            PtrEnd = CandidateTypes[0].pointer_end();
8275          Ptr != PtrEnd; ++Ptr) {
8276       // Skip pointer types that aren't pointers to object types.
8277       if (!(*Ptr)->getPointeeType()->isObjectType())
8278         continue;
8279 
8280       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8281         (!(*Ptr).isVolatileQualified() &&
8282          VisibleTypeConversionsQuals.hasVolatile()),
8283         (!(*Ptr).isRestrictQualified() &&
8284          VisibleTypeConversionsQuals.hasRestrict()));
8285     }
8286   }
8287 
8288   // C++ [over.built]p6:
8289   //   For every cv-qualified or cv-unqualified object type T, there
8290   //   exist candidate operator functions of the form
8291   //
8292   //       T&         operator*(T*);
8293   //
8294   // C++ [over.built]p7:
8295   //   For every function type T that does not have cv-qualifiers or a
8296   //   ref-qualifier, there exist candidate operator functions of the form
8297   //       T&         operator*(T*);
8298   void addUnaryStarPointerOverloads() {
8299     for (BuiltinCandidateTypeSet::iterator
8300               Ptr = CandidateTypes[0].pointer_begin(),
8301            PtrEnd = CandidateTypes[0].pointer_end();
8302          Ptr != PtrEnd; ++Ptr) {
8303       QualType ParamTy = *Ptr;
8304       QualType PointeeTy = ParamTy->getPointeeType();
8305       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8306         continue;
8307 
8308       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8309         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8310           continue;
8311 
8312       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8313     }
8314   }
8315 
8316   // C++ [over.built]p9:
8317   //  For every promoted arithmetic type T, there exist candidate
8318   //  operator functions of the form
8319   //
8320   //       T         operator+(T);
8321   //       T         operator-(T);
8322   void addUnaryPlusOrMinusArithmeticOverloads() {
8323     if (!HasArithmeticOrEnumeralCandidateType)
8324       return;
8325 
8326     for (unsigned Arith = FirstPromotedArithmeticType;
8327          Arith < LastPromotedArithmeticType; ++Arith) {
8328       QualType ArithTy = ArithmeticTypes[Arith];
8329       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8330     }
8331 
8332     // Extension: We also add these operators for vector types.
8333     for (QualType VecTy : CandidateTypes[0].vector_types())
8334       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8335   }
8336 
8337   // C++ [over.built]p8:
8338   //   For every type T, there exist candidate operator functions of
8339   //   the form
8340   //
8341   //       T*         operator+(T*);
8342   void addUnaryPlusPointerOverloads() {
8343     for (BuiltinCandidateTypeSet::iterator
8344               Ptr = CandidateTypes[0].pointer_begin(),
8345            PtrEnd = CandidateTypes[0].pointer_end();
8346          Ptr != PtrEnd; ++Ptr) {
8347       QualType ParamTy = *Ptr;
8348       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8349     }
8350   }
8351 
8352   // C++ [over.built]p10:
8353   //   For every promoted integral type T, there exist candidate
8354   //   operator functions of the form
8355   //
8356   //        T         operator~(T);
8357   void addUnaryTildePromotedIntegralOverloads() {
8358     if (!HasArithmeticOrEnumeralCandidateType)
8359       return;
8360 
8361     for (unsigned Int = FirstPromotedIntegralType;
8362          Int < LastPromotedIntegralType; ++Int) {
8363       QualType IntTy = ArithmeticTypes[Int];
8364       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8365     }
8366 
8367     // Extension: We also add this operator for vector types.
8368     for (QualType VecTy : CandidateTypes[0].vector_types())
8369       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8370   }
8371 
8372   // C++ [over.match.oper]p16:
8373   //   For every pointer to member type T or type std::nullptr_t, there
8374   //   exist candidate operator functions of the form
8375   //
8376   //        bool operator==(T,T);
8377   //        bool operator!=(T,T);
8378   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8379     /// Set of (canonical) types that we've already handled.
8380     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8381 
8382     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8383       for (BuiltinCandidateTypeSet::iterator
8384                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8385              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8386            MemPtr != MemPtrEnd;
8387            ++MemPtr) {
8388         // Don't add the same builtin candidate twice.
8389         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8390           continue;
8391 
8392         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8393         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8394       }
8395 
8396       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8397         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8398         if (AddedTypes.insert(NullPtrTy).second) {
8399           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8400           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8401         }
8402       }
8403     }
8404   }
8405 
8406   // C++ [over.built]p15:
8407   //
8408   //   For every T, where T is an enumeration type or a pointer type,
8409   //   there exist candidate operator functions of the form
8410   //
8411   //        bool       operator<(T, T);
8412   //        bool       operator>(T, T);
8413   //        bool       operator<=(T, T);
8414   //        bool       operator>=(T, T);
8415   //        bool       operator==(T, T);
8416   //        bool       operator!=(T, T);
8417   //           R       operator<=>(T, T)
8418   void addGenericBinaryPointerOrEnumeralOverloads() {
8419     // C++ [over.match.oper]p3:
8420     //   [...]the built-in candidates include all of the candidate operator
8421     //   functions defined in 13.6 that, compared to the given operator, [...]
8422     //   do not have the same parameter-type-list as any non-template non-member
8423     //   candidate.
8424     //
8425     // Note that in practice, this only affects enumeration types because there
8426     // aren't any built-in candidates of record type, and a user-defined operator
8427     // must have an operand of record or enumeration type. Also, the only other
8428     // overloaded operator with enumeration arguments, operator=,
8429     // cannot be overloaded for enumeration types, so this is the only place
8430     // where we must suppress candidates like this.
8431     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8432       UserDefinedBinaryOperators;
8433 
8434     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8435       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8436           CandidateTypes[ArgIdx].enumeration_end()) {
8437         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8438                                          CEnd = CandidateSet.end();
8439              C != CEnd; ++C) {
8440           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8441             continue;
8442 
8443           if (C->Function->isFunctionTemplateSpecialization())
8444             continue;
8445 
8446           // We interpret "same parameter-type-list" as applying to the
8447           // "synthesized candidate, with the order of the two parameters
8448           // reversed", not to the original function.
8449           bool Reversed = C->isReversed();
8450           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8451                                         ->getType()
8452                                         .getUnqualifiedType();
8453           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8454                                          ->getType()
8455                                          .getUnqualifiedType();
8456 
8457           // Skip if either parameter isn't of enumeral type.
8458           if (!FirstParamType->isEnumeralType() ||
8459               !SecondParamType->isEnumeralType())
8460             continue;
8461 
8462           // Add this operator to the set of known user-defined operators.
8463           UserDefinedBinaryOperators.insert(
8464             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8465                            S.Context.getCanonicalType(SecondParamType)));
8466         }
8467       }
8468     }
8469 
8470     /// Set of (canonical) types that we've already handled.
8471     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8472 
8473     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8474       for (BuiltinCandidateTypeSet::iterator
8475                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8476              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8477            Ptr != PtrEnd; ++Ptr) {
8478         // Don't add the same builtin candidate twice.
8479         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8480           continue;
8481 
8482         QualType ParamTypes[2] = { *Ptr, *Ptr };
8483         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8484       }
8485       for (BuiltinCandidateTypeSet::iterator
8486                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8487              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8488            Enum != EnumEnd; ++Enum) {
8489         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8490 
8491         // Don't add the same builtin candidate twice, or if a user defined
8492         // candidate exists.
8493         if (!AddedTypes.insert(CanonType).second ||
8494             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8495                                                             CanonType)))
8496           continue;
8497         QualType ParamTypes[2] = { *Enum, *Enum };
8498         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8499       }
8500     }
8501   }
8502 
8503   // C++ [over.built]p13:
8504   //
8505   //   For every cv-qualified or cv-unqualified object type T
8506   //   there exist candidate operator functions of the form
8507   //
8508   //      T*         operator+(T*, ptrdiff_t);
8509   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8510   //      T*         operator-(T*, ptrdiff_t);
8511   //      T*         operator+(ptrdiff_t, T*);
8512   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8513   //
8514   // C++ [over.built]p14:
8515   //
8516   //   For every T, where T is a pointer to object type, there
8517   //   exist candidate operator functions of the form
8518   //
8519   //      ptrdiff_t  operator-(T, T);
8520   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8521     /// Set of (canonical) types that we've already handled.
8522     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8523 
8524     for (int Arg = 0; Arg < 2; ++Arg) {
8525       QualType AsymmetricParamTypes[2] = {
8526         S.Context.getPointerDiffType(),
8527         S.Context.getPointerDiffType(),
8528       };
8529       for (BuiltinCandidateTypeSet::iterator
8530                 Ptr = CandidateTypes[Arg].pointer_begin(),
8531              PtrEnd = CandidateTypes[Arg].pointer_end();
8532            Ptr != PtrEnd; ++Ptr) {
8533         QualType PointeeTy = (*Ptr)->getPointeeType();
8534         if (!PointeeTy->isObjectType())
8535           continue;
8536 
8537         AsymmetricParamTypes[Arg] = *Ptr;
8538         if (Arg == 0 || Op == OO_Plus) {
8539           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8540           // T* operator+(ptrdiff_t, T*);
8541           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8542         }
8543         if (Op == OO_Minus) {
8544           // ptrdiff_t operator-(T, T);
8545           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8546             continue;
8547 
8548           QualType ParamTypes[2] = { *Ptr, *Ptr };
8549           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8550         }
8551       }
8552     }
8553   }
8554 
8555   // C++ [over.built]p12:
8556   //
8557   //   For every pair of promoted arithmetic types L and R, there
8558   //   exist candidate operator functions of the form
8559   //
8560   //        LR         operator*(L, R);
8561   //        LR         operator/(L, R);
8562   //        LR         operator+(L, R);
8563   //        LR         operator-(L, R);
8564   //        bool       operator<(L, R);
8565   //        bool       operator>(L, R);
8566   //        bool       operator<=(L, R);
8567   //        bool       operator>=(L, R);
8568   //        bool       operator==(L, R);
8569   //        bool       operator!=(L, R);
8570   //
8571   //   where LR is the result of the usual arithmetic conversions
8572   //   between types L and R.
8573   //
8574   // C++ [over.built]p24:
8575   //
8576   //   For every pair of promoted arithmetic types L and R, there exist
8577   //   candidate operator functions of the form
8578   //
8579   //        LR       operator?(bool, L, R);
8580   //
8581   //   where LR is the result of the usual arithmetic conversions
8582   //   between types L and R.
8583   // Our candidates ignore the first parameter.
8584   void addGenericBinaryArithmeticOverloads() {
8585     if (!HasArithmeticOrEnumeralCandidateType)
8586       return;
8587 
8588     for (unsigned Left = FirstPromotedArithmeticType;
8589          Left < LastPromotedArithmeticType; ++Left) {
8590       for (unsigned Right = FirstPromotedArithmeticType;
8591            Right < LastPromotedArithmeticType; ++Right) {
8592         QualType LandR[2] = { ArithmeticTypes[Left],
8593                               ArithmeticTypes[Right] };
8594         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8595       }
8596     }
8597 
8598     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8599     // conditional operator for vector types.
8600     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8601       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8602         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8603         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8604       }
8605   }
8606 
8607   /// Add binary operator overloads for each candidate matrix type M1, M2:
8608   ///  * (M1, M1) -> M1
8609   ///  * (M1, M1.getElementType()) -> M1
8610   ///  * (M2.getElementType(), M2) -> M2
8611   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8612   void addMatrixBinaryArithmeticOverloads() {
8613     if (!HasArithmeticOrEnumeralCandidateType)
8614       return;
8615 
8616     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8617       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8618       AddCandidate(M1, M1);
8619     }
8620 
8621     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8622       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8623       if (!CandidateTypes[0].containsMatrixType(M2))
8624         AddCandidate(M2, M2);
8625     }
8626   }
8627 
8628   // C++2a [over.built]p14:
8629   //
8630   //   For every integral type T there exists a candidate operator function
8631   //   of the form
8632   //
8633   //        std::strong_ordering operator<=>(T, T)
8634   //
8635   // C++2a [over.built]p15:
8636   //
8637   //   For every pair of floating-point types L and R, there exists a candidate
8638   //   operator function of the form
8639   //
8640   //       std::partial_ordering operator<=>(L, R);
8641   //
8642   // FIXME: The current specification for integral types doesn't play nice with
8643   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8644   // comparisons. Under the current spec this can lead to ambiguity during
8645   // overload resolution. For example:
8646   //
8647   //   enum A : int {a};
8648   //   auto x = (a <=> (long)42);
8649   //
8650   //   error: call is ambiguous for arguments 'A' and 'long'.
8651   //   note: candidate operator<=>(int, int)
8652   //   note: candidate operator<=>(long, long)
8653   //
8654   // To avoid this error, this function deviates from the specification and adds
8655   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8656   // arithmetic types (the same as the generic relational overloads).
8657   //
8658   // For now this function acts as a placeholder.
8659   void addThreeWayArithmeticOverloads() {
8660     addGenericBinaryArithmeticOverloads();
8661   }
8662 
8663   // C++ [over.built]p17:
8664   //
8665   //   For every pair of promoted integral types L and R, there
8666   //   exist candidate operator functions of the form
8667   //
8668   //      LR         operator%(L, R);
8669   //      LR         operator&(L, R);
8670   //      LR         operator^(L, R);
8671   //      LR         operator|(L, R);
8672   //      L          operator<<(L, R);
8673   //      L          operator>>(L, R);
8674   //
8675   //   where LR is the result of the usual arithmetic conversions
8676   //   between types L and R.
8677   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8678     if (!HasArithmeticOrEnumeralCandidateType)
8679       return;
8680 
8681     for (unsigned Left = FirstPromotedIntegralType;
8682          Left < LastPromotedIntegralType; ++Left) {
8683       for (unsigned Right = FirstPromotedIntegralType;
8684            Right < LastPromotedIntegralType; ++Right) {
8685         QualType LandR[2] = { ArithmeticTypes[Left],
8686                               ArithmeticTypes[Right] };
8687         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8688       }
8689     }
8690   }
8691 
8692   // C++ [over.built]p20:
8693   //
8694   //   For every pair (T, VQ), where T is an enumeration or
8695   //   pointer to member type and VQ is either volatile or
8696   //   empty, there exist candidate operator functions of the form
8697   //
8698   //        VQ T&      operator=(VQ T&, T);
8699   void addAssignmentMemberPointerOrEnumeralOverloads() {
8700     /// Set of (canonical) types that we've already handled.
8701     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8702 
8703     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8704       for (BuiltinCandidateTypeSet::iterator
8705                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8706              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8707            Enum != EnumEnd; ++Enum) {
8708         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8709           continue;
8710 
8711         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8712       }
8713 
8714       for (BuiltinCandidateTypeSet::iterator
8715                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8716              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8717            MemPtr != MemPtrEnd; ++MemPtr) {
8718         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8719           continue;
8720 
8721         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8722       }
8723     }
8724   }
8725 
8726   // C++ [over.built]p19:
8727   //
8728   //   For every pair (T, VQ), where T is any type and VQ is either
8729   //   volatile or empty, there exist candidate operator functions
8730   //   of the form
8731   //
8732   //        T*VQ&      operator=(T*VQ&, T*);
8733   //
8734   // C++ [over.built]p21:
8735   //
8736   //   For every pair (T, VQ), where T is a cv-qualified or
8737   //   cv-unqualified object type and VQ is either volatile or
8738   //   empty, there exist candidate operator functions of the form
8739   //
8740   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8741   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8742   void addAssignmentPointerOverloads(bool isEqualOp) {
8743     /// Set of (canonical) types that we've already handled.
8744     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8745 
8746     for (BuiltinCandidateTypeSet::iterator
8747               Ptr = CandidateTypes[0].pointer_begin(),
8748            PtrEnd = CandidateTypes[0].pointer_end();
8749          Ptr != PtrEnd; ++Ptr) {
8750       // If this is operator=, keep track of the builtin candidates we added.
8751       if (isEqualOp)
8752         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8753       else if (!(*Ptr)->getPointeeType()->isObjectType())
8754         continue;
8755 
8756       // non-volatile version
8757       QualType ParamTypes[2] = {
8758         S.Context.getLValueReferenceType(*Ptr),
8759         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8760       };
8761       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8762                             /*IsAssignmentOperator=*/ isEqualOp);
8763 
8764       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8765                           VisibleTypeConversionsQuals.hasVolatile();
8766       if (NeedVolatile) {
8767         // volatile version
8768         ParamTypes[0] =
8769           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8770         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8771                               /*IsAssignmentOperator=*/isEqualOp);
8772       }
8773 
8774       if (!(*Ptr).isRestrictQualified() &&
8775           VisibleTypeConversionsQuals.hasRestrict()) {
8776         // restrict version
8777         ParamTypes[0]
8778           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8779         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8780                               /*IsAssignmentOperator=*/isEqualOp);
8781 
8782         if (NeedVolatile) {
8783           // volatile restrict version
8784           ParamTypes[0]
8785             = S.Context.getLValueReferenceType(
8786                 S.Context.getCVRQualifiedType(*Ptr,
8787                                               (Qualifiers::Volatile |
8788                                                Qualifiers::Restrict)));
8789           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8790                                 /*IsAssignmentOperator=*/isEqualOp);
8791         }
8792       }
8793     }
8794 
8795     if (isEqualOp) {
8796       for (BuiltinCandidateTypeSet::iterator
8797                 Ptr = CandidateTypes[1].pointer_begin(),
8798              PtrEnd = CandidateTypes[1].pointer_end();
8799            Ptr != PtrEnd; ++Ptr) {
8800         // Make sure we don't add the same candidate twice.
8801         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8802           continue;
8803 
8804         QualType ParamTypes[2] = {
8805           S.Context.getLValueReferenceType(*Ptr),
8806           *Ptr,
8807         };
8808 
8809         // non-volatile version
8810         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8811                               /*IsAssignmentOperator=*/true);
8812 
8813         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8814                            VisibleTypeConversionsQuals.hasVolatile();
8815         if (NeedVolatile) {
8816           // volatile version
8817           ParamTypes[0] =
8818             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8819           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8820                                 /*IsAssignmentOperator=*/true);
8821         }
8822 
8823         if (!(*Ptr).isRestrictQualified() &&
8824             VisibleTypeConversionsQuals.hasRestrict()) {
8825           // restrict version
8826           ParamTypes[0]
8827             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8828           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8829                                 /*IsAssignmentOperator=*/true);
8830 
8831           if (NeedVolatile) {
8832             // volatile restrict version
8833             ParamTypes[0]
8834               = S.Context.getLValueReferenceType(
8835                   S.Context.getCVRQualifiedType(*Ptr,
8836                                                 (Qualifiers::Volatile |
8837                                                  Qualifiers::Restrict)));
8838             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8839                                   /*IsAssignmentOperator=*/true);
8840           }
8841         }
8842       }
8843     }
8844   }
8845 
8846   // C++ [over.built]p18:
8847   //
8848   //   For every triple (L, VQ, R), where L is an arithmetic type,
8849   //   VQ is either volatile or empty, and R is a promoted
8850   //   arithmetic type, there exist candidate operator functions of
8851   //   the form
8852   //
8853   //        VQ L&      operator=(VQ L&, R);
8854   //        VQ L&      operator*=(VQ L&, R);
8855   //        VQ L&      operator/=(VQ L&, R);
8856   //        VQ L&      operator+=(VQ L&, R);
8857   //        VQ L&      operator-=(VQ L&, R);
8858   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8859     if (!HasArithmeticOrEnumeralCandidateType)
8860       return;
8861 
8862     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8863       for (unsigned Right = FirstPromotedArithmeticType;
8864            Right < LastPromotedArithmeticType; ++Right) {
8865         QualType ParamTypes[2];
8866         ParamTypes[1] = ArithmeticTypes[Right];
8867         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8868             S, ArithmeticTypes[Left], Args[0]);
8869         // Add this built-in operator as a candidate (VQ is empty).
8870         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8871         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8872                               /*IsAssignmentOperator=*/isEqualOp);
8873 
8874         // Add this built-in operator as a candidate (VQ is 'volatile').
8875         if (VisibleTypeConversionsQuals.hasVolatile()) {
8876           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8877           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8878           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8879                                 /*IsAssignmentOperator=*/isEqualOp);
8880         }
8881       }
8882     }
8883 
8884     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8885     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8886       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8887         QualType ParamTypes[2];
8888         ParamTypes[1] = Vec2Ty;
8889         // Add this built-in operator as a candidate (VQ is empty).
8890         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8891         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8892                               /*IsAssignmentOperator=*/isEqualOp);
8893 
8894         // Add this built-in operator as a candidate (VQ is 'volatile').
8895         if (VisibleTypeConversionsQuals.hasVolatile()) {
8896           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8897           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8898           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8899                                 /*IsAssignmentOperator=*/isEqualOp);
8900         }
8901       }
8902   }
8903 
8904   // C++ [over.built]p22:
8905   //
8906   //   For every triple (L, VQ, R), where L is an integral type, VQ
8907   //   is either volatile or empty, and R is a promoted integral
8908   //   type, there exist candidate operator functions of the form
8909   //
8910   //        VQ L&       operator%=(VQ L&, R);
8911   //        VQ L&       operator<<=(VQ L&, R);
8912   //        VQ L&       operator>>=(VQ L&, R);
8913   //        VQ L&       operator&=(VQ L&, R);
8914   //        VQ L&       operator^=(VQ L&, R);
8915   //        VQ L&       operator|=(VQ L&, R);
8916   void addAssignmentIntegralOverloads() {
8917     if (!HasArithmeticOrEnumeralCandidateType)
8918       return;
8919 
8920     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8921       for (unsigned Right = FirstPromotedIntegralType;
8922            Right < LastPromotedIntegralType; ++Right) {
8923         QualType ParamTypes[2];
8924         ParamTypes[1] = ArithmeticTypes[Right];
8925         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8926             S, ArithmeticTypes[Left], Args[0]);
8927         // Add this built-in operator as a candidate (VQ is empty).
8928         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8929         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8930         if (VisibleTypeConversionsQuals.hasVolatile()) {
8931           // Add this built-in operator as a candidate (VQ is 'volatile').
8932           ParamTypes[0] = LeftBaseTy;
8933           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8934           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8935           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8936         }
8937       }
8938     }
8939   }
8940 
8941   // C++ [over.operator]p23:
8942   //
8943   //   There also exist candidate operator functions of the form
8944   //
8945   //        bool        operator!(bool);
8946   //        bool        operator&&(bool, bool);
8947   //        bool        operator||(bool, bool);
8948   void addExclaimOverload() {
8949     QualType ParamTy = S.Context.BoolTy;
8950     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8951                           /*IsAssignmentOperator=*/false,
8952                           /*NumContextualBoolArguments=*/1);
8953   }
8954   void addAmpAmpOrPipePipeOverload() {
8955     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8956     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8957                           /*IsAssignmentOperator=*/false,
8958                           /*NumContextualBoolArguments=*/2);
8959   }
8960 
8961   // C++ [over.built]p13:
8962   //
8963   //   For every cv-qualified or cv-unqualified object type T there
8964   //   exist candidate operator functions of the form
8965   //
8966   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8967   //        T&         operator[](T*, ptrdiff_t);
8968   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8969   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8970   //        T&         operator[](ptrdiff_t, T*);
8971   void addSubscriptOverloads() {
8972     for (BuiltinCandidateTypeSet::iterator
8973               Ptr = CandidateTypes[0].pointer_begin(),
8974            PtrEnd = CandidateTypes[0].pointer_end();
8975          Ptr != PtrEnd; ++Ptr) {
8976       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8977       QualType PointeeType = (*Ptr)->getPointeeType();
8978       if (!PointeeType->isObjectType())
8979         continue;
8980 
8981       // T& operator[](T*, ptrdiff_t)
8982       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8983     }
8984 
8985     for (BuiltinCandidateTypeSet::iterator
8986               Ptr = CandidateTypes[1].pointer_begin(),
8987            PtrEnd = CandidateTypes[1].pointer_end();
8988          Ptr != PtrEnd; ++Ptr) {
8989       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8990       QualType PointeeType = (*Ptr)->getPointeeType();
8991       if (!PointeeType->isObjectType())
8992         continue;
8993 
8994       // T& operator[](ptrdiff_t, T*)
8995       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8996     }
8997   }
8998 
8999   // C++ [over.built]p11:
9000   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9001   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9002   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9003   //    there exist candidate operator functions of the form
9004   //
9005   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9006   //
9007   //    where CV12 is the union of CV1 and CV2.
9008   void addArrowStarOverloads() {
9009     for (BuiltinCandidateTypeSet::iterator
9010              Ptr = CandidateTypes[0].pointer_begin(),
9011            PtrEnd = CandidateTypes[0].pointer_end();
9012          Ptr != PtrEnd; ++Ptr) {
9013       QualType C1Ty = (*Ptr);
9014       QualType C1;
9015       QualifierCollector Q1;
9016       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9017       if (!isa<RecordType>(C1))
9018         continue;
9019       // heuristic to reduce number of builtin candidates in the set.
9020       // Add volatile/restrict version only if there are conversions to a
9021       // volatile/restrict type.
9022       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9023         continue;
9024       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9025         continue;
9026       for (BuiltinCandidateTypeSet::iterator
9027                 MemPtr = CandidateTypes[1].member_pointer_begin(),
9028              MemPtrEnd = CandidateTypes[1].member_pointer_end();
9029            MemPtr != MemPtrEnd; ++MemPtr) {
9030         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9031         QualType C2 = QualType(mptr->getClass(), 0);
9032         C2 = C2.getUnqualifiedType();
9033         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9034           break;
9035         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9036         // build CV12 T&
9037         QualType T = mptr->getPointeeType();
9038         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9039             T.isVolatileQualified())
9040           continue;
9041         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9042             T.isRestrictQualified())
9043           continue;
9044         T = Q1.apply(S.Context, T);
9045         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9046       }
9047     }
9048   }
9049 
9050   // Note that we don't consider the first argument, since it has been
9051   // contextually converted to bool long ago. The candidates below are
9052   // therefore added as binary.
9053   //
9054   // C++ [over.built]p25:
9055   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9056   //   enumeration type, there exist candidate operator functions of the form
9057   //
9058   //        T        operator?(bool, T, T);
9059   //
9060   void addConditionalOperatorOverloads() {
9061     /// Set of (canonical) types that we've already handled.
9062     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9063 
9064     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9065       for (BuiltinCandidateTypeSet::iterator
9066                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9067              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9068            Ptr != PtrEnd; ++Ptr) {
9069         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9070           continue;
9071 
9072         QualType ParamTypes[2] = { *Ptr, *Ptr };
9073         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9074       }
9075 
9076       for (BuiltinCandidateTypeSet::iterator
9077                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9078              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9079            MemPtr != MemPtrEnd; ++MemPtr) {
9080         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9081           continue;
9082 
9083         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9084         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9085       }
9086 
9087       if (S.getLangOpts().CPlusPlus11) {
9088         for (BuiltinCandidateTypeSet::iterator
9089                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9090                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9091              Enum != EnumEnd; ++Enum) {
9092           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9093             continue;
9094 
9095           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9096             continue;
9097 
9098           QualType ParamTypes[2] = { *Enum, *Enum };
9099           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9100         }
9101       }
9102     }
9103   }
9104 };
9105 
9106 } // end anonymous namespace
9107 
9108 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9109 /// operator overloads to the candidate set (C++ [over.built]), based
9110 /// on the operator @p Op and the arguments given. For example, if the
9111 /// operator is a binary '+', this routine might add "int
9112 /// operator+(int, int)" to cover integer addition.
9113 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9114                                         SourceLocation OpLoc,
9115                                         ArrayRef<Expr *> Args,
9116                                         OverloadCandidateSet &CandidateSet) {
9117   // Find all of the types that the arguments can convert to, but only
9118   // if the operator we're looking at has built-in operator candidates
9119   // that make use of these types. Also record whether we encounter non-record
9120   // candidate types or either arithmetic or enumeral candidate types.
9121   Qualifiers VisibleTypeConversionsQuals;
9122   VisibleTypeConversionsQuals.addConst();
9123   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9124     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9125 
9126   bool HasNonRecordCandidateType = false;
9127   bool HasArithmeticOrEnumeralCandidateType = false;
9128   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9129   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9130     CandidateTypes.emplace_back(*this);
9131     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9132                                                  OpLoc,
9133                                                  true,
9134                                                  (Op == OO_Exclaim ||
9135                                                   Op == OO_AmpAmp ||
9136                                                   Op == OO_PipePipe),
9137                                                  VisibleTypeConversionsQuals);
9138     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9139         CandidateTypes[ArgIdx].hasNonRecordTypes();
9140     HasArithmeticOrEnumeralCandidateType =
9141         HasArithmeticOrEnumeralCandidateType ||
9142         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9143   }
9144 
9145   // Exit early when no non-record types have been added to the candidate set
9146   // for any of the arguments to the operator.
9147   //
9148   // We can't exit early for !, ||, or &&, since there we have always have
9149   // 'bool' overloads.
9150   if (!HasNonRecordCandidateType &&
9151       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9152     return;
9153 
9154   // Setup an object to manage the common state for building overloads.
9155   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9156                                            VisibleTypeConversionsQuals,
9157                                            HasArithmeticOrEnumeralCandidateType,
9158                                            CandidateTypes, CandidateSet);
9159 
9160   // Dispatch over the operation to add in only those overloads which apply.
9161   switch (Op) {
9162   case OO_None:
9163   case NUM_OVERLOADED_OPERATORS:
9164     llvm_unreachable("Expected an overloaded operator");
9165 
9166   case OO_New:
9167   case OO_Delete:
9168   case OO_Array_New:
9169   case OO_Array_Delete:
9170   case OO_Call:
9171     llvm_unreachable(
9172                     "Special operators don't use AddBuiltinOperatorCandidates");
9173 
9174   case OO_Comma:
9175   case OO_Arrow:
9176   case OO_Coawait:
9177     // C++ [over.match.oper]p3:
9178     //   -- For the operator ',', the unary operator '&', the
9179     //      operator '->', or the operator 'co_await', the
9180     //      built-in candidates set is empty.
9181     break;
9182 
9183   case OO_Plus: // '+' is either unary or binary
9184     if (Args.size() == 1)
9185       OpBuilder.addUnaryPlusPointerOverloads();
9186     LLVM_FALLTHROUGH;
9187 
9188   case OO_Minus: // '-' is either unary or binary
9189     if (Args.size() == 1) {
9190       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9191     } else {
9192       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9193       OpBuilder.addGenericBinaryArithmeticOverloads();
9194       OpBuilder.addMatrixBinaryArithmeticOverloads();
9195     }
9196     break;
9197 
9198   case OO_Star: // '*' is either unary or binary
9199     if (Args.size() == 1)
9200       OpBuilder.addUnaryStarPointerOverloads();
9201     else {
9202       OpBuilder.addGenericBinaryArithmeticOverloads();
9203       OpBuilder.addMatrixBinaryArithmeticOverloads();
9204     }
9205     break;
9206 
9207   case OO_Slash:
9208     OpBuilder.addGenericBinaryArithmeticOverloads();
9209     break;
9210 
9211   case OO_PlusPlus:
9212   case OO_MinusMinus:
9213     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9214     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9215     break;
9216 
9217   case OO_EqualEqual:
9218   case OO_ExclaimEqual:
9219     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9220     LLVM_FALLTHROUGH;
9221 
9222   case OO_Less:
9223   case OO_Greater:
9224   case OO_LessEqual:
9225   case OO_GreaterEqual:
9226     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9227     OpBuilder.addGenericBinaryArithmeticOverloads();
9228     break;
9229 
9230   case OO_Spaceship:
9231     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9232     OpBuilder.addThreeWayArithmeticOverloads();
9233     break;
9234 
9235   case OO_Percent:
9236   case OO_Caret:
9237   case OO_Pipe:
9238   case OO_LessLess:
9239   case OO_GreaterGreater:
9240     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9241     break;
9242 
9243   case OO_Amp: // '&' is either unary or binary
9244     if (Args.size() == 1)
9245       // C++ [over.match.oper]p3:
9246       //   -- For the operator ',', the unary operator '&', or the
9247       //      operator '->', the built-in candidates set is empty.
9248       break;
9249 
9250     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9251     break;
9252 
9253   case OO_Tilde:
9254     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9255     break;
9256 
9257   case OO_Equal:
9258     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9259     LLVM_FALLTHROUGH;
9260 
9261   case OO_PlusEqual:
9262   case OO_MinusEqual:
9263     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9264     LLVM_FALLTHROUGH;
9265 
9266   case OO_StarEqual:
9267   case OO_SlashEqual:
9268     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9269     break;
9270 
9271   case OO_PercentEqual:
9272   case OO_LessLessEqual:
9273   case OO_GreaterGreaterEqual:
9274   case OO_AmpEqual:
9275   case OO_CaretEqual:
9276   case OO_PipeEqual:
9277     OpBuilder.addAssignmentIntegralOverloads();
9278     break;
9279 
9280   case OO_Exclaim:
9281     OpBuilder.addExclaimOverload();
9282     break;
9283 
9284   case OO_AmpAmp:
9285   case OO_PipePipe:
9286     OpBuilder.addAmpAmpOrPipePipeOverload();
9287     break;
9288 
9289   case OO_Subscript:
9290     OpBuilder.addSubscriptOverloads();
9291     break;
9292 
9293   case OO_ArrowStar:
9294     OpBuilder.addArrowStarOverloads();
9295     break;
9296 
9297   case OO_Conditional:
9298     OpBuilder.addConditionalOperatorOverloads();
9299     OpBuilder.addGenericBinaryArithmeticOverloads();
9300     break;
9301   }
9302 }
9303 
9304 /// Add function candidates found via argument-dependent lookup
9305 /// to the set of overloading candidates.
9306 ///
9307 /// This routine performs argument-dependent name lookup based on the
9308 /// given function name (which may also be an operator name) and adds
9309 /// all of the overload candidates found by ADL to the overload
9310 /// candidate set (C++ [basic.lookup.argdep]).
9311 void
9312 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9313                                            SourceLocation Loc,
9314                                            ArrayRef<Expr *> Args,
9315                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9316                                            OverloadCandidateSet& CandidateSet,
9317                                            bool PartialOverloading) {
9318   ADLResult Fns;
9319 
9320   // FIXME: This approach for uniquing ADL results (and removing
9321   // redundant candidates from the set) relies on pointer-equality,
9322   // which means we need to key off the canonical decl.  However,
9323   // always going back to the canonical decl might not get us the
9324   // right set of default arguments.  What default arguments are
9325   // we supposed to consider on ADL candidates, anyway?
9326 
9327   // FIXME: Pass in the explicit template arguments?
9328   ArgumentDependentLookup(Name, Loc, Args, Fns);
9329 
9330   // Erase all of the candidates we already knew about.
9331   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9332                                    CandEnd = CandidateSet.end();
9333        Cand != CandEnd; ++Cand)
9334     if (Cand->Function) {
9335       Fns.erase(Cand->Function);
9336       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9337         Fns.erase(FunTmpl);
9338     }
9339 
9340   // For each of the ADL candidates we found, add it to the overload
9341   // set.
9342   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9343     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9344 
9345     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9346       if (ExplicitTemplateArgs)
9347         continue;
9348 
9349       AddOverloadCandidate(
9350           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9351           PartialOverloading, /*AllowExplicit=*/true,
9352           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9353       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9354         AddOverloadCandidate(
9355             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9356             /*SuppressUserConversions=*/false, PartialOverloading,
9357             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9358             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9359       }
9360     } else {
9361       auto *FTD = cast<FunctionTemplateDecl>(*I);
9362       AddTemplateOverloadCandidate(
9363           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9364           /*SuppressUserConversions=*/false, PartialOverloading,
9365           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9366       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9367               Context, FTD->getTemplatedDecl())) {
9368         AddTemplateOverloadCandidate(
9369             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9370             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9371             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9372             OverloadCandidateParamOrder::Reversed);
9373       }
9374     }
9375   }
9376 }
9377 
9378 namespace {
9379 enum class Comparison { Equal, Better, Worse };
9380 }
9381 
9382 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9383 /// overload resolution.
9384 ///
9385 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9386 /// Cand1's first N enable_if attributes have precisely the same conditions as
9387 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9388 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9389 ///
9390 /// Note that you can have a pair of candidates such that Cand1's enable_if
9391 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9392 /// worse than Cand1's.
9393 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9394                                        const FunctionDecl *Cand2) {
9395   // Common case: One (or both) decls don't have enable_if attrs.
9396   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9397   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9398   if (!Cand1Attr || !Cand2Attr) {
9399     if (Cand1Attr == Cand2Attr)
9400       return Comparison::Equal;
9401     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9402   }
9403 
9404   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9405   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9406 
9407   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9408   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9409     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9410     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9411 
9412     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9413     // has fewer enable_if attributes than Cand2, and vice versa.
9414     if (!Cand1A)
9415       return Comparison::Worse;
9416     if (!Cand2A)
9417       return Comparison::Better;
9418 
9419     Cand1ID.clear();
9420     Cand2ID.clear();
9421 
9422     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9423     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9424     if (Cand1ID != Cand2ID)
9425       return Comparison::Worse;
9426   }
9427 
9428   return Comparison::Equal;
9429 }
9430 
9431 static Comparison
9432 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9433                               const OverloadCandidate &Cand2) {
9434   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9435       !Cand2.Function->isMultiVersion())
9436     return Comparison::Equal;
9437 
9438   // If both are invalid, they are equal. If one of them is invalid, the other
9439   // is better.
9440   if (Cand1.Function->isInvalidDecl()) {
9441     if (Cand2.Function->isInvalidDecl())
9442       return Comparison::Equal;
9443     return Comparison::Worse;
9444   }
9445   if (Cand2.Function->isInvalidDecl())
9446     return Comparison::Better;
9447 
9448   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9449   // cpu_dispatch, else arbitrarily based on the identifiers.
9450   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9451   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9452   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9453   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9454 
9455   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9456     return Comparison::Equal;
9457 
9458   if (Cand1CPUDisp && !Cand2CPUDisp)
9459     return Comparison::Better;
9460   if (Cand2CPUDisp && !Cand1CPUDisp)
9461     return Comparison::Worse;
9462 
9463   if (Cand1CPUSpec && Cand2CPUSpec) {
9464     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9465       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9466                  ? Comparison::Better
9467                  : Comparison::Worse;
9468 
9469     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9470         FirstDiff = std::mismatch(
9471             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9472             Cand2CPUSpec->cpus_begin(),
9473             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9474               return LHS->getName() == RHS->getName();
9475             });
9476 
9477     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9478            "Two different cpu-specific versions should not have the same "
9479            "identifier list, otherwise they'd be the same decl!");
9480     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9481                ? Comparison::Better
9482                : Comparison::Worse;
9483   }
9484   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9485 }
9486 
9487 /// Compute the type of the implicit object parameter for the given function,
9488 /// if any. Returns None if there is no implicit object parameter, and a null
9489 /// QualType if there is a 'matches anything' implicit object parameter.
9490 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9491                                                      const FunctionDecl *F) {
9492   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9493     return llvm::None;
9494 
9495   auto *M = cast<CXXMethodDecl>(F);
9496   // Static member functions' object parameters match all types.
9497   if (M->isStatic())
9498     return QualType();
9499 
9500   QualType T = M->getThisObjectType();
9501   if (M->getRefQualifier() == RQ_RValue)
9502     return Context.getRValueReferenceType(T);
9503   return Context.getLValueReferenceType(T);
9504 }
9505 
9506 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9507                                    const FunctionDecl *F2, unsigned NumParams) {
9508   if (declaresSameEntity(F1, F2))
9509     return true;
9510 
9511   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9512     if (First) {
9513       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9514         return *T;
9515     }
9516     assert(I < F->getNumParams());
9517     return F->getParamDecl(I++)->getType();
9518   };
9519 
9520   unsigned I1 = 0, I2 = 0;
9521   for (unsigned I = 0; I != NumParams; ++I) {
9522     QualType T1 = NextParam(F1, I1, I == 0);
9523     QualType T2 = NextParam(F2, I2, I == 0);
9524     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9525       return false;
9526   }
9527   return true;
9528 }
9529 
9530 /// isBetterOverloadCandidate - Determines whether the first overload
9531 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9532 bool clang::isBetterOverloadCandidate(
9533     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9534     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9535   // Define viable functions to be better candidates than non-viable
9536   // functions.
9537   if (!Cand2.Viable)
9538     return Cand1.Viable;
9539   else if (!Cand1.Viable)
9540     return false;
9541 
9542   // C++ [over.match.best]p1:
9543   //
9544   //   -- if F is a static member function, ICS1(F) is defined such
9545   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9546   //      any function G, and, symmetrically, ICS1(G) is neither
9547   //      better nor worse than ICS1(F).
9548   unsigned StartArg = 0;
9549   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9550     StartArg = 1;
9551 
9552   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9553     // We don't allow incompatible pointer conversions in C++.
9554     if (!S.getLangOpts().CPlusPlus)
9555       return ICS.isStandard() &&
9556              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9557 
9558     // The only ill-formed conversion we allow in C++ is the string literal to
9559     // char* conversion, which is only considered ill-formed after C++11.
9560     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9561            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9562   };
9563 
9564   // Define functions that don't require ill-formed conversions for a given
9565   // argument to be better candidates than functions that do.
9566   unsigned NumArgs = Cand1.Conversions.size();
9567   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9568   bool HasBetterConversion = false;
9569   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9570     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9571     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9572     if (Cand1Bad != Cand2Bad) {
9573       if (Cand1Bad)
9574         return false;
9575       HasBetterConversion = true;
9576     }
9577   }
9578 
9579   if (HasBetterConversion)
9580     return true;
9581 
9582   // C++ [over.match.best]p1:
9583   //   A viable function F1 is defined to be a better function than another
9584   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9585   //   conversion sequence than ICSi(F2), and then...
9586   bool HasWorseConversion = false;
9587   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9588     switch (CompareImplicitConversionSequences(S, Loc,
9589                                                Cand1.Conversions[ArgIdx],
9590                                                Cand2.Conversions[ArgIdx])) {
9591     case ImplicitConversionSequence::Better:
9592       // Cand1 has a better conversion sequence.
9593       HasBetterConversion = true;
9594       break;
9595 
9596     case ImplicitConversionSequence::Worse:
9597       if (Cand1.Function && Cand2.Function &&
9598           Cand1.isReversed() != Cand2.isReversed() &&
9599           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9600                                  NumArgs)) {
9601         // Work around large-scale breakage caused by considering reversed
9602         // forms of operator== in C++20:
9603         //
9604         // When comparing a function against a reversed function with the same
9605         // parameter types, if we have a better conversion for one argument and
9606         // a worse conversion for the other, the implicit conversion sequences
9607         // are treated as being equally good.
9608         //
9609         // This prevents a comparison function from being considered ambiguous
9610         // with a reversed form that is written in the same way.
9611         //
9612         // We diagnose this as an extension from CreateOverloadedBinOp.
9613         HasWorseConversion = true;
9614         break;
9615       }
9616 
9617       // Cand1 can't be better than Cand2.
9618       return false;
9619 
9620     case ImplicitConversionSequence::Indistinguishable:
9621       // Do nothing.
9622       break;
9623     }
9624   }
9625 
9626   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9627   //       ICSj(F2), or, if not that,
9628   if (HasBetterConversion && !HasWorseConversion)
9629     return true;
9630 
9631   //   -- the context is an initialization by user-defined conversion
9632   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9633   //      from the return type of F1 to the destination type (i.e.,
9634   //      the type of the entity being initialized) is a better
9635   //      conversion sequence than the standard conversion sequence
9636   //      from the return type of F2 to the destination type.
9637   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9638       Cand1.Function && Cand2.Function &&
9639       isa<CXXConversionDecl>(Cand1.Function) &&
9640       isa<CXXConversionDecl>(Cand2.Function)) {
9641     // First check whether we prefer one of the conversion functions over the
9642     // other. This only distinguishes the results in non-standard, extension
9643     // cases such as the conversion from a lambda closure type to a function
9644     // pointer or block.
9645     ImplicitConversionSequence::CompareKind Result =
9646         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9647     if (Result == ImplicitConversionSequence::Indistinguishable)
9648       Result = CompareStandardConversionSequences(S, Loc,
9649                                                   Cand1.FinalConversion,
9650                                                   Cand2.FinalConversion);
9651 
9652     if (Result != ImplicitConversionSequence::Indistinguishable)
9653       return Result == ImplicitConversionSequence::Better;
9654 
9655     // FIXME: Compare kind of reference binding if conversion functions
9656     // convert to a reference type used in direct reference binding, per
9657     // C++14 [over.match.best]p1 section 2 bullet 3.
9658   }
9659 
9660   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9661   // as combined with the resolution to CWG issue 243.
9662   //
9663   // When the context is initialization by constructor ([over.match.ctor] or
9664   // either phase of [over.match.list]), a constructor is preferred over
9665   // a conversion function.
9666   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9667       Cand1.Function && Cand2.Function &&
9668       isa<CXXConstructorDecl>(Cand1.Function) !=
9669           isa<CXXConstructorDecl>(Cand2.Function))
9670     return isa<CXXConstructorDecl>(Cand1.Function);
9671 
9672   //    -- F1 is a non-template function and F2 is a function template
9673   //       specialization, or, if not that,
9674   bool Cand1IsSpecialization = Cand1.Function &&
9675                                Cand1.Function->getPrimaryTemplate();
9676   bool Cand2IsSpecialization = Cand2.Function &&
9677                                Cand2.Function->getPrimaryTemplate();
9678   if (Cand1IsSpecialization != Cand2IsSpecialization)
9679     return Cand2IsSpecialization;
9680 
9681   //   -- F1 and F2 are function template specializations, and the function
9682   //      template for F1 is more specialized than the template for F2
9683   //      according to the partial ordering rules described in 14.5.5.2, or,
9684   //      if not that,
9685   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9686     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9687             Cand1.Function->getPrimaryTemplate(),
9688             Cand2.Function->getPrimaryTemplate(), Loc,
9689             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9690                                                    : TPOC_Call,
9691             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9692             Cand1.isReversed() ^ Cand2.isReversed()))
9693       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9694   }
9695 
9696   //   -— F1 and F2 are non-template functions with the same
9697   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9698   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9699       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9700       Cand2.Function->hasPrototype()) {
9701     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9702     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9703     if (PT1->getNumParams() == PT2->getNumParams() &&
9704         PT1->isVariadic() == PT2->isVariadic() &&
9705         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9706       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9707       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9708       if (RC1 && RC2) {
9709         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9710         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9711                                      {RC2}, AtLeastAsConstrained1) ||
9712             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9713                                      {RC1}, AtLeastAsConstrained2))
9714           return false;
9715         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9716           return AtLeastAsConstrained1;
9717       } else if (RC1 || RC2) {
9718         return RC1 != nullptr;
9719       }
9720     }
9721   }
9722 
9723   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9724   //      class B of D, and for all arguments the corresponding parameters of
9725   //      F1 and F2 have the same type.
9726   // FIXME: Implement the "all parameters have the same type" check.
9727   bool Cand1IsInherited =
9728       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9729   bool Cand2IsInherited =
9730       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9731   if (Cand1IsInherited != Cand2IsInherited)
9732     return Cand2IsInherited;
9733   else if (Cand1IsInherited) {
9734     assert(Cand2IsInherited);
9735     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9736     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9737     if (Cand1Class->isDerivedFrom(Cand2Class))
9738       return true;
9739     if (Cand2Class->isDerivedFrom(Cand1Class))
9740       return false;
9741     // Inherited from sibling base classes: still ambiguous.
9742   }
9743 
9744   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9745   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9746   //      with reversed order of parameters and F1 is not
9747   //
9748   // We rank reversed + different operator as worse than just reversed, but
9749   // that comparison can never happen, because we only consider reversing for
9750   // the maximally-rewritten operator (== or <=>).
9751   if (Cand1.RewriteKind != Cand2.RewriteKind)
9752     return Cand1.RewriteKind < Cand2.RewriteKind;
9753 
9754   // Check C++17 tie-breakers for deduction guides.
9755   {
9756     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9757     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9758     if (Guide1 && Guide2) {
9759       //  -- F1 is generated from a deduction-guide and F2 is not
9760       if (Guide1->isImplicit() != Guide2->isImplicit())
9761         return Guide2->isImplicit();
9762 
9763       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9764       if (Guide1->isCopyDeductionCandidate())
9765         return true;
9766     }
9767   }
9768 
9769   // Check for enable_if value-based overload resolution.
9770   if (Cand1.Function && Cand2.Function) {
9771     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9772     if (Cmp != Comparison::Equal)
9773       return Cmp == Comparison::Better;
9774   }
9775 
9776   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9777     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9778     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9779            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9780   }
9781 
9782   bool HasPS1 = Cand1.Function != nullptr &&
9783                 functionHasPassObjectSizeParams(Cand1.Function);
9784   bool HasPS2 = Cand2.Function != nullptr &&
9785                 functionHasPassObjectSizeParams(Cand2.Function);
9786   if (HasPS1 != HasPS2 && HasPS1)
9787     return true;
9788 
9789   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9790   return MV == Comparison::Better;
9791 }
9792 
9793 /// Determine whether two declarations are "equivalent" for the purposes of
9794 /// name lookup and overload resolution. This applies when the same internal/no
9795 /// linkage entity is defined by two modules (probably by textually including
9796 /// the same header). In such a case, we don't consider the declarations to
9797 /// declare the same entity, but we also don't want lookups with both
9798 /// declarations visible to be ambiguous in some cases (this happens when using
9799 /// a modularized libstdc++).
9800 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9801                                                   const NamedDecl *B) {
9802   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9803   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9804   if (!VA || !VB)
9805     return false;
9806 
9807   // The declarations must be declaring the same name as an internal linkage
9808   // entity in different modules.
9809   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9810           VB->getDeclContext()->getRedeclContext()) ||
9811       getOwningModule(VA) == getOwningModule(VB) ||
9812       VA->isExternallyVisible() || VB->isExternallyVisible())
9813     return false;
9814 
9815   // Check that the declarations appear to be equivalent.
9816   //
9817   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9818   // For constants and functions, we should check the initializer or body is
9819   // the same. For non-constant variables, we shouldn't allow it at all.
9820   if (Context.hasSameType(VA->getType(), VB->getType()))
9821     return true;
9822 
9823   // Enum constants within unnamed enumerations will have different types, but
9824   // may still be similar enough to be interchangeable for our purposes.
9825   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9826     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9827       // Only handle anonymous enums. If the enumerations were named and
9828       // equivalent, they would have been merged to the same type.
9829       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9830       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9831       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9832           !Context.hasSameType(EnumA->getIntegerType(),
9833                                EnumB->getIntegerType()))
9834         return false;
9835       // Allow this only if the value is the same for both enumerators.
9836       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9837     }
9838   }
9839 
9840   // Nothing else is sufficiently similar.
9841   return false;
9842 }
9843 
9844 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9845     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9846   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9847 
9848   Module *M = getOwningModule(D);
9849   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9850       << !M << (M ? M->getFullModuleName() : "");
9851 
9852   for (auto *E : Equiv) {
9853     Module *M = getOwningModule(E);
9854     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9855         << !M << (M ? M->getFullModuleName() : "");
9856   }
9857 }
9858 
9859 /// Computes the best viable function (C++ 13.3.3)
9860 /// within an overload candidate set.
9861 ///
9862 /// \param Loc The location of the function name (or operator symbol) for
9863 /// which overload resolution occurs.
9864 ///
9865 /// \param Best If overload resolution was successful or found a deleted
9866 /// function, \p Best points to the candidate function found.
9867 ///
9868 /// \returns The result of overload resolution.
9869 OverloadingResult
9870 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9871                                          iterator &Best) {
9872   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9873   std::transform(begin(), end(), std::back_inserter(Candidates),
9874                  [](OverloadCandidate &Cand) { return &Cand; });
9875 
9876   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9877   // are accepted by both clang and NVCC. However, during a particular
9878   // compilation mode only one call variant is viable. We need to
9879   // exclude non-viable overload candidates from consideration based
9880   // only on their host/device attributes. Specifically, if one
9881   // candidate call is WrongSide and the other is SameSide, we ignore
9882   // the WrongSide candidate.
9883   if (S.getLangOpts().CUDA) {
9884     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9885     bool ContainsSameSideCandidate =
9886         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9887           // Check viable function only.
9888           return Cand->Viable && Cand->Function &&
9889                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9890                      Sema::CFP_SameSide;
9891         });
9892     if (ContainsSameSideCandidate) {
9893       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9894         // Check viable function only to avoid unnecessary data copying/moving.
9895         return Cand->Viable && Cand->Function &&
9896                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9897                    Sema::CFP_WrongSide;
9898       };
9899       llvm::erase_if(Candidates, IsWrongSideCandidate);
9900     }
9901   }
9902 
9903   // Find the best viable function.
9904   Best = end();
9905   for (auto *Cand : Candidates) {
9906     Cand->Best = false;
9907     if (Cand->Viable)
9908       if (Best == end() ||
9909           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9910         Best = Cand;
9911   }
9912 
9913   // If we didn't find any viable functions, abort.
9914   if (Best == end())
9915     return OR_No_Viable_Function;
9916 
9917   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9918 
9919   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9920   PendingBest.push_back(&*Best);
9921   Best->Best = true;
9922 
9923   // Make sure that this function is better than every other viable
9924   // function. If not, we have an ambiguity.
9925   while (!PendingBest.empty()) {
9926     auto *Curr = PendingBest.pop_back_val();
9927     for (auto *Cand : Candidates) {
9928       if (Cand->Viable && !Cand->Best &&
9929           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9930         PendingBest.push_back(Cand);
9931         Cand->Best = true;
9932 
9933         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9934                                                      Curr->Function))
9935           EquivalentCands.push_back(Cand->Function);
9936         else
9937           Best = end();
9938       }
9939     }
9940   }
9941 
9942   // If we found more than one best candidate, this is ambiguous.
9943   if (Best == end())
9944     return OR_Ambiguous;
9945 
9946   // Best is the best viable function.
9947   if (Best->Function && Best->Function->isDeleted())
9948     return OR_Deleted;
9949 
9950   if (!EquivalentCands.empty())
9951     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9952                                                     EquivalentCands);
9953 
9954   return OR_Success;
9955 }
9956 
9957 namespace {
9958 
9959 enum OverloadCandidateKind {
9960   oc_function,
9961   oc_method,
9962   oc_reversed_binary_operator,
9963   oc_constructor,
9964   oc_implicit_default_constructor,
9965   oc_implicit_copy_constructor,
9966   oc_implicit_move_constructor,
9967   oc_implicit_copy_assignment,
9968   oc_implicit_move_assignment,
9969   oc_implicit_equality_comparison,
9970   oc_inherited_constructor
9971 };
9972 
9973 enum OverloadCandidateSelect {
9974   ocs_non_template,
9975   ocs_template,
9976   ocs_described_template,
9977 };
9978 
9979 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9980 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9981                           OverloadCandidateRewriteKind CRK,
9982                           std::string &Description) {
9983 
9984   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9985   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9986     isTemplate = true;
9987     Description = S.getTemplateArgumentBindingsText(
9988         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9989   }
9990 
9991   OverloadCandidateSelect Select = [&]() {
9992     if (!Description.empty())
9993       return ocs_described_template;
9994     return isTemplate ? ocs_template : ocs_non_template;
9995   }();
9996 
9997   OverloadCandidateKind Kind = [&]() {
9998     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9999       return oc_implicit_equality_comparison;
10000 
10001     if (CRK & CRK_Reversed)
10002       return oc_reversed_binary_operator;
10003 
10004     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10005       if (!Ctor->isImplicit()) {
10006         if (isa<ConstructorUsingShadowDecl>(Found))
10007           return oc_inherited_constructor;
10008         else
10009           return oc_constructor;
10010       }
10011 
10012       if (Ctor->isDefaultConstructor())
10013         return oc_implicit_default_constructor;
10014 
10015       if (Ctor->isMoveConstructor())
10016         return oc_implicit_move_constructor;
10017 
10018       assert(Ctor->isCopyConstructor() &&
10019              "unexpected sort of implicit constructor");
10020       return oc_implicit_copy_constructor;
10021     }
10022 
10023     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10024       // This actually gets spelled 'candidate function' for now, but
10025       // it doesn't hurt to split it out.
10026       if (!Meth->isImplicit())
10027         return oc_method;
10028 
10029       if (Meth->isMoveAssignmentOperator())
10030         return oc_implicit_move_assignment;
10031 
10032       if (Meth->isCopyAssignmentOperator())
10033         return oc_implicit_copy_assignment;
10034 
10035       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10036       return oc_method;
10037     }
10038 
10039     return oc_function;
10040   }();
10041 
10042   return std::make_pair(Kind, Select);
10043 }
10044 
10045 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10046   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10047   // set.
10048   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10049     S.Diag(FoundDecl->getLocation(),
10050            diag::note_ovl_candidate_inherited_constructor)
10051       << Shadow->getNominatedBaseClass();
10052 }
10053 
10054 } // end anonymous namespace
10055 
10056 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10057                                     const FunctionDecl *FD) {
10058   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10059     bool AlwaysTrue;
10060     if (EnableIf->getCond()->isValueDependent() ||
10061         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10062       return false;
10063     if (!AlwaysTrue)
10064       return false;
10065   }
10066   return true;
10067 }
10068 
10069 /// Returns true if we can take the address of the function.
10070 ///
10071 /// \param Complain - If true, we'll emit a diagnostic
10072 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10073 ///   we in overload resolution?
10074 /// \param Loc - The location of the statement we're complaining about. Ignored
10075 ///   if we're not complaining, or if we're in overload resolution.
10076 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10077                                               bool Complain,
10078                                               bool InOverloadResolution,
10079                                               SourceLocation Loc) {
10080   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10081     if (Complain) {
10082       if (InOverloadResolution)
10083         S.Diag(FD->getBeginLoc(),
10084                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10085       else
10086         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10087     }
10088     return false;
10089   }
10090 
10091   if (FD->getTrailingRequiresClause()) {
10092     ConstraintSatisfaction Satisfaction;
10093     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10094       return false;
10095     if (!Satisfaction.IsSatisfied) {
10096       if (Complain) {
10097         if (InOverloadResolution)
10098           S.Diag(FD->getBeginLoc(),
10099                  diag::note_ovl_candidate_unsatisfied_constraints);
10100         else
10101           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10102               << FD;
10103         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10104       }
10105       return false;
10106     }
10107   }
10108 
10109   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10110     return P->hasAttr<PassObjectSizeAttr>();
10111   });
10112   if (I == FD->param_end())
10113     return true;
10114 
10115   if (Complain) {
10116     // Add one to ParamNo because it's user-facing
10117     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10118     if (InOverloadResolution)
10119       S.Diag(FD->getLocation(),
10120              diag::note_ovl_candidate_has_pass_object_size_params)
10121           << ParamNo;
10122     else
10123       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10124           << FD << ParamNo;
10125   }
10126   return false;
10127 }
10128 
10129 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10130                                                const FunctionDecl *FD) {
10131   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10132                                            /*InOverloadResolution=*/true,
10133                                            /*Loc=*/SourceLocation());
10134 }
10135 
10136 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10137                                              bool Complain,
10138                                              SourceLocation Loc) {
10139   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10140                                              /*InOverloadResolution=*/false,
10141                                              Loc);
10142 }
10143 
10144 // Notes the location of an overload candidate.
10145 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10146                                  OverloadCandidateRewriteKind RewriteKind,
10147                                  QualType DestType, bool TakingAddress) {
10148   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10149     return;
10150   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10151       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10152     return;
10153 
10154   std::string FnDesc;
10155   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10156       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10157   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10158                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10159                          << Fn << FnDesc;
10160 
10161   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10162   Diag(Fn->getLocation(), PD);
10163   MaybeEmitInheritedConstructorNote(*this, Found);
10164 }
10165 
10166 static void
10167 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10168   // Perhaps the ambiguity was caused by two atomic constraints that are
10169   // 'identical' but not equivalent:
10170   //
10171   // void foo() requires (sizeof(T) > 4) { } // #1
10172   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10173   //
10174   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10175   // #2 to subsume #1, but these constraint are not considered equivalent
10176   // according to the subsumption rules because they are not the same
10177   // source-level construct. This behavior is quite confusing and we should try
10178   // to help the user figure out what happened.
10179 
10180   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10181   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10182   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10183     if (!I->Function)
10184       continue;
10185     SmallVector<const Expr *, 3> AC;
10186     if (auto *Template = I->Function->getPrimaryTemplate())
10187       Template->getAssociatedConstraints(AC);
10188     else
10189       I->Function->getAssociatedConstraints(AC);
10190     if (AC.empty())
10191       continue;
10192     if (FirstCand == nullptr) {
10193       FirstCand = I->Function;
10194       FirstAC = AC;
10195     } else if (SecondCand == nullptr) {
10196       SecondCand = I->Function;
10197       SecondAC = AC;
10198     } else {
10199       // We have more than one pair of constrained functions - this check is
10200       // expensive and we'd rather not try to diagnose it.
10201       return;
10202     }
10203   }
10204   if (!SecondCand)
10205     return;
10206   // The diagnostic can only happen if there are associated constraints on
10207   // both sides (there needs to be some identical atomic constraint).
10208   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10209                                                       SecondCand, SecondAC))
10210     // Just show the user one diagnostic, they'll probably figure it out
10211     // from here.
10212     return;
10213 }
10214 
10215 // Notes the location of all overload candidates designated through
10216 // OverloadedExpr
10217 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10218                                      bool TakingAddress) {
10219   assert(OverloadedExpr->getType() == Context.OverloadTy);
10220 
10221   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10222   OverloadExpr *OvlExpr = Ovl.Expression;
10223 
10224   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10225                             IEnd = OvlExpr->decls_end();
10226        I != IEnd; ++I) {
10227     if (FunctionTemplateDecl *FunTmpl =
10228                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10229       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10230                             TakingAddress);
10231     } else if (FunctionDecl *Fun
10232                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10233       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10234     }
10235   }
10236 }
10237 
10238 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10239 /// "lead" diagnostic; it will be given two arguments, the source and
10240 /// target types of the conversion.
10241 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10242                                  Sema &S,
10243                                  SourceLocation CaretLoc,
10244                                  const PartialDiagnostic &PDiag) const {
10245   S.Diag(CaretLoc, PDiag)
10246     << Ambiguous.getFromType() << Ambiguous.getToType();
10247   // FIXME: The note limiting machinery is borrowed from
10248   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10249   // refactoring here.
10250   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10251   unsigned CandsShown = 0;
10252   AmbiguousConversionSequence::const_iterator I, E;
10253   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10254     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10255       break;
10256     ++CandsShown;
10257     S.NoteOverloadCandidate(I->first, I->second);
10258   }
10259   if (I != E)
10260     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10261 }
10262 
10263 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10264                                   unsigned I, bool TakingCandidateAddress) {
10265   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10266   assert(Conv.isBad());
10267   assert(Cand->Function && "for now, candidate must be a function");
10268   FunctionDecl *Fn = Cand->Function;
10269 
10270   // There's a conversion slot for the object argument if this is a
10271   // non-constructor method.  Note that 'I' corresponds the
10272   // conversion-slot index.
10273   bool isObjectArgument = false;
10274   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10275     if (I == 0)
10276       isObjectArgument = true;
10277     else
10278       I--;
10279   }
10280 
10281   std::string FnDesc;
10282   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10283       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10284                                 FnDesc);
10285 
10286   Expr *FromExpr = Conv.Bad.FromExpr;
10287   QualType FromTy = Conv.Bad.getFromType();
10288   QualType ToTy = Conv.Bad.getToType();
10289 
10290   if (FromTy == S.Context.OverloadTy) {
10291     assert(FromExpr && "overload set argument came from implicit argument?");
10292     Expr *E = FromExpr->IgnoreParens();
10293     if (isa<UnaryOperator>(E))
10294       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10295     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10296 
10297     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10298         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10299         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10300         << Name << I + 1;
10301     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10302     return;
10303   }
10304 
10305   // Do some hand-waving analysis to see if the non-viability is due
10306   // to a qualifier mismatch.
10307   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10308   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10309   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10310     CToTy = RT->getPointeeType();
10311   else {
10312     // TODO: detect and diagnose the full richness of const mismatches.
10313     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10314       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10315         CFromTy = FromPT->getPointeeType();
10316         CToTy = ToPT->getPointeeType();
10317       }
10318   }
10319 
10320   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10321       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10322     Qualifiers FromQs = CFromTy.getQualifiers();
10323     Qualifiers ToQs = CToTy.getQualifiers();
10324 
10325     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10326       if (isObjectArgument)
10327         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10328             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10329             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10330             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10331       else
10332         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10333             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10334             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10335             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10336             << ToTy->isReferenceType() << I + 1;
10337       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10338       return;
10339     }
10340 
10341     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10342       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10343           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10344           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10345           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10346           << (unsigned)isObjectArgument << I + 1;
10347       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10348       return;
10349     }
10350 
10351     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10352       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10353           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10354           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10355           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10356           << (unsigned)isObjectArgument << I + 1;
10357       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10358       return;
10359     }
10360 
10361     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10362       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10363           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10364           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10365           << FromQs.hasUnaligned() << I + 1;
10366       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10367       return;
10368     }
10369 
10370     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10371     assert(CVR && "unexpected qualifiers mismatch");
10372 
10373     if (isObjectArgument) {
10374       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10375           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10376           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10377           << (CVR - 1);
10378     } else {
10379       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10380           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10381           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10382           << (CVR - 1) << I + 1;
10383     }
10384     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10385     return;
10386   }
10387 
10388   // Special diagnostic for failure to convert an initializer list, since
10389   // telling the user that it has type void is not useful.
10390   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10391     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10392         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10393         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10394         << ToTy << (unsigned)isObjectArgument << I + 1;
10395     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10396     return;
10397   }
10398 
10399   // Diagnose references or pointers to incomplete types differently,
10400   // since it's far from impossible that the incompleteness triggered
10401   // the failure.
10402   QualType TempFromTy = FromTy.getNonReferenceType();
10403   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10404     TempFromTy = PTy->getPointeeType();
10405   if (TempFromTy->isIncompleteType()) {
10406     // Emit the generic diagnostic and, optionally, add the hints to it.
10407     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10408         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10409         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10410         << ToTy << (unsigned)isObjectArgument << I + 1
10411         << (unsigned)(Cand->Fix.Kind);
10412 
10413     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10414     return;
10415   }
10416 
10417   // Diagnose base -> derived pointer conversions.
10418   unsigned BaseToDerivedConversion = 0;
10419   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10420     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10421       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10422                                                FromPtrTy->getPointeeType()) &&
10423           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10424           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10425           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10426                           FromPtrTy->getPointeeType()))
10427         BaseToDerivedConversion = 1;
10428     }
10429   } else if (const ObjCObjectPointerType *FromPtrTy
10430                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10431     if (const ObjCObjectPointerType *ToPtrTy
10432                                         = ToTy->getAs<ObjCObjectPointerType>())
10433       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10434         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10435           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10436                                                 FromPtrTy->getPointeeType()) &&
10437               FromIface->isSuperClassOf(ToIface))
10438             BaseToDerivedConversion = 2;
10439   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10440     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10441         !FromTy->isIncompleteType() &&
10442         !ToRefTy->getPointeeType()->isIncompleteType() &&
10443         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10444       BaseToDerivedConversion = 3;
10445     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10446                ToTy.getNonReferenceType().getCanonicalType() ==
10447                FromTy.getNonReferenceType().getCanonicalType()) {
10448       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10449           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10450           << (unsigned)isObjectArgument << I + 1
10451           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10452       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10453       return;
10454     }
10455   }
10456 
10457   if (BaseToDerivedConversion) {
10458     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10459         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10460         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10461         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10462     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10463     return;
10464   }
10465 
10466   if (isa<ObjCObjectPointerType>(CFromTy) &&
10467       isa<PointerType>(CToTy)) {
10468       Qualifiers FromQs = CFromTy.getQualifiers();
10469       Qualifiers ToQs = CToTy.getQualifiers();
10470       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10471         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10472             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10473             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10474             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10475         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10476         return;
10477       }
10478   }
10479 
10480   if (TakingCandidateAddress &&
10481       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10482     return;
10483 
10484   // Emit the generic diagnostic and, optionally, add the hints to it.
10485   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10486   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10487         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10488         << ToTy << (unsigned)isObjectArgument << I + 1
10489         << (unsigned)(Cand->Fix.Kind);
10490 
10491   // If we can fix the conversion, suggest the FixIts.
10492   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10493        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10494     FDiag << *HI;
10495   S.Diag(Fn->getLocation(), FDiag);
10496 
10497   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10498 }
10499 
10500 /// Additional arity mismatch diagnosis specific to a function overload
10501 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10502 /// over a candidate in any candidate set.
10503 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10504                                unsigned NumArgs) {
10505   FunctionDecl *Fn = Cand->Function;
10506   unsigned MinParams = Fn->getMinRequiredArguments();
10507 
10508   // With invalid overloaded operators, it's possible that we think we
10509   // have an arity mismatch when in fact it looks like we have the
10510   // right number of arguments, because only overloaded operators have
10511   // the weird behavior of overloading member and non-member functions.
10512   // Just don't report anything.
10513   if (Fn->isInvalidDecl() &&
10514       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10515     return true;
10516 
10517   if (NumArgs < MinParams) {
10518     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10519            (Cand->FailureKind == ovl_fail_bad_deduction &&
10520             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10521   } else {
10522     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10523            (Cand->FailureKind == ovl_fail_bad_deduction &&
10524             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10525   }
10526 
10527   return false;
10528 }
10529 
10530 /// General arity mismatch diagnosis over a candidate in a candidate set.
10531 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10532                                   unsigned NumFormalArgs) {
10533   assert(isa<FunctionDecl>(D) &&
10534       "The templated declaration should at least be a function"
10535       " when diagnosing bad template argument deduction due to too many"
10536       " or too few arguments");
10537 
10538   FunctionDecl *Fn = cast<FunctionDecl>(D);
10539 
10540   // TODO: treat calls to a missing default constructor as a special case
10541   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10542   unsigned MinParams = Fn->getMinRequiredArguments();
10543 
10544   // at least / at most / exactly
10545   unsigned mode, modeCount;
10546   if (NumFormalArgs < MinParams) {
10547     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10548         FnTy->isTemplateVariadic())
10549       mode = 0; // "at least"
10550     else
10551       mode = 2; // "exactly"
10552     modeCount = MinParams;
10553   } else {
10554     if (MinParams != FnTy->getNumParams())
10555       mode = 1; // "at most"
10556     else
10557       mode = 2; // "exactly"
10558     modeCount = FnTy->getNumParams();
10559   }
10560 
10561   std::string Description;
10562   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10563       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10564 
10565   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10566     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10567         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10568         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10569   else
10570     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10571         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10572         << Description << mode << modeCount << NumFormalArgs;
10573 
10574   MaybeEmitInheritedConstructorNote(S, Found);
10575 }
10576 
10577 /// Arity mismatch diagnosis specific to a function overload candidate.
10578 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10579                                   unsigned NumFormalArgs) {
10580   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10581     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10582 }
10583 
10584 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10585   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10586     return TD;
10587   llvm_unreachable("Unsupported: Getting the described template declaration"
10588                    " for bad deduction diagnosis");
10589 }
10590 
10591 /// Diagnose a failed template-argument deduction.
10592 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10593                                  DeductionFailureInfo &DeductionFailure,
10594                                  unsigned NumArgs,
10595                                  bool TakingCandidateAddress) {
10596   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10597   NamedDecl *ParamD;
10598   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10599   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10600   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10601   switch (DeductionFailure.Result) {
10602   case Sema::TDK_Success:
10603     llvm_unreachable("TDK_success while diagnosing bad deduction");
10604 
10605   case Sema::TDK_Incomplete: {
10606     assert(ParamD && "no parameter found for incomplete deduction result");
10607     S.Diag(Templated->getLocation(),
10608            diag::note_ovl_candidate_incomplete_deduction)
10609         << ParamD->getDeclName();
10610     MaybeEmitInheritedConstructorNote(S, Found);
10611     return;
10612   }
10613 
10614   case Sema::TDK_IncompletePack: {
10615     assert(ParamD && "no parameter found for incomplete deduction result");
10616     S.Diag(Templated->getLocation(),
10617            diag::note_ovl_candidate_incomplete_deduction_pack)
10618         << ParamD->getDeclName()
10619         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10620         << *DeductionFailure.getFirstArg();
10621     MaybeEmitInheritedConstructorNote(S, Found);
10622     return;
10623   }
10624 
10625   case Sema::TDK_Underqualified: {
10626     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10627     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10628 
10629     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10630 
10631     // Param will have been canonicalized, but it should just be a
10632     // qualified version of ParamD, so move the qualifiers to that.
10633     QualifierCollector Qs;
10634     Qs.strip(Param);
10635     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10636     assert(S.Context.hasSameType(Param, NonCanonParam));
10637 
10638     // Arg has also been canonicalized, but there's nothing we can do
10639     // about that.  It also doesn't matter as much, because it won't
10640     // have any template parameters in it (because deduction isn't
10641     // done on dependent types).
10642     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10643 
10644     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10645         << ParamD->getDeclName() << Arg << NonCanonParam;
10646     MaybeEmitInheritedConstructorNote(S, Found);
10647     return;
10648   }
10649 
10650   case Sema::TDK_Inconsistent: {
10651     assert(ParamD && "no parameter found for inconsistent deduction result");
10652     int which = 0;
10653     if (isa<TemplateTypeParmDecl>(ParamD))
10654       which = 0;
10655     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10656       // Deduction might have failed because we deduced arguments of two
10657       // different types for a non-type template parameter.
10658       // FIXME: Use a different TDK value for this.
10659       QualType T1 =
10660           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10661       QualType T2 =
10662           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10663       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10664         S.Diag(Templated->getLocation(),
10665                diag::note_ovl_candidate_inconsistent_deduction_types)
10666           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10667           << *DeductionFailure.getSecondArg() << T2;
10668         MaybeEmitInheritedConstructorNote(S, Found);
10669         return;
10670       }
10671 
10672       which = 1;
10673     } else {
10674       which = 2;
10675     }
10676 
10677     // Tweak the diagnostic if the problem is that we deduced packs of
10678     // different arities. We'll print the actual packs anyway in case that
10679     // includes additional useful information.
10680     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10681         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10682         DeductionFailure.getFirstArg()->pack_size() !=
10683             DeductionFailure.getSecondArg()->pack_size()) {
10684       which = 3;
10685     }
10686 
10687     S.Diag(Templated->getLocation(),
10688            diag::note_ovl_candidate_inconsistent_deduction)
10689         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10690         << *DeductionFailure.getSecondArg();
10691     MaybeEmitInheritedConstructorNote(S, Found);
10692     return;
10693   }
10694 
10695   case Sema::TDK_InvalidExplicitArguments:
10696     assert(ParamD && "no parameter found for invalid explicit arguments");
10697     if (ParamD->getDeclName())
10698       S.Diag(Templated->getLocation(),
10699              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10700           << ParamD->getDeclName();
10701     else {
10702       int index = 0;
10703       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10704         index = TTP->getIndex();
10705       else if (NonTypeTemplateParmDecl *NTTP
10706                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10707         index = NTTP->getIndex();
10708       else
10709         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10710       S.Diag(Templated->getLocation(),
10711              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10712           << (index + 1);
10713     }
10714     MaybeEmitInheritedConstructorNote(S, Found);
10715     return;
10716 
10717   case Sema::TDK_ConstraintsNotSatisfied: {
10718     // Format the template argument list into the argument string.
10719     SmallString<128> TemplateArgString;
10720     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10721     TemplateArgString = " ";
10722     TemplateArgString += S.getTemplateArgumentBindingsText(
10723         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10724     if (TemplateArgString.size() == 1)
10725       TemplateArgString.clear();
10726     S.Diag(Templated->getLocation(),
10727            diag::note_ovl_candidate_unsatisfied_constraints)
10728         << TemplateArgString;
10729 
10730     S.DiagnoseUnsatisfiedConstraint(
10731         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10732     return;
10733   }
10734   case Sema::TDK_TooManyArguments:
10735   case Sema::TDK_TooFewArguments:
10736     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10737     return;
10738 
10739   case Sema::TDK_InstantiationDepth:
10740     S.Diag(Templated->getLocation(),
10741            diag::note_ovl_candidate_instantiation_depth);
10742     MaybeEmitInheritedConstructorNote(S, Found);
10743     return;
10744 
10745   case Sema::TDK_SubstitutionFailure: {
10746     // Format the template argument list into the argument string.
10747     SmallString<128> TemplateArgString;
10748     if (TemplateArgumentList *Args =
10749             DeductionFailure.getTemplateArgumentList()) {
10750       TemplateArgString = " ";
10751       TemplateArgString += S.getTemplateArgumentBindingsText(
10752           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10753       if (TemplateArgString.size() == 1)
10754         TemplateArgString.clear();
10755     }
10756 
10757     // If this candidate was disabled by enable_if, say so.
10758     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10759     if (PDiag && PDiag->second.getDiagID() ==
10760           diag::err_typename_nested_not_found_enable_if) {
10761       // FIXME: Use the source range of the condition, and the fully-qualified
10762       //        name of the enable_if template. These are both present in PDiag.
10763       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10764         << "'enable_if'" << TemplateArgString;
10765       return;
10766     }
10767 
10768     // We found a specific requirement that disabled the enable_if.
10769     if (PDiag && PDiag->second.getDiagID() ==
10770         diag::err_typename_nested_not_found_requirement) {
10771       S.Diag(Templated->getLocation(),
10772              diag::note_ovl_candidate_disabled_by_requirement)
10773         << PDiag->second.getStringArg(0) << TemplateArgString;
10774       return;
10775     }
10776 
10777     // Format the SFINAE diagnostic into the argument string.
10778     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10779     //        formatted message in another diagnostic.
10780     SmallString<128> SFINAEArgString;
10781     SourceRange R;
10782     if (PDiag) {
10783       SFINAEArgString = ": ";
10784       R = SourceRange(PDiag->first, PDiag->first);
10785       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10786     }
10787 
10788     S.Diag(Templated->getLocation(),
10789            diag::note_ovl_candidate_substitution_failure)
10790         << TemplateArgString << SFINAEArgString << R;
10791     MaybeEmitInheritedConstructorNote(S, Found);
10792     return;
10793   }
10794 
10795   case Sema::TDK_DeducedMismatch:
10796   case Sema::TDK_DeducedMismatchNested: {
10797     // Format the template argument list into the argument string.
10798     SmallString<128> TemplateArgString;
10799     if (TemplateArgumentList *Args =
10800             DeductionFailure.getTemplateArgumentList()) {
10801       TemplateArgString = " ";
10802       TemplateArgString += S.getTemplateArgumentBindingsText(
10803           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10804       if (TemplateArgString.size() == 1)
10805         TemplateArgString.clear();
10806     }
10807 
10808     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10809         << (*DeductionFailure.getCallArgIndex() + 1)
10810         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10811         << TemplateArgString
10812         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10813     break;
10814   }
10815 
10816   case Sema::TDK_NonDeducedMismatch: {
10817     // FIXME: Provide a source location to indicate what we couldn't match.
10818     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10819     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10820     if (FirstTA.getKind() == TemplateArgument::Template &&
10821         SecondTA.getKind() == TemplateArgument::Template) {
10822       TemplateName FirstTN = FirstTA.getAsTemplate();
10823       TemplateName SecondTN = SecondTA.getAsTemplate();
10824       if (FirstTN.getKind() == TemplateName::Template &&
10825           SecondTN.getKind() == TemplateName::Template) {
10826         if (FirstTN.getAsTemplateDecl()->getName() ==
10827             SecondTN.getAsTemplateDecl()->getName()) {
10828           // FIXME: This fixes a bad diagnostic where both templates are named
10829           // the same.  This particular case is a bit difficult since:
10830           // 1) It is passed as a string to the diagnostic printer.
10831           // 2) The diagnostic printer only attempts to find a better
10832           //    name for types, not decls.
10833           // Ideally, this should folded into the diagnostic printer.
10834           S.Diag(Templated->getLocation(),
10835                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10836               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10837           return;
10838         }
10839       }
10840     }
10841 
10842     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10843         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10844       return;
10845 
10846     // FIXME: For generic lambda parameters, check if the function is a lambda
10847     // call operator, and if so, emit a prettier and more informative
10848     // diagnostic that mentions 'auto' and lambda in addition to
10849     // (or instead of?) the canonical template type parameters.
10850     S.Diag(Templated->getLocation(),
10851            diag::note_ovl_candidate_non_deduced_mismatch)
10852         << FirstTA << SecondTA;
10853     return;
10854   }
10855   // TODO: diagnose these individually, then kill off
10856   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10857   case Sema::TDK_MiscellaneousDeductionFailure:
10858     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10859     MaybeEmitInheritedConstructorNote(S, Found);
10860     return;
10861   case Sema::TDK_CUDATargetMismatch:
10862     S.Diag(Templated->getLocation(),
10863            diag::note_cuda_ovl_candidate_target_mismatch);
10864     return;
10865   }
10866 }
10867 
10868 /// Diagnose a failed template-argument deduction, for function calls.
10869 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10870                                  unsigned NumArgs,
10871                                  bool TakingCandidateAddress) {
10872   unsigned TDK = Cand->DeductionFailure.Result;
10873   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10874     if (CheckArityMismatch(S, Cand, NumArgs))
10875       return;
10876   }
10877   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10878                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10879 }
10880 
10881 /// CUDA: diagnose an invalid call across targets.
10882 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10883   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10884   FunctionDecl *Callee = Cand->Function;
10885 
10886   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10887                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10888 
10889   std::string FnDesc;
10890   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10891       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10892                                 Cand->getRewriteKind(), FnDesc);
10893 
10894   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10895       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10896       << FnDesc /* Ignored */
10897       << CalleeTarget << CallerTarget;
10898 
10899   // This could be an implicit constructor for which we could not infer the
10900   // target due to a collsion. Diagnose that case.
10901   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10902   if (Meth != nullptr && Meth->isImplicit()) {
10903     CXXRecordDecl *ParentClass = Meth->getParent();
10904     Sema::CXXSpecialMember CSM;
10905 
10906     switch (FnKindPair.first) {
10907     default:
10908       return;
10909     case oc_implicit_default_constructor:
10910       CSM = Sema::CXXDefaultConstructor;
10911       break;
10912     case oc_implicit_copy_constructor:
10913       CSM = Sema::CXXCopyConstructor;
10914       break;
10915     case oc_implicit_move_constructor:
10916       CSM = Sema::CXXMoveConstructor;
10917       break;
10918     case oc_implicit_copy_assignment:
10919       CSM = Sema::CXXCopyAssignment;
10920       break;
10921     case oc_implicit_move_assignment:
10922       CSM = Sema::CXXMoveAssignment;
10923       break;
10924     };
10925 
10926     bool ConstRHS = false;
10927     if (Meth->getNumParams()) {
10928       if (const ReferenceType *RT =
10929               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10930         ConstRHS = RT->getPointeeType().isConstQualified();
10931       }
10932     }
10933 
10934     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10935                                               /* ConstRHS */ ConstRHS,
10936                                               /* Diagnose */ true);
10937   }
10938 }
10939 
10940 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10941   FunctionDecl *Callee = Cand->Function;
10942   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10943 
10944   S.Diag(Callee->getLocation(),
10945          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10946       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10947 }
10948 
10949 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10950   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10951   assert(ES.isExplicit() && "not an explicit candidate");
10952 
10953   unsigned Kind;
10954   switch (Cand->Function->getDeclKind()) {
10955   case Decl::Kind::CXXConstructor:
10956     Kind = 0;
10957     break;
10958   case Decl::Kind::CXXConversion:
10959     Kind = 1;
10960     break;
10961   case Decl::Kind::CXXDeductionGuide:
10962     Kind = Cand->Function->isImplicit() ? 0 : 2;
10963     break;
10964   default:
10965     llvm_unreachable("invalid Decl");
10966   }
10967 
10968   // Note the location of the first (in-class) declaration; a redeclaration
10969   // (particularly an out-of-class definition) will typically lack the
10970   // 'explicit' specifier.
10971   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10972   FunctionDecl *First = Cand->Function->getFirstDecl();
10973   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10974     First = Pattern->getFirstDecl();
10975 
10976   S.Diag(First->getLocation(),
10977          diag::note_ovl_candidate_explicit)
10978       << Kind << (ES.getExpr() ? 1 : 0)
10979       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10980 }
10981 
10982 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10983   FunctionDecl *Callee = Cand->Function;
10984 
10985   S.Diag(Callee->getLocation(),
10986          diag::note_ovl_candidate_disabled_by_extension)
10987     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10988 }
10989 
10990 /// Generates a 'note' diagnostic for an overload candidate.  We've
10991 /// already generated a primary error at the call site.
10992 ///
10993 /// It really does need to be a single diagnostic with its caret
10994 /// pointed at the candidate declaration.  Yes, this creates some
10995 /// major challenges of technical writing.  Yes, this makes pointing
10996 /// out problems with specific arguments quite awkward.  It's still
10997 /// better than generating twenty screens of text for every failed
10998 /// overload.
10999 ///
11000 /// It would be great to be able to express per-candidate problems
11001 /// more richly for those diagnostic clients that cared, but we'd
11002 /// still have to be just as careful with the default diagnostics.
11003 /// \param CtorDestAS Addr space of object being constructed (for ctor
11004 /// candidates only).
11005 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11006                                   unsigned NumArgs,
11007                                   bool TakingCandidateAddress,
11008                                   LangAS CtorDestAS = LangAS::Default) {
11009   FunctionDecl *Fn = Cand->Function;
11010 
11011   // Note deleted candidates, but only if they're viable.
11012   if (Cand->Viable) {
11013     if (Fn->isDeleted()) {
11014       std::string FnDesc;
11015       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11016           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11017                                     Cand->getRewriteKind(), FnDesc);
11018 
11019       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11020           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11021           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11022       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11023       return;
11024     }
11025 
11026     // We don't really have anything else to say about viable candidates.
11027     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11028     return;
11029   }
11030 
11031   switch (Cand->FailureKind) {
11032   case ovl_fail_too_many_arguments:
11033   case ovl_fail_too_few_arguments:
11034     return DiagnoseArityMismatch(S, Cand, NumArgs);
11035 
11036   case ovl_fail_bad_deduction:
11037     return DiagnoseBadDeduction(S, Cand, NumArgs,
11038                                 TakingCandidateAddress);
11039 
11040   case ovl_fail_illegal_constructor: {
11041     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11042       << (Fn->getPrimaryTemplate() ? 1 : 0);
11043     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11044     return;
11045   }
11046 
11047   case ovl_fail_object_addrspace_mismatch: {
11048     Qualifiers QualsForPrinting;
11049     QualsForPrinting.setAddressSpace(CtorDestAS);
11050     S.Diag(Fn->getLocation(),
11051            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11052         << QualsForPrinting;
11053     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11054     return;
11055   }
11056 
11057   case ovl_fail_trivial_conversion:
11058   case ovl_fail_bad_final_conversion:
11059   case ovl_fail_final_conversion_not_exact:
11060     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11061 
11062   case ovl_fail_bad_conversion: {
11063     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11064     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11065       if (Cand->Conversions[I].isBad())
11066         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11067 
11068     // FIXME: this currently happens when we're called from SemaInit
11069     // when user-conversion overload fails.  Figure out how to handle
11070     // those conditions and diagnose them well.
11071     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11072   }
11073 
11074   case ovl_fail_bad_target:
11075     return DiagnoseBadTarget(S, Cand);
11076 
11077   case ovl_fail_enable_if:
11078     return DiagnoseFailedEnableIfAttr(S, Cand);
11079 
11080   case ovl_fail_explicit:
11081     return DiagnoseFailedExplicitSpec(S, Cand);
11082 
11083   case ovl_fail_ext_disabled:
11084     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11085 
11086   case ovl_fail_inhctor_slice:
11087     // It's generally not interesting to note copy/move constructors here.
11088     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11089       return;
11090     S.Diag(Fn->getLocation(),
11091            diag::note_ovl_candidate_inherited_constructor_slice)
11092       << (Fn->getPrimaryTemplate() ? 1 : 0)
11093       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11094     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11095     return;
11096 
11097   case ovl_fail_addr_not_available: {
11098     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11099     (void)Available;
11100     assert(!Available);
11101     break;
11102   }
11103   case ovl_non_default_multiversion_function:
11104     // Do nothing, these should simply be ignored.
11105     break;
11106 
11107   case ovl_fail_constraints_not_satisfied: {
11108     std::string FnDesc;
11109     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11110         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11111                                   Cand->getRewriteKind(), FnDesc);
11112 
11113     S.Diag(Fn->getLocation(),
11114            diag::note_ovl_candidate_constraints_not_satisfied)
11115         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11116         << FnDesc /* Ignored */;
11117     ConstraintSatisfaction Satisfaction;
11118     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11119       break;
11120     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11121   }
11122   }
11123 }
11124 
11125 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11126   // Desugar the type of the surrogate down to a function type,
11127   // retaining as many typedefs as possible while still showing
11128   // the function type (and, therefore, its parameter types).
11129   QualType FnType = Cand->Surrogate->getConversionType();
11130   bool isLValueReference = false;
11131   bool isRValueReference = false;
11132   bool isPointer = false;
11133   if (const LValueReferenceType *FnTypeRef =
11134         FnType->getAs<LValueReferenceType>()) {
11135     FnType = FnTypeRef->getPointeeType();
11136     isLValueReference = true;
11137   } else if (const RValueReferenceType *FnTypeRef =
11138                FnType->getAs<RValueReferenceType>()) {
11139     FnType = FnTypeRef->getPointeeType();
11140     isRValueReference = true;
11141   }
11142   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11143     FnType = FnTypePtr->getPointeeType();
11144     isPointer = true;
11145   }
11146   // Desugar down to a function type.
11147   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11148   // Reconstruct the pointer/reference as appropriate.
11149   if (isPointer) FnType = S.Context.getPointerType(FnType);
11150   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11151   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11152 
11153   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11154     << FnType;
11155 }
11156 
11157 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11158                                          SourceLocation OpLoc,
11159                                          OverloadCandidate *Cand) {
11160   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11161   std::string TypeStr("operator");
11162   TypeStr += Opc;
11163   TypeStr += "(";
11164   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11165   if (Cand->Conversions.size() == 1) {
11166     TypeStr += ")";
11167     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11168   } else {
11169     TypeStr += ", ";
11170     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11171     TypeStr += ")";
11172     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11173   }
11174 }
11175 
11176 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11177                                          OverloadCandidate *Cand) {
11178   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11179     if (ICS.isBad()) break; // all meaningless after first invalid
11180     if (!ICS.isAmbiguous()) continue;
11181 
11182     ICS.DiagnoseAmbiguousConversion(
11183         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11184   }
11185 }
11186 
11187 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11188   if (Cand->Function)
11189     return Cand->Function->getLocation();
11190   if (Cand->IsSurrogate)
11191     return Cand->Surrogate->getLocation();
11192   return SourceLocation();
11193 }
11194 
11195 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11196   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11197   case Sema::TDK_Success:
11198   case Sema::TDK_NonDependentConversionFailure:
11199     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11200 
11201   case Sema::TDK_Invalid:
11202   case Sema::TDK_Incomplete:
11203   case Sema::TDK_IncompletePack:
11204     return 1;
11205 
11206   case Sema::TDK_Underqualified:
11207   case Sema::TDK_Inconsistent:
11208     return 2;
11209 
11210   case Sema::TDK_SubstitutionFailure:
11211   case Sema::TDK_DeducedMismatch:
11212   case Sema::TDK_ConstraintsNotSatisfied:
11213   case Sema::TDK_DeducedMismatchNested:
11214   case Sema::TDK_NonDeducedMismatch:
11215   case Sema::TDK_MiscellaneousDeductionFailure:
11216   case Sema::TDK_CUDATargetMismatch:
11217     return 3;
11218 
11219   case Sema::TDK_InstantiationDepth:
11220     return 4;
11221 
11222   case Sema::TDK_InvalidExplicitArguments:
11223     return 5;
11224 
11225   case Sema::TDK_TooManyArguments:
11226   case Sema::TDK_TooFewArguments:
11227     return 6;
11228   }
11229   llvm_unreachable("Unhandled deduction result");
11230 }
11231 
11232 namespace {
11233 struct CompareOverloadCandidatesForDisplay {
11234   Sema &S;
11235   SourceLocation Loc;
11236   size_t NumArgs;
11237   OverloadCandidateSet::CandidateSetKind CSK;
11238 
11239   CompareOverloadCandidatesForDisplay(
11240       Sema &S, SourceLocation Loc, size_t NArgs,
11241       OverloadCandidateSet::CandidateSetKind CSK)
11242       : S(S), NumArgs(NArgs), CSK(CSK) {}
11243 
11244   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11245     // If there are too many or too few arguments, that's the high-order bit we
11246     // want to sort by, even if the immediate failure kind was something else.
11247     if (C->FailureKind == ovl_fail_too_many_arguments ||
11248         C->FailureKind == ovl_fail_too_few_arguments)
11249       return static_cast<OverloadFailureKind>(C->FailureKind);
11250 
11251     if (C->Function) {
11252       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11253         return ovl_fail_too_many_arguments;
11254       if (NumArgs < C->Function->getMinRequiredArguments())
11255         return ovl_fail_too_few_arguments;
11256     }
11257 
11258     return static_cast<OverloadFailureKind>(C->FailureKind);
11259   }
11260 
11261   bool operator()(const OverloadCandidate *L,
11262                   const OverloadCandidate *R) {
11263     // Fast-path this check.
11264     if (L == R) return false;
11265 
11266     // Order first by viability.
11267     if (L->Viable) {
11268       if (!R->Viable) return true;
11269 
11270       // TODO: introduce a tri-valued comparison for overload
11271       // candidates.  Would be more worthwhile if we had a sort
11272       // that could exploit it.
11273       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11274         return true;
11275       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11276         return false;
11277     } else if (R->Viable)
11278       return false;
11279 
11280     assert(L->Viable == R->Viable);
11281 
11282     // Criteria by which we can sort non-viable candidates:
11283     if (!L->Viable) {
11284       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11285       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11286 
11287       // 1. Arity mismatches come after other candidates.
11288       if (LFailureKind == ovl_fail_too_many_arguments ||
11289           LFailureKind == ovl_fail_too_few_arguments) {
11290         if (RFailureKind == ovl_fail_too_many_arguments ||
11291             RFailureKind == ovl_fail_too_few_arguments) {
11292           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11293           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11294           if (LDist == RDist) {
11295             if (LFailureKind == RFailureKind)
11296               // Sort non-surrogates before surrogates.
11297               return !L->IsSurrogate && R->IsSurrogate;
11298             // Sort candidates requiring fewer parameters than there were
11299             // arguments given after candidates requiring more parameters
11300             // than there were arguments given.
11301             return LFailureKind == ovl_fail_too_many_arguments;
11302           }
11303           return LDist < RDist;
11304         }
11305         return false;
11306       }
11307       if (RFailureKind == ovl_fail_too_many_arguments ||
11308           RFailureKind == ovl_fail_too_few_arguments)
11309         return true;
11310 
11311       // 2. Bad conversions come first and are ordered by the number
11312       // of bad conversions and quality of good conversions.
11313       if (LFailureKind == ovl_fail_bad_conversion) {
11314         if (RFailureKind != ovl_fail_bad_conversion)
11315           return true;
11316 
11317         // The conversion that can be fixed with a smaller number of changes,
11318         // comes first.
11319         unsigned numLFixes = L->Fix.NumConversionsFixed;
11320         unsigned numRFixes = R->Fix.NumConversionsFixed;
11321         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11322         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11323         if (numLFixes != numRFixes) {
11324           return numLFixes < numRFixes;
11325         }
11326 
11327         // If there's any ordering between the defined conversions...
11328         // FIXME: this might not be transitive.
11329         assert(L->Conversions.size() == R->Conversions.size());
11330 
11331         int leftBetter = 0;
11332         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11333         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11334           switch (CompareImplicitConversionSequences(S, Loc,
11335                                                      L->Conversions[I],
11336                                                      R->Conversions[I])) {
11337           case ImplicitConversionSequence::Better:
11338             leftBetter++;
11339             break;
11340 
11341           case ImplicitConversionSequence::Worse:
11342             leftBetter--;
11343             break;
11344 
11345           case ImplicitConversionSequence::Indistinguishable:
11346             break;
11347           }
11348         }
11349         if (leftBetter > 0) return true;
11350         if (leftBetter < 0) return false;
11351 
11352       } else if (RFailureKind == ovl_fail_bad_conversion)
11353         return false;
11354 
11355       if (LFailureKind == ovl_fail_bad_deduction) {
11356         if (RFailureKind != ovl_fail_bad_deduction)
11357           return true;
11358 
11359         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11360           return RankDeductionFailure(L->DeductionFailure)
11361                < RankDeductionFailure(R->DeductionFailure);
11362       } else if (RFailureKind == ovl_fail_bad_deduction)
11363         return false;
11364 
11365       // TODO: others?
11366     }
11367 
11368     // Sort everything else by location.
11369     SourceLocation LLoc = GetLocationForCandidate(L);
11370     SourceLocation RLoc = GetLocationForCandidate(R);
11371 
11372     // Put candidates without locations (e.g. builtins) at the end.
11373     if (LLoc.isInvalid()) return false;
11374     if (RLoc.isInvalid()) return true;
11375 
11376     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11377   }
11378 };
11379 }
11380 
11381 /// CompleteNonViableCandidate - Normally, overload resolution only
11382 /// computes up to the first bad conversion. Produces the FixIt set if
11383 /// possible.
11384 static void
11385 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11386                            ArrayRef<Expr *> Args,
11387                            OverloadCandidateSet::CandidateSetKind CSK) {
11388   assert(!Cand->Viable);
11389 
11390   // Don't do anything on failures other than bad conversion.
11391   if (Cand->FailureKind != ovl_fail_bad_conversion)
11392     return;
11393 
11394   // We only want the FixIts if all the arguments can be corrected.
11395   bool Unfixable = false;
11396   // Use a implicit copy initialization to check conversion fixes.
11397   Cand->Fix.setConversionChecker(TryCopyInitialization);
11398 
11399   // Attempt to fix the bad conversion.
11400   unsigned ConvCount = Cand->Conversions.size();
11401   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11402        ++ConvIdx) {
11403     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11404     if (Cand->Conversions[ConvIdx].isInitialized() &&
11405         Cand->Conversions[ConvIdx].isBad()) {
11406       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11407       break;
11408     }
11409   }
11410 
11411   // FIXME: this should probably be preserved from the overload
11412   // operation somehow.
11413   bool SuppressUserConversions = false;
11414 
11415   unsigned ConvIdx = 0;
11416   unsigned ArgIdx = 0;
11417   ArrayRef<QualType> ParamTypes;
11418   bool Reversed = Cand->isReversed();
11419 
11420   if (Cand->IsSurrogate) {
11421     QualType ConvType
11422       = Cand->Surrogate->getConversionType().getNonReferenceType();
11423     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11424       ConvType = ConvPtrType->getPointeeType();
11425     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11426     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11427     ConvIdx = 1;
11428   } else if (Cand->Function) {
11429     ParamTypes =
11430         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11431     if (isa<CXXMethodDecl>(Cand->Function) &&
11432         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11433       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11434       ConvIdx = 1;
11435       if (CSK == OverloadCandidateSet::CSK_Operator &&
11436           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11437         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11438         ArgIdx = 1;
11439     }
11440   } else {
11441     // Builtin operator.
11442     assert(ConvCount <= 3);
11443     ParamTypes = Cand->BuiltinParamTypes;
11444   }
11445 
11446   // Fill in the rest of the conversions.
11447   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11448        ConvIdx != ConvCount;
11449        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11450     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11451     if (Cand->Conversions[ConvIdx].isInitialized()) {
11452       // We've already checked this conversion.
11453     } else if (ParamIdx < ParamTypes.size()) {
11454       if (ParamTypes[ParamIdx]->isDependentType())
11455         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11456             Args[ArgIdx]->getType());
11457       else {
11458         Cand->Conversions[ConvIdx] =
11459             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11460                                   SuppressUserConversions,
11461                                   /*InOverloadResolution=*/true,
11462                                   /*AllowObjCWritebackConversion=*/
11463                                   S.getLangOpts().ObjCAutoRefCount);
11464         // Store the FixIt in the candidate if it exists.
11465         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11466           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11467       }
11468     } else
11469       Cand->Conversions[ConvIdx].setEllipsis();
11470   }
11471 }
11472 
11473 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11474     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11475     SourceLocation OpLoc,
11476     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11477   // Sort the candidates by viability and position.  Sorting directly would
11478   // be prohibitive, so we make a set of pointers and sort those.
11479   SmallVector<OverloadCandidate*, 32> Cands;
11480   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11481   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11482     if (!Filter(*Cand))
11483       continue;
11484     switch (OCD) {
11485     case OCD_AllCandidates:
11486       if (!Cand->Viable) {
11487         if (!Cand->Function && !Cand->IsSurrogate) {
11488           // This a non-viable builtin candidate.  We do not, in general,
11489           // want to list every possible builtin candidate.
11490           continue;
11491         }
11492         CompleteNonViableCandidate(S, Cand, Args, Kind);
11493       }
11494       break;
11495 
11496     case OCD_ViableCandidates:
11497       if (!Cand->Viable)
11498         continue;
11499       break;
11500 
11501     case OCD_AmbiguousCandidates:
11502       if (!Cand->Best)
11503         continue;
11504       break;
11505     }
11506 
11507     Cands.push_back(Cand);
11508   }
11509 
11510   llvm::stable_sort(
11511       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11512 
11513   return Cands;
11514 }
11515 
11516 /// When overload resolution fails, prints diagnostic messages containing the
11517 /// candidates in the candidate set.
11518 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11519     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11520     StringRef Opc, SourceLocation OpLoc,
11521     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11522 
11523   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11524 
11525   S.Diag(PD.first, PD.second);
11526 
11527   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11528 
11529   if (OCD == OCD_AmbiguousCandidates)
11530     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11531 }
11532 
11533 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11534                                           ArrayRef<OverloadCandidate *> Cands,
11535                                           StringRef Opc, SourceLocation OpLoc) {
11536   bool ReportedAmbiguousConversions = false;
11537 
11538   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11539   unsigned CandsShown = 0;
11540   auto I = Cands.begin(), E = Cands.end();
11541   for (; I != E; ++I) {
11542     OverloadCandidate *Cand = *I;
11543 
11544     // Set an arbitrary limit on the number of candidate functions we'll spam
11545     // the user with.  FIXME: This limit should depend on details of the
11546     // candidate list.
11547     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11548       break;
11549     }
11550     ++CandsShown;
11551 
11552     if (Cand->Function)
11553       NoteFunctionCandidate(S, Cand, Args.size(),
11554                             /*TakingCandidateAddress=*/false, DestAS);
11555     else if (Cand->IsSurrogate)
11556       NoteSurrogateCandidate(S, Cand);
11557     else {
11558       assert(Cand->Viable &&
11559              "Non-viable built-in candidates are not added to Cands.");
11560       // Generally we only see ambiguities including viable builtin
11561       // operators if overload resolution got screwed up by an
11562       // ambiguous user-defined conversion.
11563       //
11564       // FIXME: It's quite possible for different conversions to see
11565       // different ambiguities, though.
11566       if (!ReportedAmbiguousConversions) {
11567         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11568         ReportedAmbiguousConversions = true;
11569       }
11570 
11571       // If this is a viable builtin, print it.
11572       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11573     }
11574   }
11575 
11576   if (I != E)
11577     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11578 }
11579 
11580 static SourceLocation
11581 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11582   return Cand->Specialization ? Cand->Specialization->getLocation()
11583                               : SourceLocation();
11584 }
11585 
11586 namespace {
11587 struct CompareTemplateSpecCandidatesForDisplay {
11588   Sema &S;
11589   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11590 
11591   bool operator()(const TemplateSpecCandidate *L,
11592                   const TemplateSpecCandidate *R) {
11593     // Fast-path this check.
11594     if (L == R)
11595       return false;
11596 
11597     // Assuming that both candidates are not matches...
11598 
11599     // Sort by the ranking of deduction failures.
11600     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11601       return RankDeductionFailure(L->DeductionFailure) <
11602              RankDeductionFailure(R->DeductionFailure);
11603 
11604     // Sort everything else by location.
11605     SourceLocation LLoc = GetLocationForCandidate(L);
11606     SourceLocation RLoc = GetLocationForCandidate(R);
11607 
11608     // Put candidates without locations (e.g. builtins) at the end.
11609     if (LLoc.isInvalid())
11610       return false;
11611     if (RLoc.isInvalid())
11612       return true;
11613 
11614     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11615   }
11616 };
11617 }
11618 
11619 /// Diagnose a template argument deduction failure.
11620 /// We are treating these failures as overload failures due to bad
11621 /// deductions.
11622 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11623                                                  bool ForTakingAddress) {
11624   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11625                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11626 }
11627 
11628 void TemplateSpecCandidateSet::destroyCandidates() {
11629   for (iterator i = begin(), e = end(); i != e; ++i) {
11630     i->DeductionFailure.Destroy();
11631   }
11632 }
11633 
11634 void TemplateSpecCandidateSet::clear() {
11635   destroyCandidates();
11636   Candidates.clear();
11637 }
11638 
11639 /// NoteCandidates - When no template specialization match is found, prints
11640 /// diagnostic messages containing the non-matching specializations that form
11641 /// the candidate set.
11642 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11643 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11644 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11645   // Sort the candidates by position (assuming no candidate is a match).
11646   // Sorting directly would be prohibitive, so we make a set of pointers
11647   // and sort those.
11648   SmallVector<TemplateSpecCandidate *, 32> Cands;
11649   Cands.reserve(size());
11650   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11651     if (Cand->Specialization)
11652       Cands.push_back(Cand);
11653     // Otherwise, this is a non-matching builtin candidate.  We do not,
11654     // in general, want to list every possible builtin candidate.
11655   }
11656 
11657   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11658 
11659   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11660   // for generalization purposes (?).
11661   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11662 
11663   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11664   unsigned CandsShown = 0;
11665   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11666     TemplateSpecCandidate *Cand = *I;
11667 
11668     // Set an arbitrary limit on the number of candidates we'll spam
11669     // the user with.  FIXME: This limit should depend on details of the
11670     // candidate list.
11671     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11672       break;
11673     ++CandsShown;
11674 
11675     assert(Cand->Specialization &&
11676            "Non-matching built-in candidates are not added to Cands.");
11677     Cand->NoteDeductionFailure(S, ForTakingAddress);
11678   }
11679 
11680   if (I != E)
11681     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11682 }
11683 
11684 // [PossiblyAFunctionType]  -->   [Return]
11685 // NonFunctionType --> NonFunctionType
11686 // R (A) --> R(A)
11687 // R (*)(A) --> R (A)
11688 // R (&)(A) --> R (A)
11689 // R (S::*)(A) --> R (A)
11690 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11691   QualType Ret = PossiblyAFunctionType;
11692   if (const PointerType *ToTypePtr =
11693     PossiblyAFunctionType->getAs<PointerType>())
11694     Ret = ToTypePtr->getPointeeType();
11695   else if (const ReferenceType *ToTypeRef =
11696     PossiblyAFunctionType->getAs<ReferenceType>())
11697     Ret = ToTypeRef->getPointeeType();
11698   else if (const MemberPointerType *MemTypePtr =
11699     PossiblyAFunctionType->getAs<MemberPointerType>())
11700     Ret = MemTypePtr->getPointeeType();
11701   Ret =
11702     Context.getCanonicalType(Ret).getUnqualifiedType();
11703   return Ret;
11704 }
11705 
11706 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11707                                  bool Complain = true) {
11708   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11709       S.DeduceReturnType(FD, Loc, Complain))
11710     return true;
11711 
11712   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11713   if (S.getLangOpts().CPlusPlus17 &&
11714       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11715       !S.ResolveExceptionSpec(Loc, FPT))
11716     return true;
11717 
11718   return false;
11719 }
11720 
11721 namespace {
11722 // A helper class to help with address of function resolution
11723 // - allows us to avoid passing around all those ugly parameters
11724 class AddressOfFunctionResolver {
11725   Sema& S;
11726   Expr* SourceExpr;
11727   const QualType& TargetType;
11728   QualType TargetFunctionType; // Extracted function type from target type
11729 
11730   bool Complain;
11731   //DeclAccessPair& ResultFunctionAccessPair;
11732   ASTContext& Context;
11733 
11734   bool TargetTypeIsNonStaticMemberFunction;
11735   bool FoundNonTemplateFunction;
11736   bool StaticMemberFunctionFromBoundPointer;
11737   bool HasComplained;
11738 
11739   OverloadExpr::FindResult OvlExprInfo;
11740   OverloadExpr *OvlExpr;
11741   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11742   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11743   TemplateSpecCandidateSet FailedCandidates;
11744 
11745 public:
11746   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11747                             const QualType &TargetType, bool Complain)
11748       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11749         Complain(Complain), Context(S.getASTContext()),
11750         TargetTypeIsNonStaticMemberFunction(
11751             !!TargetType->getAs<MemberPointerType>()),
11752         FoundNonTemplateFunction(false),
11753         StaticMemberFunctionFromBoundPointer(false),
11754         HasComplained(false),
11755         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11756         OvlExpr(OvlExprInfo.Expression),
11757         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11758     ExtractUnqualifiedFunctionTypeFromTargetType();
11759 
11760     if (TargetFunctionType->isFunctionType()) {
11761       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11762         if (!UME->isImplicitAccess() &&
11763             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11764           StaticMemberFunctionFromBoundPointer = true;
11765     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11766       DeclAccessPair dap;
11767       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11768               OvlExpr, false, &dap)) {
11769         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11770           if (!Method->isStatic()) {
11771             // If the target type is a non-function type and the function found
11772             // is a non-static member function, pretend as if that was the
11773             // target, it's the only possible type to end up with.
11774             TargetTypeIsNonStaticMemberFunction = true;
11775 
11776             // And skip adding the function if its not in the proper form.
11777             // We'll diagnose this due to an empty set of functions.
11778             if (!OvlExprInfo.HasFormOfMemberPointer)
11779               return;
11780           }
11781 
11782         Matches.push_back(std::make_pair(dap, Fn));
11783       }
11784       return;
11785     }
11786 
11787     if (OvlExpr->hasExplicitTemplateArgs())
11788       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11789 
11790     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11791       // C++ [over.over]p4:
11792       //   If more than one function is selected, [...]
11793       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11794         if (FoundNonTemplateFunction)
11795           EliminateAllTemplateMatches();
11796         else
11797           EliminateAllExceptMostSpecializedTemplate();
11798       }
11799     }
11800 
11801     if (S.getLangOpts().CUDA && Matches.size() > 1)
11802       EliminateSuboptimalCudaMatches();
11803   }
11804 
11805   bool hasComplained() const { return HasComplained; }
11806 
11807 private:
11808   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11809     QualType Discard;
11810     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11811            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11812   }
11813 
11814   /// \return true if A is considered a better overload candidate for the
11815   /// desired type than B.
11816   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11817     // If A doesn't have exactly the correct type, we don't want to classify it
11818     // as "better" than anything else. This way, the user is required to
11819     // disambiguate for us if there are multiple candidates and no exact match.
11820     return candidateHasExactlyCorrectType(A) &&
11821            (!candidateHasExactlyCorrectType(B) ||
11822             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11823   }
11824 
11825   /// \return true if we were able to eliminate all but one overload candidate,
11826   /// false otherwise.
11827   bool eliminiateSuboptimalOverloadCandidates() {
11828     // Same algorithm as overload resolution -- one pass to pick the "best",
11829     // another pass to be sure that nothing is better than the best.
11830     auto Best = Matches.begin();
11831     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11832       if (isBetterCandidate(I->second, Best->second))
11833         Best = I;
11834 
11835     const FunctionDecl *BestFn = Best->second;
11836     auto IsBestOrInferiorToBest = [this, BestFn](
11837         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11838       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11839     };
11840 
11841     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11842     // option, so we can potentially give the user a better error
11843     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11844       return false;
11845     Matches[0] = *Best;
11846     Matches.resize(1);
11847     return true;
11848   }
11849 
11850   bool isTargetTypeAFunction() const {
11851     return TargetFunctionType->isFunctionType();
11852   }
11853 
11854   // [ToType]     [Return]
11855 
11856   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11857   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11858   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11859   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11860     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11861   }
11862 
11863   // return true if any matching specializations were found
11864   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11865                                    const DeclAccessPair& CurAccessFunPair) {
11866     if (CXXMethodDecl *Method
11867               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11868       // Skip non-static function templates when converting to pointer, and
11869       // static when converting to member pointer.
11870       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11871         return false;
11872     }
11873     else if (TargetTypeIsNonStaticMemberFunction)
11874       return false;
11875 
11876     // C++ [over.over]p2:
11877     //   If the name is a function template, template argument deduction is
11878     //   done (14.8.2.2), and if the argument deduction succeeds, the
11879     //   resulting template argument list is used to generate a single
11880     //   function template specialization, which is added to the set of
11881     //   overloaded functions considered.
11882     FunctionDecl *Specialization = nullptr;
11883     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11884     if (Sema::TemplateDeductionResult Result
11885           = S.DeduceTemplateArguments(FunctionTemplate,
11886                                       &OvlExplicitTemplateArgs,
11887                                       TargetFunctionType, Specialization,
11888                                       Info, /*IsAddressOfFunction*/true)) {
11889       // Make a note of the failed deduction for diagnostics.
11890       FailedCandidates.addCandidate()
11891           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11892                MakeDeductionFailureInfo(Context, Result, Info));
11893       return false;
11894     }
11895 
11896     // Template argument deduction ensures that we have an exact match or
11897     // compatible pointer-to-function arguments that would be adjusted by ICS.
11898     // This function template specicalization works.
11899     assert(S.isSameOrCompatibleFunctionType(
11900               Context.getCanonicalType(Specialization->getType()),
11901               Context.getCanonicalType(TargetFunctionType)));
11902 
11903     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11904       return false;
11905 
11906     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11907     return true;
11908   }
11909 
11910   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11911                                       const DeclAccessPair& CurAccessFunPair) {
11912     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11913       // Skip non-static functions when converting to pointer, and static
11914       // when converting to member pointer.
11915       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11916         return false;
11917     }
11918     else if (TargetTypeIsNonStaticMemberFunction)
11919       return false;
11920 
11921     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11922       if (S.getLangOpts().CUDA)
11923         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11924           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11925             return false;
11926       if (FunDecl->isMultiVersion()) {
11927         const auto *TA = FunDecl->getAttr<TargetAttr>();
11928         if (TA && !TA->isDefaultVersion())
11929           return false;
11930       }
11931 
11932       // If any candidate has a placeholder return type, trigger its deduction
11933       // now.
11934       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11935                                Complain)) {
11936         HasComplained |= Complain;
11937         return false;
11938       }
11939 
11940       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11941         return false;
11942 
11943       // If we're in C, we need to support types that aren't exactly identical.
11944       if (!S.getLangOpts().CPlusPlus ||
11945           candidateHasExactlyCorrectType(FunDecl)) {
11946         Matches.push_back(std::make_pair(
11947             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11948         FoundNonTemplateFunction = true;
11949         return true;
11950       }
11951     }
11952 
11953     return false;
11954   }
11955 
11956   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11957     bool Ret = false;
11958 
11959     // If the overload expression doesn't have the form of a pointer to
11960     // member, don't try to convert it to a pointer-to-member type.
11961     if (IsInvalidFormOfPointerToMemberFunction())
11962       return false;
11963 
11964     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11965                                E = OvlExpr->decls_end();
11966          I != E; ++I) {
11967       // Look through any using declarations to find the underlying function.
11968       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11969 
11970       // C++ [over.over]p3:
11971       //   Non-member functions and static member functions match
11972       //   targets of type "pointer-to-function" or "reference-to-function."
11973       //   Nonstatic member functions match targets of
11974       //   type "pointer-to-member-function."
11975       // Note that according to DR 247, the containing class does not matter.
11976       if (FunctionTemplateDecl *FunctionTemplate
11977                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11978         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11979           Ret = true;
11980       }
11981       // If we have explicit template arguments supplied, skip non-templates.
11982       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11983                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11984         Ret = true;
11985     }
11986     assert(Ret || Matches.empty());
11987     return Ret;
11988   }
11989 
11990   void EliminateAllExceptMostSpecializedTemplate() {
11991     //   [...] and any given function template specialization F1 is
11992     //   eliminated if the set contains a second function template
11993     //   specialization whose function template is more specialized
11994     //   than the function template of F1 according to the partial
11995     //   ordering rules of 14.5.5.2.
11996 
11997     // The algorithm specified above is quadratic. We instead use a
11998     // two-pass algorithm (similar to the one used to identify the
11999     // best viable function in an overload set) that identifies the
12000     // best function template (if it exists).
12001 
12002     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12003     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12004       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12005 
12006     // TODO: It looks like FailedCandidates does not serve much purpose
12007     // here, since the no_viable diagnostic has index 0.
12008     UnresolvedSetIterator Result = S.getMostSpecialized(
12009         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12010         SourceExpr->getBeginLoc(), S.PDiag(),
12011         S.PDiag(diag::err_addr_ovl_ambiguous)
12012             << Matches[0].second->getDeclName(),
12013         S.PDiag(diag::note_ovl_candidate)
12014             << (unsigned)oc_function << (unsigned)ocs_described_template,
12015         Complain, TargetFunctionType);
12016 
12017     if (Result != MatchesCopy.end()) {
12018       // Make it the first and only element
12019       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12020       Matches[0].second = cast<FunctionDecl>(*Result);
12021       Matches.resize(1);
12022     } else
12023       HasComplained |= Complain;
12024   }
12025 
12026   void EliminateAllTemplateMatches() {
12027     //   [...] any function template specializations in the set are
12028     //   eliminated if the set also contains a non-template function, [...]
12029     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12030       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12031         ++I;
12032       else {
12033         Matches[I] = Matches[--N];
12034         Matches.resize(N);
12035       }
12036     }
12037   }
12038 
12039   void EliminateSuboptimalCudaMatches() {
12040     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12041   }
12042 
12043 public:
12044   void ComplainNoMatchesFound() const {
12045     assert(Matches.empty());
12046     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12047         << OvlExpr->getName() << TargetFunctionType
12048         << OvlExpr->getSourceRange();
12049     if (FailedCandidates.empty())
12050       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12051                                   /*TakingAddress=*/true);
12052     else {
12053       // We have some deduction failure messages. Use them to diagnose
12054       // the function templates, and diagnose the non-template candidates
12055       // normally.
12056       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12057                                  IEnd = OvlExpr->decls_end();
12058            I != IEnd; ++I)
12059         if (FunctionDecl *Fun =
12060                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12061           if (!functionHasPassObjectSizeParams(Fun))
12062             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12063                                     /*TakingAddress=*/true);
12064       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12065     }
12066   }
12067 
12068   bool IsInvalidFormOfPointerToMemberFunction() const {
12069     return TargetTypeIsNonStaticMemberFunction &&
12070       !OvlExprInfo.HasFormOfMemberPointer;
12071   }
12072 
12073   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12074       // TODO: Should we condition this on whether any functions might
12075       // have matched, or is it more appropriate to do that in callers?
12076       // TODO: a fixit wouldn't hurt.
12077       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12078         << TargetType << OvlExpr->getSourceRange();
12079   }
12080 
12081   bool IsStaticMemberFunctionFromBoundPointer() const {
12082     return StaticMemberFunctionFromBoundPointer;
12083   }
12084 
12085   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12086     S.Diag(OvlExpr->getBeginLoc(),
12087            diag::err_invalid_form_pointer_member_function)
12088         << OvlExpr->getSourceRange();
12089   }
12090 
12091   void ComplainOfInvalidConversion() const {
12092     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12093         << OvlExpr->getName() << TargetType;
12094   }
12095 
12096   void ComplainMultipleMatchesFound() const {
12097     assert(Matches.size() > 1);
12098     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12099         << OvlExpr->getName() << OvlExpr->getSourceRange();
12100     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12101                                 /*TakingAddress=*/true);
12102   }
12103 
12104   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12105 
12106   int getNumMatches() const { return Matches.size(); }
12107 
12108   FunctionDecl* getMatchingFunctionDecl() const {
12109     if (Matches.size() != 1) return nullptr;
12110     return Matches[0].second;
12111   }
12112 
12113   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12114     if (Matches.size() != 1) return nullptr;
12115     return &Matches[0].first;
12116   }
12117 };
12118 }
12119 
12120 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12121 /// an overloaded function (C++ [over.over]), where @p From is an
12122 /// expression with overloaded function type and @p ToType is the type
12123 /// we're trying to resolve to. For example:
12124 ///
12125 /// @code
12126 /// int f(double);
12127 /// int f(int);
12128 ///
12129 /// int (*pfd)(double) = f; // selects f(double)
12130 /// @endcode
12131 ///
12132 /// This routine returns the resulting FunctionDecl if it could be
12133 /// resolved, and NULL otherwise. When @p Complain is true, this
12134 /// routine will emit diagnostics if there is an error.
12135 FunctionDecl *
12136 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12137                                          QualType TargetType,
12138                                          bool Complain,
12139                                          DeclAccessPair &FoundResult,
12140                                          bool *pHadMultipleCandidates) {
12141   assert(AddressOfExpr->getType() == Context.OverloadTy);
12142 
12143   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12144                                      Complain);
12145   int NumMatches = Resolver.getNumMatches();
12146   FunctionDecl *Fn = nullptr;
12147   bool ShouldComplain = Complain && !Resolver.hasComplained();
12148   if (NumMatches == 0 && ShouldComplain) {
12149     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12150       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12151     else
12152       Resolver.ComplainNoMatchesFound();
12153   }
12154   else if (NumMatches > 1 && ShouldComplain)
12155     Resolver.ComplainMultipleMatchesFound();
12156   else if (NumMatches == 1) {
12157     Fn = Resolver.getMatchingFunctionDecl();
12158     assert(Fn);
12159     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12160       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12161     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12162     if (Complain) {
12163       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12164         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12165       else
12166         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12167     }
12168   }
12169 
12170   if (pHadMultipleCandidates)
12171     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12172   return Fn;
12173 }
12174 
12175 /// Given an expression that refers to an overloaded function, try to
12176 /// resolve that function to a single function that can have its address taken.
12177 /// This will modify `Pair` iff it returns non-null.
12178 ///
12179 /// This routine can only succeed if from all of the candidates in the overload
12180 /// set for SrcExpr that can have their addresses taken, there is one candidate
12181 /// that is more constrained than the rest.
12182 FunctionDecl *
12183 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12184   OverloadExpr::FindResult R = OverloadExpr::find(E);
12185   OverloadExpr *Ovl = R.Expression;
12186   bool IsResultAmbiguous = false;
12187   FunctionDecl *Result = nullptr;
12188   DeclAccessPair DAP;
12189   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12190 
12191   auto CheckMoreConstrained =
12192       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12193         SmallVector<const Expr *, 1> AC1, AC2;
12194         FD1->getAssociatedConstraints(AC1);
12195         FD2->getAssociatedConstraints(AC2);
12196         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12197         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12198           return None;
12199         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12200           return None;
12201         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12202           return None;
12203         return AtLeastAsConstrained1;
12204       };
12205 
12206   // Don't use the AddressOfResolver because we're specifically looking for
12207   // cases where we have one overload candidate that lacks
12208   // enable_if/pass_object_size/...
12209   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12210     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12211     if (!FD)
12212       return nullptr;
12213 
12214     if (!checkAddressOfFunctionIsAvailable(FD))
12215       continue;
12216 
12217     // We have more than one result - see if it is more constrained than the
12218     // previous one.
12219     if (Result) {
12220       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12221                                                                         Result);
12222       if (!MoreConstrainedThanPrevious) {
12223         IsResultAmbiguous = true;
12224         AmbiguousDecls.push_back(FD);
12225         continue;
12226       }
12227       if (!*MoreConstrainedThanPrevious)
12228         continue;
12229       // FD is more constrained - replace Result with it.
12230     }
12231     IsResultAmbiguous = false;
12232     DAP = I.getPair();
12233     Result = FD;
12234   }
12235 
12236   if (IsResultAmbiguous)
12237     return nullptr;
12238 
12239   if (Result) {
12240     SmallVector<const Expr *, 1> ResultAC;
12241     // We skipped over some ambiguous declarations which might be ambiguous with
12242     // the selected result.
12243     for (FunctionDecl *Skipped : AmbiguousDecls)
12244       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12245         return nullptr;
12246     Pair = DAP;
12247   }
12248   return Result;
12249 }
12250 
12251 /// Given an overloaded function, tries to turn it into a non-overloaded
12252 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12253 /// will perform access checks, diagnose the use of the resultant decl, and, if
12254 /// requested, potentially perform a function-to-pointer decay.
12255 ///
12256 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12257 /// Otherwise, returns true. This may emit diagnostics and return true.
12258 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12259     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12260   Expr *E = SrcExpr.get();
12261   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12262 
12263   DeclAccessPair DAP;
12264   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12265   if (!Found || Found->isCPUDispatchMultiVersion() ||
12266       Found->isCPUSpecificMultiVersion())
12267     return false;
12268 
12269   // Emitting multiple diagnostics for a function that is both inaccessible and
12270   // unavailable is consistent with our behavior elsewhere. So, always check
12271   // for both.
12272   DiagnoseUseOfDecl(Found, E->getExprLoc());
12273   CheckAddressOfMemberAccess(E, DAP);
12274   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12275   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12276     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12277   else
12278     SrcExpr = Fixed;
12279   return true;
12280 }
12281 
12282 /// Given an expression that refers to an overloaded function, try to
12283 /// resolve that overloaded function expression down to a single function.
12284 ///
12285 /// This routine can only resolve template-ids that refer to a single function
12286 /// template, where that template-id refers to a single template whose template
12287 /// arguments are either provided by the template-id or have defaults,
12288 /// as described in C++0x [temp.arg.explicit]p3.
12289 ///
12290 /// If no template-ids are found, no diagnostics are emitted and NULL is
12291 /// returned.
12292 FunctionDecl *
12293 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12294                                                   bool Complain,
12295                                                   DeclAccessPair *FoundResult) {
12296   // C++ [over.over]p1:
12297   //   [...] [Note: any redundant set of parentheses surrounding the
12298   //   overloaded function name is ignored (5.1). ]
12299   // C++ [over.over]p1:
12300   //   [...] The overloaded function name can be preceded by the &
12301   //   operator.
12302 
12303   // If we didn't actually find any template-ids, we're done.
12304   if (!ovl->hasExplicitTemplateArgs())
12305     return nullptr;
12306 
12307   TemplateArgumentListInfo ExplicitTemplateArgs;
12308   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12309   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12310 
12311   // Look through all of the overloaded functions, searching for one
12312   // whose type matches exactly.
12313   FunctionDecl *Matched = nullptr;
12314   for (UnresolvedSetIterator I = ovl->decls_begin(),
12315          E = ovl->decls_end(); I != E; ++I) {
12316     // C++0x [temp.arg.explicit]p3:
12317     //   [...] In contexts where deduction is done and fails, or in contexts
12318     //   where deduction is not done, if a template argument list is
12319     //   specified and it, along with any default template arguments,
12320     //   identifies a single function template specialization, then the
12321     //   template-id is an lvalue for the function template specialization.
12322     FunctionTemplateDecl *FunctionTemplate
12323       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12324 
12325     // C++ [over.over]p2:
12326     //   If the name is a function template, template argument deduction is
12327     //   done (14.8.2.2), and if the argument deduction succeeds, the
12328     //   resulting template argument list is used to generate a single
12329     //   function template specialization, which is added to the set of
12330     //   overloaded functions considered.
12331     FunctionDecl *Specialization = nullptr;
12332     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12333     if (TemplateDeductionResult Result
12334           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12335                                     Specialization, Info,
12336                                     /*IsAddressOfFunction*/true)) {
12337       // Make a note of the failed deduction for diagnostics.
12338       // TODO: Actually use the failed-deduction info?
12339       FailedCandidates.addCandidate()
12340           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12341                MakeDeductionFailureInfo(Context, Result, Info));
12342       continue;
12343     }
12344 
12345     assert(Specialization && "no specialization and no error?");
12346 
12347     // Multiple matches; we can't resolve to a single declaration.
12348     if (Matched) {
12349       if (Complain) {
12350         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12351           << ovl->getName();
12352         NoteAllOverloadCandidates(ovl);
12353       }
12354       return nullptr;
12355     }
12356 
12357     Matched = Specialization;
12358     if (FoundResult) *FoundResult = I.getPair();
12359   }
12360 
12361   if (Matched &&
12362       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12363     return nullptr;
12364 
12365   return Matched;
12366 }
12367 
12368 // Resolve and fix an overloaded expression that can be resolved
12369 // because it identifies a single function template specialization.
12370 //
12371 // Last three arguments should only be supplied if Complain = true
12372 //
12373 // Return true if it was logically possible to so resolve the
12374 // expression, regardless of whether or not it succeeded.  Always
12375 // returns true if 'complain' is set.
12376 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12377                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12378                       bool complain, SourceRange OpRangeForComplaining,
12379                                            QualType DestTypeForComplaining,
12380                                             unsigned DiagIDForComplaining) {
12381   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12382 
12383   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12384 
12385   DeclAccessPair found;
12386   ExprResult SingleFunctionExpression;
12387   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12388                            ovl.Expression, /*complain*/ false, &found)) {
12389     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12390       SrcExpr = ExprError();
12391       return true;
12392     }
12393 
12394     // It is only correct to resolve to an instance method if we're
12395     // resolving a form that's permitted to be a pointer to member.
12396     // Otherwise we'll end up making a bound member expression, which
12397     // is illegal in all the contexts we resolve like this.
12398     if (!ovl.HasFormOfMemberPointer &&
12399         isa<CXXMethodDecl>(fn) &&
12400         cast<CXXMethodDecl>(fn)->isInstance()) {
12401       if (!complain) return false;
12402 
12403       Diag(ovl.Expression->getExprLoc(),
12404            diag::err_bound_member_function)
12405         << 0 << ovl.Expression->getSourceRange();
12406 
12407       // TODO: I believe we only end up here if there's a mix of
12408       // static and non-static candidates (otherwise the expression
12409       // would have 'bound member' type, not 'overload' type).
12410       // Ideally we would note which candidate was chosen and why
12411       // the static candidates were rejected.
12412       SrcExpr = ExprError();
12413       return true;
12414     }
12415 
12416     // Fix the expression to refer to 'fn'.
12417     SingleFunctionExpression =
12418         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12419 
12420     // If desired, do function-to-pointer decay.
12421     if (doFunctionPointerConverion) {
12422       SingleFunctionExpression =
12423         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12424       if (SingleFunctionExpression.isInvalid()) {
12425         SrcExpr = ExprError();
12426         return true;
12427       }
12428     }
12429   }
12430 
12431   if (!SingleFunctionExpression.isUsable()) {
12432     if (complain) {
12433       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12434         << ovl.Expression->getName()
12435         << DestTypeForComplaining
12436         << OpRangeForComplaining
12437         << ovl.Expression->getQualifierLoc().getSourceRange();
12438       NoteAllOverloadCandidates(SrcExpr.get());
12439 
12440       SrcExpr = ExprError();
12441       return true;
12442     }
12443 
12444     return false;
12445   }
12446 
12447   SrcExpr = SingleFunctionExpression;
12448   return true;
12449 }
12450 
12451 /// Add a single candidate to the overload set.
12452 static void AddOverloadedCallCandidate(Sema &S,
12453                                        DeclAccessPair FoundDecl,
12454                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12455                                        ArrayRef<Expr *> Args,
12456                                        OverloadCandidateSet &CandidateSet,
12457                                        bool PartialOverloading,
12458                                        bool KnownValid) {
12459   NamedDecl *Callee = FoundDecl.getDecl();
12460   if (isa<UsingShadowDecl>(Callee))
12461     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12462 
12463   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12464     if (ExplicitTemplateArgs) {
12465       assert(!KnownValid && "Explicit template arguments?");
12466       return;
12467     }
12468     // Prevent ill-formed function decls to be added as overload candidates.
12469     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12470       return;
12471 
12472     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12473                            /*SuppressUserConversions=*/false,
12474                            PartialOverloading);
12475     return;
12476   }
12477 
12478   if (FunctionTemplateDecl *FuncTemplate
12479       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12480     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12481                                    ExplicitTemplateArgs, Args, CandidateSet,
12482                                    /*SuppressUserConversions=*/false,
12483                                    PartialOverloading);
12484     return;
12485   }
12486 
12487   assert(!KnownValid && "unhandled case in overloaded call candidate");
12488 }
12489 
12490 /// Add the overload candidates named by callee and/or found by argument
12491 /// dependent lookup to the given overload set.
12492 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12493                                        ArrayRef<Expr *> Args,
12494                                        OverloadCandidateSet &CandidateSet,
12495                                        bool PartialOverloading) {
12496 
12497 #ifndef NDEBUG
12498   // Verify that ArgumentDependentLookup is consistent with the rules
12499   // in C++0x [basic.lookup.argdep]p3:
12500   //
12501   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12502   //   and let Y be the lookup set produced by argument dependent
12503   //   lookup (defined as follows). If X contains
12504   //
12505   //     -- a declaration of a class member, or
12506   //
12507   //     -- a block-scope function declaration that is not a
12508   //        using-declaration, or
12509   //
12510   //     -- a declaration that is neither a function or a function
12511   //        template
12512   //
12513   //   then Y is empty.
12514 
12515   if (ULE->requiresADL()) {
12516     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12517            E = ULE->decls_end(); I != E; ++I) {
12518       assert(!(*I)->getDeclContext()->isRecord());
12519       assert(isa<UsingShadowDecl>(*I) ||
12520              !(*I)->getDeclContext()->isFunctionOrMethod());
12521       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12522     }
12523   }
12524 #endif
12525 
12526   // It would be nice to avoid this copy.
12527   TemplateArgumentListInfo TABuffer;
12528   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12529   if (ULE->hasExplicitTemplateArgs()) {
12530     ULE->copyTemplateArgumentsInto(TABuffer);
12531     ExplicitTemplateArgs = &TABuffer;
12532   }
12533 
12534   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12535          E = ULE->decls_end(); I != E; ++I)
12536     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12537                                CandidateSet, PartialOverloading,
12538                                /*KnownValid*/ true);
12539 
12540   if (ULE->requiresADL())
12541     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12542                                          Args, ExplicitTemplateArgs,
12543                                          CandidateSet, PartialOverloading);
12544 }
12545 
12546 /// Determine whether a declaration with the specified name could be moved into
12547 /// a different namespace.
12548 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12549   switch (Name.getCXXOverloadedOperator()) {
12550   case OO_New: case OO_Array_New:
12551   case OO_Delete: case OO_Array_Delete:
12552     return false;
12553 
12554   default:
12555     return true;
12556   }
12557 }
12558 
12559 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12560 /// template, where the non-dependent name was declared after the template
12561 /// was defined. This is common in code written for a compilers which do not
12562 /// correctly implement two-stage name lookup.
12563 ///
12564 /// Returns true if a viable candidate was found and a diagnostic was issued.
12565 static bool
12566 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12567                        const CXXScopeSpec &SS, LookupResult &R,
12568                        OverloadCandidateSet::CandidateSetKind CSK,
12569                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12570                        ArrayRef<Expr *> Args,
12571                        bool *DoDiagnoseEmptyLookup = nullptr) {
12572   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12573     return false;
12574 
12575   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12576     if (DC->isTransparentContext())
12577       continue;
12578 
12579     SemaRef.LookupQualifiedName(R, DC);
12580 
12581     if (!R.empty()) {
12582       R.suppressDiagnostics();
12583 
12584       if (isa<CXXRecordDecl>(DC)) {
12585         // Don't diagnose names we find in classes; we get much better
12586         // diagnostics for these from DiagnoseEmptyLookup.
12587         R.clear();
12588         if (DoDiagnoseEmptyLookup)
12589           *DoDiagnoseEmptyLookup = true;
12590         return false;
12591       }
12592 
12593       OverloadCandidateSet Candidates(FnLoc, CSK);
12594       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12595         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12596                                    ExplicitTemplateArgs, Args,
12597                                    Candidates, false, /*KnownValid*/ false);
12598 
12599       OverloadCandidateSet::iterator Best;
12600       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12601         // No viable functions. Don't bother the user with notes for functions
12602         // which don't work and shouldn't be found anyway.
12603         R.clear();
12604         return false;
12605       }
12606 
12607       // Find the namespaces where ADL would have looked, and suggest
12608       // declaring the function there instead.
12609       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12610       Sema::AssociatedClassSet AssociatedClasses;
12611       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12612                                                  AssociatedNamespaces,
12613                                                  AssociatedClasses);
12614       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12615       if (canBeDeclaredInNamespace(R.getLookupName())) {
12616         DeclContext *Std = SemaRef.getStdNamespace();
12617         for (Sema::AssociatedNamespaceSet::iterator
12618                it = AssociatedNamespaces.begin(),
12619                end = AssociatedNamespaces.end(); it != end; ++it) {
12620           // Never suggest declaring a function within namespace 'std'.
12621           if (Std && Std->Encloses(*it))
12622             continue;
12623 
12624           // Never suggest declaring a function within a namespace with a
12625           // reserved name, like __gnu_cxx.
12626           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12627           if (NS &&
12628               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12629             continue;
12630 
12631           SuggestedNamespaces.insert(*it);
12632         }
12633       }
12634 
12635       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12636         << R.getLookupName();
12637       if (SuggestedNamespaces.empty()) {
12638         SemaRef.Diag(Best->Function->getLocation(),
12639                      diag::note_not_found_by_two_phase_lookup)
12640           << R.getLookupName() << 0;
12641       } else if (SuggestedNamespaces.size() == 1) {
12642         SemaRef.Diag(Best->Function->getLocation(),
12643                      diag::note_not_found_by_two_phase_lookup)
12644           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12645       } else {
12646         // FIXME: It would be useful to list the associated namespaces here,
12647         // but the diagnostics infrastructure doesn't provide a way to produce
12648         // a localized representation of a list of items.
12649         SemaRef.Diag(Best->Function->getLocation(),
12650                      diag::note_not_found_by_two_phase_lookup)
12651           << R.getLookupName() << 2;
12652       }
12653 
12654       // Try to recover by calling this function.
12655       return true;
12656     }
12657 
12658     R.clear();
12659   }
12660 
12661   return false;
12662 }
12663 
12664 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12665 /// template, where the non-dependent operator was declared after the template
12666 /// was defined.
12667 ///
12668 /// Returns true if a viable candidate was found and a diagnostic was issued.
12669 static bool
12670 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12671                                SourceLocation OpLoc,
12672                                ArrayRef<Expr *> Args) {
12673   DeclarationName OpName =
12674     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12675   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12676   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12677                                 OverloadCandidateSet::CSK_Operator,
12678                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12679 }
12680 
12681 namespace {
12682 class BuildRecoveryCallExprRAII {
12683   Sema &SemaRef;
12684 public:
12685   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12686     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12687     SemaRef.IsBuildingRecoveryCallExpr = true;
12688   }
12689 
12690   ~BuildRecoveryCallExprRAII() {
12691     SemaRef.IsBuildingRecoveryCallExpr = false;
12692   }
12693 };
12694 
12695 }
12696 
12697 /// Attempts to recover from a call where no functions were found.
12698 ///
12699 /// Returns true if new candidates were found.
12700 static ExprResult
12701 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12702                       UnresolvedLookupExpr *ULE,
12703                       SourceLocation LParenLoc,
12704                       MutableArrayRef<Expr *> Args,
12705                       SourceLocation RParenLoc,
12706                       bool EmptyLookup, bool AllowTypoCorrection) {
12707   // Do not try to recover if it is already building a recovery call.
12708   // This stops infinite loops for template instantiations like
12709   //
12710   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12711   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12712   //
12713   if (SemaRef.IsBuildingRecoveryCallExpr)
12714     return ExprError();
12715   BuildRecoveryCallExprRAII RCE(SemaRef);
12716 
12717   CXXScopeSpec SS;
12718   SS.Adopt(ULE->getQualifierLoc());
12719   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12720 
12721   TemplateArgumentListInfo TABuffer;
12722   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12723   if (ULE->hasExplicitTemplateArgs()) {
12724     ULE->copyTemplateArgumentsInto(TABuffer);
12725     ExplicitTemplateArgs = &TABuffer;
12726   }
12727 
12728   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12729                  Sema::LookupOrdinaryName);
12730   bool DoDiagnoseEmptyLookup = EmptyLookup;
12731   if (!DiagnoseTwoPhaseLookup(
12732           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12733           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12734     NoTypoCorrectionCCC NoTypoValidator{};
12735     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12736                                                 ExplicitTemplateArgs != nullptr,
12737                                                 dyn_cast<MemberExpr>(Fn));
12738     CorrectionCandidateCallback &Validator =
12739         AllowTypoCorrection
12740             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12741             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12742     if (!DoDiagnoseEmptyLookup ||
12743         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12744                                     Args))
12745       return ExprError();
12746   }
12747 
12748   assert(!R.empty() && "lookup results empty despite recovery");
12749 
12750   // If recovery created an ambiguity, just bail out.
12751   if (R.isAmbiguous()) {
12752     R.suppressDiagnostics();
12753     return ExprError();
12754   }
12755 
12756   // Build an implicit member call if appropriate.  Just drop the
12757   // casts and such from the call, we don't really care.
12758   ExprResult NewFn = ExprError();
12759   if ((*R.begin())->isCXXClassMember())
12760     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12761                                                     ExplicitTemplateArgs, S);
12762   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12763     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12764                                         ExplicitTemplateArgs);
12765   else
12766     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12767 
12768   if (NewFn.isInvalid())
12769     return ExprError();
12770 
12771   // This shouldn't cause an infinite loop because we're giving it
12772   // an expression with viable lookup results, which should never
12773   // end up here.
12774   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12775                                MultiExprArg(Args.data(), Args.size()),
12776                                RParenLoc);
12777 }
12778 
12779 /// Constructs and populates an OverloadedCandidateSet from
12780 /// the given function.
12781 /// \returns true when an the ExprResult output parameter has been set.
12782 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12783                                   UnresolvedLookupExpr *ULE,
12784                                   MultiExprArg Args,
12785                                   SourceLocation RParenLoc,
12786                                   OverloadCandidateSet *CandidateSet,
12787                                   ExprResult *Result) {
12788 #ifndef NDEBUG
12789   if (ULE->requiresADL()) {
12790     // To do ADL, we must have found an unqualified name.
12791     assert(!ULE->getQualifier() && "qualified name with ADL");
12792 
12793     // We don't perform ADL for implicit declarations of builtins.
12794     // Verify that this was correctly set up.
12795     FunctionDecl *F;
12796     if (ULE->decls_begin() != ULE->decls_end() &&
12797         ULE->decls_begin() + 1 == ULE->decls_end() &&
12798         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12799         F->getBuiltinID() && F->isImplicit())
12800       llvm_unreachable("performing ADL for builtin");
12801 
12802     // We don't perform ADL in C.
12803     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12804   }
12805 #endif
12806 
12807   UnbridgedCastsSet UnbridgedCasts;
12808   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12809     *Result = ExprError();
12810     return true;
12811   }
12812 
12813   // Add the functions denoted by the callee to the set of candidate
12814   // functions, including those from argument-dependent lookup.
12815   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12816 
12817   if (getLangOpts().MSVCCompat &&
12818       CurContext->isDependentContext() && !isSFINAEContext() &&
12819       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12820 
12821     OverloadCandidateSet::iterator Best;
12822     if (CandidateSet->empty() ||
12823         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12824             OR_No_Viable_Function) {
12825       // In Microsoft mode, if we are inside a template class member function
12826       // then create a type dependent CallExpr. The goal is to postpone name
12827       // lookup to instantiation time to be able to search into type dependent
12828       // base classes.
12829       CallExpr *CE =
12830           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue,
12831                            RParenLoc, CurFPFeatureOverrides());
12832       CE->markDependentForPostponedNameLookup();
12833       *Result = CE;
12834       return true;
12835     }
12836   }
12837 
12838   if (CandidateSet->empty())
12839     return false;
12840 
12841   UnbridgedCasts.restore();
12842   return false;
12843 }
12844 
12845 // Guess at what the return type for an unresolvable overload should be.
12846 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12847                                    OverloadCandidateSet::iterator *Best) {
12848   llvm::Optional<QualType> Result;
12849   // Adjust Type after seeing a candidate.
12850   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12851     if (!Candidate.Function)
12852       return;
12853     if (Candidate.Function->isInvalidDecl())
12854       return;
12855     QualType T = Candidate.Function->getReturnType();
12856     if (T.isNull())
12857       return;
12858     if (!Result)
12859       Result = T;
12860     else if (Result != T)
12861       Result = QualType();
12862   };
12863 
12864   // Look for an unambiguous type from a progressively larger subset.
12865   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12866   //
12867   // First, consider only the best candidate.
12868   if (Best && *Best != CS.end())
12869     ConsiderCandidate(**Best);
12870   // Next, consider only viable candidates.
12871   if (!Result)
12872     for (const auto &C : CS)
12873       if (C.Viable)
12874         ConsiderCandidate(C);
12875   // Finally, consider all candidates.
12876   if (!Result)
12877     for (const auto &C : CS)
12878       ConsiderCandidate(C);
12879 
12880   return Result.getValueOr(QualType());
12881 }
12882 
12883 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12884 /// the completed call expression. If overload resolution fails, emits
12885 /// diagnostics and returns ExprError()
12886 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12887                                            UnresolvedLookupExpr *ULE,
12888                                            SourceLocation LParenLoc,
12889                                            MultiExprArg Args,
12890                                            SourceLocation RParenLoc,
12891                                            Expr *ExecConfig,
12892                                            OverloadCandidateSet *CandidateSet,
12893                                            OverloadCandidateSet::iterator *Best,
12894                                            OverloadingResult OverloadResult,
12895                                            bool AllowTypoCorrection) {
12896   if (CandidateSet->empty())
12897     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12898                                  RParenLoc, /*EmptyLookup=*/true,
12899                                  AllowTypoCorrection);
12900 
12901   switch (OverloadResult) {
12902   case OR_Success: {
12903     FunctionDecl *FDecl = (*Best)->Function;
12904     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12905     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12906       return ExprError();
12907     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12908     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12909                                          ExecConfig, /*IsExecConfig=*/false,
12910                                          (*Best)->IsADLCandidate);
12911   }
12912 
12913   case OR_No_Viable_Function: {
12914     // Try to recover by looking for viable functions which the user might
12915     // have meant to call.
12916     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12917                                                 Args, RParenLoc,
12918                                                 /*EmptyLookup=*/false,
12919                                                 AllowTypoCorrection);
12920     if (!Recovery.isInvalid())
12921       return Recovery;
12922 
12923     // If the user passes in a function that we can't take the address of, we
12924     // generally end up emitting really bad error messages. Here, we attempt to
12925     // emit better ones.
12926     for (const Expr *Arg : Args) {
12927       if (!Arg->getType()->isFunctionType())
12928         continue;
12929       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12930         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12931         if (FD &&
12932             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12933                                                        Arg->getExprLoc()))
12934           return ExprError();
12935       }
12936     }
12937 
12938     CandidateSet->NoteCandidates(
12939         PartialDiagnosticAt(
12940             Fn->getBeginLoc(),
12941             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12942                 << ULE->getName() << Fn->getSourceRange()),
12943         SemaRef, OCD_AllCandidates, Args);
12944     break;
12945   }
12946 
12947   case OR_Ambiguous:
12948     CandidateSet->NoteCandidates(
12949         PartialDiagnosticAt(Fn->getBeginLoc(),
12950                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12951                                 << ULE->getName() << Fn->getSourceRange()),
12952         SemaRef, OCD_AmbiguousCandidates, Args);
12953     break;
12954 
12955   case OR_Deleted: {
12956     CandidateSet->NoteCandidates(
12957         PartialDiagnosticAt(Fn->getBeginLoc(),
12958                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12959                                 << ULE->getName() << Fn->getSourceRange()),
12960         SemaRef, OCD_AllCandidates, Args);
12961 
12962     // We emitted an error for the unavailable/deleted function call but keep
12963     // the call in the AST.
12964     FunctionDecl *FDecl = (*Best)->Function;
12965     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12966     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12967                                          ExecConfig, /*IsExecConfig=*/false,
12968                                          (*Best)->IsADLCandidate);
12969   }
12970   }
12971 
12972   // Overload resolution failed, try to recover.
12973   SmallVector<Expr *, 8> SubExprs = {Fn};
12974   SubExprs.append(Args.begin(), Args.end());
12975   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12976                                     chooseRecoveryType(*CandidateSet, Best));
12977 }
12978 
12979 static void markUnaddressableCandidatesUnviable(Sema &S,
12980                                                 OverloadCandidateSet &CS) {
12981   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12982     if (I->Viable &&
12983         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12984       I->Viable = false;
12985       I->FailureKind = ovl_fail_addr_not_available;
12986     }
12987   }
12988 }
12989 
12990 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12991 /// (which eventually refers to the declaration Func) and the call
12992 /// arguments Args/NumArgs, attempt to resolve the function call down
12993 /// to a specific function. If overload resolution succeeds, returns
12994 /// the call expression produced by overload resolution.
12995 /// Otherwise, emits diagnostics and returns ExprError.
12996 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12997                                          UnresolvedLookupExpr *ULE,
12998                                          SourceLocation LParenLoc,
12999                                          MultiExprArg Args,
13000                                          SourceLocation RParenLoc,
13001                                          Expr *ExecConfig,
13002                                          bool AllowTypoCorrection,
13003                                          bool CalleesAddressIsTaken) {
13004   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13005                                     OverloadCandidateSet::CSK_Normal);
13006   ExprResult result;
13007 
13008   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13009                              &result))
13010     return result;
13011 
13012   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13013   // functions that aren't addressible are considered unviable.
13014   if (CalleesAddressIsTaken)
13015     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13016 
13017   OverloadCandidateSet::iterator Best;
13018   OverloadingResult OverloadResult =
13019       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13020 
13021   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13022                                   ExecConfig, &CandidateSet, &Best,
13023                                   OverloadResult, AllowTypoCorrection);
13024 }
13025 
13026 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13027   return Functions.size() > 1 ||
13028          (Functions.size() == 1 &&
13029           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13030 }
13031 
13032 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13033                                             NestedNameSpecifierLoc NNSLoc,
13034                                             DeclarationNameInfo DNI,
13035                                             const UnresolvedSetImpl &Fns,
13036                                             bool PerformADL) {
13037   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13038                                       PerformADL, IsOverloaded(Fns),
13039                                       Fns.begin(), Fns.end());
13040 }
13041 
13042 /// Create a unary operation that may resolve to an overloaded
13043 /// operator.
13044 ///
13045 /// \param OpLoc The location of the operator itself (e.g., '*').
13046 ///
13047 /// \param Opc The UnaryOperatorKind that describes this operator.
13048 ///
13049 /// \param Fns The set of non-member functions that will be
13050 /// considered by overload resolution. The caller needs to build this
13051 /// set based on the context using, e.g.,
13052 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13053 /// set should not contain any member functions; those will be added
13054 /// by CreateOverloadedUnaryOp().
13055 ///
13056 /// \param Input The input argument.
13057 ExprResult
13058 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13059                               const UnresolvedSetImpl &Fns,
13060                               Expr *Input, bool PerformADL) {
13061   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13062   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13063   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13064   // TODO: provide better source location info.
13065   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13066 
13067   if (checkPlaceholderForOverload(*this, Input))
13068     return ExprError();
13069 
13070   Expr *Args[2] = { Input, nullptr };
13071   unsigned NumArgs = 1;
13072 
13073   // For post-increment and post-decrement, add the implicit '0' as
13074   // the second argument, so that we know this is a post-increment or
13075   // post-decrement.
13076   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13077     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13078     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13079                                      SourceLocation());
13080     NumArgs = 2;
13081   }
13082 
13083   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13084 
13085   if (Input->isTypeDependent()) {
13086     if (Fns.empty())
13087       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13088                                    VK_RValue, OK_Ordinary, OpLoc, false,
13089                                    CurFPFeatureOverrides());
13090 
13091     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13092     ExprResult Fn = CreateUnresolvedLookupExpr(
13093         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13094     if (Fn.isInvalid())
13095       return ExprError();
13096     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13097                                        Context.DependentTy, VK_RValue, OpLoc,
13098                                        CurFPFeatureOverrides());
13099   }
13100 
13101   // Build an empty overload set.
13102   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13103 
13104   // Add the candidates from the given function set.
13105   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13106 
13107   // Add operator candidates that are member functions.
13108   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13109 
13110   // Add candidates from ADL.
13111   if (PerformADL) {
13112     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13113                                          /*ExplicitTemplateArgs*/nullptr,
13114                                          CandidateSet);
13115   }
13116 
13117   // Add builtin operator candidates.
13118   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13119 
13120   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13121 
13122   // Perform overload resolution.
13123   OverloadCandidateSet::iterator Best;
13124   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13125   case OR_Success: {
13126     // We found a built-in operator or an overloaded operator.
13127     FunctionDecl *FnDecl = Best->Function;
13128 
13129     if (FnDecl) {
13130       Expr *Base = nullptr;
13131       // We matched an overloaded operator. Build a call to that
13132       // operator.
13133 
13134       // Convert the arguments.
13135       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13136         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13137 
13138         ExprResult InputRes =
13139           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13140                                               Best->FoundDecl, Method);
13141         if (InputRes.isInvalid())
13142           return ExprError();
13143         Base = Input = InputRes.get();
13144       } else {
13145         // Convert the arguments.
13146         ExprResult InputInit
13147           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13148                                                       Context,
13149                                                       FnDecl->getParamDecl(0)),
13150                                       SourceLocation(),
13151                                       Input);
13152         if (InputInit.isInvalid())
13153           return ExprError();
13154         Input = InputInit.get();
13155       }
13156 
13157       // Build the actual expression node.
13158       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13159                                                 Base, HadMultipleCandidates,
13160                                                 OpLoc);
13161       if (FnExpr.isInvalid())
13162         return ExprError();
13163 
13164       // Determine the result type.
13165       QualType ResultTy = FnDecl->getReturnType();
13166       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13167       ResultTy = ResultTy.getNonLValueExprType(Context);
13168 
13169       Args[0] = Input;
13170       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13171           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13172           CurFPFeatureOverrides(), Best->IsADLCandidate);
13173 
13174       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13175         return ExprError();
13176 
13177       if (CheckFunctionCall(FnDecl, TheCall,
13178                             FnDecl->getType()->castAs<FunctionProtoType>()))
13179         return ExprError();
13180       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13181     } else {
13182       // We matched a built-in operator. Convert the arguments, then
13183       // break out so that we will build the appropriate built-in
13184       // operator node.
13185       ExprResult InputRes = PerformImplicitConversion(
13186           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13187           CCK_ForBuiltinOverloadedOp);
13188       if (InputRes.isInvalid())
13189         return ExprError();
13190       Input = InputRes.get();
13191       break;
13192     }
13193   }
13194 
13195   case OR_No_Viable_Function:
13196     // This is an erroneous use of an operator which can be overloaded by
13197     // a non-member function. Check for non-member operators which were
13198     // defined too late to be candidates.
13199     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13200       // FIXME: Recover by calling the found function.
13201       return ExprError();
13202 
13203     // No viable function; fall through to handling this as a
13204     // built-in operator, which will produce an error message for us.
13205     break;
13206 
13207   case OR_Ambiguous:
13208     CandidateSet.NoteCandidates(
13209         PartialDiagnosticAt(OpLoc,
13210                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13211                                 << UnaryOperator::getOpcodeStr(Opc)
13212                                 << Input->getType() << Input->getSourceRange()),
13213         *this, OCD_AmbiguousCandidates, ArgsArray,
13214         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13215     return ExprError();
13216 
13217   case OR_Deleted:
13218     CandidateSet.NoteCandidates(
13219         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13220                                        << UnaryOperator::getOpcodeStr(Opc)
13221                                        << Input->getSourceRange()),
13222         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13223         OpLoc);
13224     return ExprError();
13225   }
13226 
13227   // Either we found no viable overloaded operator or we matched a
13228   // built-in operator. In either case, fall through to trying to
13229   // build a built-in operation.
13230   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13231 }
13232 
13233 /// Perform lookup for an overloaded binary operator.
13234 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13235                                  OverloadedOperatorKind Op,
13236                                  const UnresolvedSetImpl &Fns,
13237                                  ArrayRef<Expr *> Args, bool PerformADL) {
13238   SourceLocation OpLoc = CandidateSet.getLocation();
13239 
13240   OverloadedOperatorKind ExtraOp =
13241       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13242           ? getRewrittenOverloadedOperator(Op)
13243           : OO_None;
13244 
13245   // Add the candidates from the given function set. This also adds the
13246   // rewritten candidates using these functions if necessary.
13247   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13248 
13249   // Add operator candidates that are member functions.
13250   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13251   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13252     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13253                                 OverloadCandidateParamOrder::Reversed);
13254 
13255   // In C++20, also add any rewritten member candidates.
13256   if (ExtraOp) {
13257     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13258     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13259       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13260                                   CandidateSet,
13261                                   OverloadCandidateParamOrder::Reversed);
13262   }
13263 
13264   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13265   // performed for an assignment operator (nor for operator[] nor operator->,
13266   // which don't get here).
13267   if (Op != OO_Equal && PerformADL) {
13268     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13269     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13270                                          /*ExplicitTemplateArgs*/ nullptr,
13271                                          CandidateSet);
13272     if (ExtraOp) {
13273       DeclarationName ExtraOpName =
13274           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13275       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13276                                            /*ExplicitTemplateArgs*/ nullptr,
13277                                            CandidateSet);
13278     }
13279   }
13280 
13281   // Add builtin operator candidates.
13282   //
13283   // FIXME: We don't add any rewritten candidates here. This is strictly
13284   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13285   // resulting in our selecting a rewritten builtin candidate. For example:
13286   //
13287   //   enum class E { e };
13288   //   bool operator!=(E, E) requires false;
13289   //   bool k = E::e != E::e;
13290   //
13291   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13292   // it seems unreasonable to consider rewritten builtin candidates. A core
13293   // issue has been filed proposing to removed this requirement.
13294   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13295 }
13296 
13297 /// Create a binary operation that may resolve to an overloaded
13298 /// operator.
13299 ///
13300 /// \param OpLoc The location of the operator itself (e.g., '+').
13301 ///
13302 /// \param Opc The BinaryOperatorKind that describes this operator.
13303 ///
13304 /// \param Fns The set of non-member functions that will be
13305 /// considered by overload resolution. The caller needs to build this
13306 /// set based on the context using, e.g.,
13307 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13308 /// set should not contain any member functions; those will be added
13309 /// by CreateOverloadedBinOp().
13310 ///
13311 /// \param LHS Left-hand argument.
13312 /// \param RHS Right-hand argument.
13313 /// \param PerformADL Whether to consider operator candidates found by ADL.
13314 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13315 ///        C++20 operator rewrites.
13316 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13317 ///        the function in question. Such a function is never a candidate in
13318 ///        our overload resolution. This also enables synthesizing a three-way
13319 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13320 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13321                                        BinaryOperatorKind Opc,
13322                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13323                                        Expr *RHS, bool PerformADL,
13324                                        bool AllowRewrittenCandidates,
13325                                        FunctionDecl *DefaultedFn) {
13326   Expr *Args[2] = { LHS, RHS };
13327   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13328 
13329   if (!getLangOpts().CPlusPlus20)
13330     AllowRewrittenCandidates = false;
13331 
13332   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13333 
13334   // If either side is type-dependent, create an appropriate dependent
13335   // expression.
13336   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13337     if (Fns.empty()) {
13338       // If there are no functions to store, just build a dependent
13339       // BinaryOperator or CompoundAssignment.
13340       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13341         return BinaryOperator::Create(
13342             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue,
13343             OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13344       return CompoundAssignOperator::Create(
13345           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13346           OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13347           Context.DependentTy);
13348     }
13349 
13350     // FIXME: save results of ADL from here?
13351     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13352     // TODO: provide better source location info in DNLoc component.
13353     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13354     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13355     ExprResult Fn = CreateUnresolvedLookupExpr(
13356         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13357     if (Fn.isInvalid())
13358       return ExprError();
13359     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13360                                        Context.DependentTy, VK_RValue, OpLoc,
13361                                        CurFPFeatureOverrides());
13362   }
13363 
13364   // Always do placeholder-like conversions on the RHS.
13365   if (checkPlaceholderForOverload(*this, Args[1]))
13366     return ExprError();
13367 
13368   // Do placeholder-like conversion on the LHS; note that we should
13369   // not get here with a PseudoObject LHS.
13370   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13371   if (checkPlaceholderForOverload(*this, Args[0]))
13372     return ExprError();
13373 
13374   // If this is the assignment operator, we only perform overload resolution
13375   // if the left-hand side is a class or enumeration type. This is actually
13376   // a hack. The standard requires that we do overload resolution between the
13377   // various built-in candidates, but as DR507 points out, this can lead to
13378   // problems. So we do it this way, which pretty much follows what GCC does.
13379   // Note that we go the traditional code path for compound assignment forms.
13380   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13381     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13382 
13383   // If this is the .* operator, which is not overloadable, just
13384   // create a built-in binary operator.
13385   if (Opc == BO_PtrMemD)
13386     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13387 
13388   // Build the overload set.
13389   OverloadCandidateSet CandidateSet(
13390       OpLoc, OverloadCandidateSet::CSK_Operator,
13391       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13392   if (DefaultedFn)
13393     CandidateSet.exclude(DefaultedFn);
13394   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13395 
13396   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13397 
13398   // Perform overload resolution.
13399   OverloadCandidateSet::iterator Best;
13400   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13401     case OR_Success: {
13402       // We found a built-in operator or an overloaded operator.
13403       FunctionDecl *FnDecl = Best->Function;
13404 
13405       bool IsReversed = Best->isReversed();
13406       if (IsReversed)
13407         std::swap(Args[0], Args[1]);
13408 
13409       if (FnDecl) {
13410         Expr *Base = nullptr;
13411         // We matched an overloaded operator. Build a call to that
13412         // operator.
13413 
13414         OverloadedOperatorKind ChosenOp =
13415             FnDecl->getDeclName().getCXXOverloadedOperator();
13416 
13417         // C++2a [over.match.oper]p9:
13418         //   If a rewritten operator== candidate is selected by overload
13419         //   resolution for an operator@, its return type shall be cv bool
13420         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13421             !FnDecl->getReturnType()->isBooleanType()) {
13422           bool IsExtension =
13423               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13424           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13425                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13426               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13427               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13428           Diag(FnDecl->getLocation(), diag::note_declared_at);
13429           if (!IsExtension)
13430             return ExprError();
13431         }
13432 
13433         if (AllowRewrittenCandidates && !IsReversed &&
13434             CandidateSet.getRewriteInfo().isReversible()) {
13435           // We could have reversed this operator, but didn't. Check if some
13436           // reversed form was a viable candidate, and if so, if it had a
13437           // better conversion for either parameter. If so, this call is
13438           // formally ambiguous, and allowing it is an extension.
13439           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13440           for (OverloadCandidate &Cand : CandidateSet) {
13441             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13442                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13443               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13444                 if (CompareImplicitConversionSequences(
13445                         *this, OpLoc, Cand.Conversions[ArgIdx],
13446                         Best->Conversions[ArgIdx]) ==
13447                     ImplicitConversionSequence::Better) {
13448                   AmbiguousWith.push_back(Cand.Function);
13449                   break;
13450                 }
13451               }
13452             }
13453           }
13454 
13455           if (!AmbiguousWith.empty()) {
13456             bool AmbiguousWithSelf =
13457                 AmbiguousWith.size() == 1 &&
13458                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13459             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13460                 << BinaryOperator::getOpcodeStr(Opc)
13461                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13462                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13463             if (AmbiguousWithSelf) {
13464               Diag(FnDecl->getLocation(),
13465                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13466             } else {
13467               Diag(FnDecl->getLocation(),
13468                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13469               for (auto *F : AmbiguousWith)
13470                 Diag(F->getLocation(),
13471                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13472             }
13473           }
13474         }
13475 
13476         // Convert the arguments.
13477         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13478           // Best->Access is only meaningful for class members.
13479           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13480 
13481           ExprResult Arg1 =
13482             PerformCopyInitialization(
13483               InitializedEntity::InitializeParameter(Context,
13484                                                      FnDecl->getParamDecl(0)),
13485               SourceLocation(), Args[1]);
13486           if (Arg1.isInvalid())
13487             return ExprError();
13488 
13489           ExprResult Arg0 =
13490             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13491                                                 Best->FoundDecl, Method);
13492           if (Arg0.isInvalid())
13493             return ExprError();
13494           Base = Args[0] = Arg0.getAs<Expr>();
13495           Args[1] = RHS = Arg1.getAs<Expr>();
13496         } else {
13497           // Convert the arguments.
13498           ExprResult Arg0 = PerformCopyInitialization(
13499             InitializedEntity::InitializeParameter(Context,
13500                                                    FnDecl->getParamDecl(0)),
13501             SourceLocation(), Args[0]);
13502           if (Arg0.isInvalid())
13503             return ExprError();
13504 
13505           ExprResult Arg1 =
13506             PerformCopyInitialization(
13507               InitializedEntity::InitializeParameter(Context,
13508                                                      FnDecl->getParamDecl(1)),
13509               SourceLocation(), Args[1]);
13510           if (Arg1.isInvalid())
13511             return ExprError();
13512           Args[0] = LHS = Arg0.getAs<Expr>();
13513           Args[1] = RHS = Arg1.getAs<Expr>();
13514         }
13515 
13516         // Build the actual expression node.
13517         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13518                                                   Best->FoundDecl, Base,
13519                                                   HadMultipleCandidates, OpLoc);
13520         if (FnExpr.isInvalid())
13521           return ExprError();
13522 
13523         // Determine the result type.
13524         QualType ResultTy = FnDecl->getReturnType();
13525         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13526         ResultTy = ResultTy.getNonLValueExprType(Context);
13527 
13528         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13529             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13530             CurFPFeatureOverrides(), Best->IsADLCandidate);
13531 
13532         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13533                                 FnDecl))
13534           return ExprError();
13535 
13536         ArrayRef<const Expr *> ArgsArray(Args, 2);
13537         const Expr *ImplicitThis = nullptr;
13538         // Cut off the implicit 'this'.
13539         if (isa<CXXMethodDecl>(FnDecl)) {
13540           ImplicitThis = ArgsArray[0];
13541           ArgsArray = ArgsArray.slice(1);
13542         }
13543 
13544         // Check for a self move.
13545         if (Op == OO_Equal)
13546           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13547 
13548         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13549                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13550                   VariadicDoesNotApply);
13551 
13552         ExprResult R = MaybeBindToTemporary(TheCall);
13553         if (R.isInvalid())
13554           return ExprError();
13555 
13556         R = CheckForImmediateInvocation(R, FnDecl);
13557         if (R.isInvalid())
13558           return ExprError();
13559 
13560         // For a rewritten candidate, we've already reversed the arguments
13561         // if needed. Perform the rest of the rewrite now.
13562         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13563             (Op == OO_Spaceship && IsReversed)) {
13564           if (Op == OO_ExclaimEqual) {
13565             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13566             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13567           } else {
13568             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13569             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13570             Expr *ZeroLiteral =
13571                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13572 
13573             Sema::CodeSynthesisContext Ctx;
13574             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13575             Ctx.Entity = FnDecl;
13576             pushCodeSynthesisContext(Ctx);
13577 
13578             R = CreateOverloadedBinOp(
13579                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13580                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13581                 /*AllowRewrittenCandidates=*/false);
13582 
13583             popCodeSynthesisContext();
13584           }
13585           if (R.isInvalid())
13586             return ExprError();
13587         } else {
13588           assert(ChosenOp == Op && "unexpected operator name");
13589         }
13590 
13591         // Make a note in the AST if we did any rewriting.
13592         if (Best->RewriteKind != CRK_None)
13593           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13594 
13595         return R;
13596       } else {
13597         // We matched a built-in operator. Convert the arguments, then
13598         // break out so that we will build the appropriate built-in
13599         // operator node.
13600         ExprResult ArgsRes0 = PerformImplicitConversion(
13601             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13602             AA_Passing, CCK_ForBuiltinOverloadedOp);
13603         if (ArgsRes0.isInvalid())
13604           return ExprError();
13605         Args[0] = ArgsRes0.get();
13606 
13607         ExprResult ArgsRes1 = PerformImplicitConversion(
13608             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13609             AA_Passing, CCK_ForBuiltinOverloadedOp);
13610         if (ArgsRes1.isInvalid())
13611           return ExprError();
13612         Args[1] = ArgsRes1.get();
13613         break;
13614       }
13615     }
13616 
13617     case OR_No_Viable_Function: {
13618       // C++ [over.match.oper]p9:
13619       //   If the operator is the operator , [...] and there are no
13620       //   viable functions, then the operator is assumed to be the
13621       //   built-in operator and interpreted according to clause 5.
13622       if (Opc == BO_Comma)
13623         break;
13624 
13625       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13626       // compare result using '==' and '<'.
13627       if (DefaultedFn && Opc == BO_Cmp) {
13628         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13629                                                           Args[1], DefaultedFn);
13630         if (E.isInvalid() || E.isUsable())
13631           return E;
13632       }
13633 
13634       // For class as left operand for assignment or compound assignment
13635       // operator do not fall through to handling in built-in, but report that
13636       // no overloaded assignment operator found
13637       ExprResult Result = ExprError();
13638       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13639       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13640                                                    Args, OpLoc);
13641       if (Args[0]->getType()->isRecordType() &&
13642           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13643         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13644              << BinaryOperator::getOpcodeStr(Opc)
13645              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13646         if (Args[0]->getType()->isIncompleteType()) {
13647           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13648             << Args[0]->getType()
13649             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13650         }
13651       } else {
13652         // This is an erroneous use of an operator which can be overloaded by
13653         // a non-member function. Check for non-member operators which were
13654         // defined too late to be candidates.
13655         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13656           // FIXME: Recover by calling the found function.
13657           return ExprError();
13658 
13659         // No viable function; try to create a built-in operation, which will
13660         // produce an error. Then, show the non-viable candidates.
13661         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13662       }
13663       assert(Result.isInvalid() &&
13664              "C++ binary operator overloading is missing candidates!");
13665       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13666       return Result;
13667     }
13668 
13669     case OR_Ambiguous:
13670       CandidateSet.NoteCandidates(
13671           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13672                                          << BinaryOperator::getOpcodeStr(Opc)
13673                                          << Args[0]->getType()
13674                                          << Args[1]->getType()
13675                                          << Args[0]->getSourceRange()
13676                                          << Args[1]->getSourceRange()),
13677           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13678           OpLoc);
13679       return ExprError();
13680 
13681     case OR_Deleted:
13682       if (isImplicitlyDeleted(Best->Function)) {
13683         FunctionDecl *DeletedFD = Best->Function;
13684         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13685         if (DFK.isSpecialMember()) {
13686           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13687             << Args[0]->getType() << DFK.asSpecialMember();
13688         } else {
13689           assert(DFK.isComparison());
13690           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13691             << Args[0]->getType() << DeletedFD;
13692         }
13693 
13694         // The user probably meant to call this special member. Just
13695         // explain why it's deleted.
13696         NoteDeletedFunction(DeletedFD);
13697         return ExprError();
13698       }
13699       CandidateSet.NoteCandidates(
13700           PartialDiagnosticAt(
13701               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13702                          << getOperatorSpelling(Best->Function->getDeclName()
13703                                                     .getCXXOverloadedOperator())
13704                          << Args[0]->getSourceRange()
13705                          << Args[1]->getSourceRange()),
13706           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13707           OpLoc);
13708       return ExprError();
13709   }
13710 
13711   // We matched a built-in operator; build it.
13712   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13713 }
13714 
13715 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13716     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13717     FunctionDecl *DefaultedFn) {
13718   const ComparisonCategoryInfo *Info =
13719       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13720   // If we're not producing a known comparison category type, we can't
13721   // synthesize a three-way comparison. Let the caller diagnose this.
13722   if (!Info)
13723     return ExprResult((Expr*)nullptr);
13724 
13725   // If we ever want to perform this synthesis more generally, we will need to
13726   // apply the temporary materialization conversion to the operands.
13727   assert(LHS->isGLValue() && RHS->isGLValue() &&
13728          "cannot use prvalue expressions more than once");
13729   Expr *OrigLHS = LHS;
13730   Expr *OrigRHS = RHS;
13731 
13732   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13733   // each of them multiple times below.
13734   LHS = new (Context)
13735       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13736                       LHS->getObjectKind(), LHS);
13737   RHS = new (Context)
13738       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13739                       RHS->getObjectKind(), RHS);
13740 
13741   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13742                                         DefaultedFn);
13743   if (Eq.isInvalid())
13744     return ExprError();
13745 
13746   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13747                                           true, DefaultedFn);
13748   if (Less.isInvalid())
13749     return ExprError();
13750 
13751   ExprResult Greater;
13752   if (Info->isPartial()) {
13753     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13754                                     DefaultedFn);
13755     if (Greater.isInvalid())
13756       return ExprError();
13757   }
13758 
13759   // Form the list of comparisons we're going to perform.
13760   struct Comparison {
13761     ExprResult Cmp;
13762     ComparisonCategoryResult Result;
13763   } Comparisons[4] =
13764   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13765                           : ComparisonCategoryResult::Equivalent},
13766     {Less, ComparisonCategoryResult::Less},
13767     {Greater, ComparisonCategoryResult::Greater},
13768     {ExprResult(), ComparisonCategoryResult::Unordered},
13769   };
13770 
13771   int I = Info->isPartial() ? 3 : 2;
13772 
13773   // Combine the comparisons with suitable conditional expressions.
13774   ExprResult Result;
13775   for (; I >= 0; --I) {
13776     // Build a reference to the comparison category constant.
13777     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13778     // FIXME: Missing a constant for a comparison category. Diagnose this?
13779     if (!VI)
13780       return ExprResult((Expr*)nullptr);
13781     ExprResult ThisResult =
13782         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13783     if (ThisResult.isInvalid())
13784       return ExprError();
13785 
13786     // Build a conditional unless this is the final case.
13787     if (Result.get()) {
13788       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13789                                   ThisResult.get(), Result.get());
13790       if (Result.isInvalid())
13791         return ExprError();
13792     } else {
13793       Result = ThisResult;
13794     }
13795   }
13796 
13797   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13798   // bind the OpaqueValueExprs before they're (repeatedly) used.
13799   Expr *SyntacticForm = BinaryOperator::Create(
13800       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13801       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13802       CurFPFeatureOverrides());
13803   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13804   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13805 }
13806 
13807 ExprResult
13808 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13809                                          SourceLocation RLoc,
13810                                          Expr *Base, Expr *Idx) {
13811   Expr *Args[2] = { Base, Idx };
13812   DeclarationName OpName =
13813       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13814 
13815   // If either side is type-dependent, create an appropriate dependent
13816   // expression.
13817   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13818 
13819     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13820     // CHECKME: no 'operator' keyword?
13821     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13822     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13823     ExprResult Fn = CreateUnresolvedLookupExpr(
13824         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
13825     if (Fn.isInvalid())
13826       return ExprError();
13827     // Can't add any actual overloads yet
13828 
13829     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
13830                                        Context.DependentTy, VK_RValue, RLoc,
13831                                        CurFPFeatureOverrides());
13832   }
13833 
13834   // Handle placeholders on both operands.
13835   if (checkPlaceholderForOverload(*this, Args[0]))
13836     return ExprError();
13837   if (checkPlaceholderForOverload(*this, Args[1]))
13838     return ExprError();
13839 
13840   // Build an empty overload set.
13841   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13842 
13843   // Subscript can only be overloaded as a member function.
13844 
13845   // Add operator candidates that are member functions.
13846   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13847 
13848   // Add builtin operator candidates.
13849   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13850 
13851   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13852 
13853   // Perform overload resolution.
13854   OverloadCandidateSet::iterator Best;
13855   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13856     case OR_Success: {
13857       // We found a built-in operator or an overloaded operator.
13858       FunctionDecl *FnDecl = Best->Function;
13859 
13860       if (FnDecl) {
13861         // We matched an overloaded operator. Build a call to that
13862         // operator.
13863 
13864         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13865 
13866         // Convert the arguments.
13867         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13868         ExprResult Arg0 =
13869           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13870                                               Best->FoundDecl, Method);
13871         if (Arg0.isInvalid())
13872           return ExprError();
13873         Args[0] = Arg0.get();
13874 
13875         // Convert the arguments.
13876         ExprResult InputInit
13877           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13878                                                       Context,
13879                                                       FnDecl->getParamDecl(0)),
13880                                       SourceLocation(),
13881                                       Args[1]);
13882         if (InputInit.isInvalid())
13883           return ExprError();
13884 
13885         Args[1] = InputInit.getAs<Expr>();
13886 
13887         // Build the actual expression node.
13888         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13889         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13890         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13891                                                   Best->FoundDecl,
13892                                                   Base,
13893                                                   HadMultipleCandidates,
13894                                                   OpLocInfo.getLoc(),
13895                                                   OpLocInfo.getInfo());
13896         if (FnExpr.isInvalid())
13897           return ExprError();
13898 
13899         // Determine the result type
13900         QualType ResultTy = FnDecl->getReturnType();
13901         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13902         ResultTy = ResultTy.getNonLValueExprType(Context);
13903 
13904         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13905             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13906             CurFPFeatureOverrides());
13907         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13908           return ExprError();
13909 
13910         if (CheckFunctionCall(Method, TheCall,
13911                               Method->getType()->castAs<FunctionProtoType>()))
13912           return ExprError();
13913 
13914         return MaybeBindToTemporary(TheCall);
13915       } else {
13916         // We matched a built-in operator. Convert the arguments, then
13917         // break out so that we will build the appropriate built-in
13918         // operator node.
13919         ExprResult ArgsRes0 = PerformImplicitConversion(
13920             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13921             AA_Passing, CCK_ForBuiltinOverloadedOp);
13922         if (ArgsRes0.isInvalid())
13923           return ExprError();
13924         Args[0] = ArgsRes0.get();
13925 
13926         ExprResult ArgsRes1 = PerformImplicitConversion(
13927             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13928             AA_Passing, CCK_ForBuiltinOverloadedOp);
13929         if (ArgsRes1.isInvalid())
13930           return ExprError();
13931         Args[1] = ArgsRes1.get();
13932 
13933         break;
13934       }
13935     }
13936 
13937     case OR_No_Viable_Function: {
13938       PartialDiagnostic PD = CandidateSet.empty()
13939           ? (PDiag(diag::err_ovl_no_oper)
13940              << Args[0]->getType() << /*subscript*/ 0
13941              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13942           : (PDiag(diag::err_ovl_no_viable_subscript)
13943              << Args[0]->getType() << Args[0]->getSourceRange()
13944              << Args[1]->getSourceRange());
13945       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13946                                   OCD_AllCandidates, Args, "[]", LLoc);
13947       return ExprError();
13948     }
13949 
13950     case OR_Ambiguous:
13951       CandidateSet.NoteCandidates(
13952           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13953                                         << "[]" << Args[0]->getType()
13954                                         << Args[1]->getType()
13955                                         << Args[0]->getSourceRange()
13956                                         << Args[1]->getSourceRange()),
13957           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13958       return ExprError();
13959 
13960     case OR_Deleted:
13961       CandidateSet.NoteCandidates(
13962           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13963                                         << "[]" << Args[0]->getSourceRange()
13964                                         << Args[1]->getSourceRange()),
13965           *this, OCD_AllCandidates, Args, "[]", LLoc);
13966       return ExprError();
13967     }
13968 
13969   // We matched a built-in operator; build it.
13970   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13971 }
13972 
13973 /// BuildCallToMemberFunction - Build a call to a member
13974 /// function. MemExpr is the expression that refers to the member
13975 /// function (and includes the object parameter), Args/NumArgs are the
13976 /// arguments to the function call (not including the object
13977 /// parameter). The caller needs to validate that the member
13978 /// expression refers to a non-static member function or an overloaded
13979 /// member function.
13980 ExprResult
13981 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13982                                 SourceLocation LParenLoc,
13983                                 MultiExprArg Args,
13984                                 SourceLocation RParenLoc) {
13985   assert(MemExprE->getType() == Context.BoundMemberTy ||
13986          MemExprE->getType() == Context.OverloadTy);
13987 
13988   // Dig out the member expression. This holds both the object
13989   // argument and the member function we're referring to.
13990   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13991 
13992   // Determine whether this is a call to a pointer-to-member function.
13993   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13994     assert(op->getType() == Context.BoundMemberTy);
13995     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13996 
13997     QualType fnType =
13998       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13999 
14000     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14001     QualType resultType = proto->getCallResultType(Context);
14002     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14003 
14004     // Check that the object type isn't more qualified than the
14005     // member function we're calling.
14006     Qualifiers funcQuals = proto->getMethodQuals();
14007 
14008     QualType objectType = op->getLHS()->getType();
14009     if (op->getOpcode() == BO_PtrMemI)
14010       objectType = objectType->castAs<PointerType>()->getPointeeType();
14011     Qualifiers objectQuals = objectType.getQualifiers();
14012 
14013     Qualifiers difference = objectQuals - funcQuals;
14014     difference.removeObjCGCAttr();
14015     difference.removeAddressSpace();
14016     if (difference) {
14017       std::string qualsString = difference.getAsString();
14018       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14019         << fnType.getUnqualifiedType()
14020         << qualsString
14021         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14022     }
14023 
14024     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14025         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14026         CurFPFeatureOverrides(), proto->getNumParams());
14027 
14028     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14029                             call, nullptr))
14030       return ExprError();
14031 
14032     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14033       return ExprError();
14034 
14035     if (CheckOtherCall(call, proto))
14036       return ExprError();
14037 
14038     return MaybeBindToTemporary(call);
14039   }
14040 
14041   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14042     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14043                             RParenLoc, CurFPFeatureOverrides());
14044 
14045   UnbridgedCastsSet UnbridgedCasts;
14046   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14047     return ExprError();
14048 
14049   MemberExpr *MemExpr;
14050   CXXMethodDecl *Method = nullptr;
14051   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14052   NestedNameSpecifier *Qualifier = nullptr;
14053   if (isa<MemberExpr>(NakedMemExpr)) {
14054     MemExpr = cast<MemberExpr>(NakedMemExpr);
14055     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14056     FoundDecl = MemExpr->getFoundDecl();
14057     Qualifier = MemExpr->getQualifier();
14058     UnbridgedCasts.restore();
14059   } else {
14060     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14061     Qualifier = UnresExpr->getQualifier();
14062 
14063     QualType ObjectType = UnresExpr->getBaseType();
14064     Expr::Classification ObjectClassification
14065       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14066                             : UnresExpr->getBase()->Classify(Context);
14067 
14068     // Add overload candidates
14069     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14070                                       OverloadCandidateSet::CSK_Normal);
14071 
14072     // FIXME: avoid copy.
14073     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14074     if (UnresExpr->hasExplicitTemplateArgs()) {
14075       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14076       TemplateArgs = &TemplateArgsBuffer;
14077     }
14078 
14079     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14080            E = UnresExpr->decls_end(); I != E; ++I) {
14081 
14082       NamedDecl *Func = *I;
14083       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14084       if (isa<UsingShadowDecl>(Func))
14085         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14086 
14087 
14088       // Microsoft supports direct constructor calls.
14089       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14090         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14091                              CandidateSet,
14092                              /*SuppressUserConversions*/ false);
14093       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14094         // If explicit template arguments were provided, we can't call a
14095         // non-template member function.
14096         if (TemplateArgs)
14097           continue;
14098 
14099         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14100                            ObjectClassification, Args, CandidateSet,
14101                            /*SuppressUserConversions=*/false);
14102       } else {
14103         AddMethodTemplateCandidate(
14104             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14105             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14106             /*SuppressUserConversions=*/false);
14107       }
14108     }
14109 
14110     DeclarationName DeclName = UnresExpr->getMemberName();
14111 
14112     UnbridgedCasts.restore();
14113 
14114     OverloadCandidateSet::iterator Best;
14115     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14116                                             Best)) {
14117     case OR_Success:
14118       Method = cast<CXXMethodDecl>(Best->Function);
14119       FoundDecl = Best->FoundDecl;
14120       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14121       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14122         return ExprError();
14123       // If FoundDecl is different from Method (such as if one is a template
14124       // and the other a specialization), make sure DiagnoseUseOfDecl is
14125       // called on both.
14126       // FIXME: This would be more comprehensively addressed by modifying
14127       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14128       // being used.
14129       if (Method != FoundDecl.getDecl() &&
14130                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14131         return ExprError();
14132       break;
14133 
14134     case OR_No_Viable_Function:
14135       CandidateSet.NoteCandidates(
14136           PartialDiagnosticAt(
14137               UnresExpr->getMemberLoc(),
14138               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14139                   << DeclName << MemExprE->getSourceRange()),
14140           *this, OCD_AllCandidates, Args);
14141       // FIXME: Leaking incoming expressions!
14142       return ExprError();
14143 
14144     case OR_Ambiguous:
14145       CandidateSet.NoteCandidates(
14146           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14147                               PDiag(diag::err_ovl_ambiguous_member_call)
14148                                   << DeclName << MemExprE->getSourceRange()),
14149           *this, OCD_AmbiguousCandidates, Args);
14150       // FIXME: Leaking incoming expressions!
14151       return ExprError();
14152 
14153     case OR_Deleted:
14154       CandidateSet.NoteCandidates(
14155           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14156                               PDiag(diag::err_ovl_deleted_member_call)
14157                                   << DeclName << MemExprE->getSourceRange()),
14158           *this, OCD_AllCandidates, Args);
14159       // FIXME: Leaking incoming expressions!
14160       return ExprError();
14161     }
14162 
14163     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14164 
14165     // If overload resolution picked a static member, build a
14166     // non-member call based on that function.
14167     if (Method->isStatic()) {
14168       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14169                                    RParenLoc);
14170     }
14171 
14172     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14173   }
14174 
14175   QualType ResultType = Method->getReturnType();
14176   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14177   ResultType = ResultType.getNonLValueExprType(Context);
14178 
14179   assert(Method && "Member call to something that isn't a method?");
14180   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14181   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14182       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14183       CurFPFeatureOverrides(), Proto->getNumParams());
14184 
14185   // Check for a valid return type.
14186   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14187                           TheCall, Method))
14188     return ExprError();
14189 
14190   // Convert the object argument (for a non-static member function call).
14191   // We only need to do this if there was actually an overload; otherwise
14192   // it was done at lookup.
14193   if (!Method->isStatic()) {
14194     ExprResult ObjectArg =
14195       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14196                                           FoundDecl, Method);
14197     if (ObjectArg.isInvalid())
14198       return ExprError();
14199     MemExpr->setBase(ObjectArg.get());
14200   }
14201 
14202   // Convert the rest of the arguments
14203   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14204                               RParenLoc))
14205     return ExprError();
14206 
14207   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14208 
14209   if (CheckFunctionCall(Method, TheCall, Proto))
14210     return ExprError();
14211 
14212   // In the case the method to call was not selected by the overloading
14213   // resolution process, we still need to handle the enable_if attribute. Do
14214   // that here, so it will not hide previous -- and more relevant -- errors.
14215   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14216     if (const EnableIfAttr *Attr =
14217             CheckEnableIf(Method, LParenLoc, Args, true)) {
14218       Diag(MemE->getMemberLoc(),
14219            diag::err_ovl_no_viable_member_function_in_call)
14220           << Method << Method->getSourceRange();
14221       Diag(Method->getLocation(),
14222            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14223           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14224       return ExprError();
14225     }
14226   }
14227 
14228   if ((isa<CXXConstructorDecl>(CurContext) ||
14229        isa<CXXDestructorDecl>(CurContext)) &&
14230       TheCall->getMethodDecl()->isPure()) {
14231     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14232 
14233     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14234         MemExpr->performsVirtualDispatch(getLangOpts())) {
14235       Diag(MemExpr->getBeginLoc(),
14236            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14237           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14238           << MD->getParent();
14239 
14240       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14241       if (getLangOpts().AppleKext)
14242         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14243             << MD->getParent() << MD->getDeclName();
14244     }
14245   }
14246 
14247   if (CXXDestructorDecl *DD =
14248           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14249     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14250     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14251     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14252                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14253                          MemExpr->getMemberLoc());
14254   }
14255 
14256   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14257                                      TheCall->getMethodDecl());
14258 }
14259 
14260 /// BuildCallToObjectOfClassType - Build a call to an object of class
14261 /// type (C++ [over.call.object]), which can end up invoking an
14262 /// overloaded function call operator (@c operator()) or performing a
14263 /// user-defined conversion on the object argument.
14264 ExprResult
14265 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14266                                    SourceLocation LParenLoc,
14267                                    MultiExprArg Args,
14268                                    SourceLocation RParenLoc) {
14269   if (checkPlaceholderForOverload(*this, Obj))
14270     return ExprError();
14271   ExprResult Object = Obj;
14272 
14273   UnbridgedCastsSet UnbridgedCasts;
14274   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14275     return ExprError();
14276 
14277   assert(Object.get()->getType()->isRecordType() &&
14278          "Requires object type argument");
14279 
14280   // C++ [over.call.object]p1:
14281   //  If the primary-expression E in the function call syntax
14282   //  evaluates to a class object of type "cv T", then the set of
14283   //  candidate functions includes at least the function call
14284   //  operators of T. The function call operators of T are obtained by
14285   //  ordinary lookup of the name operator() in the context of
14286   //  (E).operator().
14287   OverloadCandidateSet CandidateSet(LParenLoc,
14288                                     OverloadCandidateSet::CSK_Operator);
14289   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14290 
14291   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14292                           diag::err_incomplete_object_call, Object.get()))
14293     return true;
14294 
14295   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14296   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14297   LookupQualifiedName(R, Record->getDecl());
14298   R.suppressDiagnostics();
14299 
14300   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14301        Oper != OperEnd; ++Oper) {
14302     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14303                        Object.get()->Classify(Context), Args, CandidateSet,
14304                        /*SuppressUserConversion=*/false);
14305   }
14306 
14307   // C++ [over.call.object]p2:
14308   //   In addition, for each (non-explicit in C++0x) conversion function
14309   //   declared in T of the form
14310   //
14311   //        operator conversion-type-id () cv-qualifier;
14312   //
14313   //   where cv-qualifier is the same cv-qualification as, or a
14314   //   greater cv-qualification than, cv, and where conversion-type-id
14315   //   denotes the type "pointer to function of (P1,...,Pn) returning
14316   //   R", or the type "reference to pointer to function of
14317   //   (P1,...,Pn) returning R", or the type "reference to function
14318   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14319   //   is also considered as a candidate function. Similarly,
14320   //   surrogate call functions are added to the set of candidate
14321   //   functions for each conversion function declared in an
14322   //   accessible base class provided the function is not hidden
14323   //   within T by another intervening declaration.
14324   const auto &Conversions =
14325       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14326   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14327     NamedDecl *D = *I;
14328     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14329     if (isa<UsingShadowDecl>(D))
14330       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14331 
14332     // Skip over templated conversion functions; they aren't
14333     // surrogates.
14334     if (isa<FunctionTemplateDecl>(D))
14335       continue;
14336 
14337     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14338     if (!Conv->isExplicit()) {
14339       // Strip the reference type (if any) and then the pointer type (if
14340       // any) to get down to what might be a function type.
14341       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14342       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14343         ConvType = ConvPtrType->getPointeeType();
14344 
14345       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14346       {
14347         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14348                               Object.get(), Args, CandidateSet);
14349       }
14350     }
14351   }
14352 
14353   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14354 
14355   // Perform overload resolution.
14356   OverloadCandidateSet::iterator Best;
14357   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14358                                           Best)) {
14359   case OR_Success:
14360     // Overload resolution succeeded; we'll build the appropriate call
14361     // below.
14362     break;
14363 
14364   case OR_No_Viable_Function: {
14365     PartialDiagnostic PD =
14366         CandidateSet.empty()
14367             ? (PDiag(diag::err_ovl_no_oper)
14368                << Object.get()->getType() << /*call*/ 1
14369                << Object.get()->getSourceRange())
14370             : (PDiag(diag::err_ovl_no_viable_object_call)
14371                << Object.get()->getType() << Object.get()->getSourceRange());
14372     CandidateSet.NoteCandidates(
14373         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14374         OCD_AllCandidates, Args);
14375     break;
14376   }
14377   case OR_Ambiguous:
14378     CandidateSet.NoteCandidates(
14379         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14380                             PDiag(diag::err_ovl_ambiguous_object_call)
14381                                 << Object.get()->getType()
14382                                 << Object.get()->getSourceRange()),
14383         *this, OCD_AmbiguousCandidates, Args);
14384     break;
14385 
14386   case OR_Deleted:
14387     CandidateSet.NoteCandidates(
14388         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14389                             PDiag(diag::err_ovl_deleted_object_call)
14390                                 << Object.get()->getType()
14391                                 << Object.get()->getSourceRange()),
14392         *this, OCD_AllCandidates, Args);
14393     break;
14394   }
14395 
14396   if (Best == CandidateSet.end())
14397     return true;
14398 
14399   UnbridgedCasts.restore();
14400 
14401   if (Best->Function == nullptr) {
14402     // Since there is no function declaration, this is one of the
14403     // surrogate candidates. Dig out the conversion function.
14404     CXXConversionDecl *Conv
14405       = cast<CXXConversionDecl>(
14406                          Best->Conversions[0].UserDefined.ConversionFunction);
14407 
14408     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14409                               Best->FoundDecl);
14410     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14411       return ExprError();
14412     assert(Conv == Best->FoundDecl.getDecl() &&
14413              "Found Decl & conversion-to-functionptr should be same, right?!");
14414     // We selected one of the surrogate functions that converts the
14415     // object parameter to a function pointer. Perform the conversion
14416     // on the object argument, then let BuildCallExpr finish the job.
14417 
14418     // Create an implicit member expr to refer to the conversion operator.
14419     // and then call it.
14420     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14421                                              Conv, HadMultipleCandidates);
14422     if (Call.isInvalid())
14423       return ExprError();
14424     // Record usage of conversion in an implicit cast.
14425     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14426                                     CK_UserDefinedConversion, Call.get(),
14427                                     nullptr, VK_RValue);
14428 
14429     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14430   }
14431 
14432   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14433 
14434   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14435   // that calls this method, using Object for the implicit object
14436   // parameter and passing along the remaining arguments.
14437   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14438 
14439   // An error diagnostic has already been printed when parsing the declaration.
14440   if (Method->isInvalidDecl())
14441     return ExprError();
14442 
14443   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14444   unsigned NumParams = Proto->getNumParams();
14445 
14446   DeclarationNameInfo OpLocInfo(
14447                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14448   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14449   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14450                                            Obj, HadMultipleCandidates,
14451                                            OpLocInfo.getLoc(),
14452                                            OpLocInfo.getInfo());
14453   if (NewFn.isInvalid())
14454     return true;
14455 
14456   // The number of argument slots to allocate in the call. If we have default
14457   // arguments we need to allocate space for them as well. We additionally
14458   // need one more slot for the object parameter.
14459   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14460 
14461   // Build the full argument list for the method call (the implicit object
14462   // parameter is placed at the beginning of the list).
14463   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14464 
14465   bool IsError = false;
14466 
14467   // Initialize the implicit object parameter.
14468   ExprResult ObjRes =
14469     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14470                                         Best->FoundDecl, Method);
14471   if (ObjRes.isInvalid())
14472     IsError = true;
14473   else
14474     Object = ObjRes;
14475   MethodArgs[0] = Object.get();
14476 
14477   // Check the argument types.
14478   for (unsigned i = 0; i != NumParams; i++) {
14479     Expr *Arg;
14480     if (i < Args.size()) {
14481       Arg = Args[i];
14482 
14483       // Pass the argument.
14484 
14485       ExprResult InputInit
14486         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14487                                                     Context,
14488                                                     Method->getParamDecl(i)),
14489                                     SourceLocation(), Arg);
14490 
14491       IsError |= InputInit.isInvalid();
14492       Arg = InputInit.getAs<Expr>();
14493     } else {
14494       ExprResult DefArg
14495         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14496       if (DefArg.isInvalid()) {
14497         IsError = true;
14498         break;
14499       }
14500 
14501       Arg = DefArg.getAs<Expr>();
14502     }
14503 
14504     MethodArgs[i + 1] = Arg;
14505   }
14506 
14507   // If this is a variadic call, handle args passed through "...".
14508   if (Proto->isVariadic()) {
14509     // Promote the arguments (C99 6.5.2.2p7).
14510     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14511       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14512                                                         nullptr);
14513       IsError |= Arg.isInvalid();
14514       MethodArgs[i + 1] = Arg.get();
14515     }
14516   }
14517 
14518   if (IsError)
14519     return true;
14520 
14521   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14522 
14523   // Once we've built TheCall, all of the expressions are properly owned.
14524   QualType ResultTy = Method->getReturnType();
14525   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14526   ResultTy = ResultTy.getNonLValueExprType(Context);
14527 
14528   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14529       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14530       CurFPFeatureOverrides());
14531 
14532   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14533     return true;
14534 
14535   if (CheckFunctionCall(Method, TheCall, Proto))
14536     return true;
14537 
14538   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14539 }
14540 
14541 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14542 ///  (if one exists), where @c Base is an expression of class type and
14543 /// @c Member is the name of the member we're trying to find.
14544 ExprResult
14545 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14546                                bool *NoArrowOperatorFound) {
14547   assert(Base->getType()->isRecordType() &&
14548          "left-hand side must have class type");
14549 
14550   if (checkPlaceholderForOverload(*this, Base))
14551     return ExprError();
14552 
14553   SourceLocation Loc = Base->getExprLoc();
14554 
14555   // C++ [over.ref]p1:
14556   //
14557   //   [...] An expression x->m is interpreted as (x.operator->())->m
14558   //   for a class object x of type T if T::operator->() exists and if
14559   //   the operator is selected as the best match function by the
14560   //   overload resolution mechanism (13.3).
14561   DeclarationName OpName =
14562     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14563   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14564 
14565   if (RequireCompleteType(Loc, Base->getType(),
14566                           diag::err_typecheck_incomplete_tag, Base))
14567     return ExprError();
14568 
14569   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14570   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14571   R.suppressDiagnostics();
14572 
14573   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14574        Oper != OperEnd; ++Oper) {
14575     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14576                        None, CandidateSet, /*SuppressUserConversion=*/false);
14577   }
14578 
14579   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14580 
14581   // Perform overload resolution.
14582   OverloadCandidateSet::iterator Best;
14583   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14584   case OR_Success:
14585     // Overload resolution succeeded; we'll build the call below.
14586     break;
14587 
14588   case OR_No_Viable_Function: {
14589     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14590     if (CandidateSet.empty()) {
14591       QualType BaseType = Base->getType();
14592       if (NoArrowOperatorFound) {
14593         // Report this specific error to the caller instead of emitting a
14594         // diagnostic, as requested.
14595         *NoArrowOperatorFound = true;
14596         return ExprError();
14597       }
14598       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14599         << BaseType << Base->getSourceRange();
14600       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14601         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14602           << FixItHint::CreateReplacement(OpLoc, ".");
14603       }
14604     } else
14605       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14606         << "operator->" << Base->getSourceRange();
14607     CandidateSet.NoteCandidates(*this, Base, Cands);
14608     return ExprError();
14609   }
14610   case OR_Ambiguous:
14611     CandidateSet.NoteCandidates(
14612         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14613                                        << "->" << Base->getType()
14614                                        << Base->getSourceRange()),
14615         *this, OCD_AmbiguousCandidates, Base);
14616     return ExprError();
14617 
14618   case OR_Deleted:
14619     CandidateSet.NoteCandidates(
14620         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14621                                        << "->" << Base->getSourceRange()),
14622         *this, OCD_AllCandidates, Base);
14623     return ExprError();
14624   }
14625 
14626   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14627 
14628   // Convert the object parameter.
14629   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14630   ExprResult BaseResult =
14631     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14632                                         Best->FoundDecl, Method);
14633   if (BaseResult.isInvalid())
14634     return ExprError();
14635   Base = BaseResult.get();
14636 
14637   // Build the operator call.
14638   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14639                                             Base, HadMultipleCandidates, OpLoc);
14640   if (FnExpr.isInvalid())
14641     return ExprError();
14642 
14643   QualType ResultTy = Method->getReturnType();
14644   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14645   ResultTy = ResultTy.getNonLValueExprType(Context);
14646   CXXOperatorCallExpr *TheCall =
14647       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14648                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14649 
14650   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14651     return ExprError();
14652 
14653   if (CheckFunctionCall(Method, TheCall,
14654                         Method->getType()->castAs<FunctionProtoType>()))
14655     return ExprError();
14656 
14657   return MaybeBindToTemporary(TheCall);
14658 }
14659 
14660 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14661 /// a literal operator described by the provided lookup results.
14662 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14663                                           DeclarationNameInfo &SuffixInfo,
14664                                           ArrayRef<Expr*> Args,
14665                                           SourceLocation LitEndLoc,
14666                                        TemplateArgumentListInfo *TemplateArgs) {
14667   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14668 
14669   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14670                                     OverloadCandidateSet::CSK_Normal);
14671   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14672                                  TemplateArgs);
14673 
14674   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14675 
14676   // Perform overload resolution. This will usually be trivial, but might need
14677   // to perform substitutions for a literal operator template.
14678   OverloadCandidateSet::iterator Best;
14679   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14680   case OR_Success:
14681   case OR_Deleted:
14682     break;
14683 
14684   case OR_No_Viable_Function:
14685     CandidateSet.NoteCandidates(
14686         PartialDiagnosticAt(UDSuffixLoc,
14687                             PDiag(diag::err_ovl_no_viable_function_in_call)
14688                                 << R.getLookupName()),
14689         *this, OCD_AllCandidates, Args);
14690     return ExprError();
14691 
14692   case OR_Ambiguous:
14693     CandidateSet.NoteCandidates(
14694         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14695                                                 << R.getLookupName()),
14696         *this, OCD_AmbiguousCandidates, Args);
14697     return ExprError();
14698   }
14699 
14700   FunctionDecl *FD = Best->Function;
14701   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14702                                         nullptr, HadMultipleCandidates,
14703                                         SuffixInfo.getLoc(),
14704                                         SuffixInfo.getInfo());
14705   if (Fn.isInvalid())
14706     return true;
14707 
14708   // Check the argument types. This should almost always be a no-op, except
14709   // that array-to-pointer decay is applied to string literals.
14710   Expr *ConvArgs[2];
14711   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14712     ExprResult InputInit = PerformCopyInitialization(
14713       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14714       SourceLocation(), Args[ArgIdx]);
14715     if (InputInit.isInvalid())
14716       return true;
14717     ConvArgs[ArgIdx] = InputInit.get();
14718   }
14719 
14720   QualType ResultTy = FD->getReturnType();
14721   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14722   ResultTy = ResultTy.getNonLValueExprType(Context);
14723 
14724   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14725       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14726       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14727 
14728   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14729     return ExprError();
14730 
14731   if (CheckFunctionCall(FD, UDL, nullptr))
14732     return ExprError();
14733 
14734   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14735 }
14736 
14737 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14738 /// given LookupResult is non-empty, it is assumed to describe a member which
14739 /// will be invoked. Otherwise, the function will be found via argument
14740 /// dependent lookup.
14741 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14742 /// otherwise CallExpr is set to ExprError() and some non-success value
14743 /// is returned.
14744 Sema::ForRangeStatus
14745 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14746                                 SourceLocation RangeLoc,
14747                                 const DeclarationNameInfo &NameInfo,
14748                                 LookupResult &MemberLookup,
14749                                 OverloadCandidateSet *CandidateSet,
14750                                 Expr *Range, ExprResult *CallExpr) {
14751   Scope *S = nullptr;
14752 
14753   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14754   if (!MemberLookup.empty()) {
14755     ExprResult MemberRef =
14756         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14757                                  /*IsPtr=*/false, CXXScopeSpec(),
14758                                  /*TemplateKWLoc=*/SourceLocation(),
14759                                  /*FirstQualifierInScope=*/nullptr,
14760                                  MemberLookup,
14761                                  /*TemplateArgs=*/nullptr, S);
14762     if (MemberRef.isInvalid()) {
14763       *CallExpr = ExprError();
14764       return FRS_DiagnosticIssued;
14765     }
14766     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14767     if (CallExpr->isInvalid()) {
14768       *CallExpr = ExprError();
14769       return FRS_DiagnosticIssued;
14770     }
14771   } else {
14772     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14773                                                 NestedNameSpecifierLoc(),
14774                                                 NameInfo, UnresolvedSet<0>());
14775     if (FnR.isInvalid())
14776       return FRS_DiagnosticIssued;
14777     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14778 
14779     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14780                                                     CandidateSet, CallExpr);
14781     if (CandidateSet->empty() || CandidateSetError) {
14782       *CallExpr = ExprError();
14783       return FRS_NoViableFunction;
14784     }
14785     OverloadCandidateSet::iterator Best;
14786     OverloadingResult OverloadResult =
14787         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14788 
14789     if (OverloadResult == OR_No_Viable_Function) {
14790       *CallExpr = ExprError();
14791       return FRS_NoViableFunction;
14792     }
14793     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14794                                          Loc, nullptr, CandidateSet, &Best,
14795                                          OverloadResult,
14796                                          /*AllowTypoCorrection=*/false);
14797     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14798       *CallExpr = ExprError();
14799       return FRS_DiagnosticIssued;
14800     }
14801   }
14802   return FRS_Success;
14803 }
14804 
14805 
14806 /// FixOverloadedFunctionReference - E is an expression that refers to
14807 /// a C++ overloaded function (possibly with some parentheses and
14808 /// perhaps a '&' around it). We have resolved the overloaded function
14809 /// to the function declaration Fn, so patch up the expression E to
14810 /// refer (possibly indirectly) to Fn. Returns the new expr.
14811 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14812                                            FunctionDecl *Fn) {
14813   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14814     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14815                                                    Found, Fn);
14816     if (SubExpr == PE->getSubExpr())
14817       return PE;
14818 
14819     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14820   }
14821 
14822   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14823     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14824                                                    Found, Fn);
14825     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14826                                SubExpr->getType()) &&
14827            "Implicit cast type cannot be determined from overload");
14828     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14829     if (SubExpr == ICE->getSubExpr())
14830       return ICE;
14831 
14832     return ImplicitCastExpr::Create(Context, ICE->getType(),
14833                                     ICE->getCastKind(),
14834                                     SubExpr, nullptr,
14835                                     ICE->getValueKind());
14836   }
14837 
14838   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14839     if (!GSE->isResultDependent()) {
14840       Expr *SubExpr =
14841           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14842       if (SubExpr == GSE->getResultExpr())
14843         return GSE;
14844 
14845       // Replace the resulting type information before rebuilding the generic
14846       // selection expression.
14847       ArrayRef<Expr *> A = GSE->getAssocExprs();
14848       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14849       unsigned ResultIdx = GSE->getResultIndex();
14850       AssocExprs[ResultIdx] = SubExpr;
14851 
14852       return GenericSelectionExpr::Create(
14853           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14854           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14855           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14856           ResultIdx);
14857     }
14858     // Rather than fall through to the unreachable, return the original generic
14859     // selection expression.
14860     return GSE;
14861   }
14862 
14863   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14864     assert(UnOp->getOpcode() == UO_AddrOf &&
14865            "Can only take the address of an overloaded function");
14866     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14867       if (Method->isStatic()) {
14868         // Do nothing: static member functions aren't any different
14869         // from non-member functions.
14870       } else {
14871         // Fix the subexpression, which really has to be an
14872         // UnresolvedLookupExpr holding an overloaded member function
14873         // or template.
14874         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14875                                                        Found, Fn);
14876         if (SubExpr == UnOp->getSubExpr())
14877           return UnOp;
14878 
14879         assert(isa<DeclRefExpr>(SubExpr)
14880                && "fixed to something other than a decl ref");
14881         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14882                && "fixed to a member ref with no nested name qualifier");
14883 
14884         // We have taken the address of a pointer to member
14885         // function. Perform the computation here so that we get the
14886         // appropriate pointer to member type.
14887         QualType ClassType
14888           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14889         QualType MemPtrType
14890           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14891         // Under the MS ABI, lock down the inheritance model now.
14892         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14893           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14894 
14895         return UnaryOperator::Create(
14896             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14897             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14898       }
14899     }
14900     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14901                                                    Found, Fn);
14902     if (SubExpr == UnOp->getSubExpr())
14903       return UnOp;
14904 
14905     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14906                                  Context.getPointerType(SubExpr->getType()),
14907                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14908                                  false, CurFPFeatureOverrides());
14909   }
14910 
14911   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14912     // FIXME: avoid copy.
14913     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14914     if (ULE->hasExplicitTemplateArgs()) {
14915       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14916       TemplateArgs = &TemplateArgsBuffer;
14917     }
14918 
14919     DeclRefExpr *DRE =
14920         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14921                          ULE->getQualifierLoc(), Found.getDecl(),
14922                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14923     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14924     return DRE;
14925   }
14926 
14927   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14928     // FIXME: avoid copy.
14929     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14930     if (MemExpr->hasExplicitTemplateArgs()) {
14931       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14932       TemplateArgs = &TemplateArgsBuffer;
14933     }
14934 
14935     Expr *Base;
14936 
14937     // If we're filling in a static method where we used to have an
14938     // implicit member access, rewrite to a simple decl ref.
14939     if (MemExpr->isImplicitAccess()) {
14940       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14941         DeclRefExpr *DRE = BuildDeclRefExpr(
14942             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14943             MemExpr->getQualifierLoc(), Found.getDecl(),
14944             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14945         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14946         return DRE;
14947       } else {
14948         SourceLocation Loc = MemExpr->getMemberLoc();
14949         if (MemExpr->getQualifier())
14950           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14951         Base =
14952             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14953       }
14954     } else
14955       Base = MemExpr->getBase();
14956 
14957     ExprValueKind valueKind;
14958     QualType type;
14959     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14960       valueKind = VK_LValue;
14961       type = Fn->getType();
14962     } else {
14963       valueKind = VK_RValue;
14964       type = Context.BoundMemberTy;
14965     }
14966 
14967     return BuildMemberExpr(
14968         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14969         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14970         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14971         type, valueKind, OK_Ordinary, TemplateArgs);
14972   }
14973 
14974   llvm_unreachable("Invalid reference to overloaded function");
14975 }
14976 
14977 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14978                                                 DeclAccessPair Found,
14979                                                 FunctionDecl *Fn) {
14980   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14981 }
14982