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 
4988     if (const auto *AT = S.Context.getAsArrayType(ToType)) {
4989       if (S.IsStringInit(From->getInit(0), AT)) {
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 
5004   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5005   // C++11 [over.ics.list]p2:
5006   //   If the parameter type is std::initializer_list<X> or "array of X" and
5007   //   all the elements can be implicitly converted to X, the implicit
5008   //   conversion sequence is the worst conversion necessary to convert an
5009   //   element of the list to X.
5010   //
5011   // C++14 [over.ics.list]p3:
5012   //   Otherwise, if the parameter type is "array of N X", if the initializer
5013   //   list has exactly N elements or if it has fewer than N elements and X is
5014   //   default-constructible, and if all the elements of the initializer list
5015   //   can be implicitly converted to X, the implicit conversion sequence is
5016   //   the worst conversion necessary to convert an element of the list to X.
5017   //
5018   // FIXME: We're missing a lot of these checks.
5019   bool toStdInitializerList = false;
5020   QualType X;
5021   if (ToType->isArrayType())
5022     X = S.Context.getAsArrayType(ToType)->getElementType();
5023   else
5024     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5025   if (!X.isNull()) {
5026     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5027       Expr *Init = From->getInit(i);
5028       ImplicitConversionSequence ICS =
5029           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5030                                 InOverloadResolution,
5031                                 AllowObjCWritebackConversion);
5032       // If a single element isn't convertible, fail.
5033       if (ICS.isBad()) {
5034         Result = ICS;
5035         break;
5036       }
5037       // Otherwise, look for the worst conversion.
5038       if (Result.isBad() || CompareImplicitConversionSequences(
5039                                 S, From->getBeginLoc(), ICS, Result) ==
5040                                 ImplicitConversionSequence::Worse)
5041         Result = ICS;
5042     }
5043 
5044     // For an empty list, we won't have computed any conversion sequence.
5045     // Introduce the identity conversion sequence.
5046     if (From->getNumInits() == 0) {
5047       Result.setStandard();
5048       Result.Standard.setAsIdentityConversion();
5049       Result.Standard.setFromType(ToType);
5050       Result.Standard.setAllToTypes(ToType);
5051     }
5052 
5053     Result.setStdInitializerListElement(toStdInitializerList);
5054     return Result;
5055   }
5056 
5057   // C++14 [over.ics.list]p4:
5058   // C++11 [over.ics.list]p3:
5059   //   Otherwise, if the parameter is a non-aggregate class X and overload
5060   //   resolution chooses a single best constructor [...] the implicit
5061   //   conversion sequence is a user-defined conversion sequence. If multiple
5062   //   constructors are viable but none is better than the others, the
5063   //   implicit conversion sequence is a user-defined conversion sequence.
5064   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5065     // This function can deal with initializer lists.
5066     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5067                                     AllowedExplicit::None,
5068                                     InOverloadResolution, /*CStyle=*/false,
5069                                     AllowObjCWritebackConversion,
5070                                     /*AllowObjCConversionOnExplicit=*/false);
5071   }
5072 
5073   // C++14 [over.ics.list]p5:
5074   // C++11 [over.ics.list]p4:
5075   //   Otherwise, if the parameter has an aggregate type which can be
5076   //   initialized from the initializer list [...] the implicit conversion
5077   //   sequence is a user-defined conversion sequence.
5078   if (ToType->isAggregateType()) {
5079     // Type is an aggregate, argument is an init list. At this point it comes
5080     // down to checking whether the initialization works.
5081     // FIXME: Find out whether this parameter is consumed or not.
5082     InitializedEntity Entity =
5083         InitializedEntity::InitializeParameter(S.Context, ToType,
5084                                                /*Consumed=*/false);
5085     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5086                                                                  From)) {
5087       Result.setUserDefined();
5088       Result.UserDefined.Before.setAsIdentityConversion();
5089       // Initializer lists don't have a type.
5090       Result.UserDefined.Before.setFromType(QualType());
5091       Result.UserDefined.Before.setAllToTypes(QualType());
5092 
5093       Result.UserDefined.After.setAsIdentityConversion();
5094       Result.UserDefined.After.setFromType(ToType);
5095       Result.UserDefined.After.setAllToTypes(ToType);
5096       Result.UserDefined.ConversionFunction = nullptr;
5097     }
5098     return Result;
5099   }
5100 
5101   // C++14 [over.ics.list]p6:
5102   // C++11 [over.ics.list]p5:
5103   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5104   if (ToType->isReferenceType()) {
5105     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5106     // mention initializer lists in any way. So we go by what list-
5107     // initialization would do and try to extrapolate from that.
5108 
5109     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5110 
5111     // If the initializer list has a single element that is reference-related
5112     // to the parameter type, we initialize the reference from that.
5113     if (From->getNumInits() == 1) {
5114       Expr *Init = From->getInit(0);
5115 
5116       QualType T2 = Init->getType();
5117 
5118       // If the initializer is the address of an overloaded function, try
5119       // to resolve the overloaded function. If all goes well, T2 is the
5120       // type of the resulting function.
5121       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5122         DeclAccessPair Found;
5123         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5124                                    Init, ToType, false, Found))
5125           T2 = Fn->getType();
5126       }
5127 
5128       // Compute some basic properties of the types and the initializer.
5129       Sema::ReferenceCompareResult RefRelationship =
5130           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5131 
5132       if (RefRelationship >= Sema::Ref_Related) {
5133         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5134                                 SuppressUserConversions,
5135                                 /*AllowExplicit=*/false);
5136       }
5137     }
5138 
5139     // Otherwise, we bind the reference to a temporary created from the
5140     // initializer list.
5141     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5142                                InOverloadResolution,
5143                                AllowObjCWritebackConversion);
5144     if (Result.isFailure())
5145       return Result;
5146     assert(!Result.isEllipsis() &&
5147            "Sub-initialization cannot result in ellipsis conversion.");
5148 
5149     // Can we even bind to a temporary?
5150     if (ToType->isRValueReferenceType() ||
5151         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5152       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5153                                             Result.UserDefined.After;
5154       SCS.ReferenceBinding = true;
5155       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5156       SCS.BindsToRvalue = true;
5157       SCS.BindsToFunctionLvalue = false;
5158       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5159       SCS.ObjCLifetimeConversionBinding = false;
5160     } else
5161       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5162                     From, ToType);
5163     return Result;
5164   }
5165 
5166   // C++14 [over.ics.list]p7:
5167   // C++11 [over.ics.list]p6:
5168   //   Otherwise, if the parameter type is not a class:
5169   if (!ToType->isRecordType()) {
5170     //    - if the initializer list has one element that is not itself an
5171     //      initializer list, the implicit conversion sequence is the one
5172     //      required to convert the element to the parameter type.
5173     unsigned NumInits = From->getNumInits();
5174     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5175       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5176                                      SuppressUserConversions,
5177                                      InOverloadResolution,
5178                                      AllowObjCWritebackConversion);
5179     //    - if the initializer list has no elements, the implicit conversion
5180     //      sequence is the identity conversion.
5181     else if (NumInits == 0) {
5182       Result.setStandard();
5183       Result.Standard.setAsIdentityConversion();
5184       Result.Standard.setFromType(ToType);
5185       Result.Standard.setAllToTypes(ToType);
5186     }
5187     return Result;
5188   }
5189 
5190   // C++14 [over.ics.list]p8:
5191   // C++11 [over.ics.list]p7:
5192   //   In all cases other than those enumerated above, no conversion is possible
5193   return Result;
5194 }
5195 
5196 /// TryCopyInitialization - Try to copy-initialize a value of type
5197 /// ToType from the expression From. Return the implicit conversion
5198 /// sequence required to pass this argument, which may be a bad
5199 /// conversion sequence (meaning that the argument cannot be passed to
5200 /// a parameter of this type). If @p SuppressUserConversions, then we
5201 /// do not permit any user-defined conversion sequences.
5202 static ImplicitConversionSequence
5203 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5204                       bool SuppressUserConversions,
5205                       bool InOverloadResolution,
5206                       bool AllowObjCWritebackConversion,
5207                       bool AllowExplicit) {
5208   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5209     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5210                              InOverloadResolution,AllowObjCWritebackConversion);
5211 
5212   if (ToType->isReferenceType())
5213     return TryReferenceInit(S, From, ToType,
5214                             /*FIXME:*/ From->getBeginLoc(),
5215                             SuppressUserConversions, AllowExplicit);
5216 
5217   return TryImplicitConversion(S, From, ToType,
5218                                SuppressUserConversions,
5219                                AllowedExplicit::None,
5220                                InOverloadResolution,
5221                                /*CStyle=*/false,
5222                                AllowObjCWritebackConversion,
5223                                /*AllowObjCConversionOnExplicit=*/false);
5224 }
5225 
5226 static bool TryCopyInitialization(const CanQualType FromQTy,
5227                                   const CanQualType ToQTy,
5228                                   Sema &S,
5229                                   SourceLocation Loc,
5230                                   ExprValueKind FromVK) {
5231   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5232   ImplicitConversionSequence ICS =
5233     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5234 
5235   return !ICS.isBad();
5236 }
5237 
5238 /// TryObjectArgumentInitialization - Try to initialize the object
5239 /// parameter of the given member function (@c Method) from the
5240 /// expression @p From.
5241 static ImplicitConversionSequence
5242 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5243                                 Expr::Classification FromClassification,
5244                                 CXXMethodDecl *Method,
5245                                 CXXRecordDecl *ActingContext) {
5246   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5247   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5248   //                 const volatile object.
5249   Qualifiers Quals = Method->getMethodQualifiers();
5250   if (isa<CXXDestructorDecl>(Method)) {
5251     Quals.addConst();
5252     Quals.addVolatile();
5253   }
5254 
5255   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5256 
5257   // Set up the conversion sequence as a "bad" conversion, to allow us
5258   // to exit early.
5259   ImplicitConversionSequence ICS;
5260 
5261   // We need to have an object of class type.
5262   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5263     FromType = PT->getPointeeType();
5264 
5265     // When we had a pointer, it's implicitly dereferenced, so we
5266     // better have an lvalue.
5267     assert(FromClassification.isLValue());
5268   }
5269 
5270   assert(FromType->isRecordType());
5271 
5272   // C++0x [over.match.funcs]p4:
5273   //   For non-static member functions, the type of the implicit object
5274   //   parameter is
5275   //
5276   //     - "lvalue reference to cv X" for functions declared without a
5277   //        ref-qualifier or with the & ref-qualifier
5278   //     - "rvalue reference to cv X" for functions declared with the &&
5279   //        ref-qualifier
5280   //
5281   // where X is the class of which the function is a member and cv is the
5282   // cv-qualification on the member function declaration.
5283   //
5284   // However, when finding an implicit conversion sequence for the argument, we
5285   // are not allowed to perform user-defined conversions
5286   // (C++ [over.match.funcs]p5). We perform a simplified version of
5287   // reference binding here, that allows class rvalues to bind to
5288   // non-constant references.
5289 
5290   // First check the qualifiers.
5291   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5292   if (ImplicitParamType.getCVRQualifiers()
5293                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5294       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5295     ICS.setBad(BadConversionSequence::bad_qualifiers,
5296                FromType, ImplicitParamType);
5297     return ICS;
5298   }
5299 
5300   if (FromTypeCanon.hasAddressSpace()) {
5301     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5302     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5303     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5304       ICS.setBad(BadConversionSequence::bad_qualifiers,
5305                  FromType, ImplicitParamType);
5306       return ICS;
5307     }
5308   }
5309 
5310   // Check that we have either the same type or a derived type. It
5311   // affects the conversion rank.
5312   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5313   ImplicitConversionKind SecondKind;
5314   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5315     SecondKind = ICK_Identity;
5316   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5317     SecondKind = ICK_Derived_To_Base;
5318   else {
5319     ICS.setBad(BadConversionSequence::unrelated_class,
5320                FromType, ImplicitParamType);
5321     return ICS;
5322   }
5323 
5324   // Check the ref-qualifier.
5325   switch (Method->getRefQualifier()) {
5326   case RQ_None:
5327     // Do nothing; we don't care about lvalueness or rvalueness.
5328     break;
5329 
5330   case RQ_LValue:
5331     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5332       // non-const lvalue reference cannot bind to an rvalue
5333       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5334                  ImplicitParamType);
5335       return ICS;
5336     }
5337     break;
5338 
5339   case RQ_RValue:
5340     if (!FromClassification.isRValue()) {
5341       // rvalue reference cannot bind to an lvalue
5342       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5343                  ImplicitParamType);
5344       return ICS;
5345     }
5346     break;
5347   }
5348 
5349   // Success. Mark this as a reference binding.
5350   ICS.setStandard();
5351   ICS.Standard.setAsIdentityConversion();
5352   ICS.Standard.Second = SecondKind;
5353   ICS.Standard.setFromType(FromType);
5354   ICS.Standard.setAllToTypes(ImplicitParamType);
5355   ICS.Standard.ReferenceBinding = true;
5356   ICS.Standard.DirectBinding = true;
5357   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5358   ICS.Standard.BindsToFunctionLvalue = false;
5359   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5360   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5361     = (Method->getRefQualifier() == RQ_None);
5362   return ICS;
5363 }
5364 
5365 /// PerformObjectArgumentInitialization - Perform initialization of
5366 /// the implicit object parameter for the given Method with the given
5367 /// expression.
5368 ExprResult
5369 Sema::PerformObjectArgumentInitialization(Expr *From,
5370                                           NestedNameSpecifier *Qualifier,
5371                                           NamedDecl *FoundDecl,
5372                                           CXXMethodDecl *Method) {
5373   QualType FromRecordType, DestType;
5374   QualType ImplicitParamRecordType  =
5375     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5376 
5377   Expr::Classification FromClassification;
5378   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5379     FromRecordType = PT->getPointeeType();
5380     DestType = Method->getThisType();
5381     FromClassification = Expr::Classification::makeSimpleLValue();
5382   } else {
5383     FromRecordType = From->getType();
5384     DestType = ImplicitParamRecordType;
5385     FromClassification = From->Classify(Context);
5386 
5387     // When performing member access on an rvalue, materialize a temporary.
5388     if (From->isRValue()) {
5389       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5390                                             Method->getRefQualifier() !=
5391                                                 RefQualifierKind::RQ_RValue);
5392     }
5393   }
5394 
5395   // Note that we always use the true parent context when performing
5396   // the actual argument initialization.
5397   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5398       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5399       Method->getParent());
5400   if (ICS.isBad()) {
5401     switch (ICS.Bad.Kind) {
5402     case BadConversionSequence::bad_qualifiers: {
5403       Qualifiers FromQs = FromRecordType.getQualifiers();
5404       Qualifiers ToQs = DestType.getQualifiers();
5405       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5406       if (CVR) {
5407         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5408             << Method->getDeclName() << FromRecordType << (CVR - 1)
5409             << From->getSourceRange();
5410         Diag(Method->getLocation(), diag::note_previous_decl)
5411           << Method->getDeclName();
5412         return ExprError();
5413       }
5414       break;
5415     }
5416 
5417     case BadConversionSequence::lvalue_ref_to_rvalue:
5418     case BadConversionSequence::rvalue_ref_to_lvalue: {
5419       bool IsRValueQualified =
5420         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5421       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5422           << Method->getDeclName() << FromClassification.isRValue()
5423           << IsRValueQualified;
5424       Diag(Method->getLocation(), diag::note_previous_decl)
5425         << Method->getDeclName();
5426       return ExprError();
5427     }
5428 
5429     case BadConversionSequence::no_conversion:
5430     case BadConversionSequence::unrelated_class:
5431       break;
5432     }
5433 
5434     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5435            << ImplicitParamRecordType << FromRecordType
5436            << From->getSourceRange();
5437   }
5438 
5439   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5440     ExprResult FromRes =
5441       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5442     if (FromRes.isInvalid())
5443       return ExprError();
5444     From = FromRes.get();
5445   }
5446 
5447   if (!Context.hasSameType(From->getType(), DestType)) {
5448     CastKind CK;
5449     QualType PteeTy = DestType->getPointeeType();
5450     LangAS DestAS =
5451         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5452     if (FromRecordType.getAddressSpace() != DestAS)
5453       CK = CK_AddressSpaceConversion;
5454     else
5455       CK = CK_NoOp;
5456     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5457   }
5458   return From;
5459 }
5460 
5461 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5462 /// expression From to bool (C++0x [conv]p3).
5463 static ImplicitConversionSequence
5464 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5465   // C++ [dcl.init]/17.8:
5466   //   - Otherwise, if the initialization is direct-initialization, the source
5467   //     type is std::nullptr_t, and the destination type is bool, the initial
5468   //     value of the object being initialized is false.
5469   if (From->getType()->isNullPtrType())
5470     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5471                                                         S.Context.BoolTy,
5472                                                         From->isGLValue());
5473 
5474   // All other direct-initialization of bool is equivalent to an implicit
5475   // conversion to bool in which explicit conversions are permitted.
5476   return TryImplicitConversion(S, From, S.Context.BoolTy,
5477                                /*SuppressUserConversions=*/false,
5478                                AllowedExplicit::Conversions,
5479                                /*InOverloadResolution=*/false,
5480                                /*CStyle=*/false,
5481                                /*AllowObjCWritebackConversion=*/false,
5482                                /*AllowObjCConversionOnExplicit=*/false);
5483 }
5484 
5485 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5486 /// of the expression From to bool (C++0x [conv]p3).
5487 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5488   if (checkPlaceholderForOverload(*this, From))
5489     return ExprError();
5490 
5491   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5492   if (!ICS.isBad())
5493     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5494 
5495   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5496     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5497            << From->getType() << From->getSourceRange();
5498   return ExprError();
5499 }
5500 
5501 /// Check that the specified conversion is permitted in a converted constant
5502 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5503 /// is acceptable.
5504 static bool CheckConvertedConstantConversions(Sema &S,
5505                                               StandardConversionSequence &SCS) {
5506   // Since we know that the target type is an integral or unscoped enumeration
5507   // type, most conversion kinds are impossible. All possible First and Third
5508   // conversions are fine.
5509   switch (SCS.Second) {
5510   case ICK_Identity:
5511   case ICK_Integral_Promotion:
5512   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5513   case ICK_Zero_Queue_Conversion:
5514     return true;
5515 
5516   case ICK_Boolean_Conversion:
5517     // Conversion from an integral or unscoped enumeration type to bool is
5518     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5519     // conversion, so we allow it in a converted constant expression.
5520     //
5521     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5522     // a lot of popular code. We should at least add a warning for this
5523     // (non-conforming) extension.
5524     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5525            SCS.getToType(2)->isBooleanType();
5526 
5527   case ICK_Pointer_Conversion:
5528   case ICK_Pointer_Member:
5529     // C++1z: null pointer conversions and null member pointer conversions are
5530     // only permitted if the source type is std::nullptr_t.
5531     return SCS.getFromType()->isNullPtrType();
5532 
5533   case ICK_Floating_Promotion:
5534   case ICK_Complex_Promotion:
5535   case ICK_Floating_Conversion:
5536   case ICK_Complex_Conversion:
5537   case ICK_Floating_Integral:
5538   case ICK_Compatible_Conversion:
5539   case ICK_Derived_To_Base:
5540   case ICK_Vector_Conversion:
5541   case ICK_SVE_Vector_Conversion:
5542   case ICK_Vector_Splat:
5543   case ICK_Complex_Real:
5544   case ICK_Block_Pointer_Conversion:
5545   case ICK_TransparentUnionConversion:
5546   case ICK_Writeback_Conversion:
5547   case ICK_Zero_Event_Conversion:
5548   case ICK_C_Only_Conversion:
5549   case ICK_Incompatible_Pointer_Conversion:
5550     return false;
5551 
5552   case ICK_Lvalue_To_Rvalue:
5553   case ICK_Array_To_Pointer:
5554   case ICK_Function_To_Pointer:
5555     llvm_unreachable("found a first conversion kind in Second");
5556 
5557   case ICK_Function_Conversion:
5558   case ICK_Qualification:
5559     llvm_unreachable("found a third conversion kind in Second");
5560 
5561   case ICK_Num_Conversion_Kinds:
5562     break;
5563   }
5564 
5565   llvm_unreachable("unknown conversion kind");
5566 }
5567 
5568 /// CheckConvertedConstantExpression - Check that the expression From is a
5569 /// converted constant expression of type T, perform the conversion and produce
5570 /// the converted expression, per C++11 [expr.const]p3.
5571 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5572                                                    QualType T, APValue &Value,
5573                                                    Sema::CCEKind CCE,
5574                                                    bool RequireInt) {
5575   assert(S.getLangOpts().CPlusPlus11 &&
5576          "converted constant expression outside C++11");
5577 
5578   if (checkPlaceholderForOverload(S, From))
5579     return ExprError();
5580 
5581   // C++1z [expr.const]p3:
5582   //  A converted constant expression of type T is an expression,
5583   //  implicitly converted to type T, where the converted
5584   //  expression is a constant expression and the implicit conversion
5585   //  sequence contains only [... list of conversions ...].
5586   // C++1z [stmt.if]p2:
5587   //  If the if statement is of the form if constexpr, the value of the
5588   //  condition shall be a contextually converted constant expression of type
5589   //  bool.
5590   ImplicitConversionSequence ICS =
5591       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5592           ? TryContextuallyConvertToBool(S, From)
5593           : TryCopyInitialization(S, From, T,
5594                                   /*SuppressUserConversions=*/false,
5595                                   /*InOverloadResolution=*/false,
5596                                   /*AllowObjCWritebackConversion=*/false,
5597                                   /*AllowExplicit=*/false);
5598   StandardConversionSequence *SCS = nullptr;
5599   switch (ICS.getKind()) {
5600   case ImplicitConversionSequence::StandardConversion:
5601     SCS = &ICS.Standard;
5602     break;
5603   case ImplicitConversionSequence::UserDefinedConversion:
5604     // We are converting to a non-class type, so the Before sequence
5605     // must be trivial.
5606     SCS = &ICS.UserDefined.After;
5607     break;
5608   case ImplicitConversionSequence::AmbiguousConversion:
5609   case ImplicitConversionSequence::BadConversion:
5610     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5611       return S.Diag(From->getBeginLoc(),
5612                     diag::err_typecheck_converted_constant_expression)
5613              << From->getType() << From->getSourceRange() << T;
5614     return ExprError();
5615 
5616   case ImplicitConversionSequence::EllipsisConversion:
5617     llvm_unreachable("ellipsis conversion in converted constant expression");
5618   }
5619 
5620   // Check that we would only use permitted conversions.
5621   if (!CheckConvertedConstantConversions(S, *SCS)) {
5622     return S.Diag(From->getBeginLoc(),
5623                   diag::err_typecheck_converted_constant_expression_disallowed)
5624            << From->getType() << From->getSourceRange() << T;
5625   }
5626   // [...] and where the reference binding (if any) binds directly.
5627   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5628     return S.Diag(From->getBeginLoc(),
5629                   diag::err_typecheck_converted_constant_expression_indirect)
5630            << From->getType() << From->getSourceRange() << T;
5631   }
5632 
5633   ExprResult Result =
5634       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5635   if (Result.isInvalid())
5636     return Result;
5637 
5638   // C++2a [intro.execution]p5:
5639   //   A full-expression is [...] a constant-expression [...]
5640   Result =
5641       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5642                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5643   if (Result.isInvalid())
5644     return Result;
5645 
5646   // Check for a narrowing implicit conversion.
5647   bool ReturnPreNarrowingValue = false;
5648   APValue PreNarrowingValue;
5649   QualType PreNarrowingType;
5650   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5651                                 PreNarrowingType)) {
5652   case NK_Dependent_Narrowing:
5653     // Implicit conversion to a narrower type, but the expression is
5654     // value-dependent so we can't tell whether it's actually narrowing.
5655   case NK_Variable_Narrowing:
5656     // Implicit conversion to a narrower type, and the value is not a constant
5657     // expression. We'll diagnose this in a moment.
5658   case NK_Not_Narrowing:
5659     break;
5660 
5661   case NK_Constant_Narrowing:
5662     if (CCE == Sema::CCEK_ArrayBound &&
5663         PreNarrowingType->isIntegralOrEnumerationType() &&
5664         PreNarrowingValue.isInt()) {
5665       // Don't diagnose array bound narrowing here; we produce more precise
5666       // errors by allowing the un-narrowed value through.
5667       ReturnPreNarrowingValue = true;
5668       break;
5669     }
5670     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5671         << CCE << /*Constant*/ 1
5672         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5673     break;
5674 
5675   case NK_Type_Narrowing:
5676     // FIXME: It would be better to diagnose that the expression is not a
5677     // constant expression.
5678     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5679         << CCE << /*Constant*/ 0 << From->getType() << T;
5680     break;
5681   }
5682 
5683   if (Result.get()->isValueDependent()) {
5684     Value = APValue();
5685     return Result;
5686   }
5687 
5688   // Check the expression is a constant expression.
5689   SmallVector<PartialDiagnosticAt, 8> Notes;
5690   Expr::EvalResult Eval;
5691   Eval.Diag = &Notes;
5692   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5693                                    ? Expr::EvaluateForMangling
5694                                    : Expr::EvaluateForCodeGen;
5695 
5696   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5697       (RequireInt && !Eval.Val.isInt())) {
5698     // The expression can't be folded, so we can't keep it at this position in
5699     // the AST.
5700     Result = ExprError();
5701   } else {
5702     Value = Eval.Val;
5703 
5704     if (Notes.empty()) {
5705       // It's a constant expression.
5706       Expr *E = ConstantExpr::Create(S.Context, Result.get(), Value);
5707       if (ReturnPreNarrowingValue)
5708         Value = std::move(PreNarrowingValue);
5709       return E;
5710     }
5711   }
5712 
5713   // It's not a constant expression. Produce an appropriate diagnostic.
5714   if (Notes.size() == 1 &&
5715       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5716     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5717   else {
5718     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5719         << CCE << From->getSourceRange();
5720     for (unsigned I = 0; I < Notes.size(); ++I)
5721       S.Diag(Notes[I].first, Notes[I].second);
5722   }
5723   return ExprError();
5724 }
5725 
5726 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5727                                                   APValue &Value, CCEKind CCE) {
5728   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5729 }
5730 
5731 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5732                                                   llvm::APSInt &Value,
5733                                                   CCEKind CCE) {
5734   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5735 
5736   APValue V;
5737   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5738   if (!R.isInvalid() && !R.get()->isValueDependent())
5739     Value = V.getInt();
5740   return R;
5741 }
5742 
5743 
5744 /// dropPointerConversions - If the given standard conversion sequence
5745 /// involves any pointer conversions, remove them.  This may change
5746 /// the result type of the conversion sequence.
5747 static void dropPointerConversion(StandardConversionSequence &SCS) {
5748   if (SCS.Second == ICK_Pointer_Conversion) {
5749     SCS.Second = ICK_Identity;
5750     SCS.Third = ICK_Identity;
5751     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5752   }
5753 }
5754 
5755 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5756 /// convert the expression From to an Objective-C pointer type.
5757 static ImplicitConversionSequence
5758 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5759   // Do an implicit conversion to 'id'.
5760   QualType Ty = S.Context.getObjCIdType();
5761   ImplicitConversionSequence ICS
5762     = TryImplicitConversion(S, From, Ty,
5763                             // FIXME: Are these flags correct?
5764                             /*SuppressUserConversions=*/false,
5765                             AllowedExplicit::Conversions,
5766                             /*InOverloadResolution=*/false,
5767                             /*CStyle=*/false,
5768                             /*AllowObjCWritebackConversion=*/false,
5769                             /*AllowObjCConversionOnExplicit=*/true);
5770 
5771   // Strip off any final conversions to 'id'.
5772   switch (ICS.getKind()) {
5773   case ImplicitConversionSequence::BadConversion:
5774   case ImplicitConversionSequence::AmbiguousConversion:
5775   case ImplicitConversionSequence::EllipsisConversion:
5776     break;
5777 
5778   case ImplicitConversionSequence::UserDefinedConversion:
5779     dropPointerConversion(ICS.UserDefined.After);
5780     break;
5781 
5782   case ImplicitConversionSequence::StandardConversion:
5783     dropPointerConversion(ICS.Standard);
5784     break;
5785   }
5786 
5787   return ICS;
5788 }
5789 
5790 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5791 /// conversion of the expression From to an Objective-C pointer type.
5792 /// Returns a valid but null ExprResult if no conversion sequence exists.
5793 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5794   if (checkPlaceholderForOverload(*this, From))
5795     return ExprError();
5796 
5797   QualType Ty = Context.getObjCIdType();
5798   ImplicitConversionSequence ICS =
5799     TryContextuallyConvertToObjCPointer(*this, From);
5800   if (!ICS.isBad())
5801     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5802   return ExprResult();
5803 }
5804 
5805 /// Determine whether the provided type is an integral type, or an enumeration
5806 /// type of a permitted flavor.
5807 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5808   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5809                                  : T->isIntegralOrUnscopedEnumerationType();
5810 }
5811 
5812 static ExprResult
5813 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5814                             Sema::ContextualImplicitConverter &Converter,
5815                             QualType T, UnresolvedSetImpl &ViableConversions) {
5816 
5817   if (Converter.Suppress)
5818     return ExprError();
5819 
5820   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5821   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5822     CXXConversionDecl *Conv =
5823         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5824     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5825     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5826   }
5827   return From;
5828 }
5829 
5830 static bool
5831 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5832                            Sema::ContextualImplicitConverter &Converter,
5833                            QualType T, bool HadMultipleCandidates,
5834                            UnresolvedSetImpl &ExplicitConversions) {
5835   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5836     DeclAccessPair Found = ExplicitConversions[0];
5837     CXXConversionDecl *Conversion =
5838         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5839 
5840     // The user probably meant to invoke the given explicit
5841     // conversion; use it.
5842     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5843     std::string TypeStr;
5844     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5845 
5846     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5847         << FixItHint::CreateInsertion(From->getBeginLoc(),
5848                                       "static_cast<" + TypeStr + ">(")
5849         << FixItHint::CreateInsertion(
5850                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5851     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5852 
5853     // If we aren't in a SFINAE context, build a call to the
5854     // explicit conversion function.
5855     if (SemaRef.isSFINAEContext())
5856       return true;
5857 
5858     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5859     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5860                                                        HadMultipleCandidates);
5861     if (Result.isInvalid())
5862       return true;
5863     // Record usage of conversion in an implicit cast.
5864     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5865                                     CK_UserDefinedConversion, Result.get(),
5866                                     nullptr, Result.get()->getValueKind(),
5867                                     SemaRef.CurFPFeatureOverrides());
5868   }
5869   return false;
5870 }
5871 
5872 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5873                              Sema::ContextualImplicitConverter &Converter,
5874                              QualType T, bool HadMultipleCandidates,
5875                              DeclAccessPair &Found) {
5876   CXXConversionDecl *Conversion =
5877       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5878   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5879 
5880   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5881   if (!Converter.SuppressConversion) {
5882     if (SemaRef.isSFINAEContext())
5883       return true;
5884 
5885     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5886         << From->getSourceRange();
5887   }
5888 
5889   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5890                                                      HadMultipleCandidates);
5891   if (Result.isInvalid())
5892     return true;
5893   // Record usage of conversion in an implicit cast.
5894   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5895                                   CK_UserDefinedConversion, Result.get(),
5896                                   nullptr, Result.get()->getValueKind(),
5897                                   SemaRef.CurFPFeatureOverrides());
5898   return false;
5899 }
5900 
5901 static ExprResult finishContextualImplicitConversion(
5902     Sema &SemaRef, SourceLocation Loc, Expr *From,
5903     Sema::ContextualImplicitConverter &Converter) {
5904   if (!Converter.match(From->getType()) && !Converter.Suppress)
5905     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5906         << From->getSourceRange();
5907 
5908   return SemaRef.DefaultLvalueConversion(From);
5909 }
5910 
5911 static void
5912 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5913                                   UnresolvedSetImpl &ViableConversions,
5914                                   OverloadCandidateSet &CandidateSet) {
5915   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5916     DeclAccessPair FoundDecl = ViableConversions[I];
5917     NamedDecl *D = FoundDecl.getDecl();
5918     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5919     if (isa<UsingShadowDecl>(D))
5920       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5921 
5922     CXXConversionDecl *Conv;
5923     FunctionTemplateDecl *ConvTemplate;
5924     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5925       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5926     else
5927       Conv = cast<CXXConversionDecl>(D);
5928 
5929     if (ConvTemplate)
5930       SemaRef.AddTemplateConversionCandidate(
5931           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5932           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5933     else
5934       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5935                                      ToType, CandidateSet,
5936                                      /*AllowObjCConversionOnExplicit=*/false,
5937                                      /*AllowExplicit*/ true);
5938   }
5939 }
5940 
5941 /// Attempt to convert the given expression to a type which is accepted
5942 /// by the given converter.
5943 ///
5944 /// This routine will attempt to convert an expression of class type to a
5945 /// type accepted by the specified converter. In C++11 and before, the class
5946 /// must have a single non-explicit conversion function converting to a matching
5947 /// type. In C++1y, there can be multiple such conversion functions, but only
5948 /// one target type.
5949 ///
5950 /// \param Loc The source location of the construct that requires the
5951 /// conversion.
5952 ///
5953 /// \param From The expression we're converting from.
5954 ///
5955 /// \param Converter Used to control and diagnose the conversion process.
5956 ///
5957 /// \returns The expression, converted to an integral or enumeration type if
5958 /// successful.
5959 ExprResult Sema::PerformContextualImplicitConversion(
5960     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5961   // We can't perform any more checking for type-dependent expressions.
5962   if (From->isTypeDependent())
5963     return From;
5964 
5965   // Process placeholders immediately.
5966   if (From->hasPlaceholderType()) {
5967     ExprResult result = CheckPlaceholderExpr(From);
5968     if (result.isInvalid())
5969       return result;
5970     From = result.get();
5971   }
5972 
5973   // If the expression already has a matching type, we're golden.
5974   QualType T = From->getType();
5975   if (Converter.match(T))
5976     return DefaultLvalueConversion(From);
5977 
5978   // FIXME: Check for missing '()' if T is a function type?
5979 
5980   // We can only perform contextual implicit conversions on objects of class
5981   // type.
5982   const RecordType *RecordTy = T->getAs<RecordType>();
5983   if (!RecordTy || !getLangOpts().CPlusPlus) {
5984     if (!Converter.Suppress)
5985       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5986     return From;
5987   }
5988 
5989   // We must have a complete class type.
5990   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5991     ContextualImplicitConverter &Converter;
5992     Expr *From;
5993 
5994     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5995         : Converter(Converter), From(From) {}
5996 
5997     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5998       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5999     }
6000   } IncompleteDiagnoser(Converter, From);
6001 
6002   if (Converter.Suppress ? !isCompleteType(Loc, T)
6003                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6004     return From;
6005 
6006   // Look for a conversion to an integral or enumeration type.
6007   UnresolvedSet<4>
6008       ViableConversions; // These are *potentially* viable in C++1y.
6009   UnresolvedSet<4> ExplicitConversions;
6010   const auto &Conversions =
6011       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6012 
6013   bool HadMultipleCandidates =
6014       (std::distance(Conversions.begin(), Conversions.end()) > 1);
6015 
6016   // To check that there is only one target type, in C++1y:
6017   QualType ToType;
6018   bool HasUniqueTargetType = true;
6019 
6020   // Collect explicit or viable (potentially in C++1y) conversions.
6021   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6022     NamedDecl *D = (*I)->getUnderlyingDecl();
6023     CXXConversionDecl *Conversion;
6024     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6025     if (ConvTemplate) {
6026       if (getLangOpts().CPlusPlus14)
6027         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6028       else
6029         continue; // C++11 does not consider conversion operator templates(?).
6030     } else
6031       Conversion = cast<CXXConversionDecl>(D);
6032 
6033     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6034            "Conversion operator templates are considered potentially "
6035            "viable in C++1y");
6036 
6037     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6038     if (Converter.match(CurToType) || ConvTemplate) {
6039 
6040       if (Conversion->isExplicit()) {
6041         // FIXME: For C++1y, do we need this restriction?
6042         // cf. diagnoseNoViableConversion()
6043         if (!ConvTemplate)
6044           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6045       } else {
6046         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6047           if (ToType.isNull())
6048             ToType = CurToType.getUnqualifiedType();
6049           else if (HasUniqueTargetType &&
6050                    (CurToType.getUnqualifiedType() != ToType))
6051             HasUniqueTargetType = false;
6052         }
6053         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6054       }
6055     }
6056   }
6057 
6058   if (getLangOpts().CPlusPlus14) {
6059     // C++1y [conv]p6:
6060     // ... An expression e of class type E appearing in such a context
6061     // is said to be contextually implicitly converted to a specified
6062     // type T and is well-formed if and only if e can be implicitly
6063     // converted to a type T that is determined as follows: E is searched
6064     // for conversion functions whose return type is cv T or reference to
6065     // cv T such that T is allowed by the context. There shall be
6066     // exactly one such T.
6067 
6068     // If no unique T is found:
6069     if (ToType.isNull()) {
6070       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6071                                      HadMultipleCandidates,
6072                                      ExplicitConversions))
6073         return ExprError();
6074       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6075     }
6076 
6077     // If more than one unique Ts are found:
6078     if (!HasUniqueTargetType)
6079       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6080                                          ViableConversions);
6081 
6082     // If one unique T is found:
6083     // First, build a candidate set from the previously recorded
6084     // potentially viable conversions.
6085     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6086     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6087                                       CandidateSet);
6088 
6089     // Then, perform overload resolution over the candidate set.
6090     OverloadCandidateSet::iterator Best;
6091     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6092     case OR_Success: {
6093       // Apply this conversion.
6094       DeclAccessPair Found =
6095           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6096       if (recordConversion(*this, Loc, From, Converter, T,
6097                            HadMultipleCandidates, Found))
6098         return ExprError();
6099       break;
6100     }
6101     case OR_Ambiguous:
6102       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6103                                          ViableConversions);
6104     case OR_No_Viable_Function:
6105       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6106                                      HadMultipleCandidates,
6107                                      ExplicitConversions))
6108         return ExprError();
6109       LLVM_FALLTHROUGH;
6110     case OR_Deleted:
6111       // We'll complain below about a non-integral condition type.
6112       break;
6113     }
6114   } else {
6115     switch (ViableConversions.size()) {
6116     case 0: {
6117       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6118                                      HadMultipleCandidates,
6119                                      ExplicitConversions))
6120         return ExprError();
6121 
6122       // We'll complain below about a non-integral condition type.
6123       break;
6124     }
6125     case 1: {
6126       // Apply this conversion.
6127       DeclAccessPair Found = ViableConversions[0];
6128       if (recordConversion(*this, Loc, From, Converter, T,
6129                            HadMultipleCandidates, Found))
6130         return ExprError();
6131       break;
6132     }
6133     default:
6134       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6135                                          ViableConversions);
6136     }
6137   }
6138 
6139   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6140 }
6141 
6142 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6143 /// an acceptable non-member overloaded operator for a call whose
6144 /// arguments have types T1 (and, if non-empty, T2). This routine
6145 /// implements the check in C++ [over.match.oper]p3b2 concerning
6146 /// enumeration types.
6147 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6148                                                    FunctionDecl *Fn,
6149                                                    ArrayRef<Expr *> Args) {
6150   QualType T1 = Args[0]->getType();
6151   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6152 
6153   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6154     return true;
6155 
6156   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6157     return true;
6158 
6159   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6160   if (Proto->getNumParams() < 1)
6161     return false;
6162 
6163   if (T1->isEnumeralType()) {
6164     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6165     if (Context.hasSameUnqualifiedType(T1, ArgType))
6166       return true;
6167   }
6168 
6169   if (Proto->getNumParams() < 2)
6170     return false;
6171 
6172   if (!T2.isNull() && T2->isEnumeralType()) {
6173     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6174     if (Context.hasSameUnqualifiedType(T2, ArgType))
6175       return true;
6176   }
6177 
6178   return false;
6179 }
6180 
6181 /// AddOverloadCandidate - Adds the given function to the set of
6182 /// candidate functions, using the given function call arguments.  If
6183 /// @p SuppressUserConversions, then don't allow user-defined
6184 /// conversions via constructors or conversion operators.
6185 ///
6186 /// \param PartialOverloading true if we are performing "partial" overloading
6187 /// based on an incomplete set of function arguments. This feature is used by
6188 /// code completion.
6189 void Sema::AddOverloadCandidate(
6190     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6191     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6192     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6193     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6194     OverloadCandidateParamOrder PO) {
6195   const FunctionProtoType *Proto
6196     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6197   assert(Proto && "Functions without a prototype cannot be overloaded");
6198   assert(!Function->getDescribedFunctionTemplate() &&
6199          "Use AddTemplateOverloadCandidate for function templates");
6200 
6201   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6202     if (!isa<CXXConstructorDecl>(Method)) {
6203       // If we get here, it's because we're calling a member function
6204       // that is named without a member access expression (e.g.,
6205       // "this->f") that was either written explicitly or created
6206       // implicitly. This can happen with a qualified call to a member
6207       // function, e.g., X::f(). We use an empty type for the implied
6208       // object argument (C++ [over.call.func]p3), and the acting context
6209       // is irrelevant.
6210       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6211                          Expr::Classification::makeSimpleLValue(), Args,
6212                          CandidateSet, SuppressUserConversions,
6213                          PartialOverloading, EarlyConversions, PO);
6214       return;
6215     }
6216     // We treat a constructor like a non-member function, since its object
6217     // argument doesn't participate in overload resolution.
6218   }
6219 
6220   if (!CandidateSet.isNewCandidate(Function, PO))
6221     return;
6222 
6223   // C++11 [class.copy]p11: [DR1402]
6224   //   A defaulted move constructor that is defined as deleted is ignored by
6225   //   overload resolution.
6226   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6227   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6228       Constructor->isMoveConstructor())
6229     return;
6230 
6231   // Overload resolution is always an unevaluated context.
6232   EnterExpressionEvaluationContext Unevaluated(
6233       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6234 
6235   // C++ [over.match.oper]p3:
6236   //   if no operand has a class type, only those non-member functions in the
6237   //   lookup set that have a first parameter of type T1 or "reference to
6238   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6239   //   is a right operand) a second parameter of type T2 or "reference to
6240   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6241   //   candidate functions.
6242   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6243       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6244     return;
6245 
6246   // Add this candidate
6247   OverloadCandidate &Candidate =
6248       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6249   Candidate.FoundDecl = FoundDecl;
6250   Candidate.Function = Function;
6251   Candidate.Viable = true;
6252   Candidate.RewriteKind =
6253       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6254   Candidate.IsSurrogate = false;
6255   Candidate.IsADLCandidate = IsADLCandidate;
6256   Candidate.IgnoreObjectArgument = false;
6257   Candidate.ExplicitCallArguments = Args.size();
6258 
6259   // Explicit functions are not actually candidates at all if we're not
6260   // allowing them in this context, but keep them around so we can point
6261   // to them in diagnostics.
6262   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6263     Candidate.Viable = false;
6264     Candidate.FailureKind = ovl_fail_explicit;
6265     return;
6266   }
6267 
6268   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6269       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6270     Candidate.Viable = false;
6271     Candidate.FailureKind = ovl_non_default_multiversion_function;
6272     return;
6273   }
6274 
6275   if (Constructor) {
6276     // C++ [class.copy]p3:
6277     //   A member function template is never instantiated to perform the copy
6278     //   of a class object to an object of its class type.
6279     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6280     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6281         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6282          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6283                        ClassType))) {
6284       Candidate.Viable = false;
6285       Candidate.FailureKind = ovl_fail_illegal_constructor;
6286       return;
6287     }
6288 
6289     // C++ [over.match.funcs]p8: (proposed DR resolution)
6290     //   A constructor inherited from class type C that has a first parameter
6291     //   of type "reference to P" (including such a constructor instantiated
6292     //   from a template) is excluded from the set of candidate functions when
6293     //   constructing an object of type cv D if the argument list has exactly
6294     //   one argument and D is reference-related to P and P is reference-related
6295     //   to C.
6296     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6297     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6298         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6299       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6300       QualType C = Context.getRecordType(Constructor->getParent());
6301       QualType D = Context.getRecordType(Shadow->getParent());
6302       SourceLocation Loc = Args.front()->getExprLoc();
6303       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6304           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6305         Candidate.Viable = false;
6306         Candidate.FailureKind = ovl_fail_inhctor_slice;
6307         return;
6308       }
6309     }
6310 
6311     // Check that the constructor is capable of constructing an object in the
6312     // destination address space.
6313     if (!Qualifiers::isAddressSpaceSupersetOf(
6314             Constructor->getMethodQualifiers().getAddressSpace(),
6315             CandidateSet.getDestAS())) {
6316       Candidate.Viable = false;
6317       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6318     }
6319   }
6320 
6321   unsigned NumParams = Proto->getNumParams();
6322 
6323   // (C++ 13.3.2p2): A candidate function having fewer than m
6324   // parameters is viable only if it has an ellipsis in its parameter
6325   // list (8.3.5).
6326   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6327       !Proto->isVariadic()) {
6328     Candidate.Viable = false;
6329     Candidate.FailureKind = ovl_fail_too_many_arguments;
6330     return;
6331   }
6332 
6333   // (C++ 13.3.2p2): A candidate function having more than m parameters
6334   // is viable only if the (m+1)st parameter has a default argument
6335   // (8.3.6). For the purposes of overload resolution, the
6336   // parameter list is truncated on the right, so that there are
6337   // exactly m parameters.
6338   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6339   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6340     // Not enough arguments.
6341     Candidate.Viable = false;
6342     Candidate.FailureKind = ovl_fail_too_few_arguments;
6343     return;
6344   }
6345 
6346   // (CUDA B.1): Check for invalid calls between targets.
6347   if (getLangOpts().CUDA)
6348     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6349       // Skip the check for callers that are implicit members, because in this
6350       // case we may not yet know what the member's target is; the target is
6351       // inferred for the member automatically, based on the bases and fields of
6352       // the class.
6353       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6354         Candidate.Viable = false;
6355         Candidate.FailureKind = ovl_fail_bad_target;
6356         return;
6357       }
6358 
6359   if (Function->getTrailingRequiresClause()) {
6360     ConstraintSatisfaction Satisfaction;
6361     if (CheckFunctionConstraints(Function, Satisfaction) ||
6362         !Satisfaction.IsSatisfied) {
6363       Candidate.Viable = false;
6364       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6365       return;
6366     }
6367   }
6368 
6369   // Determine the implicit conversion sequences for each of the
6370   // arguments.
6371   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6372     unsigned ConvIdx =
6373         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6374     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6375       // We already formed a conversion sequence for this parameter during
6376       // template argument deduction.
6377     } else if (ArgIdx < NumParams) {
6378       // (C++ 13.3.2p3): for F to be a viable function, there shall
6379       // exist for each argument an implicit conversion sequence
6380       // (13.3.3.1) that converts that argument to the corresponding
6381       // parameter of F.
6382       QualType ParamType = Proto->getParamType(ArgIdx);
6383       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6384           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6385           /*InOverloadResolution=*/true,
6386           /*AllowObjCWritebackConversion=*/
6387           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6388       if (Candidate.Conversions[ConvIdx].isBad()) {
6389         Candidate.Viable = false;
6390         Candidate.FailureKind = ovl_fail_bad_conversion;
6391         return;
6392       }
6393     } else {
6394       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6395       // argument for which there is no corresponding parameter is
6396       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6397       Candidate.Conversions[ConvIdx].setEllipsis();
6398     }
6399   }
6400 
6401   if (EnableIfAttr *FailedAttr =
6402           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6403     Candidate.Viable = false;
6404     Candidate.FailureKind = ovl_fail_enable_if;
6405     Candidate.DeductionFailure.Data = FailedAttr;
6406     return;
6407   }
6408 
6409   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6410     Candidate.Viable = false;
6411     Candidate.FailureKind = ovl_fail_ext_disabled;
6412     return;
6413   }
6414 }
6415 
6416 ObjCMethodDecl *
6417 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6418                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6419   if (Methods.size() <= 1)
6420     return nullptr;
6421 
6422   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6423     bool Match = true;
6424     ObjCMethodDecl *Method = Methods[b];
6425     unsigned NumNamedArgs = Sel.getNumArgs();
6426     // Method might have more arguments than selector indicates. This is due
6427     // to addition of c-style arguments in method.
6428     if (Method->param_size() > NumNamedArgs)
6429       NumNamedArgs = Method->param_size();
6430     if (Args.size() < NumNamedArgs)
6431       continue;
6432 
6433     for (unsigned i = 0; i < NumNamedArgs; i++) {
6434       // We can't do any type-checking on a type-dependent argument.
6435       if (Args[i]->isTypeDependent()) {
6436         Match = false;
6437         break;
6438       }
6439 
6440       ParmVarDecl *param = Method->parameters()[i];
6441       Expr *argExpr = Args[i];
6442       assert(argExpr && "SelectBestMethod(): missing expression");
6443 
6444       // Strip the unbridged-cast placeholder expression off unless it's
6445       // a consumed argument.
6446       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6447           !param->hasAttr<CFConsumedAttr>())
6448         argExpr = stripARCUnbridgedCast(argExpr);
6449 
6450       // If the parameter is __unknown_anytype, move on to the next method.
6451       if (param->getType() == Context.UnknownAnyTy) {
6452         Match = false;
6453         break;
6454       }
6455 
6456       ImplicitConversionSequence ConversionState
6457         = TryCopyInitialization(*this, argExpr, param->getType(),
6458                                 /*SuppressUserConversions*/false,
6459                                 /*InOverloadResolution=*/true,
6460                                 /*AllowObjCWritebackConversion=*/
6461                                 getLangOpts().ObjCAutoRefCount,
6462                                 /*AllowExplicit*/false);
6463       // This function looks for a reasonably-exact match, so we consider
6464       // incompatible pointer conversions to be a failure here.
6465       if (ConversionState.isBad() ||
6466           (ConversionState.isStandard() &&
6467            ConversionState.Standard.Second ==
6468                ICK_Incompatible_Pointer_Conversion)) {
6469         Match = false;
6470         break;
6471       }
6472     }
6473     // Promote additional arguments to variadic methods.
6474     if (Match && Method->isVariadic()) {
6475       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6476         if (Args[i]->isTypeDependent()) {
6477           Match = false;
6478           break;
6479         }
6480         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6481                                                           nullptr);
6482         if (Arg.isInvalid()) {
6483           Match = false;
6484           break;
6485         }
6486       }
6487     } else {
6488       // Check for extra arguments to non-variadic methods.
6489       if (Args.size() != NumNamedArgs)
6490         Match = false;
6491       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6492         // Special case when selectors have no argument. In this case, select
6493         // one with the most general result type of 'id'.
6494         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6495           QualType ReturnT = Methods[b]->getReturnType();
6496           if (ReturnT->isObjCIdType())
6497             return Methods[b];
6498         }
6499       }
6500     }
6501 
6502     if (Match)
6503       return Method;
6504   }
6505   return nullptr;
6506 }
6507 
6508 static bool convertArgsForAvailabilityChecks(
6509     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6510     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6511     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6512   if (ThisArg) {
6513     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6514     assert(!isa<CXXConstructorDecl>(Method) &&
6515            "Shouldn't have `this` for ctors!");
6516     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6517     ExprResult R = S.PerformObjectArgumentInitialization(
6518         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6519     if (R.isInvalid())
6520       return false;
6521     ConvertedThis = R.get();
6522   } else {
6523     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6524       (void)MD;
6525       assert((MissingImplicitThis || MD->isStatic() ||
6526               isa<CXXConstructorDecl>(MD)) &&
6527              "Expected `this` for non-ctor instance methods");
6528     }
6529     ConvertedThis = nullptr;
6530   }
6531 
6532   // Ignore any variadic arguments. Converting them is pointless, since the
6533   // user can't refer to them in the function condition.
6534   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6535 
6536   // Convert the arguments.
6537   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6538     ExprResult R;
6539     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6540                                         S.Context, Function->getParamDecl(I)),
6541                                     SourceLocation(), Args[I]);
6542 
6543     if (R.isInvalid())
6544       return false;
6545 
6546     ConvertedArgs.push_back(R.get());
6547   }
6548 
6549   if (Trap.hasErrorOccurred())
6550     return false;
6551 
6552   // Push default arguments if needed.
6553   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6554     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6555       ParmVarDecl *P = Function->getParamDecl(i);
6556       if (!P->hasDefaultArg())
6557         return false;
6558       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6559       if (R.isInvalid())
6560         return false;
6561       ConvertedArgs.push_back(R.get());
6562     }
6563 
6564     if (Trap.hasErrorOccurred())
6565       return false;
6566   }
6567   return true;
6568 }
6569 
6570 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6571                                   SourceLocation CallLoc,
6572                                   ArrayRef<Expr *> Args,
6573                                   bool MissingImplicitThis) {
6574   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6575   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6576     return nullptr;
6577 
6578   SFINAETrap Trap(*this);
6579   SmallVector<Expr *, 16> ConvertedArgs;
6580   // FIXME: We should look into making enable_if late-parsed.
6581   Expr *DiscardedThis;
6582   if (!convertArgsForAvailabilityChecks(
6583           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6584           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6585     return *EnableIfAttrs.begin();
6586 
6587   for (auto *EIA : EnableIfAttrs) {
6588     APValue Result;
6589     // FIXME: This doesn't consider value-dependent cases, because doing so is
6590     // very difficult. Ideally, we should handle them more gracefully.
6591     if (EIA->getCond()->isValueDependent() ||
6592         !EIA->getCond()->EvaluateWithSubstitution(
6593             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6594       return EIA;
6595 
6596     if (!Result.isInt() || !Result.getInt().getBoolValue())
6597       return EIA;
6598   }
6599   return nullptr;
6600 }
6601 
6602 template <typename CheckFn>
6603 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6604                                         bool ArgDependent, SourceLocation Loc,
6605                                         CheckFn &&IsSuccessful) {
6606   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6607   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6608     if (ArgDependent == DIA->getArgDependent())
6609       Attrs.push_back(DIA);
6610   }
6611 
6612   // Common case: No diagnose_if attributes, so we can quit early.
6613   if (Attrs.empty())
6614     return false;
6615 
6616   auto WarningBegin = std::stable_partition(
6617       Attrs.begin(), Attrs.end(),
6618       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6619 
6620   // Note that diagnose_if attributes are late-parsed, so they appear in the
6621   // correct order (unlike enable_if attributes).
6622   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6623                                IsSuccessful);
6624   if (ErrAttr != WarningBegin) {
6625     const DiagnoseIfAttr *DIA = *ErrAttr;
6626     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6627     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6628         << DIA->getParent() << DIA->getCond()->getSourceRange();
6629     return true;
6630   }
6631 
6632   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6633     if (IsSuccessful(DIA)) {
6634       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6635       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6636           << DIA->getParent() << DIA->getCond()->getSourceRange();
6637     }
6638 
6639   return false;
6640 }
6641 
6642 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6643                                                const Expr *ThisArg,
6644                                                ArrayRef<const Expr *> Args,
6645                                                SourceLocation Loc) {
6646   return diagnoseDiagnoseIfAttrsWith(
6647       *this, Function, /*ArgDependent=*/true, Loc,
6648       [&](const DiagnoseIfAttr *DIA) {
6649         APValue Result;
6650         // It's sane to use the same Args for any redecl of this function, since
6651         // EvaluateWithSubstitution only cares about the position of each
6652         // argument in the arg list, not the ParmVarDecl* it maps to.
6653         if (!DIA->getCond()->EvaluateWithSubstitution(
6654                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6655           return false;
6656         return Result.isInt() && Result.getInt().getBoolValue();
6657       });
6658 }
6659 
6660 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6661                                                  SourceLocation Loc) {
6662   return diagnoseDiagnoseIfAttrsWith(
6663       *this, ND, /*ArgDependent=*/false, Loc,
6664       [&](const DiagnoseIfAttr *DIA) {
6665         bool Result;
6666         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6667                Result;
6668       });
6669 }
6670 
6671 /// Add all of the function declarations in the given function set to
6672 /// the overload candidate set.
6673 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6674                                  ArrayRef<Expr *> Args,
6675                                  OverloadCandidateSet &CandidateSet,
6676                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6677                                  bool SuppressUserConversions,
6678                                  bool PartialOverloading,
6679                                  bool FirstArgumentIsBase) {
6680   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6681     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6682     ArrayRef<Expr *> FunctionArgs = Args;
6683 
6684     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6685     FunctionDecl *FD =
6686         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6687 
6688     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6689       QualType ObjectType;
6690       Expr::Classification ObjectClassification;
6691       if (Args.size() > 0) {
6692         if (Expr *E = Args[0]) {
6693           // Use the explicit base to restrict the lookup:
6694           ObjectType = E->getType();
6695           // Pointers in the object arguments are implicitly dereferenced, so we
6696           // always classify them as l-values.
6697           if (!ObjectType.isNull() && ObjectType->isPointerType())
6698             ObjectClassification = Expr::Classification::makeSimpleLValue();
6699           else
6700             ObjectClassification = E->Classify(Context);
6701         } // .. else there is an implicit base.
6702         FunctionArgs = Args.slice(1);
6703       }
6704       if (FunTmpl) {
6705         AddMethodTemplateCandidate(
6706             FunTmpl, F.getPair(),
6707             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6708             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6709             FunctionArgs, CandidateSet, SuppressUserConversions,
6710             PartialOverloading);
6711       } else {
6712         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6713                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6714                            ObjectClassification, FunctionArgs, CandidateSet,
6715                            SuppressUserConversions, PartialOverloading);
6716       }
6717     } else {
6718       // This branch handles both standalone functions and static methods.
6719 
6720       // Slice the first argument (which is the base) when we access
6721       // static method as non-static.
6722       if (Args.size() > 0 &&
6723           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6724                         !isa<CXXConstructorDecl>(FD)))) {
6725         assert(cast<CXXMethodDecl>(FD)->isStatic());
6726         FunctionArgs = Args.slice(1);
6727       }
6728       if (FunTmpl) {
6729         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6730                                      ExplicitTemplateArgs, FunctionArgs,
6731                                      CandidateSet, SuppressUserConversions,
6732                                      PartialOverloading);
6733       } else {
6734         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6735                              SuppressUserConversions, PartialOverloading);
6736       }
6737     }
6738   }
6739 }
6740 
6741 /// AddMethodCandidate - Adds a named decl (which is some kind of
6742 /// method) as a method candidate to the given overload set.
6743 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6744                               Expr::Classification ObjectClassification,
6745                               ArrayRef<Expr *> Args,
6746                               OverloadCandidateSet &CandidateSet,
6747                               bool SuppressUserConversions,
6748                               OverloadCandidateParamOrder PO) {
6749   NamedDecl *Decl = FoundDecl.getDecl();
6750   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6751 
6752   if (isa<UsingShadowDecl>(Decl))
6753     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6754 
6755   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6756     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6757            "Expected a member function template");
6758     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6759                                /*ExplicitArgs*/ nullptr, ObjectType,
6760                                ObjectClassification, Args, CandidateSet,
6761                                SuppressUserConversions, false, PO);
6762   } else {
6763     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6764                        ObjectType, ObjectClassification, Args, CandidateSet,
6765                        SuppressUserConversions, false, None, PO);
6766   }
6767 }
6768 
6769 /// AddMethodCandidate - Adds the given C++ member function to the set
6770 /// of candidate functions, using the given function call arguments
6771 /// and the object argument (@c Object). For example, in a call
6772 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6773 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6774 /// allow user-defined conversions via constructors or conversion
6775 /// operators.
6776 void
6777 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6778                          CXXRecordDecl *ActingContext, QualType ObjectType,
6779                          Expr::Classification ObjectClassification,
6780                          ArrayRef<Expr *> Args,
6781                          OverloadCandidateSet &CandidateSet,
6782                          bool SuppressUserConversions,
6783                          bool PartialOverloading,
6784                          ConversionSequenceList EarlyConversions,
6785                          OverloadCandidateParamOrder PO) {
6786   const FunctionProtoType *Proto
6787     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6788   assert(Proto && "Methods without a prototype cannot be overloaded");
6789   assert(!isa<CXXConstructorDecl>(Method) &&
6790          "Use AddOverloadCandidate for constructors");
6791 
6792   if (!CandidateSet.isNewCandidate(Method, PO))
6793     return;
6794 
6795   // C++11 [class.copy]p23: [DR1402]
6796   //   A defaulted move assignment operator that is defined as deleted is
6797   //   ignored by overload resolution.
6798   if (Method->isDefaulted() && Method->isDeleted() &&
6799       Method->isMoveAssignmentOperator())
6800     return;
6801 
6802   // Overload resolution is always an unevaluated context.
6803   EnterExpressionEvaluationContext Unevaluated(
6804       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6805 
6806   // Add this candidate
6807   OverloadCandidate &Candidate =
6808       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6809   Candidate.FoundDecl = FoundDecl;
6810   Candidate.Function = Method;
6811   Candidate.RewriteKind =
6812       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6813   Candidate.IsSurrogate = false;
6814   Candidate.IgnoreObjectArgument = false;
6815   Candidate.ExplicitCallArguments = Args.size();
6816 
6817   unsigned NumParams = Proto->getNumParams();
6818 
6819   // (C++ 13.3.2p2): A candidate function having fewer than m
6820   // parameters is viable only if it has an ellipsis in its parameter
6821   // list (8.3.5).
6822   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6823       !Proto->isVariadic()) {
6824     Candidate.Viable = false;
6825     Candidate.FailureKind = ovl_fail_too_many_arguments;
6826     return;
6827   }
6828 
6829   // (C++ 13.3.2p2): A candidate function having more than m parameters
6830   // is viable only if the (m+1)st parameter has a default argument
6831   // (8.3.6). For the purposes of overload resolution, the
6832   // parameter list is truncated on the right, so that there are
6833   // exactly m parameters.
6834   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6835   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6836     // Not enough arguments.
6837     Candidate.Viable = false;
6838     Candidate.FailureKind = ovl_fail_too_few_arguments;
6839     return;
6840   }
6841 
6842   Candidate.Viable = true;
6843 
6844   if (Method->isStatic() || ObjectType.isNull())
6845     // The implicit object argument is ignored.
6846     Candidate.IgnoreObjectArgument = true;
6847   else {
6848     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6849     // Determine the implicit conversion sequence for the object
6850     // parameter.
6851     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6852         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6853         Method, ActingContext);
6854     if (Candidate.Conversions[ConvIdx].isBad()) {
6855       Candidate.Viable = false;
6856       Candidate.FailureKind = ovl_fail_bad_conversion;
6857       return;
6858     }
6859   }
6860 
6861   // (CUDA B.1): Check for invalid calls between targets.
6862   if (getLangOpts().CUDA)
6863     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6864       if (!IsAllowedCUDACall(Caller, Method)) {
6865         Candidate.Viable = false;
6866         Candidate.FailureKind = ovl_fail_bad_target;
6867         return;
6868       }
6869 
6870   if (Method->getTrailingRequiresClause()) {
6871     ConstraintSatisfaction Satisfaction;
6872     if (CheckFunctionConstraints(Method, Satisfaction) ||
6873         !Satisfaction.IsSatisfied) {
6874       Candidate.Viable = false;
6875       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6876       return;
6877     }
6878   }
6879 
6880   // Determine the implicit conversion sequences for each of the
6881   // arguments.
6882   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6883     unsigned ConvIdx =
6884         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6885     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6886       // We already formed a conversion sequence for this parameter during
6887       // template argument deduction.
6888     } else if (ArgIdx < NumParams) {
6889       // (C++ 13.3.2p3): for F to be a viable function, there shall
6890       // exist for each argument an implicit conversion sequence
6891       // (13.3.3.1) that converts that argument to the corresponding
6892       // parameter of F.
6893       QualType ParamType = Proto->getParamType(ArgIdx);
6894       Candidate.Conversions[ConvIdx]
6895         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6896                                 SuppressUserConversions,
6897                                 /*InOverloadResolution=*/true,
6898                                 /*AllowObjCWritebackConversion=*/
6899                                   getLangOpts().ObjCAutoRefCount);
6900       if (Candidate.Conversions[ConvIdx].isBad()) {
6901         Candidate.Viable = false;
6902         Candidate.FailureKind = ovl_fail_bad_conversion;
6903         return;
6904       }
6905     } else {
6906       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6907       // argument for which there is no corresponding parameter is
6908       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6909       Candidate.Conversions[ConvIdx].setEllipsis();
6910     }
6911   }
6912 
6913   if (EnableIfAttr *FailedAttr =
6914           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6915     Candidate.Viable = false;
6916     Candidate.FailureKind = ovl_fail_enable_if;
6917     Candidate.DeductionFailure.Data = FailedAttr;
6918     return;
6919   }
6920 
6921   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6922       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6923     Candidate.Viable = false;
6924     Candidate.FailureKind = ovl_non_default_multiversion_function;
6925   }
6926 }
6927 
6928 /// Add a C++ member function template as a candidate to the candidate
6929 /// set, using template argument deduction to produce an appropriate member
6930 /// function template specialization.
6931 void Sema::AddMethodTemplateCandidate(
6932     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6933     CXXRecordDecl *ActingContext,
6934     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6935     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6936     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6937     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6938   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6939     return;
6940 
6941   // C++ [over.match.funcs]p7:
6942   //   In each case where a candidate is a function template, candidate
6943   //   function template specializations are generated using template argument
6944   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6945   //   candidate functions in the usual way.113) A given name can refer to one
6946   //   or more function templates and also to a set of overloaded non-template
6947   //   functions. In such a case, the candidate functions generated from each
6948   //   function template are combined with the set of non-template candidate
6949   //   functions.
6950   TemplateDeductionInfo Info(CandidateSet.getLocation());
6951   FunctionDecl *Specialization = nullptr;
6952   ConversionSequenceList Conversions;
6953   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6954           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6955           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6956             return CheckNonDependentConversions(
6957                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6958                 SuppressUserConversions, ActingContext, ObjectType,
6959                 ObjectClassification, PO);
6960           })) {
6961     OverloadCandidate &Candidate =
6962         CandidateSet.addCandidate(Conversions.size(), Conversions);
6963     Candidate.FoundDecl = FoundDecl;
6964     Candidate.Function = MethodTmpl->getTemplatedDecl();
6965     Candidate.Viable = false;
6966     Candidate.RewriteKind =
6967       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6968     Candidate.IsSurrogate = false;
6969     Candidate.IgnoreObjectArgument =
6970         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6971         ObjectType.isNull();
6972     Candidate.ExplicitCallArguments = Args.size();
6973     if (Result == TDK_NonDependentConversionFailure)
6974       Candidate.FailureKind = ovl_fail_bad_conversion;
6975     else {
6976       Candidate.FailureKind = ovl_fail_bad_deduction;
6977       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6978                                                             Info);
6979     }
6980     return;
6981   }
6982 
6983   // Add the function template specialization produced by template argument
6984   // deduction as a candidate.
6985   assert(Specialization && "Missing member function template specialization?");
6986   assert(isa<CXXMethodDecl>(Specialization) &&
6987          "Specialization is not a member function?");
6988   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6989                      ActingContext, ObjectType, ObjectClassification, Args,
6990                      CandidateSet, SuppressUserConversions, PartialOverloading,
6991                      Conversions, PO);
6992 }
6993 
6994 /// Determine whether a given function template has a simple explicit specifier
6995 /// or a non-value-dependent explicit-specification that evaluates to true.
6996 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6997   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6998 }
6999 
7000 /// Add a C++ function template specialization as a candidate
7001 /// in the candidate set, using template argument deduction to produce
7002 /// an appropriate function template specialization.
7003 void Sema::AddTemplateOverloadCandidate(
7004     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7005     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7006     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7007     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7008     OverloadCandidateParamOrder PO) {
7009   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7010     return;
7011 
7012   // If the function template has a non-dependent explicit specification,
7013   // exclude it now if appropriate; we are not permitted to perform deduction
7014   // and substitution in this case.
7015   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7016     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7017     Candidate.FoundDecl = FoundDecl;
7018     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7019     Candidate.Viable = false;
7020     Candidate.FailureKind = ovl_fail_explicit;
7021     return;
7022   }
7023 
7024   // C++ [over.match.funcs]p7:
7025   //   In each case where a candidate is a function template, candidate
7026   //   function template specializations are generated using template argument
7027   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
7028   //   candidate functions in the usual way.113) A given name can refer to one
7029   //   or more function templates and also to a set of overloaded non-template
7030   //   functions. In such a case, the candidate functions generated from each
7031   //   function template are combined with the set of non-template candidate
7032   //   functions.
7033   TemplateDeductionInfo Info(CandidateSet.getLocation());
7034   FunctionDecl *Specialization = nullptr;
7035   ConversionSequenceList Conversions;
7036   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7037           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7038           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7039             return CheckNonDependentConversions(
7040                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7041                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7042           })) {
7043     OverloadCandidate &Candidate =
7044         CandidateSet.addCandidate(Conversions.size(), Conversions);
7045     Candidate.FoundDecl = FoundDecl;
7046     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7047     Candidate.Viable = false;
7048     Candidate.RewriteKind =
7049       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7050     Candidate.IsSurrogate = false;
7051     Candidate.IsADLCandidate = IsADLCandidate;
7052     // Ignore the object argument if there is one, since we don't have an object
7053     // type.
7054     Candidate.IgnoreObjectArgument =
7055         isa<CXXMethodDecl>(Candidate.Function) &&
7056         !isa<CXXConstructorDecl>(Candidate.Function);
7057     Candidate.ExplicitCallArguments = Args.size();
7058     if (Result == TDK_NonDependentConversionFailure)
7059       Candidate.FailureKind = ovl_fail_bad_conversion;
7060     else {
7061       Candidate.FailureKind = ovl_fail_bad_deduction;
7062       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7063                                                             Info);
7064     }
7065     return;
7066   }
7067 
7068   // Add the function template specialization produced by template argument
7069   // deduction as a candidate.
7070   assert(Specialization && "Missing function template specialization?");
7071   AddOverloadCandidate(
7072       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7073       PartialOverloading, AllowExplicit,
7074       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7075 }
7076 
7077 /// Check that implicit conversion sequences can be formed for each argument
7078 /// whose corresponding parameter has a non-dependent type, per DR1391's
7079 /// [temp.deduct.call]p10.
7080 bool Sema::CheckNonDependentConversions(
7081     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7082     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7083     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7084     CXXRecordDecl *ActingContext, QualType ObjectType,
7085     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7086   // FIXME: The cases in which we allow explicit conversions for constructor
7087   // arguments never consider calling a constructor template. It's not clear
7088   // that is correct.
7089   const bool AllowExplicit = false;
7090 
7091   auto *FD = FunctionTemplate->getTemplatedDecl();
7092   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7093   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7094   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7095 
7096   Conversions =
7097       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7098 
7099   // Overload resolution is always an unevaluated context.
7100   EnterExpressionEvaluationContext Unevaluated(
7101       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7102 
7103   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7104   // require that, but this check should never result in a hard error, and
7105   // overload resolution is permitted to sidestep instantiations.
7106   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7107       !ObjectType.isNull()) {
7108     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7109     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7110         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7111         Method, ActingContext);
7112     if (Conversions[ConvIdx].isBad())
7113       return true;
7114   }
7115 
7116   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7117        ++I) {
7118     QualType ParamType = ParamTypes[I];
7119     if (!ParamType->isDependentType()) {
7120       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7121                              ? 0
7122                              : (ThisConversions + I);
7123       Conversions[ConvIdx]
7124         = TryCopyInitialization(*this, Args[I], ParamType,
7125                                 SuppressUserConversions,
7126                                 /*InOverloadResolution=*/true,
7127                                 /*AllowObjCWritebackConversion=*/
7128                                   getLangOpts().ObjCAutoRefCount,
7129                                 AllowExplicit);
7130       if (Conversions[ConvIdx].isBad())
7131         return true;
7132     }
7133   }
7134 
7135   return false;
7136 }
7137 
7138 /// Determine whether this is an allowable conversion from the result
7139 /// of an explicit conversion operator to the expected type, per C++
7140 /// [over.match.conv]p1 and [over.match.ref]p1.
7141 ///
7142 /// \param ConvType The return type of the conversion function.
7143 ///
7144 /// \param ToType The type we are converting to.
7145 ///
7146 /// \param AllowObjCPointerConversion Allow a conversion from one
7147 /// Objective-C pointer to another.
7148 ///
7149 /// \returns true if the conversion is allowable, false otherwise.
7150 static bool isAllowableExplicitConversion(Sema &S,
7151                                           QualType ConvType, QualType ToType,
7152                                           bool AllowObjCPointerConversion) {
7153   QualType ToNonRefType = ToType.getNonReferenceType();
7154 
7155   // Easy case: the types are the same.
7156   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7157     return true;
7158 
7159   // Allow qualification conversions.
7160   bool ObjCLifetimeConversion;
7161   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7162                                   ObjCLifetimeConversion))
7163     return true;
7164 
7165   // If we're not allowed to consider Objective-C pointer conversions,
7166   // we're done.
7167   if (!AllowObjCPointerConversion)
7168     return false;
7169 
7170   // Is this an Objective-C pointer conversion?
7171   bool IncompatibleObjC = false;
7172   QualType ConvertedType;
7173   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7174                                    IncompatibleObjC);
7175 }
7176 
7177 /// AddConversionCandidate - Add a C++ conversion function as a
7178 /// candidate in the candidate set (C++ [over.match.conv],
7179 /// C++ [over.match.copy]). From is the expression we're converting from,
7180 /// and ToType is the type that we're eventually trying to convert to
7181 /// (which may or may not be the same type as the type that the
7182 /// conversion function produces).
7183 void Sema::AddConversionCandidate(
7184     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7185     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7186     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7187     bool AllowExplicit, bool AllowResultConversion) {
7188   assert(!Conversion->getDescribedFunctionTemplate() &&
7189          "Conversion function templates use AddTemplateConversionCandidate");
7190   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7191   if (!CandidateSet.isNewCandidate(Conversion))
7192     return;
7193 
7194   // If the conversion function has an undeduced return type, trigger its
7195   // deduction now.
7196   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7197     if (DeduceReturnType(Conversion, From->getExprLoc()))
7198       return;
7199     ConvType = Conversion->getConversionType().getNonReferenceType();
7200   }
7201 
7202   // If we don't allow any conversion of the result type, ignore conversion
7203   // functions that don't convert to exactly (possibly cv-qualified) T.
7204   if (!AllowResultConversion &&
7205       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7206     return;
7207 
7208   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7209   // operator is only a candidate if its return type is the target type or
7210   // can be converted to the target type with a qualification conversion.
7211   //
7212   // FIXME: Include such functions in the candidate list and explain why we
7213   // can't select them.
7214   if (Conversion->isExplicit() &&
7215       !isAllowableExplicitConversion(*this, ConvType, ToType,
7216                                      AllowObjCConversionOnExplicit))
7217     return;
7218 
7219   // Overload resolution is always an unevaluated context.
7220   EnterExpressionEvaluationContext Unevaluated(
7221       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7222 
7223   // Add this candidate
7224   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7225   Candidate.FoundDecl = FoundDecl;
7226   Candidate.Function = Conversion;
7227   Candidate.IsSurrogate = false;
7228   Candidate.IgnoreObjectArgument = false;
7229   Candidate.FinalConversion.setAsIdentityConversion();
7230   Candidate.FinalConversion.setFromType(ConvType);
7231   Candidate.FinalConversion.setAllToTypes(ToType);
7232   Candidate.Viable = true;
7233   Candidate.ExplicitCallArguments = 1;
7234 
7235   // Explicit functions are not actually candidates at all if we're not
7236   // allowing them in this context, but keep them around so we can point
7237   // to them in diagnostics.
7238   if (!AllowExplicit && Conversion->isExplicit()) {
7239     Candidate.Viable = false;
7240     Candidate.FailureKind = ovl_fail_explicit;
7241     return;
7242   }
7243 
7244   // C++ [over.match.funcs]p4:
7245   //   For conversion functions, the function is considered to be a member of
7246   //   the class of the implicit implied object argument for the purpose of
7247   //   defining the type of the implicit object parameter.
7248   //
7249   // Determine the implicit conversion sequence for the implicit
7250   // object parameter.
7251   QualType ImplicitParamType = From->getType();
7252   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7253     ImplicitParamType = FromPtrType->getPointeeType();
7254   CXXRecordDecl *ConversionContext
7255     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7256 
7257   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7258       *this, CandidateSet.getLocation(), From->getType(),
7259       From->Classify(Context), Conversion, ConversionContext);
7260 
7261   if (Candidate.Conversions[0].isBad()) {
7262     Candidate.Viable = false;
7263     Candidate.FailureKind = ovl_fail_bad_conversion;
7264     return;
7265   }
7266 
7267   if (Conversion->getTrailingRequiresClause()) {
7268     ConstraintSatisfaction Satisfaction;
7269     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7270         !Satisfaction.IsSatisfied) {
7271       Candidate.Viable = false;
7272       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7273       return;
7274     }
7275   }
7276 
7277   // We won't go through a user-defined type conversion function to convert a
7278   // derived to base as such conversions are given Conversion Rank. They only
7279   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7280   QualType FromCanon
7281     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7282   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7283   if (FromCanon == ToCanon ||
7284       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7285     Candidate.Viable = false;
7286     Candidate.FailureKind = ovl_fail_trivial_conversion;
7287     return;
7288   }
7289 
7290   // To determine what the conversion from the result of calling the
7291   // conversion function to the type we're eventually trying to
7292   // convert to (ToType), we need to synthesize a call to the
7293   // conversion function and attempt copy initialization from it. This
7294   // makes sure that we get the right semantics with respect to
7295   // lvalues/rvalues and the type. Fortunately, we can allocate this
7296   // call on the stack and we don't need its arguments to be
7297   // well-formed.
7298   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7299                             VK_LValue, From->getBeginLoc());
7300   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7301                                 Context.getPointerType(Conversion->getType()),
7302                                 CK_FunctionToPointerDecay, &ConversionRef,
7303                                 VK_RValue, FPOptionsOverride());
7304 
7305   QualType ConversionType = Conversion->getConversionType();
7306   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7307     Candidate.Viable = false;
7308     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7309     return;
7310   }
7311 
7312   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7313 
7314   // Note that it is safe to allocate CallExpr on the stack here because
7315   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7316   // allocator).
7317   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7318 
7319   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7320   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7321       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7322 
7323   ImplicitConversionSequence ICS =
7324       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7325                             /*SuppressUserConversions=*/true,
7326                             /*InOverloadResolution=*/false,
7327                             /*AllowObjCWritebackConversion=*/false);
7328 
7329   switch (ICS.getKind()) {
7330   case ImplicitConversionSequence::StandardConversion:
7331     Candidate.FinalConversion = ICS.Standard;
7332 
7333     // C++ [over.ics.user]p3:
7334     //   If the user-defined conversion is specified by a specialization of a
7335     //   conversion function template, the second standard conversion sequence
7336     //   shall have exact match rank.
7337     if (Conversion->getPrimaryTemplate() &&
7338         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7339       Candidate.Viable = false;
7340       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7341       return;
7342     }
7343 
7344     // C++0x [dcl.init.ref]p5:
7345     //    In the second case, if the reference is an rvalue reference and
7346     //    the second standard conversion sequence of the user-defined
7347     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7348     //    program is ill-formed.
7349     if (ToType->isRValueReferenceType() &&
7350         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7351       Candidate.Viable = false;
7352       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7353       return;
7354     }
7355     break;
7356 
7357   case ImplicitConversionSequence::BadConversion:
7358     Candidate.Viable = false;
7359     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7360     return;
7361 
7362   default:
7363     llvm_unreachable(
7364            "Can only end up with a standard conversion sequence or failure");
7365   }
7366 
7367   if (EnableIfAttr *FailedAttr =
7368           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7369     Candidate.Viable = false;
7370     Candidate.FailureKind = ovl_fail_enable_if;
7371     Candidate.DeductionFailure.Data = FailedAttr;
7372     return;
7373   }
7374 
7375   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7376       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7377     Candidate.Viable = false;
7378     Candidate.FailureKind = ovl_non_default_multiversion_function;
7379   }
7380 }
7381 
7382 /// Adds a conversion function template specialization
7383 /// candidate to the overload set, using template argument deduction
7384 /// to deduce the template arguments of the conversion function
7385 /// template from the type that we are converting to (C++
7386 /// [temp.deduct.conv]).
7387 void Sema::AddTemplateConversionCandidate(
7388     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7389     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7390     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7391     bool AllowExplicit, bool AllowResultConversion) {
7392   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7393          "Only conversion function templates permitted here");
7394 
7395   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7396     return;
7397 
7398   // If the function template has a non-dependent explicit specification,
7399   // exclude it now if appropriate; we are not permitted to perform deduction
7400   // and substitution in this case.
7401   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7402     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7403     Candidate.FoundDecl = FoundDecl;
7404     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7405     Candidate.Viable = false;
7406     Candidate.FailureKind = ovl_fail_explicit;
7407     return;
7408   }
7409 
7410   TemplateDeductionInfo Info(CandidateSet.getLocation());
7411   CXXConversionDecl *Specialization = nullptr;
7412   if (TemplateDeductionResult Result
7413         = DeduceTemplateArguments(FunctionTemplate, ToType,
7414                                   Specialization, Info)) {
7415     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7416     Candidate.FoundDecl = FoundDecl;
7417     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7418     Candidate.Viable = false;
7419     Candidate.FailureKind = ovl_fail_bad_deduction;
7420     Candidate.IsSurrogate = false;
7421     Candidate.IgnoreObjectArgument = false;
7422     Candidate.ExplicitCallArguments = 1;
7423     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7424                                                           Info);
7425     return;
7426   }
7427 
7428   // Add the conversion function template specialization produced by
7429   // template argument deduction as a candidate.
7430   assert(Specialization && "Missing function template specialization?");
7431   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7432                          CandidateSet, AllowObjCConversionOnExplicit,
7433                          AllowExplicit, AllowResultConversion);
7434 }
7435 
7436 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7437 /// converts the given @c Object to a function pointer via the
7438 /// conversion function @c Conversion, and then attempts to call it
7439 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7440 /// the type of function that we'll eventually be calling.
7441 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7442                                  DeclAccessPair FoundDecl,
7443                                  CXXRecordDecl *ActingContext,
7444                                  const FunctionProtoType *Proto,
7445                                  Expr *Object,
7446                                  ArrayRef<Expr *> Args,
7447                                  OverloadCandidateSet& CandidateSet) {
7448   if (!CandidateSet.isNewCandidate(Conversion))
7449     return;
7450 
7451   // Overload resolution is always an unevaluated context.
7452   EnterExpressionEvaluationContext Unevaluated(
7453       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7454 
7455   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7456   Candidate.FoundDecl = FoundDecl;
7457   Candidate.Function = nullptr;
7458   Candidate.Surrogate = Conversion;
7459   Candidate.Viable = true;
7460   Candidate.IsSurrogate = true;
7461   Candidate.IgnoreObjectArgument = false;
7462   Candidate.ExplicitCallArguments = Args.size();
7463 
7464   // Determine the implicit conversion sequence for the implicit
7465   // object parameter.
7466   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7467       *this, CandidateSet.getLocation(), Object->getType(),
7468       Object->Classify(Context), Conversion, ActingContext);
7469   if (ObjectInit.isBad()) {
7470     Candidate.Viable = false;
7471     Candidate.FailureKind = ovl_fail_bad_conversion;
7472     Candidate.Conversions[0] = ObjectInit;
7473     return;
7474   }
7475 
7476   // The first conversion is actually a user-defined conversion whose
7477   // first conversion is ObjectInit's standard conversion (which is
7478   // effectively a reference binding). Record it as such.
7479   Candidate.Conversions[0].setUserDefined();
7480   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7481   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7482   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7483   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7484   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7485   Candidate.Conversions[0].UserDefined.After
7486     = Candidate.Conversions[0].UserDefined.Before;
7487   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7488 
7489   // Find the
7490   unsigned NumParams = Proto->getNumParams();
7491 
7492   // (C++ 13.3.2p2): A candidate function having fewer than m
7493   // parameters is viable only if it has an ellipsis in its parameter
7494   // list (8.3.5).
7495   if (Args.size() > NumParams && !Proto->isVariadic()) {
7496     Candidate.Viable = false;
7497     Candidate.FailureKind = ovl_fail_too_many_arguments;
7498     return;
7499   }
7500 
7501   // Function types don't have any default arguments, so just check if
7502   // we have enough arguments.
7503   if (Args.size() < NumParams) {
7504     // Not enough arguments.
7505     Candidate.Viable = false;
7506     Candidate.FailureKind = ovl_fail_too_few_arguments;
7507     return;
7508   }
7509 
7510   // Determine the implicit conversion sequences for each of the
7511   // arguments.
7512   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7513     if (ArgIdx < NumParams) {
7514       // (C++ 13.3.2p3): for F to be a viable function, there shall
7515       // exist for each argument an implicit conversion sequence
7516       // (13.3.3.1) that converts that argument to the corresponding
7517       // parameter of F.
7518       QualType ParamType = Proto->getParamType(ArgIdx);
7519       Candidate.Conversions[ArgIdx + 1]
7520         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7521                                 /*SuppressUserConversions=*/false,
7522                                 /*InOverloadResolution=*/false,
7523                                 /*AllowObjCWritebackConversion=*/
7524                                   getLangOpts().ObjCAutoRefCount);
7525       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7526         Candidate.Viable = false;
7527         Candidate.FailureKind = ovl_fail_bad_conversion;
7528         return;
7529       }
7530     } else {
7531       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7532       // argument for which there is no corresponding parameter is
7533       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7534       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7535     }
7536   }
7537 
7538   if (EnableIfAttr *FailedAttr =
7539           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7540     Candidate.Viable = false;
7541     Candidate.FailureKind = ovl_fail_enable_if;
7542     Candidate.DeductionFailure.Data = FailedAttr;
7543     return;
7544   }
7545 }
7546 
7547 /// Add all of the non-member operator function declarations in the given
7548 /// function set to the overload candidate set.
7549 void Sema::AddNonMemberOperatorCandidates(
7550     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7551     OverloadCandidateSet &CandidateSet,
7552     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7553   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7554     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7555     ArrayRef<Expr *> FunctionArgs = Args;
7556 
7557     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7558     FunctionDecl *FD =
7559         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7560 
7561     // Don't consider rewritten functions if we're not rewriting.
7562     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7563       continue;
7564 
7565     assert(!isa<CXXMethodDecl>(FD) &&
7566            "unqualified operator lookup found a member function");
7567 
7568     if (FunTmpl) {
7569       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7570                                    FunctionArgs, CandidateSet);
7571       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7572         AddTemplateOverloadCandidate(
7573             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7574             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7575             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7576     } else {
7577       if (ExplicitTemplateArgs)
7578         continue;
7579       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7580       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7581         AddOverloadCandidate(FD, F.getPair(),
7582                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7583                              false, false, true, false, ADLCallKind::NotADL,
7584                              None, OverloadCandidateParamOrder::Reversed);
7585     }
7586   }
7587 }
7588 
7589 /// Add overload candidates for overloaded operators that are
7590 /// member functions.
7591 ///
7592 /// Add the overloaded operator candidates that are member functions
7593 /// for the operator Op that was used in an operator expression such
7594 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7595 /// CandidateSet will store the added overload candidates. (C++
7596 /// [over.match.oper]).
7597 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7598                                        SourceLocation OpLoc,
7599                                        ArrayRef<Expr *> Args,
7600                                        OverloadCandidateSet &CandidateSet,
7601                                        OverloadCandidateParamOrder PO) {
7602   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7603 
7604   // C++ [over.match.oper]p3:
7605   //   For a unary operator @ with an operand of a type whose
7606   //   cv-unqualified version is T1, and for a binary operator @ with
7607   //   a left operand of a type whose cv-unqualified version is T1 and
7608   //   a right operand of a type whose cv-unqualified version is T2,
7609   //   three sets of candidate functions, designated member
7610   //   candidates, non-member candidates and built-in candidates, are
7611   //   constructed as follows:
7612   QualType T1 = Args[0]->getType();
7613 
7614   //     -- If T1 is a complete class type or a class currently being
7615   //        defined, the set of member candidates is the result of the
7616   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7617   //        the set of member candidates is empty.
7618   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7619     // Complete the type if it can be completed.
7620     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7621       return;
7622     // If the type is neither complete nor being defined, bail out now.
7623     if (!T1Rec->getDecl()->getDefinition())
7624       return;
7625 
7626     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7627     LookupQualifiedName(Operators, T1Rec->getDecl());
7628     Operators.suppressDiagnostics();
7629 
7630     for (LookupResult::iterator Oper = Operators.begin(),
7631                              OperEnd = Operators.end();
7632          Oper != OperEnd;
7633          ++Oper)
7634       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7635                          Args[0]->Classify(Context), Args.slice(1),
7636                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7637   }
7638 }
7639 
7640 /// AddBuiltinCandidate - Add a candidate for a built-in
7641 /// operator. ResultTy and ParamTys are the result and parameter types
7642 /// of the built-in candidate, respectively. Args and NumArgs are the
7643 /// arguments being passed to the candidate. IsAssignmentOperator
7644 /// should be true when this built-in candidate is an assignment
7645 /// operator. NumContextualBoolArguments is the number of arguments
7646 /// (at the beginning of the argument list) that will be contextually
7647 /// converted to bool.
7648 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7649                                OverloadCandidateSet& CandidateSet,
7650                                bool IsAssignmentOperator,
7651                                unsigned NumContextualBoolArguments) {
7652   // Overload resolution is always an unevaluated context.
7653   EnterExpressionEvaluationContext Unevaluated(
7654       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7655 
7656   // Add this candidate
7657   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7658   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7659   Candidate.Function = nullptr;
7660   Candidate.IsSurrogate = false;
7661   Candidate.IgnoreObjectArgument = false;
7662   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7663 
7664   // Determine the implicit conversion sequences for each of the
7665   // arguments.
7666   Candidate.Viable = true;
7667   Candidate.ExplicitCallArguments = Args.size();
7668   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7669     // C++ [over.match.oper]p4:
7670     //   For the built-in assignment operators, conversions of the
7671     //   left operand are restricted as follows:
7672     //     -- no temporaries are introduced to hold the left operand, and
7673     //     -- no user-defined conversions are applied to the left
7674     //        operand to achieve a type match with the left-most
7675     //        parameter of a built-in candidate.
7676     //
7677     // We block these conversions by turning off user-defined
7678     // conversions, since that is the only way that initialization of
7679     // a reference to a non-class type can occur from something that
7680     // is not of the same type.
7681     if (ArgIdx < NumContextualBoolArguments) {
7682       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7683              "Contextual conversion to bool requires bool type");
7684       Candidate.Conversions[ArgIdx]
7685         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7686     } else {
7687       Candidate.Conversions[ArgIdx]
7688         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7689                                 ArgIdx == 0 && IsAssignmentOperator,
7690                                 /*InOverloadResolution=*/false,
7691                                 /*AllowObjCWritebackConversion=*/
7692                                   getLangOpts().ObjCAutoRefCount);
7693     }
7694     if (Candidate.Conversions[ArgIdx].isBad()) {
7695       Candidate.Viable = false;
7696       Candidate.FailureKind = ovl_fail_bad_conversion;
7697       break;
7698     }
7699   }
7700 }
7701 
7702 namespace {
7703 
7704 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7705 /// candidate operator functions for built-in operators (C++
7706 /// [over.built]). The types are separated into pointer types and
7707 /// enumeration types.
7708 class BuiltinCandidateTypeSet  {
7709   /// TypeSet - A set of types.
7710   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7711                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7712 
7713   /// PointerTypes - The set of pointer types that will be used in the
7714   /// built-in candidates.
7715   TypeSet PointerTypes;
7716 
7717   /// MemberPointerTypes - The set of member pointer types that will be
7718   /// used in the built-in candidates.
7719   TypeSet MemberPointerTypes;
7720 
7721   /// EnumerationTypes - The set of enumeration types that will be
7722   /// used in the built-in candidates.
7723   TypeSet EnumerationTypes;
7724 
7725   /// The set of vector types that will be used in the built-in
7726   /// candidates.
7727   TypeSet VectorTypes;
7728 
7729   /// The set of matrix types that will be used in the built-in
7730   /// candidates.
7731   TypeSet MatrixTypes;
7732 
7733   /// A flag indicating non-record types are viable candidates
7734   bool HasNonRecordTypes;
7735 
7736   /// A flag indicating whether either arithmetic or enumeration types
7737   /// were present in the candidate set.
7738   bool HasArithmeticOrEnumeralTypes;
7739 
7740   /// A flag indicating whether the nullptr type was present in the
7741   /// candidate set.
7742   bool HasNullPtrType;
7743 
7744   /// Sema - The semantic analysis instance where we are building the
7745   /// candidate type set.
7746   Sema &SemaRef;
7747 
7748   /// Context - The AST context in which we will build the type sets.
7749   ASTContext &Context;
7750 
7751   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7752                                                const Qualifiers &VisibleQuals);
7753   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7754 
7755 public:
7756   /// iterator - Iterates through the types that are part of the set.
7757   typedef TypeSet::iterator iterator;
7758 
7759   BuiltinCandidateTypeSet(Sema &SemaRef)
7760     : HasNonRecordTypes(false),
7761       HasArithmeticOrEnumeralTypes(false),
7762       HasNullPtrType(false),
7763       SemaRef(SemaRef),
7764       Context(SemaRef.Context) { }
7765 
7766   void AddTypesConvertedFrom(QualType Ty,
7767                              SourceLocation Loc,
7768                              bool AllowUserConversions,
7769                              bool AllowExplicitConversions,
7770                              const Qualifiers &VisibleTypeConversionsQuals);
7771 
7772   /// pointer_begin - First pointer type found;
7773   iterator pointer_begin() { return PointerTypes.begin(); }
7774 
7775   /// pointer_end - Past the last pointer type found;
7776   iterator pointer_end() { return PointerTypes.end(); }
7777 
7778   /// member_pointer_begin - First member pointer type found;
7779   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7780 
7781   /// member_pointer_end - Past the last member pointer type found;
7782   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7783 
7784   /// enumeration_begin - First enumeration type found;
7785   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7786 
7787   /// enumeration_end - Past the last enumeration type found;
7788   iterator enumeration_end() { return EnumerationTypes.end(); }
7789 
7790   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7791 
7792   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7793 
7794   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7795   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7796   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7797   bool hasNullPtrType() const { return HasNullPtrType; }
7798 };
7799 
7800 } // end anonymous namespace
7801 
7802 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7803 /// the set of pointer types along with any more-qualified variants of
7804 /// that type. For example, if @p Ty is "int const *", this routine
7805 /// will add "int const *", "int const volatile *", "int const
7806 /// restrict *", and "int const volatile restrict *" to the set of
7807 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7808 /// false otherwise.
7809 ///
7810 /// FIXME: what to do about extended qualifiers?
7811 bool
7812 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7813                                              const Qualifiers &VisibleQuals) {
7814 
7815   // Insert this type.
7816   if (!PointerTypes.insert(Ty))
7817     return false;
7818 
7819   QualType PointeeTy;
7820   const PointerType *PointerTy = Ty->getAs<PointerType>();
7821   bool buildObjCPtr = false;
7822   if (!PointerTy) {
7823     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7824     PointeeTy = PTy->getPointeeType();
7825     buildObjCPtr = true;
7826   } else {
7827     PointeeTy = PointerTy->getPointeeType();
7828   }
7829 
7830   // Don't add qualified variants of arrays. For one, they're not allowed
7831   // (the qualifier would sink to the element type), and for another, the
7832   // only overload situation where it matters is subscript or pointer +- int,
7833   // and those shouldn't have qualifier variants anyway.
7834   if (PointeeTy->isArrayType())
7835     return true;
7836 
7837   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7838   bool hasVolatile = VisibleQuals.hasVolatile();
7839   bool hasRestrict = VisibleQuals.hasRestrict();
7840 
7841   // Iterate through all strict supersets of BaseCVR.
7842   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7843     if ((CVR | BaseCVR) != CVR) continue;
7844     // Skip over volatile if no volatile found anywhere in the types.
7845     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7846 
7847     // Skip over restrict if no restrict found anywhere in the types, or if
7848     // the type cannot be restrict-qualified.
7849     if ((CVR & Qualifiers::Restrict) &&
7850         (!hasRestrict ||
7851          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7852       continue;
7853 
7854     // Build qualified pointee type.
7855     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7856 
7857     // Build qualified pointer type.
7858     QualType QPointerTy;
7859     if (!buildObjCPtr)
7860       QPointerTy = Context.getPointerType(QPointeeTy);
7861     else
7862       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7863 
7864     // Insert qualified pointer type.
7865     PointerTypes.insert(QPointerTy);
7866   }
7867 
7868   return true;
7869 }
7870 
7871 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7872 /// to the set of pointer types along with any more-qualified variants of
7873 /// that type. For example, if @p Ty is "int const *", this routine
7874 /// will add "int const *", "int const volatile *", "int const
7875 /// restrict *", and "int const volatile restrict *" to the set of
7876 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7877 /// false otherwise.
7878 ///
7879 /// FIXME: what to do about extended qualifiers?
7880 bool
7881 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7882     QualType Ty) {
7883   // Insert this type.
7884   if (!MemberPointerTypes.insert(Ty))
7885     return false;
7886 
7887   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7888   assert(PointerTy && "type was not a member pointer type!");
7889 
7890   QualType PointeeTy = PointerTy->getPointeeType();
7891   // Don't add qualified variants of arrays. For one, they're not allowed
7892   // (the qualifier would sink to the element type), and for another, the
7893   // only overload situation where it matters is subscript or pointer +- int,
7894   // and those shouldn't have qualifier variants anyway.
7895   if (PointeeTy->isArrayType())
7896     return true;
7897   const Type *ClassTy = PointerTy->getClass();
7898 
7899   // Iterate through all strict supersets of the pointee type's CVR
7900   // qualifiers.
7901   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7902   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7903     if ((CVR | BaseCVR) != CVR) continue;
7904 
7905     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7906     MemberPointerTypes.insert(
7907       Context.getMemberPointerType(QPointeeTy, ClassTy));
7908   }
7909 
7910   return true;
7911 }
7912 
7913 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7914 /// Ty can be implicit converted to the given set of @p Types. We're
7915 /// primarily interested in pointer types and enumeration types. We also
7916 /// take member pointer types, for the conditional operator.
7917 /// AllowUserConversions is true if we should look at the conversion
7918 /// functions of a class type, and AllowExplicitConversions if we
7919 /// should also include the explicit conversion functions of a class
7920 /// type.
7921 void
7922 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7923                                                SourceLocation Loc,
7924                                                bool AllowUserConversions,
7925                                                bool AllowExplicitConversions,
7926                                                const Qualifiers &VisibleQuals) {
7927   // Only deal with canonical types.
7928   Ty = Context.getCanonicalType(Ty);
7929 
7930   // Look through reference types; they aren't part of the type of an
7931   // expression for the purposes of conversions.
7932   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7933     Ty = RefTy->getPointeeType();
7934 
7935   // If we're dealing with an array type, decay to the pointer.
7936   if (Ty->isArrayType())
7937     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7938 
7939   // Otherwise, we don't care about qualifiers on the type.
7940   Ty = Ty.getLocalUnqualifiedType();
7941 
7942   // Flag if we ever add a non-record type.
7943   const RecordType *TyRec = Ty->getAs<RecordType>();
7944   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7945 
7946   // Flag if we encounter an arithmetic type.
7947   HasArithmeticOrEnumeralTypes =
7948     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7949 
7950   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7951     PointerTypes.insert(Ty);
7952   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7953     // Insert our type, and its more-qualified variants, into the set
7954     // of types.
7955     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7956       return;
7957   } else if (Ty->isMemberPointerType()) {
7958     // Member pointers are far easier, since the pointee can't be converted.
7959     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7960       return;
7961   } else if (Ty->isEnumeralType()) {
7962     HasArithmeticOrEnumeralTypes = true;
7963     EnumerationTypes.insert(Ty);
7964   } else if (Ty->isVectorType()) {
7965     // We treat vector types as arithmetic types in many contexts as an
7966     // extension.
7967     HasArithmeticOrEnumeralTypes = true;
7968     VectorTypes.insert(Ty);
7969   } else if (Ty->isMatrixType()) {
7970     // Similar to vector types, we treat vector types as arithmetic types in
7971     // many contexts as an extension.
7972     HasArithmeticOrEnumeralTypes = true;
7973     MatrixTypes.insert(Ty);
7974   } else if (Ty->isNullPtrType()) {
7975     HasNullPtrType = true;
7976   } else if (AllowUserConversions && TyRec) {
7977     // No conversion functions in incomplete types.
7978     if (!SemaRef.isCompleteType(Loc, Ty))
7979       return;
7980 
7981     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7982     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7983       if (isa<UsingShadowDecl>(D))
7984         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7985 
7986       // Skip conversion function templates; they don't tell us anything
7987       // about which builtin types we can convert to.
7988       if (isa<FunctionTemplateDecl>(D))
7989         continue;
7990 
7991       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7992       if (AllowExplicitConversions || !Conv->isExplicit()) {
7993         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7994                               VisibleQuals);
7995       }
7996     }
7997   }
7998 }
7999 /// Helper function for adjusting address spaces for the pointer or reference
8000 /// operands of builtin operators depending on the argument.
8001 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8002                                                         Expr *Arg) {
8003   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8004 }
8005 
8006 /// Helper function for AddBuiltinOperatorCandidates() that adds
8007 /// the volatile- and non-volatile-qualified assignment operators for the
8008 /// given type to the candidate set.
8009 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8010                                                    QualType T,
8011                                                    ArrayRef<Expr *> Args,
8012                                     OverloadCandidateSet &CandidateSet) {
8013   QualType ParamTypes[2];
8014 
8015   // T& operator=(T&, T)
8016   ParamTypes[0] = S.Context.getLValueReferenceType(
8017       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8018   ParamTypes[1] = T;
8019   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8020                         /*IsAssignmentOperator=*/true);
8021 
8022   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8023     // volatile T& operator=(volatile T&, T)
8024     ParamTypes[0] = S.Context.getLValueReferenceType(
8025         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8026                                                 Args[0]));
8027     ParamTypes[1] = T;
8028     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8029                           /*IsAssignmentOperator=*/true);
8030   }
8031 }
8032 
8033 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8034 /// if any, found in visible type conversion functions found in ArgExpr's type.
8035 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8036     Qualifiers VRQuals;
8037     const RecordType *TyRec;
8038     if (const MemberPointerType *RHSMPType =
8039         ArgExpr->getType()->getAs<MemberPointerType>())
8040       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8041     else
8042       TyRec = ArgExpr->getType()->getAs<RecordType>();
8043     if (!TyRec) {
8044       // Just to be safe, assume the worst case.
8045       VRQuals.addVolatile();
8046       VRQuals.addRestrict();
8047       return VRQuals;
8048     }
8049 
8050     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8051     if (!ClassDecl->hasDefinition())
8052       return VRQuals;
8053 
8054     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8055       if (isa<UsingShadowDecl>(D))
8056         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8057       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8058         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8059         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8060           CanTy = ResTypeRef->getPointeeType();
8061         // Need to go down the pointer/mempointer chain and add qualifiers
8062         // as see them.
8063         bool done = false;
8064         while (!done) {
8065           if (CanTy.isRestrictQualified())
8066             VRQuals.addRestrict();
8067           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8068             CanTy = ResTypePtr->getPointeeType();
8069           else if (const MemberPointerType *ResTypeMPtr =
8070                 CanTy->getAs<MemberPointerType>())
8071             CanTy = ResTypeMPtr->getPointeeType();
8072           else
8073             done = true;
8074           if (CanTy.isVolatileQualified())
8075             VRQuals.addVolatile();
8076           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8077             return VRQuals;
8078         }
8079       }
8080     }
8081     return VRQuals;
8082 }
8083 
8084 namespace {
8085 
8086 /// Helper class to manage the addition of builtin operator overload
8087 /// candidates. It provides shared state and utility methods used throughout
8088 /// the process, as well as a helper method to add each group of builtin
8089 /// operator overloads from the standard to a candidate set.
8090 class BuiltinOperatorOverloadBuilder {
8091   // Common instance state available to all overload candidate addition methods.
8092   Sema &S;
8093   ArrayRef<Expr *> Args;
8094   Qualifiers VisibleTypeConversionsQuals;
8095   bool HasArithmeticOrEnumeralCandidateType;
8096   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8097   OverloadCandidateSet &CandidateSet;
8098 
8099   static constexpr int ArithmeticTypesCap = 24;
8100   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8101 
8102   // Define some indices used to iterate over the arithmetic types in
8103   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8104   // types are that preserved by promotion (C++ [over.built]p2).
8105   unsigned FirstIntegralType,
8106            LastIntegralType;
8107   unsigned FirstPromotedIntegralType,
8108            LastPromotedIntegralType;
8109   unsigned FirstPromotedArithmeticType,
8110            LastPromotedArithmeticType;
8111   unsigned NumArithmeticTypes;
8112 
8113   void InitArithmeticTypes() {
8114     // Start of promoted types.
8115     FirstPromotedArithmeticType = 0;
8116     ArithmeticTypes.push_back(S.Context.FloatTy);
8117     ArithmeticTypes.push_back(S.Context.DoubleTy);
8118     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8119     if (S.Context.getTargetInfo().hasFloat128Type())
8120       ArithmeticTypes.push_back(S.Context.Float128Ty);
8121 
8122     // Start of integral types.
8123     FirstIntegralType = ArithmeticTypes.size();
8124     FirstPromotedIntegralType = ArithmeticTypes.size();
8125     ArithmeticTypes.push_back(S.Context.IntTy);
8126     ArithmeticTypes.push_back(S.Context.LongTy);
8127     ArithmeticTypes.push_back(S.Context.LongLongTy);
8128     if (S.Context.getTargetInfo().hasInt128Type())
8129       ArithmeticTypes.push_back(S.Context.Int128Ty);
8130     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8131     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8132     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8133     if (S.Context.getTargetInfo().hasInt128Type())
8134       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8135     LastPromotedIntegralType = ArithmeticTypes.size();
8136     LastPromotedArithmeticType = ArithmeticTypes.size();
8137     // End of promoted types.
8138 
8139     ArithmeticTypes.push_back(S.Context.BoolTy);
8140     ArithmeticTypes.push_back(S.Context.CharTy);
8141     ArithmeticTypes.push_back(S.Context.WCharTy);
8142     if (S.Context.getLangOpts().Char8)
8143       ArithmeticTypes.push_back(S.Context.Char8Ty);
8144     ArithmeticTypes.push_back(S.Context.Char16Ty);
8145     ArithmeticTypes.push_back(S.Context.Char32Ty);
8146     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8147     ArithmeticTypes.push_back(S.Context.ShortTy);
8148     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8149     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8150     LastIntegralType = ArithmeticTypes.size();
8151     NumArithmeticTypes = ArithmeticTypes.size();
8152     // End of integral types.
8153     // FIXME: What about complex? What about half?
8154 
8155     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8156            "Enough inline storage for all arithmetic types.");
8157   }
8158 
8159   /// Helper method to factor out the common pattern of adding overloads
8160   /// for '++' and '--' builtin operators.
8161   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8162                                            bool HasVolatile,
8163                                            bool HasRestrict) {
8164     QualType ParamTypes[2] = {
8165       S.Context.getLValueReferenceType(CandidateTy),
8166       S.Context.IntTy
8167     };
8168 
8169     // Non-volatile version.
8170     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8171 
8172     // Use a heuristic to reduce number of builtin candidates in the set:
8173     // add volatile version only if there are conversions to a volatile type.
8174     if (HasVolatile) {
8175       ParamTypes[0] =
8176         S.Context.getLValueReferenceType(
8177           S.Context.getVolatileType(CandidateTy));
8178       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8179     }
8180 
8181     // Add restrict version only if there are conversions to a restrict type
8182     // and our candidate type is a non-restrict-qualified pointer.
8183     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8184         !CandidateTy.isRestrictQualified()) {
8185       ParamTypes[0]
8186         = S.Context.getLValueReferenceType(
8187             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8188       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8189 
8190       if (HasVolatile) {
8191         ParamTypes[0]
8192           = S.Context.getLValueReferenceType(
8193               S.Context.getCVRQualifiedType(CandidateTy,
8194                                             (Qualifiers::Volatile |
8195                                              Qualifiers::Restrict)));
8196         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8197       }
8198     }
8199 
8200   }
8201 
8202   /// Helper to add an overload candidate for a binary builtin with types \p L
8203   /// and \p R.
8204   void AddCandidate(QualType L, QualType R) {
8205     QualType LandR[2] = {L, R};
8206     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8207   }
8208 
8209 public:
8210   BuiltinOperatorOverloadBuilder(
8211     Sema &S, ArrayRef<Expr *> Args,
8212     Qualifiers VisibleTypeConversionsQuals,
8213     bool HasArithmeticOrEnumeralCandidateType,
8214     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8215     OverloadCandidateSet &CandidateSet)
8216     : S(S), Args(Args),
8217       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8218       HasArithmeticOrEnumeralCandidateType(
8219         HasArithmeticOrEnumeralCandidateType),
8220       CandidateTypes(CandidateTypes),
8221       CandidateSet(CandidateSet) {
8222 
8223     InitArithmeticTypes();
8224   }
8225 
8226   // Increment is deprecated for bool since C++17.
8227   //
8228   // C++ [over.built]p3:
8229   //
8230   //   For every pair (T, VQ), where T is an arithmetic type other
8231   //   than bool, and VQ is either volatile or empty, there exist
8232   //   candidate operator functions of the form
8233   //
8234   //       VQ T&      operator++(VQ T&);
8235   //       T          operator++(VQ T&, int);
8236   //
8237   // C++ [over.built]p4:
8238   //
8239   //   For every pair (T, VQ), where T is an arithmetic type other
8240   //   than bool, and VQ is either volatile or empty, there exist
8241   //   candidate operator functions of the form
8242   //
8243   //       VQ T&      operator--(VQ T&);
8244   //       T          operator--(VQ T&, int);
8245   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8246     if (!HasArithmeticOrEnumeralCandidateType)
8247       return;
8248 
8249     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8250       const auto TypeOfT = ArithmeticTypes[Arith];
8251       if (TypeOfT == S.Context.BoolTy) {
8252         if (Op == OO_MinusMinus)
8253           continue;
8254         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8255           continue;
8256       }
8257       addPlusPlusMinusMinusStyleOverloads(
8258         TypeOfT,
8259         VisibleTypeConversionsQuals.hasVolatile(),
8260         VisibleTypeConversionsQuals.hasRestrict());
8261     }
8262   }
8263 
8264   // C++ [over.built]p5:
8265   //
8266   //   For every pair (T, VQ), where T is a cv-qualified or
8267   //   cv-unqualified object type, and VQ is either volatile or
8268   //   empty, there exist candidate operator functions of the form
8269   //
8270   //       T*VQ&      operator++(T*VQ&);
8271   //       T*VQ&      operator--(T*VQ&);
8272   //       T*         operator++(T*VQ&, int);
8273   //       T*         operator--(T*VQ&, int);
8274   void addPlusPlusMinusMinusPointerOverloads() {
8275     for (BuiltinCandidateTypeSet::iterator
8276               Ptr = CandidateTypes[0].pointer_begin(),
8277            PtrEnd = CandidateTypes[0].pointer_end();
8278          Ptr != PtrEnd; ++Ptr) {
8279       // Skip pointer types that aren't pointers to object types.
8280       if (!(*Ptr)->getPointeeType()->isObjectType())
8281         continue;
8282 
8283       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8284         (!(*Ptr).isVolatileQualified() &&
8285          VisibleTypeConversionsQuals.hasVolatile()),
8286         (!(*Ptr).isRestrictQualified() &&
8287          VisibleTypeConversionsQuals.hasRestrict()));
8288     }
8289   }
8290 
8291   // C++ [over.built]p6:
8292   //   For every cv-qualified or cv-unqualified object type T, there
8293   //   exist candidate operator functions of the form
8294   //
8295   //       T&         operator*(T*);
8296   //
8297   // C++ [over.built]p7:
8298   //   For every function type T that does not have cv-qualifiers or a
8299   //   ref-qualifier, there exist candidate operator functions of the form
8300   //       T&         operator*(T*);
8301   void addUnaryStarPointerOverloads() {
8302     for (BuiltinCandidateTypeSet::iterator
8303               Ptr = CandidateTypes[0].pointer_begin(),
8304            PtrEnd = CandidateTypes[0].pointer_end();
8305          Ptr != PtrEnd; ++Ptr) {
8306       QualType ParamTy = *Ptr;
8307       QualType PointeeTy = ParamTy->getPointeeType();
8308       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8309         continue;
8310 
8311       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8312         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8313           continue;
8314 
8315       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8316     }
8317   }
8318 
8319   // C++ [over.built]p9:
8320   //  For every promoted arithmetic type T, there exist candidate
8321   //  operator functions of the form
8322   //
8323   //       T         operator+(T);
8324   //       T         operator-(T);
8325   void addUnaryPlusOrMinusArithmeticOverloads() {
8326     if (!HasArithmeticOrEnumeralCandidateType)
8327       return;
8328 
8329     for (unsigned Arith = FirstPromotedArithmeticType;
8330          Arith < LastPromotedArithmeticType; ++Arith) {
8331       QualType ArithTy = ArithmeticTypes[Arith];
8332       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8333     }
8334 
8335     // Extension: We also add these operators for vector types.
8336     for (QualType VecTy : CandidateTypes[0].vector_types())
8337       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8338   }
8339 
8340   // C++ [over.built]p8:
8341   //   For every type T, there exist candidate operator functions of
8342   //   the form
8343   //
8344   //       T*         operator+(T*);
8345   void addUnaryPlusPointerOverloads() {
8346     for (BuiltinCandidateTypeSet::iterator
8347               Ptr = CandidateTypes[0].pointer_begin(),
8348            PtrEnd = CandidateTypes[0].pointer_end();
8349          Ptr != PtrEnd; ++Ptr) {
8350       QualType ParamTy = *Ptr;
8351       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8352     }
8353   }
8354 
8355   // C++ [over.built]p10:
8356   //   For every promoted integral type T, there exist candidate
8357   //   operator functions of the form
8358   //
8359   //        T         operator~(T);
8360   void addUnaryTildePromotedIntegralOverloads() {
8361     if (!HasArithmeticOrEnumeralCandidateType)
8362       return;
8363 
8364     for (unsigned Int = FirstPromotedIntegralType;
8365          Int < LastPromotedIntegralType; ++Int) {
8366       QualType IntTy = ArithmeticTypes[Int];
8367       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8368     }
8369 
8370     // Extension: We also add this operator for vector types.
8371     for (QualType VecTy : CandidateTypes[0].vector_types())
8372       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8373   }
8374 
8375   // C++ [over.match.oper]p16:
8376   //   For every pointer to member type T or type std::nullptr_t, there
8377   //   exist candidate operator functions of the form
8378   //
8379   //        bool operator==(T,T);
8380   //        bool operator!=(T,T);
8381   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8382     /// Set of (canonical) types that we've already handled.
8383     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8384 
8385     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8386       for (BuiltinCandidateTypeSet::iterator
8387                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8388              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8389            MemPtr != MemPtrEnd;
8390            ++MemPtr) {
8391         // Don't add the same builtin candidate twice.
8392         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8393           continue;
8394 
8395         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8396         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8397       }
8398 
8399       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8400         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8401         if (AddedTypes.insert(NullPtrTy).second) {
8402           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8403           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8404         }
8405       }
8406     }
8407   }
8408 
8409   // C++ [over.built]p15:
8410   //
8411   //   For every T, where T is an enumeration type or a pointer type,
8412   //   there exist candidate operator functions of the form
8413   //
8414   //        bool       operator<(T, T);
8415   //        bool       operator>(T, T);
8416   //        bool       operator<=(T, T);
8417   //        bool       operator>=(T, T);
8418   //        bool       operator==(T, T);
8419   //        bool       operator!=(T, T);
8420   //           R       operator<=>(T, T)
8421   void addGenericBinaryPointerOrEnumeralOverloads() {
8422     // C++ [over.match.oper]p3:
8423     //   [...]the built-in candidates include all of the candidate operator
8424     //   functions defined in 13.6 that, compared to the given operator, [...]
8425     //   do not have the same parameter-type-list as any non-template non-member
8426     //   candidate.
8427     //
8428     // Note that in practice, this only affects enumeration types because there
8429     // aren't any built-in candidates of record type, and a user-defined operator
8430     // must have an operand of record or enumeration type. Also, the only other
8431     // overloaded operator with enumeration arguments, operator=,
8432     // cannot be overloaded for enumeration types, so this is the only place
8433     // where we must suppress candidates like this.
8434     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8435       UserDefinedBinaryOperators;
8436 
8437     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8438       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8439           CandidateTypes[ArgIdx].enumeration_end()) {
8440         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8441                                          CEnd = CandidateSet.end();
8442              C != CEnd; ++C) {
8443           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8444             continue;
8445 
8446           if (C->Function->isFunctionTemplateSpecialization())
8447             continue;
8448 
8449           // We interpret "same parameter-type-list" as applying to the
8450           // "synthesized candidate, with the order of the two parameters
8451           // reversed", not to the original function.
8452           bool Reversed = C->isReversed();
8453           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8454                                         ->getType()
8455                                         .getUnqualifiedType();
8456           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8457                                          ->getType()
8458                                          .getUnqualifiedType();
8459 
8460           // Skip if either parameter isn't of enumeral type.
8461           if (!FirstParamType->isEnumeralType() ||
8462               !SecondParamType->isEnumeralType())
8463             continue;
8464 
8465           // Add this operator to the set of known user-defined operators.
8466           UserDefinedBinaryOperators.insert(
8467             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8468                            S.Context.getCanonicalType(SecondParamType)));
8469         }
8470       }
8471     }
8472 
8473     /// Set of (canonical) types that we've already handled.
8474     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8475 
8476     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8477       for (BuiltinCandidateTypeSet::iterator
8478                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8479              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8480            Ptr != PtrEnd; ++Ptr) {
8481         // Don't add the same builtin candidate twice.
8482         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8483           continue;
8484 
8485         QualType ParamTypes[2] = { *Ptr, *Ptr };
8486         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8487       }
8488       for (BuiltinCandidateTypeSet::iterator
8489                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8490              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8491            Enum != EnumEnd; ++Enum) {
8492         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8493 
8494         // Don't add the same builtin candidate twice, or if a user defined
8495         // candidate exists.
8496         if (!AddedTypes.insert(CanonType).second ||
8497             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8498                                                             CanonType)))
8499           continue;
8500         QualType ParamTypes[2] = { *Enum, *Enum };
8501         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8502       }
8503     }
8504   }
8505 
8506   // C++ [over.built]p13:
8507   //
8508   //   For every cv-qualified or cv-unqualified object type T
8509   //   there exist candidate operator functions of the form
8510   //
8511   //      T*         operator+(T*, ptrdiff_t);
8512   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8513   //      T*         operator-(T*, ptrdiff_t);
8514   //      T*         operator+(ptrdiff_t, T*);
8515   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8516   //
8517   // C++ [over.built]p14:
8518   //
8519   //   For every T, where T is a pointer to object type, there
8520   //   exist candidate operator functions of the form
8521   //
8522   //      ptrdiff_t  operator-(T, T);
8523   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8524     /// Set of (canonical) types that we've already handled.
8525     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8526 
8527     for (int Arg = 0; Arg < 2; ++Arg) {
8528       QualType AsymmetricParamTypes[2] = {
8529         S.Context.getPointerDiffType(),
8530         S.Context.getPointerDiffType(),
8531       };
8532       for (BuiltinCandidateTypeSet::iterator
8533                 Ptr = CandidateTypes[Arg].pointer_begin(),
8534              PtrEnd = CandidateTypes[Arg].pointer_end();
8535            Ptr != PtrEnd; ++Ptr) {
8536         QualType PointeeTy = (*Ptr)->getPointeeType();
8537         if (!PointeeTy->isObjectType())
8538           continue;
8539 
8540         AsymmetricParamTypes[Arg] = *Ptr;
8541         if (Arg == 0 || Op == OO_Plus) {
8542           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8543           // T* operator+(ptrdiff_t, T*);
8544           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8545         }
8546         if (Op == OO_Minus) {
8547           // ptrdiff_t operator-(T, T);
8548           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8549             continue;
8550 
8551           QualType ParamTypes[2] = { *Ptr, *Ptr };
8552           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8553         }
8554       }
8555     }
8556   }
8557 
8558   // C++ [over.built]p12:
8559   //
8560   //   For every pair of promoted arithmetic types L and R, there
8561   //   exist candidate operator functions of the form
8562   //
8563   //        LR         operator*(L, R);
8564   //        LR         operator/(L, R);
8565   //        LR         operator+(L, R);
8566   //        LR         operator-(L, R);
8567   //        bool       operator<(L, R);
8568   //        bool       operator>(L, R);
8569   //        bool       operator<=(L, R);
8570   //        bool       operator>=(L, R);
8571   //        bool       operator==(L, R);
8572   //        bool       operator!=(L, R);
8573   //
8574   //   where LR is the result of the usual arithmetic conversions
8575   //   between types L and R.
8576   //
8577   // C++ [over.built]p24:
8578   //
8579   //   For every pair of promoted arithmetic types L and R, there exist
8580   //   candidate operator functions of the form
8581   //
8582   //        LR       operator?(bool, L, R);
8583   //
8584   //   where LR is the result of the usual arithmetic conversions
8585   //   between types L and R.
8586   // Our candidates ignore the first parameter.
8587   void addGenericBinaryArithmeticOverloads() {
8588     if (!HasArithmeticOrEnumeralCandidateType)
8589       return;
8590 
8591     for (unsigned Left = FirstPromotedArithmeticType;
8592          Left < LastPromotedArithmeticType; ++Left) {
8593       for (unsigned Right = FirstPromotedArithmeticType;
8594            Right < LastPromotedArithmeticType; ++Right) {
8595         QualType LandR[2] = { ArithmeticTypes[Left],
8596                               ArithmeticTypes[Right] };
8597         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8598       }
8599     }
8600 
8601     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8602     // conditional operator for vector types.
8603     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8604       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8605         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8606         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8607       }
8608   }
8609 
8610   /// Add binary operator overloads for each candidate matrix type M1, M2:
8611   ///  * (M1, M1) -> M1
8612   ///  * (M1, M1.getElementType()) -> M1
8613   ///  * (M2.getElementType(), M2) -> M2
8614   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8615   void addMatrixBinaryArithmeticOverloads() {
8616     if (!HasArithmeticOrEnumeralCandidateType)
8617       return;
8618 
8619     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8620       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8621       AddCandidate(M1, M1);
8622     }
8623 
8624     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8625       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8626       if (!CandidateTypes[0].containsMatrixType(M2))
8627         AddCandidate(M2, M2);
8628     }
8629   }
8630 
8631   // C++2a [over.built]p14:
8632   //
8633   //   For every integral type T there exists a candidate operator function
8634   //   of the form
8635   //
8636   //        std::strong_ordering operator<=>(T, T)
8637   //
8638   // C++2a [over.built]p15:
8639   //
8640   //   For every pair of floating-point types L and R, there exists a candidate
8641   //   operator function of the form
8642   //
8643   //       std::partial_ordering operator<=>(L, R);
8644   //
8645   // FIXME: The current specification for integral types doesn't play nice with
8646   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8647   // comparisons. Under the current spec this can lead to ambiguity during
8648   // overload resolution. For example:
8649   //
8650   //   enum A : int {a};
8651   //   auto x = (a <=> (long)42);
8652   //
8653   //   error: call is ambiguous for arguments 'A' and 'long'.
8654   //   note: candidate operator<=>(int, int)
8655   //   note: candidate operator<=>(long, long)
8656   //
8657   // To avoid this error, this function deviates from the specification and adds
8658   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8659   // arithmetic types (the same as the generic relational overloads).
8660   //
8661   // For now this function acts as a placeholder.
8662   void addThreeWayArithmeticOverloads() {
8663     addGenericBinaryArithmeticOverloads();
8664   }
8665 
8666   // C++ [over.built]p17:
8667   //
8668   //   For every pair of promoted integral types L and R, there
8669   //   exist candidate operator functions of the form
8670   //
8671   //      LR         operator%(L, R);
8672   //      LR         operator&(L, R);
8673   //      LR         operator^(L, R);
8674   //      LR         operator|(L, R);
8675   //      L          operator<<(L, R);
8676   //      L          operator>>(L, R);
8677   //
8678   //   where LR is the result of the usual arithmetic conversions
8679   //   between types L and R.
8680   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8681     if (!HasArithmeticOrEnumeralCandidateType)
8682       return;
8683 
8684     for (unsigned Left = FirstPromotedIntegralType;
8685          Left < LastPromotedIntegralType; ++Left) {
8686       for (unsigned Right = FirstPromotedIntegralType;
8687            Right < LastPromotedIntegralType; ++Right) {
8688         QualType LandR[2] = { ArithmeticTypes[Left],
8689                               ArithmeticTypes[Right] };
8690         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8691       }
8692     }
8693   }
8694 
8695   // C++ [over.built]p20:
8696   //
8697   //   For every pair (T, VQ), where T is an enumeration or
8698   //   pointer to member type and VQ is either volatile or
8699   //   empty, there exist candidate operator functions of the form
8700   //
8701   //        VQ T&      operator=(VQ T&, T);
8702   void addAssignmentMemberPointerOrEnumeralOverloads() {
8703     /// Set of (canonical) types that we've already handled.
8704     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8705 
8706     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8707       for (BuiltinCandidateTypeSet::iterator
8708                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8709              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8710            Enum != EnumEnd; ++Enum) {
8711         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8712           continue;
8713 
8714         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8715       }
8716 
8717       for (BuiltinCandidateTypeSet::iterator
8718                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8719              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8720            MemPtr != MemPtrEnd; ++MemPtr) {
8721         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8722           continue;
8723 
8724         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8725       }
8726     }
8727   }
8728 
8729   // C++ [over.built]p19:
8730   //
8731   //   For every pair (T, VQ), where T is any type and VQ is either
8732   //   volatile or empty, there exist candidate operator functions
8733   //   of the form
8734   //
8735   //        T*VQ&      operator=(T*VQ&, T*);
8736   //
8737   // C++ [over.built]p21:
8738   //
8739   //   For every pair (T, VQ), where T is a cv-qualified or
8740   //   cv-unqualified object type and VQ is either volatile or
8741   //   empty, there exist candidate operator functions of the form
8742   //
8743   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8744   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8745   void addAssignmentPointerOverloads(bool isEqualOp) {
8746     /// Set of (canonical) types that we've already handled.
8747     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8748 
8749     for (BuiltinCandidateTypeSet::iterator
8750               Ptr = CandidateTypes[0].pointer_begin(),
8751            PtrEnd = CandidateTypes[0].pointer_end();
8752          Ptr != PtrEnd; ++Ptr) {
8753       // If this is operator=, keep track of the builtin candidates we added.
8754       if (isEqualOp)
8755         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8756       else if (!(*Ptr)->getPointeeType()->isObjectType())
8757         continue;
8758 
8759       // non-volatile version
8760       QualType ParamTypes[2] = {
8761         S.Context.getLValueReferenceType(*Ptr),
8762         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8763       };
8764       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8765                             /*IsAssignmentOperator=*/ isEqualOp);
8766 
8767       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8768                           VisibleTypeConversionsQuals.hasVolatile();
8769       if (NeedVolatile) {
8770         // volatile version
8771         ParamTypes[0] =
8772           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8773         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8774                               /*IsAssignmentOperator=*/isEqualOp);
8775       }
8776 
8777       if (!(*Ptr).isRestrictQualified() &&
8778           VisibleTypeConversionsQuals.hasRestrict()) {
8779         // restrict version
8780         ParamTypes[0]
8781           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8782         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8783                               /*IsAssignmentOperator=*/isEqualOp);
8784 
8785         if (NeedVolatile) {
8786           // volatile restrict version
8787           ParamTypes[0]
8788             = S.Context.getLValueReferenceType(
8789                 S.Context.getCVRQualifiedType(*Ptr,
8790                                               (Qualifiers::Volatile |
8791                                                Qualifiers::Restrict)));
8792           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8793                                 /*IsAssignmentOperator=*/isEqualOp);
8794         }
8795       }
8796     }
8797 
8798     if (isEqualOp) {
8799       for (BuiltinCandidateTypeSet::iterator
8800                 Ptr = CandidateTypes[1].pointer_begin(),
8801              PtrEnd = CandidateTypes[1].pointer_end();
8802            Ptr != PtrEnd; ++Ptr) {
8803         // Make sure we don't add the same candidate twice.
8804         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8805           continue;
8806 
8807         QualType ParamTypes[2] = {
8808           S.Context.getLValueReferenceType(*Ptr),
8809           *Ptr,
8810         };
8811 
8812         // non-volatile version
8813         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8814                               /*IsAssignmentOperator=*/true);
8815 
8816         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8817                            VisibleTypeConversionsQuals.hasVolatile();
8818         if (NeedVolatile) {
8819           // volatile version
8820           ParamTypes[0] =
8821             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8822           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8823                                 /*IsAssignmentOperator=*/true);
8824         }
8825 
8826         if (!(*Ptr).isRestrictQualified() &&
8827             VisibleTypeConversionsQuals.hasRestrict()) {
8828           // restrict version
8829           ParamTypes[0]
8830             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8831           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8832                                 /*IsAssignmentOperator=*/true);
8833 
8834           if (NeedVolatile) {
8835             // volatile restrict version
8836             ParamTypes[0]
8837               = S.Context.getLValueReferenceType(
8838                   S.Context.getCVRQualifiedType(*Ptr,
8839                                                 (Qualifiers::Volatile |
8840                                                  Qualifiers::Restrict)));
8841             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8842                                   /*IsAssignmentOperator=*/true);
8843           }
8844         }
8845       }
8846     }
8847   }
8848 
8849   // C++ [over.built]p18:
8850   //
8851   //   For every triple (L, VQ, R), where L is an arithmetic type,
8852   //   VQ is either volatile or empty, and R is a promoted
8853   //   arithmetic type, there exist candidate operator functions of
8854   //   the form
8855   //
8856   //        VQ L&      operator=(VQ L&, R);
8857   //        VQ L&      operator*=(VQ L&, R);
8858   //        VQ L&      operator/=(VQ L&, R);
8859   //        VQ L&      operator+=(VQ L&, R);
8860   //        VQ L&      operator-=(VQ L&, R);
8861   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8862     if (!HasArithmeticOrEnumeralCandidateType)
8863       return;
8864 
8865     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8866       for (unsigned Right = FirstPromotedArithmeticType;
8867            Right < LastPromotedArithmeticType; ++Right) {
8868         QualType ParamTypes[2];
8869         ParamTypes[1] = ArithmeticTypes[Right];
8870         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8871             S, ArithmeticTypes[Left], Args[0]);
8872         // Add this built-in operator as a candidate (VQ is empty).
8873         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8874         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8875                               /*IsAssignmentOperator=*/isEqualOp);
8876 
8877         // Add this built-in operator as a candidate (VQ is 'volatile').
8878         if (VisibleTypeConversionsQuals.hasVolatile()) {
8879           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8880           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8881           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8882                                 /*IsAssignmentOperator=*/isEqualOp);
8883         }
8884       }
8885     }
8886 
8887     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8888     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8889       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8890         QualType ParamTypes[2];
8891         ParamTypes[1] = Vec2Ty;
8892         // Add this built-in operator as a candidate (VQ is empty).
8893         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8894         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8895                               /*IsAssignmentOperator=*/isEqualOp);
8896 
8897         // Add this built-in operator as a candidate (VQ is 'volatile').
8898         if (VisibleTypeConversionsQuals.hasVolatile()) {
8899           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8900           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8901           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8902                                 /*IsAssignmentOperator=*/isEqualOp);
8903         }
8904       }
8905   }
8906 
8907   // C++ [over.built]p22:
8908   //
8909   //   For every triple (L, VQ, R), where L is an integral type, VQ
8910   //   is either volatile or empty, and R is a promoted integral
8911   //   type, there exist candidate operator functions of the form
8912   //
8913   //        VQ L&       operator%=(VQ L&, R);
8914   //        VQ L&       operator<<=(VQ L&, R);
8915   //        VQ L&       operator>>=(VQ L&, R);
8916   //        VQ L&       operator&=(VQ L&, R);
8917   //        VQ L&       operator^=(VQ L&, R);
8918   //        VQ L&       operator|=(VQ L&, R);
8919   void addAssignmentIntegralOverloads() {
8920     if (!HasArithmeticOrEnumeralCandidateType)
8921       return;
8922 
8923     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8924       for (unsigned Right = FirstPromotedIntegralType;
8925            Right < LastPromotedIntegralType; ++Right) {
8926         QualType ParamTypes[2];
8927         ParamTypes[1] = ArithmeticTypes[Right];
8928         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8929             S, ArithmeticTypes[Left], Args[0]);
8930         // Add this built-in operator as a candidate (VQ is empty).
8931         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8932         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8933         if (VisibleTypeConversionsQuals.hasVolatile()) {
8934           // Add this built-in operator as a candidate (VQ is 'volatile').
8935           ParamTypes[0] = LeftBaseTy;
8936           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8937           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8938           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8939         }
8940       }
8941     }
8942   }
8943 
8944   // C++ [over.operator]p23:
8945   //
8946   //   There also exist candidate operator functions of the form
8947   //
8948   //        bool        operator!(bool);
8949   //        bool        operator&&(bool, bool);
8950   //        bool        operator||(bool, bool);
8951   void addExclaimOverload() {
8952     QualType ParamTy = S.Context.BoolTy;
8953     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8954                           /*IsAssignmentOperator=*/false,
8955                           /*NumContextualBoolArguments=*/1);
8956   }
8957   void addAmpAmpOrPipePipeOverload() {
8958     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8959     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8960                           /*IsAssignmentOperator=*/false,
8961                           /*NumContextualBoolArguments=*/2);
8962   }
8963 
8964   // C++ [over.built]p13:
8965   //
8966   //   For every cv-qualified or cv-unqualified object type T there
8967   //   exist candidate operator functions of the form
8968   //
8969   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8970   //        T&         operator[](T*, ptrdiff_t);
8971   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8972   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8973   //        T&         operator[](ptrdiff_t, T*);
8974   void addSubscriptOverloads() {
8975     for (BuiltinCandidateTypeSet::iterator
8976               Ptr = CandidateTypes[0].pointer_begin(),
8977            PtrEnd = CandidateTypes[0].pointer_end();
8978          Ptr != PtrEnd; ++Ptr) {
8979       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8980       QualType PointeeType = (*Ptr)->getPointeeType();
8981       if (!PointeeType->isObjectType())
8982         continue;
8983 
8984       // T& operator[](T*, ptrdiff_t)
8985       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8986     }
8987 
8988     for (BuiltinCandidateTypeSet::iterator
8989               Ptr = CandidateTypes[1].pointer_begin(),
8990            PtrEnd = CandidateTypes[1].pointer_end();
8991          Ptr != PtrEnd; ++Ptr) {
8992       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8993       QualType PointeeType = (*Ptr)->getPointeeType();
8994       if (!PointeeType->isObjectType())
8995         continue;
8996 
8997       // T& operator[](ptrdiff_t, T*)
8998       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8999     }
9000   }
9001 
9002   // C++ [over.built]p11:
9003   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9004   //    C1 is the same type as C2 or is a derived class of C2, T is an object
9005   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9006   //    there exist candidate operator functions of the form
9007   //
9008   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9009   //
9010   //    where CV12 is the union of CV1 and CV2.
9011   void addArrowStarOverloads() {
9012     for (BuiltinCandidateTypeSet::iterator
9013              Ptr = CandidateTypes[0].pointer_begin(),
9014            PtrEnd = CandidateTypes[0].pointer_end();
9015          Ptr != PtrEnd; ++Ptr) {
9016       QualType C1Ty = (*Ptr);
9017       QualType C1;
9018       QualifierCollector Q1;
9019       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9020       if (!isa<RecordType>(C1))
9021         continue;
9022       // heuristic to reduce number of builtin candidates in the set.
9023       // Add volatile/restrict version only if there are conversions to a
9024       // volatile/restrict type.
9025       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9026         continue;
9027       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9028         continue;
9029       for (BuiltinCandidateTypeSet::iterator
9030                 MemPtr = CandidateTypes[1].member_pointer_begin(),
9031              MemPtrEnd = CandidateTypes[1].member_pointer_end();
9032            MemPtr != MemPtrEnd; ++MemPtr) {
9033         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9034         QualType C2 = QualType(mptr->getClass(), 0);
9035         C2 = C2.getUnqualifiedType();
9036         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9037           break;
9038         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9039         // build CV12 T&
9040         QualType T = mptr->getPointeeType();
9041         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9042             T.isVolatileQualified())
9043           continue;
9044         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9045             T.isRestrictQualified())
9046           continue;
9047         T = Q1.apply(S.Context, T);
9048         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9049       }
9050     }
9051   }
9052 
9053   // Note that we don't consider the first argument, since it has been
9054   // contextually converted to bool long ago. The candidates below are
9055   // therefore added as binary.
9056   //
9057   // C++ [over.built]p25:
9058   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9059   //   enumeration type, there exist candidate operator functions of the form
9060   //
9061   //        T        operator?(bool, T, T);
9062   //
9063   void addConditionalOperatorOverloads() {
9064     /// Set of (canonical) types that we've already handled.
9065     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9066 
9067     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9068       for (BuiltinCandidateTypeSet::iterator
9069                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9070              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9071            Ptr != PtrEnd; ++Ptr) {
9072         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9073           continue;
9074 
9075         QualType ParamTypes[2] = { *Ptr, *Ptr };
9076         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9077       }
9078 
9079       for (BuiltinCandidateTypeSet::iterator
9080                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9081              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9082            MemPtr != MemPtrEnd; ++MemPtr) {
9083         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9084           continue;
9085 
9086         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9087         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9088       }
9089 
9090       if (S.getLangOpts().CPlusPlus11) {
9091         for (BuiltinCandidateTypeSet::iterator
9092                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9093                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9094              Enum != EnumEnd; ++Enum) {
9095           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9096             continue;
9097 
9098           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9099             continue;
9100 
9101           QualType ParamTypes[2] = { *Enum, *Enum };
9102           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9103         }
9104       }
9105     }
9106   }
9107 };
9108 
9109 } // end anonymous namespace
9110 
9111 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9112 /// operator overloads to the candidate set (C++ [over.built]), based
9113 /// on the operator @p Op and the arguments given. For example, if the
9114 /// operator is a binary '+', this routine might add "int
9115 /// operator+(int, int)" to cover integer addition.
9116 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9117                                         SourceLocation OpLoc,
9118                                         ArrayRef<Expr *> Args,
9119                                         OverloadCandidateSet &CandidateSet) {
9120   // Find all of the types that the arguments can convert to, but only
9121   // if the operator we're looking at has built-in operator candidates
9122   // that make use of these types. Also record whether we encounter non-record
9123   // candidate types or either arithmetic or enumeral candidate types.
9124   Qualifiers VisibleTypeConversionsQuals;
9125   VisibleTypeConversionsQuals.addConst();
9126   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9127     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9128 
9129   bool HasNonRecordCandidateType = false;
9130   bool HasArithmeticOrEnumeralCandidateType = false;
9131   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9132   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9133     CandidateTypes.emplace_back(*this);
9134     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9135                                                  OpLoc,
9136                                                  true,
9137                                                  (Op == OO_Exclaim ||
9138                                                   Op == OO_AmpAmp ||
9139                                                   Op == OO_PipePipe),
9140                                                  VisibleTypeConversionsQuals);
9141     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9142         CandidateTypes[ArgIdx].hasNonRecordTypes();
9143     HasArithmeticOrEnumeralCandidateType =
9144         HasArithmeticOrEnumeralCandidateType ||
9145         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9146   }
9147 
9148   // Exit early when no non-record types have been added to the candidate set
9149   // for any of the arguments to the operator.
9150   //
9151   // We can't exit early for !, ||, or &&, since there we have always have
9152   // 'bool' overloads.
9153   if (!HasNonRecordCandidateType &&
9154       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9155     return;
9156 
9157   // Setup an object to manage the common state for building overloads.
9158   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9159                                            VisibleTypeConversionsQuals,
9160                                            HasArithmeticOrEnumeralCandidateType,
9161                                            CandidateTypes, CandidateSet);
9162 
9163   // Dispatch over the operation to add in only those overloads which apply.
9164   switch (Op) {
9165   case OO_None:
9166   case NUM_OVERLOADED_OPERATORS:
9167     llvm_unreachable("Expected an overloaded operator");
9168 
9169   case OO_New:
9170   case OO_Delete:
9171   case OO_Array_New:
9172   case OO_Array_Delete:
9173   case OO_Call:
9174     llvm_unreachable(
9175                     "Special operators don't use AddBuiltinOperatorCandidates");
9176 
9177   case OO_Comma:
9178   case OO_Arrow:
9179   case OO_Coawait:
9180     // C++ [over.match.oper]p3:
9181     //   -- For the operator ',', the unary operator '&', the
9182     //      operator '->', or the operator 'co_await', the
9183     //      built-in candidates set is empty.
9184     break;
9185 
9186   case OO_Plus: // '+' is either unary or binary
9187     if (Args.size() == 1)
9188       OpBuilder.addUnaryPlusPointerOverloads();
9189     LLVM_FALLTHROUGH;
9190 
9191   case OO_Minus: // '-' is either unary or binary
9192     if (Args.size() == 1) {
9193       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9194     } else {
9195       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9196       OpBuilder.addGenericBinaryArithmeticOverloads();
9197       OpBuilder.addMatrixBinaryArithmeticOverloads();
9198     }
9199     break;
9200 
9201   case OO_Star: // '*' is either unary or binary
9202     if (Args.size() == 1)
9203       OpBuilder.addUnaryStarPointerOverloads();
9204     else {
9205       OpBuilder.addGenericBinaryArithmeticOverloads();
9206       OpBuilder.addMatrixBinaryArithmeticOverloads();
9207     }
9208     break;
9209 
9210   case OO_Slash:
9211     OpBuilder.addGenericBinaryArithmeticOverloads();
9212     break;
9213 
9214   case OO_PlusPlus:
9215   case OO_MinusMinus:
9216     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9217     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9218     break;
9219 
9220   case OO_EqualEqual:
9221   case OO_ExclaimEqual:
9222     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9223     LLVM_FALLTHROUGH;
9224 
9225   case OO_Less:
9226   case OO_Greater:
9227   case OO_LessEqual:
9228   case OO_GreaterEqual:
9229     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9230     OpBuilder.addGenericBinaryArithmeticOverloads();
9231     break;
9232 
9233   case OO_Spaceship:
9234     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9235     OpBuilder.addThreeWayArithmeticOverloads();
9236     break;
9237 
9238   case OO_Percent:
9239   case OO_Caret:
9240   case OO_Pipe:
9241   case OO_LessLess:
9242   case OO_GreaterGreater:
9243     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9244     break;
9245 
9246   case OO_Amp: // '&' is either unary or binary
9247     if (Args.size() == 1)
9248       // C++ [over.match.oper]p3:
9249       //   -- For the operator ',', the unary operator '&', or the
9250       //      operator '->', the built-in candidates set is empty.
9251       break;
9252 
9253     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9254     break;
9255 
9256   case OO_Tilde:
9257     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9258     break;
9259 
9260   case OO_Equal:
9261     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9262     LLVM_FALLTHROUGH;
9263 
9264   case OO_PlusEqual:
9265   case OO_MinusEqual:
9266     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9267     LLVM_FALLTHROUGH;
9268 
9269   case OO_StarEqual:
9270   case OO_SlashEqual:
9271     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9272     break;
9273 
9274   case OO_PercentEqual:
9275   case OO_LessLessEqual:
9276   case OO_GreaterGreaterEqual:
9277   case OO_AmpEqual:
9278   case OO_CaretEqual:
9279   case OO_PipeEqual:
9280     OpBuilder.addAssignmentIntegralOverloads();
9281     break;
9282 
9283   case OO_Exclaim:
9284     OpBuilder.addExclaimOverload();
9285     break;
9286 
9287   case OO_AmpAmp:
9288   case OO_PipePipe:
9289     OpBuilder.addAmpAmpOrPipePipeOverload();
9290     break;
9291 
9292   case OO_Subscript:
9293     OpBuilder.addSubscriptOverloads();
9294     break;
9295 
9296   case OO_ArrowStar:
9297     OpBuilder.addArrowStarOverloads();
9298     break;
9299 
9300   case OO_Conditional:
9301     OpBuilder.addConditionalOperatorOverloads();
9302     OpBuilder.addGenericBinaryArithmeticOverloads();
9303     break;
9304   }
9305 }
9306 
9307 /// Add function candidates found via argument-dependent lookup
9308 /// to the set of overloading candidates.
9309 ///
9310 /// This routine performs argument-dependent name lookup based on the
9311 /// given function name (which may also be an operator name) and adds
9312 /// all of the overload candidates found by ADL to the overload
9313 /// candidate set (C++ [basic.lookup.argdep]).
9314 void
9315 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9316                                            SourceLocation Loc,
9317                                            ArrayRef<Expr *> Args,
9318                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9319                                            OverloadCandidateSet& CandidateSet,
9320                                            bool PartialOverloading) {
9321   ADLResult Fns;
9322 
9323   // FIXME: This approach for uniquing ADL results (and removing
9324   // redundant candidates from the set) relies on pointer-equality,
9325   // which means we need to key off the canonical decl.  However,
9326   // always going back to the canonical decl might not get us the
9327   // right set of default arguments.  What default arguments are
9328   // we supposed to consider on ADL candidates, anyway?
9329 
9330   // FIXME: Pass in the explicit template arguments?
9331   ArgumentDependentLookup(Name, Loc, Args, Fns);
9332 
9333   // Erase all of the candidates we already knew about.
9334   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9335                                    CandEnd = CandidateSet.end();
9336        Cand != CandEnd; ++Cand)
9337     if (Cand->Function) {
9338       Fns.erase(Cand->Function);
9339       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9340         Fns.erase(FunTmpl);
9341     }
9342 
9343   // For each of the ADL candidates we found, add it to the overload
9344   // set.
9345   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9346     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9347 
9348     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9349       if (ExplicitTemplateArgs)
9350         continue;
9351 
9352       AddOverloadCandidate(
9353           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9354           PartialOverloading, /*AllowExplicit=*/true,
9355           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9356       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9357         AddOverloadCandidate(
9358             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9359             /*SuppressUserConversions=*/false, PartialOverloading,
9360             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9361             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9362       }
9363     } else {
9364       auto *FTD = cast<FunctionTemplateDecl>(*I);
9365       AddTemplateOverloadCandidate(
9366           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9367           /*SuppressUserConversions=*/false, PartialOverloading,
9368           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9369       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9370               Context, FTD->getTemplatedDecl())) {
9371         AddTemplateOverloadCandidate(
9372             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9373             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9374             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9375             OverloadCandidateParamOrder::Reversed);
9376       }
9377     }
9378   }
9379 }
9380 
9381 namespace {
9382 enum class Comparison { Equal, Better, Worse };
9383 }
9384 
9385 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9386 /// overload resolution.
9387 ///
9388 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9389 /// Cand1's first N enable_if attributes have precisely the same conditions as
9390 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9391 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9392 ///
9393 /// Note that you can have a pair of candidates such that Cand1's enable_if
9394 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9395 /// worse than Cand1's.
9396 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9397                                        const FunctionDecl *Cand2) {
9398   // Common case: One (or both) decls don't have enable_if attrs.
9399   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9400   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9401   if (!Cand1Attr || !Cand2Attr) {
9402     if (Cand1Attr == Cand2Attr)
9403       return Comparison::Equal;
9404     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9405   }
9406 
9407   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9408   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9409 
9410   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9411   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9412     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9413     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9414 
9415     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9416     // has fewer enable_if attributes than Cand2, and vice versa.
9417     if (!Cand1A)
9418       return Comparison::Worse;
9419     if (!Cand2A)
9420       return Comparison::Better;
9421 
9422     Cand1ID.clear();
9423     Cand2ID.clear();
9424 
9425     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9426     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9427     if (Cand1ID != Cand2ID)
9428       return Comparison::Worse;
9429   }
9430 
9431   return Comparison::Equal;
9432 }
9433 
9434 static Comparison
9435 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9436                               const OverloadCandidate &Cand2) {
9437   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9438       !Cand2.Function->isMultiVersion())
9439     return Comparison::Equal;
9440 
9441   // If both are invalid, they are equal. If one of them is invalid, the other
9442   // is better.
9443   if (Cand1.Function->isInvalidDecl()) {
9444     if (Cand2.Function->isInvalidDecl())
9445       return Comparison::Equal;
9446     return Comparison::Worse;
9447   }
9448   if (Cand2.Function->isInvalidDecl())
9449     return Comparison::Better;
9450 
9451   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9452   // cpu_dispatch, else arbitrarily based on the identifiers.
9453   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9454   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9455   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9456   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9457 
9458   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9459     return Comparison::Equal;
9460 
9461   if (Cand1CPUDisp && !Cand2CPUDisp)
9462     return Comparison::Better;
9463   if (Cand2CPUDisp && !Cand1CPUDisp)
9464     return Comparison::Worse;
9465 
9466   if (Cand1CPUSpec && Cand2CPUSpec) {
9467     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9468       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9469                  ? Comparison::Better
9470                  : Comparison::Worse;
9471 
9472     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9473         FirstDiff = std::mismatch(
9474             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9475             Cand2CPUSpec->cpus_begin(),
9476             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9477               return LHS->getName() == RHS->getName();
9478             });
9479 
9480     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9481            "Two different cpu-specific versions should not have the same "
9482            "identifier list, otherwise they'd be the same decl!");
9483     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9484                ? Comparison::Better
9485                : Comparison::Worse;
9486   }
9487   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9488 }
9489 
9490 /// Compute the type of the implicit object parameter for the given function,
9491 /// if any. Returns None if there is no implicit object parameter, and a null
9492 /// QualType if there is a 'matches anything' implicit object parameter.
9493 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9494                                                      const FunctionDecl *F) {
9495   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9496     return llvm::None;
9497 
9498   auto *M = cast<CXXMethodDecl>(F);
9499   // Static member functions' object parameters match all types.
9500   if (M->isStatic())
9501     return QualType();
9502 
9503   QualType T = M->getThisObjectType();
9504   if (M->getRefQualifier() == RQ_RValue)
9505     return Context.getRValueReferenceType(T);
9506   return Context.getLValueReferenceType(T);
9507 }
9508 
9509 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9510                                    const FunctionDecl *F2, unsigned NumParams) {
9511   if (declaresSameEntity(F1, F2))
9512     return true;
9513 
9514   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9515     if (First) {
9516       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9517         return *T;
9518     }
9519     assert(I < F->getNumParams());
9520     return F->getParamDecl(I++)->getType();
9521   };
9522 
9523   unsigned I1 = 0, I2 = 0;
9524   for (unsigned I = 0; I != NumParams; ++I) {
9525     QualType T1 = NextParam(F1, I1, I == 0);
9526     QualType T2 = NextParam(F2, I2, I == 0);
9527     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9528       return false;
9529   }
9530   return true;
9531 }
9532 
9533 /// isBetterOverloadCandidate - Determines whether the first overload
9534 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9535 bool clang::isBetterOverloadCandidate(
9536     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9537     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9538   // Define viable functions to be better candidates than non-viable
9539   // functions.
9540   if (!Cand2.Viable)
9541     return Cand1.Viable;
9542   else if (!Cand1.Viable)
9543     return false;
9544 
9545   // C++ [over.match.best]p1:
9546   //
9547   //   -- if F is a static member function, ICS1(F) is defined such
9548   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9549   //      any function G, and, symmetrically, ICS1(G) is neither
9550   //      better nor worse than ICS1(F).
9551   unsigned StartArg = 0;
9552   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9553     StartArg = 1;
9554 
9555   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9556     // We don't allow incompatible pointer conversions in C++.
9557     if (!S.getLangOpts().CPlusPlus)
9558       return ICS.isStandard() &&
9559              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9560 
9561     // The only ill-formed conversion we allow in C++ is the string literal to
9562     // char* conversion, which is only considered ill-formed after C++11.
9563     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9564            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9565   };
9566 
9567   // Define functions that don't require ill-formed conversions for a given
9568   // argument to be better candidates than functions that do.
9569   unsigned NumArgs = Cand1.Conversions.size();
9570   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9571   bool HasBetterConversion = false;
9572   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9573     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9574     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9575     if (Cand1Bad != Cand2Bad) {
9576       if (Cand1Bad)
9577         return false;
9578       HasBetterConversion = true;
9579     }
9580   }
9581 
9582   if (HasBetterConversion)
9583     return true;
9584 
9585   // C++ [over.match.best]p1:
9586   //   A viable function F1 is defined to be a better function than another
9587   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9588   //   conversion sequence than ICSi(F2), and then...
9589   bool HasWorseConversion = false;
9590   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9591     switch (CompareImplicitConversionSequences(S, Loc,
9592                                                Cand1.Conversions[ArgIdx],
9593                                                Cand2.Conversions[ArgIdx])) {
9594     case ImplicitConversionSequence::Better:
9595       // Cand1 has a better conversion sequence.
9596       HasBetterConversion = true;
9597       break;
9598 
9599     case ImplicitConversionSequence::Worse:
9600       if (Cand1.Function && Cand2.Function &&
9601           Cand1.isReversed() != Cand2.isReversed() &&
9602           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9603                                  NumArgs)) {
9604         // Work around large-scale breakage caused by considering reversed
9605         // forms of operator== in C++20:
9606         //
9607         // When comparing a function against a reversed function with the same
9608         // parameter types, if we have a better conversion for one argument and
9609         // a worse conversion for the other, the implicit conversion sequences
9610         // are treated as being equally good.
9611         //
9612         // This prevents a comparison function from being considered ambiguous
9613         // with a reversed form that is written in the same way.
9614         //
9615         // We diagnose this as an extension from CreateOverloadedBinOp.
9616         HasWorseConversion = true;
9617         break;
9618       }
9619 
9620       // Cand1 can't be better than Cand2.
9621       return false;
9622 
9623     case ImplicitConversionSequence::Indistinguishable:
9624       // Do nothing.
9625       break;
9626     }
9627   }
9628 
9629   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9630   //       ICSj(F2), or, if not that,
9631   if (HasBetterConversion && !HasWorseConversion)
9632     return true;
9633 
9634   //   -- the context is an initialization by user-defined conversion
9635   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9636   //      from the return type of F1 to the destination type (i.e.,
9637   //      the type of the entity being initialized) is a better
9638   //      conversion sequence than the standard conversion sequence
9639   //      from the return type of F2 to the destination type.
9640   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9641       Cand1.Function && Cand2.Function &&
9642       isa<CXXConversionDecl>(Cand1.Function) &&
9643       isa<CXXConversionDecl>(Cand2.Function)) {
9644     // First check whether we prefer one of the conversion functions over the
9645     // other. This only distinguishes the results in non-standard, extension
9646     // cases such as the conversion from a lambda closure type to a function
9647     // pointer or block.
9648     ImplicitConversionSequence::CompareKind Result =
9649         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9650     if (Result == ImplicitConversionSequence::Indistinguishable)
9651       Result = CompareStandardConversionSequences(S, Loc,
9652                                                   Cand1.FinalConversion,
9653                                                   Cand2.FinalConversion);
9654 
9655     if (Result != ImplicitConversionSequence::Indistinguishable)
9656       return Result == ImplicitConversionSequence::Better;
9657 
9658     // FIXME: Compare kind of reference binding if conversion functions
9659     // convert to a reference type used in direct reference binding, per
9660     // C++14 [over.match.best]p1 section 2 bullet 3.
9661   }
9662 
9663   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9664   // as combined with the resolution to CWG issue 243.
9665   //
9666   // When the context is initialization by constructor ([over.match.ctor] or
9667   // either phase of [over.match.list]), a constructor is preferred over
9668   // a conversion function.
9669   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9670       Cand1.Function && Cand2.Function &&
9671       isa<CXXConstructorDecl>(Cand1.Function) !=
9672           isa<CXXConstructorDecl>(Cand2.Function))
9673     return isa<CXXConstructorDecl>(Cand1.Function);
9674 
9675   //    -- F1 is a non-template function and F2 is a function template
9676   //       specialization, or, if not that,
9677   bool Cand1IsSpecialization = Cand1.Function &&
9678                                Cand1.Function->getPrimaryTemplate();
9679   bool Cand2IsSpecialization = Cand2.Function &&
9680                                Cand2.Function->getPrimaryTemplate();
9681   if (Cand1IsSpecialization != Cand2IsSpecialization)
9682     return Cand2IsSpecialization;
9683 
9684   //   -- F1 and F2 are function template specializations, and the function
9685   //      template for F1 is more specialized than the template for F2
9686   //      according to the partial ordering rules described in 14.5.5.2, or,
9687   //      if not that,
9688   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9689     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9690             Cand1.Function->getPrimaryTemplate(),
9691             Cand2.Function->getPrimaryTemplate(), Loc,
9692             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9693                                                    : TPOC_Call,
9694             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9695             Cand1.isReversed() ^ Cand2.isReversed()))
9696       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9697   }
9698 
9699   //   -— F1 and F2 are non-template functions with the same
9700   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9701   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9702       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9703       Cand2.Function->hasPrototype()) {
9704     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9705     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9706     if (PT1->getNumParams() == PT2->getNumParams() &&
9707         PT1->isVariadic() == PT2->isVariadic() &&
9708         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9709       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9710       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9711       if (RC1 && RC2) {
9712         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9713         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9714                                      {RC2}, AtLeastAsConstrained1) ||
9715             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9716                                      {RC1}, AtLeastAsConstrained2))
9717           return false;
9718         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9719           return AtLeastAsConstrained1;
9720       } else if (RC1 || RC2) {
9721         return RC1 != nullptr;
9722       }
9723     }
9724   }
9725 
9726   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9727   //      class B of D, and for all arguments the corresponding parameters of
9728   //      F1 and F2 have the same type.
9729   // FIXME: Implement the "all parameters have the same type" check.
9730   bool Cand1IsInherited =
9731       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9732   bool Cand2IsInherited =
9733       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9734   if (Cand1IsInherited != Cand2IsInherited)
9735     return Cand2IsInherited;
9736   else if (Cand1IsInherited) {
9737     assert(Cand2IsInherited);
9738     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9739     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9740     if (Cand1Class->isDerivedFrom(Cand2Class))
9741       return true;
9742     if (Cand2Class->isDerivedFrom(Cand1Class))
9743       return false;
9744     // Inherited from sibling base classes: still ambiguous.
9745   }
9746 
9747   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9748   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9749   //      with reversed order of parameters and F1 is not
9750   //
9751   // We rank reversed + different operator as worse than just reversed, but
9752   // that comparison can never happen, because we only consider reversing for
9753   // the maximally-rewritten operator (== or <=>).
9754   if (Cand1.RewriteKind != Cand2.RewriteKind)
9755     return Cand1.RewriteKind < Cand2.RewriteKind;
9756 
9757   // Check C++17 tie-breakers for deduction guides.
9758   {
9759     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9760     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9761     if (Guide1 && Guide2) {
9762       //  -- F1 is generated from a deduction-guide and F2 is not
9763       if (Guide1->isImplicit() != Guide2->isImplicit())
9764         return Guide2->isImplicit();
9765 
9766       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9767       if (Guide1->isCopyDeductionCandidate())
9768         return true;
9769     }
9770   }
9771 
9772   // Check for enable_if value-based overload resolution.
9773   if (Cand1.Function && Cand2.Function) {
9774     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9775     if (Cmp != Comparison::Equal)
9776       return Cmp == Comparison::Better;
9777   }
9778 
9779   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9780     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9781     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9782            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9783   }
9784 
9785   bool HasPS1 = Cand1.Function != nullptr &&
9786                 functionHasPassObjectSizeParams(Cand1.Function);
9787   bool HasPS2 = Cand2.Function != nullptr &&
9788                 functionHasPassObjectSizeParams(Cand2.Function);
9789   if (HasPS1 != HasPS2 && HasPS1)
9790     return true;
9791 
9792   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9793   return MV == Comparison::Better;
9794 }
9795 
9796 /// Determine whether two declarations are "equivalent" for the purposes of
9797 /// name lookup and overload resolution. This applies when the same internal/no
9798 /// linkage entity is defined by two modules (probably by textually including
9799 /// the same header). In such a case, we don't consider the declarations to
9800 /// declare the same entity, but we also don't want lookups with both
9801 /// declarations visible to be ambiguous in some cases (this happens when using
9802 /// a modularized libstdc++).
9803 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9804                                                   const NamedDecl *B) {
9805   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9806   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9807   if (!VA || !VB)
9808     return false;
9809 
9810   // The declarations must be declaring the same name as an internal linkage
9811   // entity in different modules.
9812   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9813           VB->getDeclContext()->getRedeclContext()) ||
9814       getOwningModule(VA) == getOwningModule(VB) ||
9815       VA->isExternallyVisible() || VB->isExternallyVisible())
9816     return false;
9817 
9818   // Check that the declarations appear to be equivalent.
9819   //
9820   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9821   // For constants and functions, we should check the initializer or body is
9822   // the same. For non-constant variables, we shouldn't allow it at all.
9823   if (Context.hasSameType(VA->getType(), VB->getType()))
9824     return true;
9825 
9826   // Enum constants within unnamed enumerations will have different types, but
9827   // may still be similar enough to be interchangeable for our purposes.
9828   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9829     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9830       // Only handle anonymous enums. If the enumerations were named and
9831       // equivalent, they would have been merged to the same type.
9832       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9833       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9834       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9835           !Context.hasSameType(EnumA->getIntegerType(),
9836                                EnumB->getIntegerType()))
9837         return false;
9838       // Allow this only if the value is the same for both enumerators.
9839       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9840     }
9841   }
9842 
9843   // Nothing else is sufficiently similar.
9844   return false;
9845 }
9846 
9847 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9848     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9849   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9850 
9851   Module *M = getOwningModule(D);
9852   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9853       << !M << (M ? M->getFullModuleName() : "");
9854 
9855   for (auto *E : Equiv) {
9856     Module *M = getOwningModule(E);
9857     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9858         << !M << (M ? M->getFullModuleName() : "");
9859   }
9860 }
9861 
9862 /// Computes the best viable function (C++ 13.3.3)
9863 /// within an overload candidate set.
9864 ///
9865 /// \param Loc The location of the function name (or operator symbol) for
9866 /// which overload resolution occurs.
9867 ///
9868 /// \param Best If overload resolution was successful or found a deleted
9869 /// function, \p Best points to the candidate function found.
9870 ///
9871 /// \returns The result of overload resolution.
9872 OverloadingResult
9873 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9874                                          iterator &Best) {
9875   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9876   std::transform(begin(), end(), std::back_inserter(Candidates),
9877                  [](OverloadCandidate &Cand) { return &Cand; });
9878 
9879   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9880   // are accepted by both clang and NVCC. However, during a particular
9881   // compilation mode only one call variant is viable. We need to
9882   // exclude non-viable overload candidates from consideration based
9883   // only on their host/device attributes. Specifically, if one
9884   // candidate call is WrongSide and the other is SameSide, we ignore
9885   // the WrongSide candidate.
9886   if (S.getLangOpts().CUDA) {
9887     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9888     bool ContainsSameSideCandidate =
9889         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9890           // Check viable function only.
9891           return Cand->Viable && Cand->Function &&
9892                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9893                      Sema::CFP_SameSide;
9894         });
9895     if (ContainsSameSideCandidate) {
9896       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9897         // Check viable function only to avoid unnecessary data copying/moving.
9898         return Cand->Viable && Cand->Function &&
9899                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9900                    Sema::CFP_WrongSide;
9901       };
9902       llvm::erase_if(Candidates, IsWrongSideCandidate);
9903     }
9904   }
9905 
9906   // Find the best viable function.
9907   Best = end();
9908   for (auto *Cand : Candidates) {
9909     Cand->Best = false;
9910     if (Cand->Viable)
9911       if (Best == end() ||
9912           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9913         Best = Cand;
9914   }
9915 
9916   // If we didn't find any viable functions, abort.
9917   if (Best == end())
9918     return OR_No_Viable_Function;
9919 
9920   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9921 
9922   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9923   PendingBest.push_back(&*Best);
9924   Best->Best = true;
9925 
9926   // Make sure that this function is better than every other viable
9927   // function. If not, we have an ambiguity.
9928   while (!PendingBest.empty()) {
9929     auto *Curr = PendingBest.pop_back_val();
9930     for (auto *Cand : Candidates) {
9931       if (Cand->Viable && !Cand->Best &&
9932           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9933         PendingBest.push_back(Cand);
9934         Cand->Best = true;
9935 
9936         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9937                                                      Curr->Function))
9938           EquivalentCands.push_back(Cand->Function);
9939         else
9940           Best = end();
9941       }
9942     }
9943   }
9944 
9945   // If we found more than one best candidate, this is ambiguous.
9946   if (Best == end())
9947     return OR_Ambiguous;
9948 
9949   // Best is the best viable function.
9950   if (Best->Function && Best->Function->isDeleted())
9951     return OR_Deleted;
9952 
9953   if (!EquivalentCands.empty())
9954     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9955                                                     EquivalentCands);
9956 
9957   return OR_Success;
9958 }
9959 
9960 namespace {
9961 
9962 enum OverloadCandidateKind {
9963   oc_function,
9964   oc_method,
9965   oc_reversed_binary_operator,
9966   oc_constructor,
9967   oc_implicit_default_constructor,
9968   oc_implicit_copy_constructor,
9969   oc_implicit_move_constructor,
9970   oc_implicit_copy_assignment,
9971   oc_implicit_move_assignment,
9972   oc_implicit_equality_comparison,
9973   oc_inherited_constructor
9974 };
9975 
9976 enum OverloadCandidateSelect {
9977   ocs_non_template,
9978   ocs_template,
9979   ocs_described_template,
9980 };
9981 
9982 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9983 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9984                           OverloadCandidateRewriteKind CRK,
9985                           std::string &Description) {
9986 
9987   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9988   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9989     isTemplate = true;
9990     Description = S.getTemplateArgumentBindingsText(
9991         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9992   }
9993 
9994   OverloadCandidateSelect Select = [&]() {
9995     if (!Description.empty())
9996       return ocs_described_template;
9997     return isTemplate ? ocs_template : ocs_non_template;
9998   }();
9999 
10000   OverloadCandidateKind Kind = [&]() {
10001     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10002       return oc_implicit_equality_comparison;
10003 
10004     if (CRK & CRK_Reversed)
10005       return oc_reversed_binary_operator;
10006 
10007     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10008       if (!Ctor->isImplicit()) {
10009         if (isa<ConstructorUsingShadowDecl>(Found))
10010           return oc_inherited_constructor;
10011         else
10012           return oc_constructor;
10013       }
10014 
10015       if (Ctor->isDefaultConstructor())
10016         return oc_implicit_default_constructor;
10017 
10018       if (Ctor->isMoveConstructor())
10019         return oc_implicit_move_constructor;
10020 
10021       assert(Ctor->isCopyConstructor() &&
10022              "unexpected sort of implicit constructor");
10023       return oc_implicit_copy_constructor;
10024     }
10025 
10026     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10027       // This actually gets spelled 'candidate function' for now, but
10028       // it doesn't hurt to split it out.
10029       if (!Meth->isImplicit())
10030         return oc_method;
10031 
10032       if (Meth->isMoveAssignmentOperator())
10033         return oc_implicit_move_assignment;
10034 
10035       if (Meth->isCopyAssignmentOperator())
10036         return oc_implicit_copy_assignment;
10037 
10038       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10039       return oc_method;
10040     }
10041 
10042     return oc_function;
10043   }();
10044 
10045   return std::make_pair(Kind, Select);
10046 }
10047 
10048 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10049   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10050   // set.
10051   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10052     S.Diag(FoundDecl->getLocation(),
10053            diag::note_ovl_candidate_inherited_constructor)
10054       << Shadow->getNominatedBaseClass();
10055 }
10056 
10057 } // end anonymous namespace
10058 
10059 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10060                                     const FunctionDecl *FD) {
10061   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10062     bool AlwaysTrue;
10063     if (EnableIf->getCond()->isValueDependent() ||
10064         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10065       return false;
10066     if (!AlwaysTrue)
10067       return false;
10068   }
10069   return true;
10070 }
10071 
10072 /// Returns true if we can take the address of the function.
10073 ///
10074 /// \param Complain - If true, we'll emit a diagnostic
10075 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10076 ///   we in overload resolution?
10077 /// \param Loc - The location of the statement we're complaining about. Ignored
10078 ///   if we're not complaining, or if we're in overload resolution.
10079 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10080                                               bool Complain,
10081                                               bool InOverloadResolution,
10082                                               SourceLocation Loc) {
10083   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10084     if (Complain) {
10085       if (InOverloadResolution)
10086         S.Diag(FD->getBeginLoc(),
10087                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10088       else
10089         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10090     }
10091     return false;
10092   }
10093 
10094   if (FD->getTrailingRequiresClause()) {
10095     ConstraintSatisfaction Satisfaction;
10096     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10097       return false;
10098     if (!Satisfaction.IsSatisfied) {
10099       if (Complain) {
10100         if (InOverloadResolution)
10101           S.Diag(FD->getBeginLoc(),
10102                  diag::note_ovl_candidate_unsatisfied_constraints);
10103         else
10104           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10105               << FD;
10106         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10107       }
10108       return false;
10109     }
10110   }
10111 
10112   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10113     return P->hasAttr<PassObjectSizeAttr>();
10114   });
10115   if (I == FD->param_end())
10116     return true;
10117 
10118   if (Complain) {
10119     // Add one to ParamNo because it's user-facing
10120     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10121     if (InOverloadResolution)
10122       S.Diag(FD->getLocation(),
10123              diag::note_ovl_candidate_has_pass_object_size_params)
10124           << ParamNo;
10125     else
10126       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10127           << FD << ParamNo;
10128   }
10129   return false;
10130 }
10131 
10132 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10133                                                const FunctionDecl *FD) {
10134   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10135                                            /*InOverloadResolution=*/true,
10136                                            /*Loc=*/SourceLocation());
10137 }
10138 
10139 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10140                                              bool Complain,
10141                                              SourceLocation Loc) {
10142   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10143                                              /*InOverloadResolution=*/false,
10144                                              Loc);
10145 }
10146 
10147 // Notes the location of an overload candidate.
10148 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10149                                  OverloadCandidateRewriteKind RewriteKind,
10150                                  QualType DestType, bool TakingAddress) {
10151   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10152     return;
10153   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10154       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10155     return;
10156 
10157   std::string FnDesc;
10158   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10159       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10160   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10161                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10162                          << Fn << FnDesc;
10163 
10164   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10165   Diag(Fn->getLocation(), PD);
10166   MaybeEmitInheritedConstructorNote(*this, Found);
10167 }
10168 
10169 static void
10170 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10171   // Perhaps the ambiguity was caused by two atomic constraints that are
10172   // 'identical' but not equivalent:
10173   //
10174   // void foo() requires (sizeof(T) > 4) { } // #1
10175   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10176   //
10177   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10178   // #2 to subsume #1, but these constraint are not considered equivalent
10179   // according to the subsumption rules because they are not the same
10180   // source-level construct. This behavior is quite confusing and we should try
10181   // to help the user figure out what happened.
10182 
10183   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10184   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10185   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10186     if (!I->Function)
10187       continue;
10188     SmallVector<const Expr *, 3> AC;
10189     if (auto *Template = I->Function->getPrimaryTemplate())
10190       Template->getAssociatedConstraints(AC);
10191     else
10192       I->Function->getAssociatedConstraints(AC);
10193     if (AC.empty())
10194       continue;
10195     if (FirstCand == nullptr) {
10196       FirstCand = I->Function;
10197       FirstAC = AC;
10198     } else if (SecondCand == nullptr) {
10199       SecondCand = I->Function;
10200       SecondAC = AC;
10201     } else {
10202       // We have more than one pair of constrained functions - this check is
10203       // expensive and we'd rather not try to diagnose it.
10204       return;
10205     }
10206   }
10207   if (!SecondCand)
10208     return;
10209   // The diagnostic can only happen if there are associated constraints on
10210   // both sides (there needs to be some identical atomic constraint).
10211   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10212                                                       SecondCand, SecondAC))
10213     // Just show the user one diagnostic, they'll probably figure it out
10214     // from here.
10215     return;
10216 }
10217 
10218 // Notes the location of all overload candidates designated through
10219 // OverloadedExpr
10220 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10221                                      bool TakingAddress) {
10222   assert(OverloadedExpr->getType() == Context.OverloadTy);
10223 
10224   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10225   OverloadExpr *OvlExpr = Ovl.Expression;
10226 
10227   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10228                             IEnd = OvlExpr->decls_end();
10229        I != IEnd; ++I) {
10230     if (FunctionTemplateDecl *FunTmpl =
10231                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10232       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10233                             TakingAddress);
10234     } else if (FunctionDecl *Fun
10235                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10236       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10237     }
10238   }
10239 }
10240 
10241 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10242 /// "lead" diagnostic; it will be given two arguments, the source and
10243 /// target types of the conversion.
10244 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10245                                  Sema &S,
10246                                  SourceLocation CaretLoc,
10247                                  const PartialDiagnostic &PDiag) const {
10248   S.Diag(CaretLoc, PDiag)
10249     << Ambiguous.getFromType() << Ambiguous.getToType();
10250   // FIXME: The note limiting machinery is borrowed from
10251   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10252   // refactoring here.
10253   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10254   unsigned CandsShown = 0;
10255   AmbiguousConversionSequence::const_iterator I, E;
10256   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10257     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10258       break;
10259     ++CandsShown;
10260     S.NoteOverloadCandidate(I->first, I->second);
10261   }
10262   if (I != E)
10263     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10264 }
10265 
10266 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10267                                   unsigned I, bool TakingCandidateAddress) {
10268   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10269   assert(Conv.isBad());
10270   assert(Cand->Function && "for now, candidate must be a function");
10271   FunctionDecl *Fn = Cand->Function;
10272 
10273   // There's a conversion slot for the object argument if this is a
10274   // non-constructor method.  Note that 'I' corresponds the
10275   // conversion-slot index.
10276   bool isObjectArgument = false;
10277   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10278     if (I == 0)
10279       isObjectArgument = true;
10280     else
10281       I--;
10282   }
10283 
10284   std::string FnDesc;
10285   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10286       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10287                                 FnDesc);
10288 
10289   Expr *FromExpr = Conv.Bad.FromExpr;
10290   QualType FromTy = Conv.Bad.getFromType();
10291   QualType ToTy = Conv.Bad.getToType();
10292 
10293   if (FromTy == S.Context.OverloadTy) {
10294     assert(FromExpr && "overload set argument came from implicit argument?");
10295     Expr *E = FromExpr->IgnoreParens();
10296     if (isa<UnaryOperator>(E))
10297       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10298     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10299 
10300     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10301         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10302         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10303         << Name << I + 1;
10304     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10305     return;
10306   }
10307 
10308   // Do some hand-waving analysis to see if the non-viability is due
10309   // to a qualifier mismatch.
10310   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10311   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10312   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10313     CToTy = RT->getPointeeType();
10314   else {
10315     // TODO: detect and diagnose the full richness of const mismatches.
10316     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10317       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10318         CFromTy = FromPT->getPointeeType();
10319         CToTy = ToPT->getPointeeType();
10320       }
10321   }
10322 
10323   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10324       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10325     Qualifiers FromQs = CFromTy.getQualifiers();
10326     Qualifiers ToQs = CToTy.getQualifiers();
10327 
10328     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10329       if (isObjectArgument)
10330         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10331             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10332             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10333             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10334       else
10335         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10336             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10337             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10338             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10339             << ToTy->isReferenceType() << I + 1;
10340       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10341       return;
10342     }
10343 
10344     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10345       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10346           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10347           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10348           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10349           << (unsigned)isObjectArgument << I + 1;
10350       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10351       return;
10352     }
10353 
10354     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10355       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10356           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10357           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10358           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10359           << (unsigned)isObjectArgument << I + 1;
10360       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10361       return;
10362     }
10363 
10364     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10365       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10366           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10367           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10368           << FromQs.hasUnaligned() << I + 1;
10369       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10370       return;
10371     }
10372 
10373     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10374     assert(CVR && "unexpected qualifiers mismatch");
10375 
10376     if (isObjectArgument) {
10377       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10378           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10379           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10380           << (CVR - 1);
10381     } else {
10382       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10383           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10384           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10385           << (CVR - 1) << I + 1;
10386     }
10387     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10388     return;
10389   }
10390 
10391   // Special diagnostic for failure to convert an initializer list, since
10392   // telling the user that it has type void is not useful.
10393   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10394     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10395         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10396         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10397         << ToTy << (unsigned)isObjectArgument << I + 1;
10398     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10399     return;
10400   }
10401 
10402   // Diagnose references or pointers to incomplete types differently,
10403   // since it's far from impossible that the incompleteness triggered
10404   // the failure.
10405   QualType TempFromTy = FromTy.getNonReferenceType();
10406   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10407     TempFromTy = PTy->getPointeeType();
10408   if (TempFromTy->isIncompleteType()) {
10409     // Emit the generic diagnostic and, optionally, add the hints to it.
10410     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10411         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10412         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10413         << ToTy << (unsigned)isObjectArgument << I + 1
10414         << (unsigned)(Cand->Fix.Kind);
10415 
10416     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10417     return;
10418   }
10419 
10420   // Diagnose base -> derived pointer conversions.
10421   unsigned BaseToDerivedConversion = 0;
10422   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10423     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10424       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10425                                                FromPtrTy->getPointeeType()) &&
10426           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10427           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10428           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10429                           FromPtrTy->getPointeeType()))
10430         BaseToDerivedConversion = 1;
10431     }
10432   } else if (const ObjCObjectPointerType *FromPtrTy
10433                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10434     if (const ObjCObjectPointerType *ToPtrTy
10435                                         = ToTy->getAs<ObjCObjectPointerType>())
10436       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10437         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10438           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10439                                                 FromPtrTy->getPointeeType()) &&
10440               FromIface->isSuperClassOf(ToIface))
10441             BaseToDerivedConversion = 2;
10442   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10443     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10444         !FromTy->isIncompleteType() &&
10445         !ToRefTy->getPointeeType()->isIncompleteType() &&
10446         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10447       BaseToDerivedConversion = 3;
10448     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10449                ToTy.getNonReferenceType().getCanonicalType() ==
10450                FromTy.getNonReferenceType().getCanonicalType()) {
10451       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10452           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10453           << (unsigned)isObjectArgument << I + 1
10454           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10455       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10456       return;
10457     }
10458   }
10459 
10460   if (BaseToDerivedConversion) {
10461     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10462         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10463         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10464         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10465     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10466     return;
10467   }
10468 
10469   if (isa<ObjCObjectPointerType>(CFromTy) &&
10470       isa<PointerType>(CToTy)) {
10471       Qualifiers FromQs = CFromTy.getQualifiers();
10472       Qualifiers ToQs = CToTy.getQualifiers();
10473       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10474         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10475             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10476             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10477             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10478         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10479         return;
10480       }
10481   }
10482 
10483   if (TakingCandidateAddress &&
10484       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10485     return;
10486 
10487   // Emit the generic diagnostic and, optionally, add the hints to it.
10488   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10489   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10490         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10491         << ToTy << (unsigned)isObjectArgument << I + 1
10492         << (unsigned)(Cand->Fix.Kind);
10493 
10494   // If we can fix the conversion, suggest the FixIts.
10495   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10496        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10497     FDiag << *HI;
10498   S.Diag(Fn->getLocation(), FDiag);
10499 
10500   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10501 }
10502 
10503 /// Additional arity mismatch diagnosis specific to a function overload
10504 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10505 /// over a candidate in any candidate set.
10506 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10507                                unsigned NumArgs) {
10508   FunctionDecl *Fn = Cand->Function;
10509   unsigned MinParams = Fn->getMinRequiredArguments();
10510 
10511   // With invalid overloaded operators, it's possible that we think we
10512   // have an arity mismatch when in fact it looks like we have the
10513   // right number of arguments, because only overloaded operators have
10514   // the weird behavior of overloading member and non-member functions.
10515   // Just don't report anything.
10516   if (Fn->isInvalidDecl() &&
10517       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10518     return true;
10519 
10520   if (NumArgs < MinParams) {
10521     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10522            (Cand->FailureKind == ovl_fail_bad_deduction &&
10523             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10524   } else {
10525     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10526            (Cand->FailureKind == ovl_fail_bad_deduction &&
10527             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10528   }
10529 
10530   return false;
10531 }
10532 
10533 /// General arity mismatch diagnosis over a candidate in a candidate set.
10534 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10535                                   unsigned NumFormalArgs) {
10536   assert(isa<FunctionDecl>(D) &&
10537       "The templated declaration should at least be a function"
10538       " when diagnosing bad template argument deduction due to too many"
10539       " or too few arguments");
10540 
10541   FunctionDecl *Fn = cast<FunctionDecl>(D);
10542 
10543   // TODO: treat calls to a missing default constructor as a special case
10544   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10545   unsigned MinParams = Fn->getMinRequiredArguments();
10546 
10547   // at least / at most / exactly
10548   unsigned mode, modeCount;
10549   if (NumFormalArgs < MinParams) {
10550     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10551         FnTy->isTemplateVariadic())
10552       mode = 0; // "at least"
10553     else
10554       mode = 2; // "exactly"
10555     modeCount = MinParams;
10556   } else {
10557     if (MinParams != FnTy->getNumParams())
10558       mode = 1; // "at most"
10559     else
10560       mode = 2; // "exactly"
10561     modeCount = FnTy->getNumParams();
10562   }
10563 
10564   std::string Description;
10565   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10566       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10567 
10568   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10569     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10570         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10571         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10572   else
10573     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10574         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10575         << Description << mode << modeCount << NumFormalArgs;
10576 
10577   MaybeEmitInheritedConstructorNote(S, Found);
10578 }
10579 
10580 /// Arity mismatch diagnosis specific to a function overload candidate.
10581 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10582                                   unsigned NumFormalArgs) {
10583   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10584     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10585 }
10586 
10587 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10588   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10589     return TD;
10590   llvm_unreachable("Unsupported: Getting the described template declaration"
10591                    " for bad deduction diagnosis");
10592 }
10593 
10594 /// Diagnose a failed template-argument deduction.
10595 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10596                                  DeductionFailureInfo &DeductionFailure,
10597                                  unsigned NumArgs,
10598                                  bool TakingCandidateAddress) {
10599   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10600   NamedDecl *ParamD;
10601   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10602   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10603   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10604   switch (DeductionFailure.Result) {
10605   case Sema::TDK_Success:
10606     llvm_unreachable("TDK_success while diagnosing bad deduction");
10607 
10608   case Sema::TDK_Incomplete: {
10609     assert(ParamD && "no parameter found for incomplete deduction result");
10610     S.Diag(Templated->getLocation(),
10611            diag::note_ovl_candidate_incomplete_deduction)
10612         << ParamD->getDeclName();
10613     MaybeEmitInheritedConstructorNote(S, Found);
10614     return;
10615   }
10616 
10617   case Sema::TDK_IncompletePack: {
10618     assert(ParamD && "no parameter found for incomplete deduction result");
10619     S.Diag(Templated->getLocation(),
10620            diag::note_ovl_candidate_incomplete_deduction_pack)
10621         << ParamD->getDeclName()
10622         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10623         << *DeductionFailure.getFirstArg();
10624     MaybeEmitInheritedConstructorNote(S, Found);
10625     return;
10626   }
10627 
10628   case Sema::TDK_Underqualified: {
10629     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10630     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10631 
10632     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10633 
10634     // Param will have been canonicalized, but it should just be a
10635     // qualified version of ParamD, so move the qualifiers to that.
10636     QualifierCollector Qs;
10637     Qs.strip(Param);
10638     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10639     assert(S.Context.hasSameType(Param, NonCanonParam));
10640 
10641     // Arg has also been canonicalized, but there's nothing we can do
10642     // about that.  It also doesn't matter as much, because it won't
10643     // have any template parameters in it (because deduction isn't
10644     // done on dependent types).
10645     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10646 
10647     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10648         << ParamD->getDeclName() << Arg << NonCanonParam;
10649     MaybeEmitInheritedConstructorNote(S, Found);
10650     return;
10651   }
10652 
10653   case Sema::TDK_Inconsistent: {
10654     assert(ParamD && "no parameter found for inconsistent deduction result");
10655     int which = 0;
10656     if (isa<TemplateTypeParmDecl>(ParamD))
10657       which = 0;
10658     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10659       // Deduction might have failed because we deduced arguments of two
10660       // different types for a non-type template parameter.
10661       // FIXME: Use a different TDK value for this.
10662       QualType T1 =
10663           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10664       QualType T2 =
10665           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10666       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10667         S.Diag(Templated->getLocation(),
10668                diag::note_ovl_candidate_inconsistent_deduction_types)
10669           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10670           << *DeductionFailure.getSecondArg() << T2;
10671         MaybeEmitInheritedConstructorNote(S, Found);
10672         return;
10673       }
10674 
10675       which = 1;
10676     } else {
10677       which = 2;
10678     }
10679 
10680     // Tweak the diagnostic if the problem is that we deduced packs of
10681     // different arities. We'll print the actual packs anyway in case that
10682     // includes additional useful information.
10683     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10684         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10685         DeductionFailure.getFirstArg()->pack_size() !=
10686             DeductionFailure.getSecondArg()->pack_size()) {
10687       which = 3;
10688     }
10689 
10690     S.Diag(Templated->getLocation(),
10691            diag::note_ovl_candidate_inconsistent_deduction)
10692         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10693         << *DeductionFailure.getSecondArg();
10694     MaybeEmitInheritedConstructorNote(S, Found);
10695     return;
10696   }
10697 
10698   case Sema::TDK_InvalidExplicitArguments:
10699     assert(ParamD && "no parameter found for invalid explicit arguments");
10700     if (ParamD->getDeclName())
10701       S.Diag(Templated->getLocation(),
10702              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10703           << ParamD->getDeclName();
10704     else {
10705       int index = 0;
10706       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10707         index = TTP->getIndex();
10708       else if (NonTypeTemplateParmDecl *NTTP
10709                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10710         index = NTTP->getIndex();
10711       else
10712         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10713       S.Diag(Templated->getLocation(),
10714              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10715           << (index + 1);
10716     }
10717     MaybeEmitInheritedConstructorNote(S, Found);
10718     return;
10719 
10720   case Sema::TDK_ConstraintsNotSatisfied: {
10721     // Format the template argument list into the argument string.
10722     SmallString<128> TemplateArgString;
10723     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10724     TemplateArgString = " ";
10725     TemplateArgString += S.getTemplateArgumentBindingsText(
10726         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10727     if (TemplateArgString.size() == 1)
10728       TemplateArgString.clear();
10729     S.Diag(Templated->getLocation(),
10730            diag::note_ovl_candidate_unsatisfied_constraints)
10731         << TemplateArgString;
10732 
10733     S.DiagnoseUnsatisfiedConstraint(
10734         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10735     return;
10736   }
10737   case Sema::TDK_TooManyArguments:
10738   case Sema::TDK_TooFewArguments:
10739     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10740     return;
10741 
10742   case Sema::TDK_InstantiationDepth:
10743     S.Diag(Templated->getLocation(),
10744            diag::note_ovl_candidate_instantiation_depth);
10745     MaybeEmitInheritedConstructorNote(S, Found);
10746     return;
10747 
10748   case Sema::TDK_SubstitutionFailure: {
10749     // Format the template argument list into the argument string.
10750     SmallString<128> TemplateArgString;
10751     if (TemplateArgumentList *Args =
10752             DeductionFailure.getTemplateArgumentList()) {
10753       TemplateArgString = " ";
10754       TemplateArgString += S.getTemplateArgumentBindingsText(
10755           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10756       if (TemplateArgString.size() == 1)
10757         TemplateArgString.clear();
10758     }
10759 
10760     // If this candidate was disabled by enable_if, say so.
10761     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10762     if (PDiag && PDiag->second.getDiagID() ==
10763           diag::err_typename_nested_not_found_enable_if) {
10764       // FIXME: Use the source range of the condition, and the fully-qualified
10765       //        name of the enable_if template. These are both present in PDiag.
10766       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10767         << "'enable_if'" << TemplateArgString;
10768       return;
10769     }
10770 
10771     // We found a specific requirement that disabled the enable_if.
10772     if (PDiag && PDiag->second.getDiagID() ==
10773         diag::err_typename_nested_not_found_requirement) {
10774       S.Diag(Templated->getLocation(),
10775              diag::note_ovl_candidate_disabled_by_requirement)
10776         << PDiag->second.getStringArg(0) << TemplateArgString;
10777       return;
10778     }
10779 
10780     // Format the SFINAE diagnostic into the argument string.
10781     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10782     //        formatted message in another diagnostic.
10783     SmallString<128> SFINAEArgString;
10784     SourceRange R;
10785     if (PDiag) {
10786       SFINAEArgString = ": ";
10787       R = SourceRange(PDiag->first, PDiag->first);
10788       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10789     }
10790 
10791     S.Diag(Templated->getLocation(),
10792            diag::note_ovl_candidate_substitution_failure)
10793         << TemplateArgString << SFINAEArgString << R;
10794     MaybeEmitInheritedConstructorNote(S, Found);
10795     return;
10796   }
10797 
10798   case Sema::TDK_DeducedMismatch:
10799   case Sema::TDK_DeducedMismatchNested: {
10800     // Format the template argument list into the argument string.
10801     SmallString<128> TemplateArgString;
10802     if (TemplateArgumentList *Args =
10803             DeductionFailure.getTemplateArgumentList()) {
10804       TemplateArgString = " ";
10805       TemplateArgString += S.getTemplateArgumentBindingsText(
10806           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10807       if (TemplateArgString.size() == 1)
10808         TemplateArgString.clear();
10809     }
10810 
10811     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10812         << (*DeductionFailure.getCallArgIndex() + 1)
10813         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10814         << TemplateArgString
10815         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10816     break;
10817   }
10818 
10819   case Sema::TDK_NonDeducedMismatch: {
10820     // FIXME: Provide a source location to indicate what we couldn't match.
10821     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10822     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10823     if (FirstTA.getKind() == TemplateArgument::Template &&
10824         SecondTA.getKind() == TemplateArgument::Template) {
10825       TemplateName FirstTN = FirstTA.getAsTemplate();
10826       TemplateName SecondTN = SecondTA.getAsTemplate();
10827       if (FirstTN.getKind() == TemplateName::Template &&
10828           SecondTN.getKind() == TemplateName::Template) {
10829         if (FirstTN.getAsTemplateDecl()->getName() ==
10830             SecondTN.getAsTemplateDecl()->getName()) {
10831           // FIXME: This fixes a bad diagnostic where both templates are named
10832           // the same.  This particular case is a bit difficult since:
10833           // 1) It is passed as a string to the diagnostic printer.
10834           // 2) The diagnostic printer only attempts to find a better
10835           //    name for types, not decls.
10836           // Ideally, this should folded into the diagnostic printer.
10837           S.Diag(Templated->getLocation(),
10838                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10839               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10840           return;
10841         }
10842       }
10843     }
10844 
10845     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10846         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10847       return;
10848 
10849     // FIXME: For generic lambda parameters, check if the function is a lambda
10850     // call operator, and if so, emit a prettier and more informative
10851     // diagnostic that mentions 'auto' and lambda in addition to
10852     // (or instead of?) the canonical template type parameters.
10853     S.Diag(Templated->getLocation(),
10854            diag::note_ovl_candidate_non_deduced_mismatch)
10855         << FirstTA << SecondTA;
10856     return;
10857   }
10858   // TODO: diagnose these individually, then kill off
10859   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10860   case Sema::TDK_MiscellaneousDeductionFailure:
10861     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10862     MaybeEmitInheritedConstructorNote(S, Found);
10863     return;
10864   case Sema::TDK_CUDATargetMismatch:
10865     S.Diag(Templated->getLocation(),
10866            diag::note_cuda_ovl_candidate_target_mismatch);
10867     return;
10868   }
10869 }
10870 
10871 /// Diagnose a failed template-argument deduction, for function calls.
10872 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10873                                  unsigned NumArgs,
10874                                  bool TakingCandidateAddress) {
10875   unsigned TDK = Cand->DeductionFailure.Result;
10876   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10877     if (CheckArityMismatch(S, Cand, NumArgs))
10878       return;
10879   }
10880   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10881                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10882 }
10883 
10884 /// CUDA: diagnose an invalid call across targets.
10885 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10886   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10887   FunctionDecl *Callee = Cand->Function;
10888 
10889   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10890                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10891 
10892   std::string FnDesc;
10893   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10894       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10895                                 Cand->getRewriteKind(), FnDesc);
10896 
10897   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10898       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10899       << FnDesc /* Ignored */
10900       << CalleeTarget << CallerTarget;
10901 
10902   // This could be an implicit constructor for which we could not infer the
10903   // target due to a collsion. Diagnose that case.
10904   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10905   if (Meth != nullptr && Meth->isImplicit()) {
10906     CXXRecordDecl *ParentClass = Meth->getParent();
10907     Sema::CXXSpecialMember CSM;
10908 
10909     switch (FnKindPair.first) {
10910     default:
10911       return;
10912     case oc_implicit_default_constructor:
10913       CSM = Sema::CXXDefaultConstructor;
10914       break;
10915     case oc_implicit_copy_constructor:
10916       CSM = Sema::CXXCopyConstructor;
10917       break;
10918     case oc_implicit_move_constructor:
10919       CSM = Sema::CXXMoveConstructor;
10920       break;
10921     case oc_implicit_copy_assignment:
10922       CSM = Sema::CXXCopyAssignment;
10923       break;
10924     case oc_implicit_move_assignment:
10925       CSM = Sema::CXXMoveAssignment;
10926       break;
10927     };
10928 
10929     bool ConstRHS = false;
10930     if (Meth->getNumParams()) {
10931       if (const ReferenceType *RT =
10932               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10933         ConstRHS = RT->getPointeeType().isConstQualified();
10934       }
10935     }
10936 
10937     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10938                                               /* ConstRHS */ ConstRHS,
10939                                               /* Diagnose */ true);
10940   }
10941 }
10942 
10943 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10944   FunctionDecl *Callee = Cand->Function;
10945   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10946 
10947   S.Diag(Callee->getLocation(),
10948          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10949       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10950 }
10951 
10952 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10953   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10954   assert(ES.isExplicit() && "not an explicit candidate");
10955 
10956   unsigned Kind;
10957   switch (Cand->Function->getDeclKind()) {
10958   case Decl::Kind::CXXConstructor:
10959     Kind = 0;
10960     break;
10961   case Decl::Kind::CXXConversion:
10962     Kind = 1;
10963     break;
10964   case Decl::Kind::CXXDeductionGuide:
10965     Kind = Cand->Function->isImplicit() ? 0 : 2;
10966     break;
10967   default:
10968     llvm_unreachable("invalid Decl");
10969   }
10970 
10971   // Note the location of the first (in-class) declaration; a redeclaration
10972   // (particularly an out-of-class definition) will typically lack the
10973   // 'explicit' specifier.
10974   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10975   FunctionDecl *First = Cand->Function->getFirstDecl();
10976   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10977     First = Pattern->getFirstDecl();
10978 
10979   S.Diag(First->getLocation(),
10980          diag::note_ovl_candidate_explicit)
10981       << Kind << (ES.getExpr() ? 1 : 0)
10982       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10983 }
10984 
10985 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10986   FunctionDecl *Callee = Cand->Function;
10987 
10988   S.Diag(Callee->getLocation(),
10989          diag::note_ovl_candidate_disabled_by_extension)
10990     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10991 }
10992 
10993 /// Generates a 'note' diagnostic for an overload candidate.  We've
10994 /// already generated a primary error at the call site.
10995 ///
10996 /// It really does need to be a single diagnostic with its caret
10997 /// pointed at the candidate declaration.  Yes, this creates some
10998 /// major challenges of technical writing.  Yes, this makes pointing
10999 /// out problems with specific arguments quite awkward.  It's still
11000 /// better than generating twenty screens of text for every failed
11001 /// overload.
11002 ///
11003 /// It would be great to be able to express per-candidate problems
11004 /// more richly for those diagnostic clients that cared, but we'd
11005 /// still have to be just as careful with the default diagnostics.
11006 /// \param CtorDestAS Addr space of object being constructed (for ctor
11007 /// candidates only).
11008 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
11009                                   unsigned NumArgs,
11010                                   bool TakingCandidateAddress,
11011                                   LangAS CtorDestAS = LangAS::Default) {
11012   FunctionDecl *Fn = Cand->Function;
11013 
11014   // Note deleted candidates, but only if they're viable.
11015   if (Cand->Viable) {
11016     if (Fn->isDeleted()) {
11017       std::string FnDesc;
11018       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11019           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11020                                     Cand->getRewriteKind(), FnDesc);
11021 
11022       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
11023           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11024           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
11025       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11026       return;
11027     }
11028 
11029     // We don't really have anything else to say about viable candidates.
11030     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11031     return;
11032   }
11033 
11034   switch (Cand->FailureKind) {
11035   case ovl_fail_too_many_arguments:
11036   case ovl_fail_too_few_arguments:
11037     return DiagnoseArityMismatch(S, Cand, NumArgs);
11038 
11039   case ovl_fail_bad_deduction:
11040     return DiagnoseBadDeduction(S, Cand, NumArgs,
11041                                 TakingCandidateAddress);
11042 
11043   case ovl_fail_illegal_constructor: {
11044     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11045       << (Fn->getPrimaryTemplate() ? 1 : 0);
11046     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11047     return;
11048   }
11049 
11050   case ovl_fail_object_addrspace_mismatch: {
11051     Qualifiers QualsForPrinting;
11052     QualsForPrinting.setAddressSpace(CtorDestAS);
11053     S.Diag(Fn->getLocation(),
11054            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11055         << QualsForPrinting;
11056     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11057     return;
11058   }
11059 
11060   case ovl_fail_trivial_conversion:
11061   case ovl_fail_bad_final_conversion:
11062   case ovl_fail_final_conversion_not_exact:
11063     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11064 
11065   case ovl_fail_bad_conversion: {
11066     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11067     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11068       if (Cand->Conversions[I].isBad())
11069         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11070 
11071     // FIXME: this currently happens when we're called from SemaInit
11072     // when user-conversion overload fails.  Figure out how to handle
11073     // those conditions and diagnose them well.
11074     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11075   }
11076 
11077   case ovl_fail_bad_target:
11078     return DiagnoseBadTarget(S, Cand);
11079 
11080   case ovl_fail_enable_if:
11081     return DiagnoseFailedEnableIfAttr(S, Cand);
11082 
11083   case ovl_fail_explicit:
11084     return DiagnoseFailedExplicitSpec(S, Cand);
11085 
11086   case ovl_fail_ext_disabled:
11087     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11088 
11089   case ovl_fail_inhctor_slice:
11090     // It's generally not interesting to note copy/move constructors here.
11091     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11092       return;
11093     S.Diag(Fn->getLocation(),
11094            diag::note_ovl_candidate_inherited_constructor_slice)
11095       << (Fn->getPrimaryTemplate() ? 1 : 0)
11096       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11097     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11098     return;
11099 
11100   case ovl_fail_addr_not_available: {
11101     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11102     (void)Available;
11103     assert(!Available);
11104     break;
11105   }
11106   case ovl_non_default_multiversion_function:
11107     // Do nothing, these should simply be ignored.
11108     break;
11109 
11110   case ovl_fail_constraints_not_satisfied: {
11111     std::string FnDesc;
11112     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11113         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11114                                   Cand->getRewriteKind(), FnDesc);
11115 
11116     S.Diag(Fn->getLocation(),
11117            diag::note_ovl_candidate_constraints_not_satisfied)
11118         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11119         << FnDesc /* Ignored */;
11120     ConstraintSatisfaction Satisfaction;
11121     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11122       break;
11123     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11124   }
11125   }
11126 }
11127 
11128 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11129   // Desugar the type of the surrogate down to a function type,
11130   // retaining as many typedefs as possible while still showing
11131   // the function type (and, therefore, its parameter types).
11132   QualType FnType = Cand->Surrogate->getConversionType();
11133   bool isLValueReference = false;
11134   bool isRValueReference = false;
11135   bool isPointer = false;
11136   if (const LValueReferenceType *FnTypeRef =
11137         FnType->getAs<LValueReferenceType>()) {
11138     FnType = FnTypeRef->getPointeeType();
11139     isLValueReference = true;
11140   } else if (const RValueReferenceType *FnTypeRef =
11141                FnType->getAs<RValueReferenceType>()) {
11142     FnType = FnTypeRef->getPointeeType();
11143     isRValueReference = true;
11144   }
11145   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11146     FnType = FnTypePtr->getPointeeType();
11147     isPointer = true;
11148   }
11149   // Desugar down to a function type.
11150   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11151   // Reconstruct the pointer/reference as appropriate.
11152   if (isPointer) FnType = S.Context.getPointerType(FnType);
11153   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11154   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11155 
11156   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11157     << FnType;
11158 }
11159 
11160 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11161                                          SourceLocation OpLoc,
11162                                          OverloadCandidate *Cand) {
11163   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11164   std::string TypeStr("operator");
11165   TypeStr += Opc;
11166   TypeStr += "(";
11167   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11168   if (Cand->Conversions.size() == 1) {
11169     TypeStr += ")";
11170     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11171   } else {
11172     TypeStr += ", ";
11173     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11174     TypeStr += ")";
11175     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11176   }
11177 }
11178 
11179 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11180                                          OverloadCandidate *Cand) {
11181   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11182     if (ICS.isBad()) break; // all meaningless after first invalid
11183     if (!ICS.isAmbiguous()) continue;
11184 
11185     ICS.DiagnoseAmbiguousConversion(
11186         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11187   }
11188 }
11189 
11190 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11191   if (Cand->Function)
11192     return Cand->Function->getLocation();
11193   if (Cand->IsSurrogate)
11194     return Cand->Surrogate->getLocation();
11195   return SourceLocation();
11196 }
11197 
11198 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11199   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11200   case Sema::TDK_Success:
11201   case Sema::TDK_NonDependentConversionFailure:
11202     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11203 
11204   case Sema::TDK_Invalid:
11205   case Sema::TDK_Incomplete:
11206   case Sema::TDK_IncompletePack:
11207     return 1;
11208 
11209   case Sema::TDK_Underqualified:
11210   case Sema::TDK_Inconsistent:
11211     return 2;
11212 
11213   case Sema::TDK_SubstitutionFailure:
11214   case Sema::TDK_DeducedMismatch:
11215   case Sema::TDK_ConstraintsNotSatisfied:
11216   case Sema::TDK_DeducedMismatchNested:
11217   case Sema::TDK_NonDeducedMismatch:
11218   case Sema::TDK_MiscellaneousDeductionFailure:
11219   case Sema::TDK_CUDATargetMismatch:
11220     return 3;
11221 
11222   case Sema::TDK_InstantiationDepth:
11223     return 4;
11224 
11225   case Sema::TDK_InvalidExplicitArguments:
11226     return 5;
11227 
11228   case Sema::TDK_TooManyArguments:
11229   case Sema::TDK_TooFewArguments:
11230     return 6;
11231   }
11232   llvm_unreachable("Unhandled deduction result");
11233 }
11234 
11235 namespace {
11236 struct CompareOverloadCandidatesForDisplay {
11237   Sema &S;
11238   SourceLocation Loc;
11239   size_t NumArgs;
11240   OverloadCandidateSet::CandidateSetKind CSK;
11241 
11242   CompareOverloadCandidatesForDisplay(
11243       Sema &S, SourceLocation Loc, size_t NArgs,
11244       OverloadCandidateSet::CandidateSetKind CSK)
11245       : S(S), NumArgs(NArgs), CSK(CSK) {}
11246 
11247   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11248     // If there are too many or too few arguments, that's the high-order bit we
11249     // want to sort by, even if the immediate failure kind was something else.
11250     if (C->FailureKind == ovl_fail_too_many_arguments ||
11251         C->FailureKind == ovl_fail_too_few_arguments)
11252       return static_cast<OverloadFailureKind>(C->FailureKind);
11253 
11254     if (C->Function) {
11255       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11256         return ovl_fail_too_many_arguments;
11257       if (NumArgs < C->Function->getMinRequiredArguments())
11258         return ovl_fail_too_few_arguments;
11259     }
11260 
11261     return static_cast<OverloadFailureKind>(C->FailureKind);
11262   }
11263 
11264   bool operator()(const OverloadCandidate *L,
11265                   const OverloadCandidate *R) {
11266     // Fast-path this check.
11267     if (L == R) return false;
11268 
11269     // Order first by viability.
11270     if (L->Viable) {
11271       if (!R->Viable) return true;
11272 
11273       // TODO: introduce a tri-valued comparison for overload
11274       // candidates.  Would be more worthwhile if we had a sort
11275       // that could exploit it.
11276       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11277         return true;
11278       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11279         return false;
11280     } else if (R->Viable)
11281       return false;
11282 
11283     assert(L->Viable == R->Viable);
11284 
11285     // Criteria by which we can sort non-viable candidates:
11286     if (!L->Viable) {
11287       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11288       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11289 
11290       // 1. Arity mismatches come after other candidates.
11291       if (LFailureKind == ovl_fail_too_many_arguments ||
11292           LFailureKind == ovl_fail_too_few_arguments) {
11293         if (RFailureKind == ovl_fail_too_many_arguments ||
11294             RFailureKind == ovl_fail_too_few_arguments) {
11295           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11296           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11297           if (LDist == RDist) {
11298             if (LFailureKind == RFailureKind)
11299               // Sort non-surrogates before surrogates.
11300               return !L->IsSurrogate && R->IsSurrogate;
11301             // Sort candidates requiring fewer parameters than there were
11302             // arguments given after candidates requiring more parameters
11303             // than there were arguments given.
11304             return LFailureKind == ovl_fail_too_many_arguments;
11305           }
11306           return LDist < RDist;
11307         }
11308         return false;
11309       }
11310       if (RFailureKind == ovl_fail_too_many_arguments ||
11311           RFailureKind == ovl_fail_too_few_arguments)
11312         return true;
11313 
11314       // 2. Bad conversions come first and are ordered by the number
11315       // of bad conversions and quality of good conversions.
11316       if (LFailureKind == ovl_fail_bad_conversion) {
11317         if (RFailureKind != ovl_fail_bad_conversion)
11318           return true;
11319 
11320         // The conversion that can be fixed with a smaller number of changes,
11321         // comes first.
11322         unsigned numLFixes = L->Fix.NumConversionsFixed;
11323         unsigned numRFixes = R->Fix.NumConversionsFixed;
11324         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11325         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11326         if (numLFixes != numRFixes) {
11327           return numLFixes < numRFixes;
11328         }
11329 
11330         // If there's any ordering between the defined conversions...
11331         // FIXME: this might not be transitive.
11332         assert(L->Conversions.size() == R->Conversions.size());
11333 
11334         int leftBetter = 0;
11335         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11336         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11337           switch (CompareImplicitConversionSequences(S, Loc,
11338                                                      L->Conversions[I],
11339                                                      R->Conversions[I])) {
11340           case ImplicitConversionSequence::Better:
11341             leftBetter++;
11342             break;
11343 
11344           case ImplicitConversionSequence::Worse:
11345             leftBetter--;
11346             break;
11347 
11348           case ImplicitConversionSequence::Indistinguishable:
11349             break;
11350           }
11351         }
11352         if (leftBetter > 0) return true;
11353         if (leftBetter < 0) return false;
11354 
11355       } else if (RFailureKind == ovl_fail_bad_conversion)
11356         return false;
11357 
11358       if (LFailureKind == ovl_fail_bad_deduction) {
11359         if (RFailureKind != ovl_fail_bad_deduction)
11360           return true;
11361 
11362         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11363           return RankDeductionFailure(L->DeductionFailure)
11364                < RankDeductionFailure(R->DeductionFailure);
11365       } else if (RFailureKind == ovl_fail_bad_deduction)
11366         return false;
11367 
11368       // TODO: others?
11369     }
11370 
11371     // Sort everything else by location.
11372     SourceLocation LLoc = GetLocationForCandidate(L);
11373     SourceLocation RLoc = GetLocationForCandidate(R);
11374 
11375     // Put candidates without locations (e.g. builtins) at the end.
11376     if (LLoc.isInvalid()) return false;
11377     if (RLoc.isInvalid()) return true;
11378 
11379     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11380   }
11381 };
11382 }
11383 
11384 /// CompleteNonViableCandidate - Normally, overload resolution only
11385 /// computes up to the first bad conversion. Produces the FixIt set if
11386 /// possible.
11387 static void
11388 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11389                            ArrayRef<Expr *> Args,
11390                            OverloadCandidateSet::CandidateSetKind CSK) {
11391   assert(!Cand->Viable);
11392 
11393   // Don't do anything on failures other than bad conversion.
11394   if (Cand->FailureKind != ovl_fail_bad_conversion)
11395     return;
11396 
11397   // We only want the FixIts if all the arguments can be corrected.
11398   bool Unfixable = false;
11399   // Use a implicit copy initialization to check conversion fixes.
11400   Cand->Fix.setConversionChecker(TryCopyInitialization);
11401 
11402   // Attempt to fix the bad conversion.
11403   unsigned ConvCount = Cand->Conversions.size();
11404   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11405        ++ConvIdx) {
11406     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11407     if (Cand->Conversions[ConvIdx].isInitialized() &&
11408         Cand->Conversions[ConvIdx].isBad()) {
11409       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11410       break;
11411     }
11412   }
11413 
11414   // FIXME: this should probably be preserved from the overload
11415   // operation somehow.
11416   bool SuppressUserConversions = false;
11417 
11418   unsigned ConvIdx = 0;
11419   unsigned ArgIdx = 0;
11420   ArrayRef<QualType> ParamTypes;
11421   bool Reversed = Cand->isReversed();
11422 
11423   if (Cand->IsSurrogate) {
11424     QualType ConvType
11425       = Cand->Surrogate->getConversionType().getNonReferenceType();
11426     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11427       ConvType = ConvPtrType->getPointeeType();
11428     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11429     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11430     ConvIdx = 1;
11431   } else if (Cand->Function) {
11432     ParamTypes =
11433         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11434     if (isa<CXXMethodDecl>(Cand->Function) &&
11435         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11436       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11437       ConvIdx = 1;
11438       if (CSK == OverloadCandidateSet::CSK_Operator &&
11439           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11440         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11441         ArgIdx = 1;
11442     }
11443   } else {
11444     // Builtin operator.
11445     assert(ConvCount <= 3);
11446     ParamTypes = Cand->BuiltinParamTypes;
11447   }
11448 
11449   // Fill in the rest of the conversions.
11450   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11451        ConvIdx != ConvCount;
11452        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11453     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11454     if (Cand->Conversions[ConvIdx].isInitialized()) {
11455       // We've already checked this conversion.
11456     } else if (ParamIdx < ParamTypes.size()) {
11457       if (ParamTypes[ParamIdx]->isDependentType())
11458         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11459             Args[ArgIdx]->getType());
11460       else {
11461         Cand->Conversions[ConvIdx] =
11462             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11463                                   SuppressUserConversions,
11464                                   /*InOverloadResolution=*/true,
11465                                   /*AllowObjCWritebackConversion=*/
11466                                   S.getLangOpts().ObjCAutoRefCount);
11467         // Store the FixIt in the candidate if it exists.
11468         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11469           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11470       }
11471     } else
11472       Cand->Conversions[ConvIdx].setEllipsis();
11473   }
11474 }
11475 
11476 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11477     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11478     SourceLocation OpLoc,
11479     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11480   // Sort the candidates by viability and position.  Sorting directly would
11481   // be prohibitive, so we make a set of pointers and sort those.
11482   SmallVector<OverloadCandidate*, 32> Cands;
11483   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11484   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11485     if (!Filter(*Cand))
11486       continue;
11487     switch (OCD) {
11488     case OCD_AllCandidates:
11489       if (!Cand->Viable) {
11490         if (!Cand->Function && !Cand->IsSurrogate) {
11491           // This a non-viable builtin candidate.  We do not, in general,
11492           // want to list every possible builtin candidate.
11493           continue;
11494         }
11495         CompleteNonViableCandidate(S, Cand, Args, Kind);
11496       }
11497       break;
11498 
11499     case OCD_ViableCandidates:
11500       if (!Cand->Viable)
11501         continue;
11502       break;
11503 
11504     case OCD_AmbiguousCandidates:
11505       if (!Cand->Best)
11506         continue;
11507       break;
11508     }
11509 
11510     Cands.push_back(Cand);
11511   }
11512 
11513   llvm::stable_sort(
11514       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11515 
11516   return Cands;
11517 }
11518 
11519 /// When overload resolution fails, prints diagnostic messages containing the
11520 /// candidates in the candidate set.
11521 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11522     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11523     StringRef Opc, SourceLocation OpLoc,
11524     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11525 
11526   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11527 
11528   S.Diag(PD.first, PD.second);
11529 
11530   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11531 
11532   if (OCD == OCD_AmbiguousCandidates)
11533     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11534 }
11535 
11536 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11537                                           ArrayRef<OverloadCandidate *> Cands,
11538                                           StringRef Opc, SourceLocation OpLoc) {
11539   bool ReportedAmbiguousConversions = false;
11540 
11541   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11542   unsigned CandsShown = 0;
11543   auto I = Cands.begin(), E = Cands.end();
11544   for (; I != E; ++I) {
11545     OverloadCandidate *Cand = *I;
11546 
11547     // Set an arbitrary limit on the number of candidate functions we'll spam
11548     // the user with.  FIXME: This limit should depend on details of the
11549     // candidate list.
11550     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11551       break;
11552     }
11553     ++CandsShown;
11554 
11555     if (Cand->Function)
11556       NoteFunctionCandidate(S, Cand, Args.size(),
11557                             /*TakingCandidateAddress=*/false, DestAS);
11558     else if (Cand->IsSurrogate)
11559       NoteSurrogateCandidate(S, Cand);
11560     else {
11561       assert(Cand->Viable &&
11562              "Non-viable built-in candidates are not added to Cands.");
11563       // Generally we only see ambiguities including viable builtin
11564       // operators if overload resolution got screwed up by an
11565       // ambiguous user-defined conversion.
11566       //
11567       // FIXME: It's quite possible for different conversions to see
11568       // different ambiguities, though.
11569       if (!ReportedAmbiguousConversions) {
11570         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11571         ReportedAmbiguousConversions = true;
11572       }
11573 
11574       // If this is a viable builtin, print it.
11575       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11576     }
11577   }
11578 
11579   if (I != E)
11580     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11581 }
11582 
11583 static SourceLocation
11584 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11585   return Cand->Specialization ? Cand->Specialization->getLocation()
11586                               : SourceLocation();
11587 }
11588 
11589 namespace {
11590 struct CompareTemplateSpecCandidatesForDisplay {
11591   Sema &S;
11592   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11593 
11594   bool operator()(const TemplateSpecCandidate *L,
11595                   const TemplateSpecCandidate *R) {
11596     // Fast-path this check.
11597     if (L == R)
11598       return false;
11599 
11600     // Assuming that both candidates are not matches...
11601 
11602     // Sort by the ranking of deduction failures.
11603     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11604       return RankDeductionFailure(L->DeductionFailure) <
11605              RankDeductionFailure(R->DeductionFailure);
11606 
11607     // Sort everything else by location.
11608     SourceLocation LLoc = GetLocationForCandidate(L);
11609     SourceLocation RLoc = GetLocationForCandidate(R);
11610 
11611     // Put candidates without locations (e.g. builtins) at the end.
11612     if (LLoc.isInvalid())
11613       return false;
11614     if (RLoc.isInvalid())
11615       return true;
11616 
11617     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11618   }
11619 };
11620 }
11621 
11622 /// Diagnose a template argument deduction failure.
11623 /// We are treating these failures as overload failures due to bad
11624 /// deductions.
11625 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11626                                                  bool ForTakingAddress) {
11627   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11628                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11629 }
11630 
11631 void TemplateSpecCandidateSet::destroyCandidates() {
11632   for (iterator i = begin(), e = end(); i != e; ++i) {
11633     i->DeductionFailure.Destroy();
11634   }
11635 }
11636 
11637 void TemplateSpecCandidateSet::clear() {
11638   destroyCandidates();
11639   Candidates.clear();
11640 }
11641 
11642 /// NoteCandidates - When no template specialization match is found, prints
11643 /// diagnostic messages containing the non-matching specializations that form
11644 /// the candidate set.
11645 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11646 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11647 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11648   // Sort the candidates by position (assuming no candidate is a match).
11649   // Sorting directly would be prohibitive, so we make a set of pointers
11650   // and sort those.
11651   SmallVector<TemplateSpecCandidate *, 32> Cands;
11652   Cands.reserve(size());
11653   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11654     if (Cand->Specialization)
11655       Cands.push_back(Cand);
11656     // Otherwise, this is a non-matching builtin candidate.  We do not,
11657     // in general, want to list every possible builtin candidate.
11658   }
11659 
11660   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11661 
11662   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11663   // for generalization purposes (?).
11664   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11665 
11666   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11667   unsigned CandsShown = 0;
11668   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11669     TemplateSpecCandidate *Cand = *I;
11670 
11671     // Set an arbitrary limit on the number of candidates we'll spam
11672     // the user with.  FIXME: This limit should depend on details of the
11673     // candidate list.
11674     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11675       break;
11676     ++CandsShown;
11677 
11678     assert(Cand->Specialization &&
11679            "Non-matching built-in candidates are not added to Cands.");
11680     Cand->NoteDeductionFailure(S, ForTakingAddress);
11681   }
11682 
11683   if (I != E)
11684     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11685 }
11686 
11687 // [PossiblyAFunctionType]  -->   [Return]
11688 // NonFunctionType --> NonFunctionType
11689 // R (A) --> R(A)
11690 // R (*)(A) --> R (A)
11691 // R (&)(A) --> R (A)
11692 // R (S::*)(A) --> R (A)
11693 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11694   QualType Ret = PossiblyAFunctionType;
11695   if (const PointerType *ToTypePtr =
11696     PossiblyAFunctionType->getAs<PointerType>())
11697     Ret = ToTypePtr->getPointeeType();
11698   else if (const ReferenceType *ToTypeRef =
11699     PossiblyAFunctionType->getAs<ReferenceType>())
11700     Ret = ToTypeRef->getPointeeType();
11701   else if (const MemberPointerType *MemTypePtr =
11702     PossiblyAFunctionType->getAs<MemberPointerType>())
11703     Ret = MemTypePtr->getPointeeType();
11704   Ret =
11705     Context.getCanonicalType(Ret).getUnqualifiedType();
11706   return Ret;
11707 }
11708 
11709 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11710                                  bool Complain = true) {
11711   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11712       S.DeduceReturnType(FD, Loc, Complain))
11713     return true;
11714 
11715   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11716   if (S.getLangOpts().CPlusPlus17 &&
11717       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11718       !S.ResolveExceptionSpec(Loc, FPT))
11719     return true;
11720 
11721   return false;
11722 }
11723 
11724 namespace {
11725 // A helper class to help with address of function resolution
11726 // - allows us to avoid passing around all those ugly parameters
11727 class AddressOfFunctionResolver {
11728   Sema& S;
11729   Expr* SourceExpr;
11730   const QualType& TargetType;
11731   QualType TargetFunctionType; // Extracted function type from target type
11732 
11733   bool Complain;
11734   //DeclAccessPair& ResultFunctionAccessPair;
11735   ASTContext& Context;
11736 
11737   bool TargetTypeIsNonStaticMemberFunction;
11738   bool FoundNonTemplateFunction;
11739   bool StaticMemberFunctionFromBoundPointer;
11740   bool HasComplained;
11741 
11742   OverloadExpr::FindResult OvlExprInfo;
11743   OverloadExpr *OvlExpr;
11744   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11745   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11746   TemplateSpecCandidateSet FailedCandidates;
11747 
11748 public:
11749   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11750                             const QualType &TargetType, bool Complain)
11751       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11752         Complain(Complain), Context(S.getASTContext()),
11753         TargetTypeIsNonStaticMemberFunction(
11754             !!TargetType->getAs<MemberPointerType>()),
11755         FoundNonTemplateFunction(false),
11756         StaticMemberFunctionFromBoundPointer(false),
11757         HasComplained(false),
11758         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11759         OvlExpr(OvlExprInfo.Expression),
11760         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11761     ExtractUnqualifiedFunctionTypeFromTargetType();
11762 
11763     if (TargetFunctionType->isFunctionType()) {
11764       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11765         if (!UME->isImplicitAccess() &&
11766             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11767           StaticMemberFunctionFromBoundPointer = true;
11768     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11769       DeclAccessPair dap;
11770       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11771               OvlExpr, false, &dap)) {
11772         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11773           if (!Method->isStatic()) {
11774             // If the target type is a non-function type and the function found
11775             // is a non-static member function, pretend as if that was the
11776             // target, it's the only possible type to end up with.
11777             TargetTypeIsNonStaticMemberFunction = true;
11778 
11779             // And skip adding the function if its not in the proper form.
11780             // We'll diagnose this due to an empty set of functions.
11781             if (!OvlExprInfo.HasFormOfMemberPointer)
11782               return;
11783           }
11784 
11785         Matches.push_back(std::make_pair(dap, Fn));
11786       }
11787       return;
11788     }
11789 
11790     if (OvlExpr->hasExplicitTemplateArgs())
11791       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11792 
11793     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11794       // C++ [over.over]p4:
11795       //   If more than one function is selected, [...]
11796       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11797         if (FoundNonTemplateFunction)
11798           EliminateAllTemplateMatches();
11799         else
11800           EliminateAllExceptMostSpecializedTemplate();
11801       }
11802     }
11803 
11804     if (S.getLangOpts().CUDA && Matches.size() > 1)
11805       EliminateSuboptimalCudaMatches();
11806   }
11807 
11808   bool hasComplained() const { return HasComplained; }
11809 
11810 private:
11811   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11812     QualType Discard;
11813     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11814            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11815   }
11816 
11817   /// \return true if A is considered a better overload candidate for the
11818   /// desired type than B.
11819   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11820     // If A doesn't have exactly the correct type, we don't want to classify it
11821     // as "better" than anything else. This way, the user is required to
11822     // disambiguate for us if there are multiple candidates and no exact match.
11823     return candidateHasExactlyCorrectType(A) &&
11824            (!candidateHasExactlyCorrectType(B) ||
11825             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11826   }
11827 
11828   /// \return true if we were able to eliminate all but one overload candidate,
11829   /// false otherwise.
11830   bool eliminiateSuboptimalOverloadCandidates() {
11831     // Same algorithm as overload resolution -- one pass to pick the "best",
11832     // another pass to be sure that nothing is better than the best.
11833     auto Best = Matches.begin();
11834     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11835       if (isBetterCandidate(I->second, Best->second))
11836         Best = I;
11837 
11838     const FunctionDecl *BestFn = Best->second;
11839     auto IsBestOrInferiorToBest = [this, BestFn](
11840         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11841       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11842     };
11843 
11844     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11845     // option, so we can potentially give the user a better error
11846     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11847       return false;
11848     Matches[0] = *Best;
11849     Matches.resize(1);
11850     return true;
11851   }
11852 
11853   bool isTargetTypeAFunction() const {
11854     return TargetFunctionType->isFunctionType();
11855   }
11856 
11857   // [ToType]     [Return]
11858 
11859   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11860   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11861   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11862   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11863     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11864   }
11865 
11866   // return true if any matching specializations were found
11867   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11868                                    const DeclAccessPair& CurAccessFunPair) {
11869     if (CXXMethodDecl *Method
11870               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11871       // Skip non-static function templates when converting to pointer, and
11872       // static when converting to member pointer.
11873       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11874         return false;
11875     }
11876     else if (TargetTypeIsNonStaticMemberFunction)
11877       return false;
11878 
11879     // C++ [over.over]p2:
11880     //   If the name is a function template, template argument deduction is
11881     //   done (14.8.2.2), and if the argument deduction succeeds, the
11882     //   resulting template argument list is used to generate a single
11883     //   function template specialization, which is added to the set of
11884     //   overloaded functions considered.
11885     FunctionDecl *Specialization = nullptr;
11886     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11887     if (Sema::TemplateDeductionResult Result
11888           = S.DeduceTemplateArguments(FunctionTemplate,
11889                                       &OvlExplicitTemplateArgs,
11890                                       TargetFunctionType, Specialization,
11891                                       Info, /*IsAddressOfFunction*/true)) {
11892       // Make a note of the failed deduction for diagnostics.
11893       FailedCandidates.addCandidate()
11894           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11895                MakeDeductionFailureInfo(Context, Result, Info));
11896       return false;
11897     }
11898 
11899     // Template argument deduction ensures that we have an exact match or
11900     // compatible pointer-to-function arguments that would be adjusted by ICS.
11901     // This function template specicalization works.
11902     assert(S.isSameOrCompatibleFunctionType(
11903               Context.getCanonicalType(Specialization->getType()),
11904               Context.getCanonicalType(TargetFunctionType)));
11905 
11906     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11907       return false;
11908 
11909     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11910     return true;
11911   }
11912 
11913   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11914                                       const DeclAccessPair& CurAccessFunPair) {
11915     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11916       // Skip non-static functions when converting to pointer, and static
11917       // when converting to member pointer.
11918       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11919         return false;
11920     }
11921     else if (TargetTypeIsNonStaticMemberFunction)
11922       return false;
11923 
11924     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11925       if (S.getLangOpts().CUDA)
11926         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11927           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11928             return false;
11929       if (FunDecl->isMultiVersion()) {
11930         const auto *TA = FunDecl->getAttr<TargetAttr>();
11931         if (TA && !TA->isDefaultVersion())
11932           return false;
11933       }
11934 
11935       // If any candidate has a placeholder return type, trigger its deduction
11936       // now.
11937       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11938                                Complain)) {
11939         HasComplained |= Complain;
11940         return false;
11941       }
11942 
11943       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11944         return false;
11945 
11946       // If we're in C, we need to support types that aren't exactly identical.
11947       if (!S.getLangOpts().CPlusPlus ||
11948           candidateHasExactlyCorrectType(FunDecl)) {
11949         Matches.push_back(std::make_pair(
11950             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11951         FoundNonTemplateFunction = true;
11952         return true;
11953       }
11954     }
11955 
11956     return false;
11957   }
11958 
11959   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11960     bool Ret = false;
11961 
11962     // If the overload expression doesn't have the form of a pointer to
11963     // member, don't try to convert it to a pointer-to-member type.
11964     if (IsInvalidFormOfPointerToMemberFunction())
11965       return false;
11966 
11967     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11968                                E = OvlExpr->decls_end();
11969          I != E; ++I) {
11970       // Look through any using declarations to find the underlying function.
11971       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11972 
11973       // C++ [over.over]p3:
11974       //   Non-member functions and static member functions match
11975       //   targets of type "pointer-to-function" or "reference-to-function."
11976       //   Nonstatic member functions match targets of
11977       //   type "pointer-to-member-function."
11978       // Note that according to DR 247, the containing class does not matter.
11979       if (FunctionTemplateDecl *FunctionTemplate
11980                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11981         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11982           Ret = true;
11983       }
11984       // If we have explicit template arguments supplied, skip non-templates.
11985       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11986                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11987         Ret = true;
11988     }
11989     assert(Ret || Matches.empty());
11990     return Ret;
11991   }
11992 
11993   void EliminateAllExceptMostSpecializedTemplate() {
11994     //   [...] and any given function template specialization F1 is
11995     //   eliminated if the set contains a second function template
11996     //   specialization whose function template is more specialized
11997     //   than the function template of F1 according to the partial
11998     //   ordering rules of 14.5.5.2.
11999 
12000     // The algorithm specified above is quadratic. We instead use a
12001     // two-pass algorithm (similar to the one used to identify the
12002     // best viable function in an overload set) that identifies the
12003     // best function template (if it exists).
12004 
12005     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
12006     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
12007       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
12008 
12009     // TODO: It looks like FailedCandidates does not serve much purpose
12010     // here, since the no_viable diagnostic has index 0.
12011     UnresolvedSetIterator Result = S.getMostSpecialized(
12012         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
12013         SourceExpr->getBeginLoc(), S.PDiag(),
12014         S.PDiag(diag::err_addr_ovl_ambiguous)
12015             << Matches[0].second->getDeclName(),
12016         S.PDiag(diag::note_ovl_candidate)
12017             << (unsigned)oc_function << (unsigned)ocs_described_template,
12018         Complain, TargetFunctionType);
12019 
12020     if (Result != MatchesCopy.end()) {
12021       // Make it the first and only element
12022       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
12023       Matches[0].second = cast<FunctionDecl>(*Result);
12024       Matches.resize(1);
12025     } else
12026       HasComplained |= Complain;
12027   }
12028 
12029   void EliminateAllTemplateMatches() {
12030     //   [...] any function template specializations in the set are
12031     //   eliminated if the set also contains a non-template function, [...]
12032     for (unsigned I = 0, N = Matches.size(); I != N; ) {
12033       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12034         ++I;
12035       else {
12036         Matches[I] = Matches[--N];
12037         Matches.resize(N);
12038       }
12039     }
12040   }
12041 
12042   void EliminateSuboptimalCudaMatches() {
12043     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12044   }
12045 
12046 public:
12047   void ComplainNoMatchesFound() const {
12048     assert(Matches.empty());
12049     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12050         << OvlExpr->getName() << TargetFunctionType
12051         << OvlExpr->getSourceRange();
12052     if (FailedCandidates.empty())
12053       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12054                                   /*TakingAddress=*/true);
12055     else {
12056       // We have some deduction failure messages. Use them to diagnose
12057       // the function templates, and diagnose the non-template candidates
12058       // normally.
12059       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12060                                  IEnd = OvlExpr->decls_end();
12061            I != IEnd; ++I)
12062         if (FunctionDecl *Fun =
12063                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12064           if (!functionHasPassObjectSizeParams(Fun))
12065             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12066                                     /*TakingAddress=*/true);
12067       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12068     }
12069   }
12070 
12071   bool IsInvalidFormOfPointerToMemberFunction() const {
12072     return TargetTypeIsNonStaticMemberFunction &&
12073       !OvlExprInfo.HasFormOfMemberPointer;
12074   }
12075 
12076   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12077       // TODO: Should we condition this on whether any functions might
12078       // have matched, or is it more appropriate to do that in callers?
12079       // TODO: a fixit wouldn't hurt.
12080       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12081         << TargetType << OvlExpr->getSourceRange();
12082   }
12083 
12084   bool IsStaticMemberFunctionFromBoundPointer() const {
12085     return StaticMemberFunctionFromBoundPointer;
12086   }
12087 
12088   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12089     S.Diag(OvlExpr->getBeginLoc(),
12090            diag::err_invalid_form_pointer_member_function)
12091         << OvlExpr->getSourceRange();
12092   }
12093 
12094   void ComplainOfInvalidConversion() const {
12095     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12096         << OvlExpr->getName() << TargetType;
12097   }
12098 
12099   void ComplainMultipleMatchesFound() const {
12100     assert(Matches.size() > 1);
12101     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12102         << OvlExpr->getName() << OvlExpr->getSourceRange();
12103     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12104                                 /*TakingAddress=*/true);
12105   }
12106 
12107   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12108 
12109   int getNumMatches() const { return Matches.size(); }
12110 
12111   FunctionDecl* getMatchingFunctionDecl() const {
12112     if (Matches.size() != 1) return nullptr;
12113     return Matches[0].second;
12114   }
12115 
12116   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12117     if (Matches.size() != 1) return nullptr;
12118     return &Matches[0].first;
12119   }
12120 };
12121 }
12122 
12123 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12124 /// an overloaded function (C++ [over.over]), where @p From is an
12125 /// expression with overloaded function type and @p ToType is the type
12126 /// we're trying to resolve to. For example:
12127 ///
12128 /// @code
12129 /// int f(double);
12130 /// int f(int);
12131 ///
12132 /// int (*pfd)(double) = f; // selects f(double)
12133 /// @endcode
12134 ///
12135 /// This routine returns the resulting FunctionDecl if it could be
12136 /// resolved, and NULL otherwise. When @p Complain is true, this
12137 /// routine will emit diagnostics if there is an error.
12138 FunctionDecl *
12139 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12140                                          QualType TargetType,
12141                                          bool Complain,
12142                                          DeclAccessPair &FoundResult,
12143                                          bool *pHadMultipleCandidates) {
12144   assert(AddressOfExpr->getType() == Context.OverloadTy);
12145 
12146   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12147                                      Complain);
12148   int NumMatches = Resolver.getNumMatches();
12149   FunctionDecl *Fn = nullptr;
12150   bool ShouldComplain = Complain && !Resolver.hasComplained();
12151   if (NumMatches == 0 && ShouldComplain) {
12152     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12153       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12154     else
12155       Resolver.ComplainNoMatchesFound();
12156   }
12157   else if (NumMatches > 1 && ShouldComplain)
12158     Resolver.ComplainMultipleMatchesFound();
12159   else if (NumMatches == 1) {
12160     Fn = Resolver.getMatchingFunctionDecl();
12161     assert(Fn);
12162     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12163       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12164     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12165     if (Complain) {
12166       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12167         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12168       else
12169         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12170     }
12171   }
12172 
12173   if (pHadMultipleCandidates)
12174     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12175   return Fn;
12176 }
12177 
12178 /// Given an expression that refers to an overloaded function, try to
12179 /// resolve that function to a single function that can have its address taken.
12180 /// This will modify `Pair` iff it returns non-null.
12181 ///
12182 /// This routine can only succeed if from all of the candidates in the overload
12183 /// set for SrcExpr that can have their addresses taken, there is one candidate
12184 /// that is more constrained than the rest.
12185 FunctionDecl *
12186 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12187   OverloadExpr::FindResult R = OverloadExpr::find(E);
12188   OverloadExpr *Ovl = R.Expression;
12189   bool IsResultAmbiguous = false;
12190   FunctionDecl *Result = nullptr;
12191   DeclAccessPair DAP;
12192   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12193 
12194   auto CheckMoreConstrained =
12195       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12196         SmallVector<const Expr *, 1> AC1, AC2;
12197         FD1->getAssociatedConstraints(AC1);
12198         FD2->getAssociatedConstraints(AC2);
12199         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12200         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12201           return None;
12202         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12203           return None;
12204         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12205           return None;
12206         return AtLeastAsConstrained1;
12207       };
12208 
12209   // Don't use the AddressOfResolver because we're specifically looking for
12210   // cases where we have one overload candidate that lacks
12211   // enable_if/pass_object_size/...
12212   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12213     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12214     if (!FD)
12215       return nullptr;
12216 
12217     if (!checkAddressOfFunctionIsAvailable(FD))
12218       continue;
12219 
12220     // We have more than one result - see if it is more constrained than the
12221     // previous one.
12222     if (Result) {
12223       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12224                                                                         Result);
12225       if (!MoreConstrainedThanPrevious) {
12226         IsResultAmbiguous = true;
12227         AmbiguousDecls.push_back(FD);
12228         continue;
12229       }
12230       if (!*MoreConstrainedThanPrevious)
12231         continue;
12232       // FD is more constrained - replace Result with it.
12233     }
12234     IsResultAmbiguous = false;
12235     DAP = I.getPair();
12236     Result = FD;
12237   }
12238 
12239   if (IsResultAmbiguous)
12240     return nullptr;
12241 
12242   if (Result) {
12243     SmallVector<const Expr *, 1> ResultAC;
12244     // We skipped over some ambiguous declarations which might be ambiguous with
12245     // the selected result.
12246     for (FunctionDecl *Skipped : AmbiguousDecls)
12247       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12248         return nullptr;
12249     Pair = DAP;
12250   }
12251   return Result;
12252 }
12253 
12254 /// Given an overloaded function, tries to turn it into a non-overloaded
12255 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12256 /// will perform access checks, diagnose the use of the resultant decl, and, if
12257 /// requested, potentially perform a function-to-pointer decay.
12258 ///
12259 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12260 /// Otherwise, returns true. This may emit diagnostics and return true.
12261 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12262     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12263   Expr *E = SrcExpr.get();
12264   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12265 
12266   DeclAccessPair DAP;
12267   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12268   if (!Found || Found->isCPUDispatchMultiVersion() ||
12269       Found->isCPUSpecificMultiVersion())
12270     return false;
12271 
12272   // Emitting multiple diagnostics for a function that is both inaccessible and
12273   // unavailable is consistent with our behavior elsewhere. So, always check
12274   // for both.
12275   DiagnoseUseOfDecl(Found, E->getExprLoc());
12276   CheckAddressOfMemberAccess(E, DAP);
12277   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12278   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12279     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12280   else
12281     SrcExpr = Fixed;
12282   return true;
12283 }
12284 
12285 /// Given an expression that refers to an overloaded function, try to
12286 /// resolve that overloaded function expression down to a single function.
12287 ///
12288 /// This routine can only resolve template-ids that refer to a single function
12289 /// template, where that template-id refers to a single template whose template
12290 /// arguments are either provided by the template-id or have defaults,
12291 /// as described in C++0x [temp.arg.explicit]p3.
12292 ///
12293 /// If no template-ids are found, no diagnostics are emitted and NULL is
12294 /// returned.
12295 FunctionDecl *
12296 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12297                                                   bool Complain,
12298                                                   DeclAccessPair *FoundResult) {
12299   // C++ [over.over]p1:
12300   //   [...] [Note: any redundant set of parentheses surrounding the
12301   //   overloaded function name is ignored (5.1). ]
12302   // C++ [over.over]p1:
12303   //   [...] The overloaded function name can be preceded by the &
12304   //   operator.
12305 
12306   // If we didn't actually find any template-ids, we're done.
12307   if (!ovl->hasExplicitTemplateArgs())
12308     return nullptr;
12309 
12310   TemplateArgumentListInfo ExplicitTemplateArgs;
12311   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12312   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12313 
12314   // Look through all of the overloaded functions, searching for one
12315   // whose type matches exactly.
12316   FunctionDecl *Matched = nullptr;
12317   for (UnresolvedSetIterator I = ovl->decls_begin(),
12318          E = ovl->decls_end(); I != E; ++I) {
12319     // C++0x [temp.arg.explicit]p3:
12320     //   [...] In contexts where deduction is done and fails, or in contexts
12321     //   where deduction is not done, if a template argument list is
12322     //   specified and it, along with any default template arguments,
12323     //   identifies a single function template specialization, then the
12324     //   template-id is an lvalue for the function template specialization.
12325     FunctionTemplateDecl *FunctionTemplate
12326       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12327 
12328     // C++ [over.over]p2:
12329     //   If the name is a function template, template argument deduction is
12330     //   done (14.8.2.2), and if the argument deduction succeeds, the
12331     //   resulting template argument list is used to generate a single
12332     //   function template specialization, which is added to the set of
12333     //   overloaded functions considered.
12334     FunctionDecl *Specialization = nullptr;
12335     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12336     if (TemplateDeductionResult Result
12337           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12338                                     Specialization, Info,
12339                                     /*IsAddressOfFunction*/true)) {
12340       // Make a note of the failed deduction for diagnostics.
12341       // TODO: Actually use the failed-deduction info?
12342       FailedCandidates.addCandidate()
12343           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12344                MakeDeductionFailureInfo(Context, Result, Info));
12345       continue;
12346     }
12347 
12348     assert(Specialization && "no specialization and no error?");
12349 
12350     // Multiple matches; we can't resolve to a single declaration.
12351     if (Matched) {
12352       if (Complain) {
12353         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12354           << ovl->getName();
12355         NoteAllOverloadCandidates(ovl);
12356       }
12357       return nullptr;
12358     }
12359 
12360     Matched = Specialization;
12361     if (FoundResult) *FoundResult = I.getPair();
12362   }
12363 
12364   if (Matched &&
12365       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12366     return nullptr;
12367 
12368   return Matched;
12369 }
12370 
12371 // Resolve and fix an overloaded expression that can be resolved
12372 // because it identifies a single function template specialization.
12373 //
12374 // Last three arguments should only be supplied if Complain = true
12375 //
12376 // Return true if it was logically possible to so resolve the
12377 // expression, regardless of whether or not it succeeded.  Always
12378 // returns true if 'complain' is set.
12379 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12380                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12381                       bool complain, SourceRange OpRangeForComplaining,
12382                                            QualType DestTypeForComplaining,
12383                                             unsigned DiagIDForComplaining) {
12384   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12385 
12386   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12387 
12388   DeclAccessPair found;
12389   ExprResult SingleFunctionExpression;
12390   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12391                            ovl.Expression, /*complain*/ false, &found)) {
12392     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12393       SrcExpr = ExprError();
12394       return true;
12395     }
12396 
12397     // It is only correct to resolve to an instance method if we're
12398     // resolving a form that's permitted to be a pointer to member.
12399     // Otherwise we'll end up making a bound member expression, which
12400     // is illegal in all the contexts we resolve like this.
12401     if (!ovl.HasFormOfMemberPointer &&
12402         isa<CXXMethodDecl>(fn) &&
12403         cast<CXXMethodDecl>(fn)->isInstance()) {
12404       if (!complain) return false;
12405 
12406       Diag(ovl.Expression->getExprLoc(),
12407            diag::err_bound_member_function)
12408         << 0 << ovl.Expression->getSourceRange();
12409 
12410       // TODO: I believe we only end up here if there's a mix of
12411       // static and non-static candidates (otherwise the expression
12412       // would have 'bound member' type, not 'overload' type).
12413       // Ideally we would note which candidate was chosen and why
12414       // the static candidates were rejected.
12415       SrcExpr = ExprError();
12416       return true;
12417     }
12418 
12419     // Fix the expression to refer to 'fn'.
12420     SingleFunctionExpression =
12421         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12422 
12423     // If desired, do function-to-pointer decay.
12424     if (doFunctionPointerConverion) {
12425       SingleFunctionExpression =
12426         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12427       if (SingleFunctionExpression.isInvalid()) {
12428         SrcExpr = ExprError();
12429         return true;
12430       }
12431     }
12432   }
12433 
12434   if (!SingleFunctionExpression.isUsable()) {
12435     if (complain) {
12436       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12437         << ovl.Expression->getName()
12438         << DestTypeForComplaining
12439         << OpRangeForComplaining
12440         << ovl.Expression->getQualifierLoc().getSourceRange();
12441       NoteAllOverloadCandidates(SrcExpr.get());
12442 
12443       SrcExpr = ExprError();
12444       return true;
12445     }
12446 
12447     return false;
12448   }
12449 
12450   SrcExpr = SingleFunctionExpression;
12451   return true;
12452 }
12453 
12454 /// Add a single candidate to the overload set.
12455 static void AddOverloadedCallCandidate(Sema &S,
12456                                        DeclAccessPair FoundDecl,
12457                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12458                                        ArrayRef<Expr *> Args,
12459                                        OverloadCandidateSet &CandidateSet,
12460                                        bool PartialOverloading,
12461                                        bool KnownValid) {
12462   NamedDecl *Callee = FoundDecl.getDecl();
12463   if (isa<UsingShadowDecl>(Callee))
12464     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12465 
12466   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12467     if (ExplicitTemplateArgs) {
12468       assert(!KnownValid && "Explicit template arguments?");
12469       return;
12470     }
12471     // Prevent ill-formed function decls to be added as overload candidates.
12472     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12473       return;
12474 
12475     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12476                            /*SuppressUserConversions=*/false,
12477                            PartialOverloading);
12478     return;
12479   }
12480 
12481   if (FunctionTemplateDecl *FuncTemplate
12482       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12483     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12484                                    ExplicitTemplateArgs, Args, CandidateSet,
12485                                    /*SuppressUserConversions=*/false,
12486                                    PartialOverloading);
12487     return;
12488   }
12489 
12490   assert(!KnownValid && "unhandled case in overloaded call candidate");
12491 }
12492 
12493 /// Add the overload candidates named by callee and/or found by argument
12494 /// dependent lookup to the given overload set.
12495 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12496                                        ArrayRef<Expr *> Args,
12497                                        OverloadCandidateSet &CandidateSet,
12498                                        bool PartialOverloading) {
12499 
12500 #ifndef NDEBUG
12501   // Verify that ArgumentDependentLookup is consistent with the rules
12502   // in C++0x [basic.lookup.argdep]p3:
12503   //
12504   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12505   //   and let Y be the lookup set produced by argument dependent
12506   //   lookup (defined as follows). If X contains
12507   //
12508   //     -- a declaration of a class member, or
12509   //
12510   //     -- a block-scope function declaration that is not a
12511   //        using-declaration, or
12512   //
12513   //     -- a declaration that is neither a function or a function
12514   //        template
12515   //
12516   //   then Y is empty.
12517 
12518   if (ULE->requiresADL()) {
12519     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12520            E = ULE->decls_end(); I != E; ++I) {
12521       assert(!(*I)->getDeclContext()->isRecord());
12522       assert(isa<UsingShadowDecl>(*I) ||
12523              !(*I)->getDeclContext()->isFunctionOrMethod());
12524       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12525     }
12526   }
12527 #endif
12528 
12529   // It would be nice to avoid this copy.
12530   TemplateArgumentListInfo TABuffer;
12531   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12532   if (ULE->hasExplicitTemplateArgs()) {
12533     ULE->copyTemplateArgumentsInto(TABuffer);
12534     ExplicitTemplateArgs = &TABuffer;
12535   }
12536 
12537   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12538          E = ULE->decls_end(); I != E; ++I)
12539     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12540                                CandidateSet, PartialOverloading,
12541                                /*KnownValid*/ true);
12542 
12543   if (ULE->requiresADL())
12544     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12545                                          Args, ExplicitTemplateArgs,
12546                                          CandidateSet, PartialOverloading);
12547 }
12548 
12549 /// Determine whether a declaration with the specified name could be moved into
12550 /// a different namespace.
12551 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12552   switch (Name.getCXXOverloadedOperator()) {
12553   case OO_New: case OO_Array_New:
12554   case OO_Delete: case OO_Array_Delete:
12555     return false;
12556 
12557   default:
12558     return true;
12559   }
12560 }
12561 
12562 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12563 /// template, where the non-dependent name was declared after the template
12564 /// was defined. This is common in code written for a compilers which do not
12565 /// correctly implement two-stage name lookup.
12566 ///
12567 /// Returns true if a viable candidate was found and a diagnostic was issued.
12568 static bool
12569 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12570                        const CXXScopeSpec &SS, LookupResult &R,
12571                        OverloadCandidateSet::CandidateSetKind CSK,
12572                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12573                        ArrayRef<Expr *> Args,
12574                        bool *DoDiagnoseEmptyLookup = nullptr) {
12575   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12576     return false;
12577 
12578   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12579     if (DC->isTransparentContext())
12580       continue;
12581 
12582     SemaRef.LookupQualifiedName(R, DC);
12583 
12584     if (!R.empty()) {
12585       R.suppressDiagnostics();
12586 
12587       if (isa<CXXRecordDecl>(DC)) {
12588         // Don't diagnose names we find in classes; we get much better
12589         // diagnostics for these from DiagnoseEmptyLookup.
12590         R.clear();
12591         if (DoDiagnoseEmptyLookup)
12592           *DoDiagnoseEmptyLookup = true;
12593         return false;
12594       }
12595 
12596       OverloadCandidateSet Candidates(FnLoc, CSK);
12597       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12598         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12599                                    ExplicitTemplateArgs, Args,
12600                                    Candidates, false, /*KnownValid*/ false);
12601 
12602       OverloadCandidateSet::iterator Best;
12603       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12604         // No viable functions. Don't bother the user with notes for functions
12605         // which don't work and shouldn't be found anyway.
12606         R.clear();
12607         return false;
12608       }
12609 
12610       // Find the namespaces where ADL would have looked, and suggest
12611       // declaring the function there instead.
12612       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12613       Sema::AssociatedClassSet AssociatedClasses;
12614       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12615                                                  AssociatedNamespaces,
12616                                                  AssociatedClasses);
12617       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12618       if (canBeDeclaredInNamespace(R.getLookupName())) {
12619         DeclContext *Std = SemaRef.getStdNamespace();
12620         for (Sema::AssociatedNamespaceSet::iterator
12621                it = AssociatedNamespaces.begin(),
12622                end = AssociatedNamespaces.end(); it != end; ++it) {
12623           // Never suggest declaring a function within namespace 'std'.
12624           if (Std && Std->Encloses(*it))
12625             continue;
12626 
12627           // Never suggest declaring a function within a namespace with a
12628           // reserved name, like __gnu_cxx.
12629           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12630           if (NS &&
12631               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12632             continue;
12633 
12634           SuggestedNamespaces.insert(*it);
12635         }
12636       }
12637 
12638       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12639         << R.getLookupName();
12640       if (SuggestedNamespaces.empty()) {
12641         SemaRef.Diag(Best->Function->getLocation(),
12642                      diag::note_not_found_by_two_phase_lookup)
12643           << R.getLookupName() << 0;
12644       } else if (SuggestedNamespaces.size() == 1) {
12645         SemaRef.Diag(Best->Function->getLocation(),
12646                      diag::note_not_found_by_two_phase_lookup)
12647           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12648       } else {
12649         // FIXME: It would be useful to list the associated namespaces here,
12650         // but the diagnostics infrastructure doesn't provide a way to produce
12651         // a localized representation of a list of items.
12652         SemaRef.Diag(Best->Function->getLocation(),
12653                      diag::note_not_found_by_two_phase_lookup)
12654           << R.getLookupName() << 2;
12655       }
12656 
12657       // Try to recover by calling this function.
12658       return true;
12659     }
12660 
12661     R.clear();
12662   }
12663 
12664   return false;
12665 }
12666 
12667 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12668 /// template, where the non-dependent operator was declared after the template
12669 /// was defined.
12670 ///
12671 /// Returns true if a viable candidate was found and a diagnostic was issued.
12672 static bool
12673 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12674                                SourceLocation OpLoc,
12675                                ArrayRef<Expr *> Args) {
12676   DeclarationName OpName =
12677     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12678   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12679   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12680                                 OverloadCandidateSet::CSK_Operator,
12681                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12682 }
12683 
12684 namespace {
12685 class BuildRecoveryCallExprRAII {
12686   Sema &SemaRef;
12687 public:
12688   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12689     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12690     SemaRef.IsBuildingRecoveryCallExpr = true;
12691   }
12692 
12693   ~BuildRecoveryCallExprRAII() {
12694     SemaRef.IsBuildingRecoveryCallExpr = false;
12695   }
12696 };
12697 
12698 }
12699 
12700 /// Attempts to recover from a call where no functions were found.
12701 ///
12702 /// Returns true if new candidates were found.
12703 static ExprResult
12704 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12705                       UnresolvedLookupExpr *ULE,
12706                       SourceLocation LParenLoc,
12707                       MutableArrayRef<Expr *> Args,
12708                       SourceLocation RParenLoc,
12709                       bool EmptyLookup, bool AllowTypoCorrection) {
12710   // Do not try to recover if it is already building a recovery call.
12711   // This stops infinite loops for template instantiations like
12712   //
12713   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12714   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12715   //
12716   if (SemaRef.IsBuildingRecoveryCallExpr)
12717     return ExprError();
12718   BuildRecoveryCallExprRAII RCE(SemaRef);
12719 
12720   CXXScopeSpec SS;
12721   SS.Adopt(ULE->getQualifierLoc());
12722   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12723 
12724   TemplateArgumentListInfo TABuffer;
12725   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12726   if (ULE->hasExplicitTemplateArgs()) {
12727     ULE->copyTemplateArgumentsInto(TABuffer);
12728     ExplicitTemplateArgs = &TABuffer;
12729   }
12730 
12731   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12732                  Sema::LookupOrdinaryName);
12733   bool DoDiagnoseEmptyLookup = EmptyLookup;
12734   if (!DiagnoseTwoPhaseLookup(
12735           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12736           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12737     NoTypoCorrectionCCC NoTypoValidator{};
12738     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12739                                                 ExplicitTemplateArgs != nullptr,
12740                                                 dyn_cast<MemberExpr>(Fn));
12741     CorrectionCandidateCallback &Validator =
12742         AllowTypoCorrection
12743             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12744             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12745     if (!DoDiagnoseEmptyLookup ||
12746         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12747                                     Args))
12748       return ExprError();
12749   }
12750 
12751   assert(!R.empty() && "lookup results empty despite recovery");
12752 
12753   // If recovery created an ambiguity, just bail out.
12754   if (R.isAmbiguous()) {
12755     R.suppressDiagnostics();
12756     return ExprError();
12757   }
12758 
12759   // Build an implicit member call if appropriate.  Just drop the
12760   // casts and such from the call, we don't really care.
12761   ExprResult NewFn = ExprError();
12762   if ((*R.begin())->isCXXClassMember())
12763     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12764                                                     ExplicitTemplateArgs, S);
12765   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12766     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12767                                         ExplicitTemplateArgs);
12768   else
12769     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12770 
12771   if (NewFn.isInvalid())
12772     return ExprError();
12773 
12774   // This shouldn't cause an infinite loop because we're giving it
12775   // an expression with viable lookup results, which should never
12776   // end up here.
12777   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12778                                MultiExprArg(Args.data(), Args.size()),
12779                                RParenLoc);
12780 }
12781 
12782 /// Constructs and populates an OverloadedCandidateSet from
12783 /// the given function.
12784 /// \returns true when an the ExprResult output parameter has been set.
12785 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12786                                   UnresolvedLookupExpr *ULE,
12787                                   MultiExprArg Args,
12788                                   SourceLocation RParenLoc,
12789                                   OverloadCandidateSet *CandidateSet,
12790                                   ExprResult *Result) {
12791 #ifndef NDEBUG
12792   if (ULE->requiresADL()) {
12793     // To do ADL, we must have found an unqualified name.
12794     assert(!ULE->getQualifier() && "qualified name with ADL");
12795 
12796     // We don't perform ADL for implicit declarations of builtins.
12797     // Verify that this was correctly set up.
12798     FunctionDecl *F;
12799     if (ULE->decls_begin() != ULE->decls_end() &&
12800         ULE->decls_begin() + 1 == ULE->decls_end() &&
12801         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12802         F->getBuiltinID() && F->isImplicit())
12803       llvm_unreachable("performing ADL for builtin");
12804 
12805     // We don't perform ADL in C.
12806     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12807   }
12808 #endif
12809 
12810   UnbridgedCastsSet UnbridgedCasts;
12811   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12812     *Result = ExprError();
12813     return true;
12814   }
12815 
12816   // Add the functions denoted by the callee to the set of candidate
12817   // functions, including those from argument-dependent lookup.
12818   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12819 
12820   if (getLangOpts().MSVCCompat &&
12821       CurContext->isDependentContext() && !isSFINAEContext() &&
12822       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12823 
12824     OverloadCandidateSet::iterator Best;
12825     if (CandidateSet->empty() ||
12826         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12827             OR_No_Viable_Function) {
12828       // In Microsoft mode, if we are inside a template class member function
12829       // then create a type dependent CallExpr. The goal is to postpone name
12830       // lookup to instantiation time to be able to search into type dependent
12831       // base classes.
12832       CallExpr *CE =
12833           CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_RValue,
12834                            RParenLoc, CurFPFeatureOverrides());
12835       CE->markDependentForPostponedNameLookup();
12836       *Result = CE;
12837       return true;
12838     }
12839   }
12840 
12841   if (CandidateSet->empty())
12842     return false;
12843 
12844   UnbridgedCasts.restore();
12845   return false;
12846 }
12847 
12848 // Guess at what the return type for an unresolvable overload should be.
12849 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12850                                    OverloadCandidateSet::iterator *Best) {
12851   llvm::Optional<QualType> Result;
12852   // Adjust Type after seeing a candidate.
12853   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12854     if (!Candidate.Function)
12855       return;
12856     if (Candidate.Function->isInvalidDecl())
12857       return;
12858     QualType T = Candidate.Function->getReturnType();
12859     if (T.isNull())
12860       return;
12861     if (!Result)
12862       Result = T;
12863     else if (Result != T)
12864       Result = QualType();
12865   };
12866 
12867   // Look for an unambiguous type from a progressively larger subset.
12868   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12869   //
12870   // First, consider only the best candidate.
12871   if (Best && *Best != CS.end())
12872     ConsiderCandidate(**Best);
12873   // Next, consider only viable candidates.
12874   if (!Result)
12875     for (const auto &C : CS)
12876       if (C.Viable)
12877         ConsiderCandidate(C);
12878   // Finally, consider all candidates.
12879   if (!Result)
12880     for (const auto &C : CS)
12881       ConsiderCandidate(C);
12882 
12883   if (!Result)
12884     return QualType();
12885   auto Value = Result.getValue();
12886   if (Value.isNull() || Value->isUndeducedType())
12887     return QualType();
12888   return Value;
12889 }
12890 
12891 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12892 /// the completed call expression. If overload resolution fails, emits
12893 /// diagnostics and returns ExprError()
12894 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12895                                            UnresolvedLookupExpr *ULE,
12896                                            SourceLocation LParenLoc,
12897                                            MultiExprArg Args,
12898                                            SourceLocation RParenLoc,
12899                                            Expr *ExecConfig,
12900                                            OverloadCandidateSet *CandidateSet,
12901                                            OverloadCandidateSet::iterator *Best,
12902                                            OverloadingResult OverloadResult,
12903                                            bool AllowTypoCorrection) {
12904   if (CandidateSet->empty())
12905     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12906                                  RParenLoc, /*EmptyLookup=*/true,
12907                                  AllowTypoCorrection);
12908 
12909   switch (OverloadResult) {
12910   case OR_Success: {
12911     FunctionDecl *FDecl = (*Best)->Function;
12912     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12913     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12914       return ExprError();
12915     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12916     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12917                                          ExecConfig, /*IsExecConfig=*/false,
12918                                          (*Best)->IsADLCandidate);
12919   }
12920 
12921   case OR_No_Viable_Function: {
12922     // Try to recover by looking for viable functions which the user might
12923     // have meant to call.
12924     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12925                                                 Args, RParenLoc,
12926                                                 /*EmptyLookup=*/false,
12927                                                 AllowTypoCorrection);
12928     if (!Recovery.isInvalid())
12929       return Recovery;
12930 
12931     // If the user passes in a function that we can't take the address of, we
12932     // generally end up emitting really bad error messages. Here, we attempt to
12933     // emit better ones.
12934     for (const Expr *Arg : Args) {
12935       if (!Arg->getType()->isFunctionType())
12936         continue;
12937       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12938         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12939         if (FD &&
12940             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12941                                                        Arg->getExprLoc()))
12942           return ExprError();
12943       }
12944     }
12945 
12946     CandidateSet->NoteCandidates(
12947         PartialDiagnosticAt(
12948             Fn->getBeginLoc(),
12949             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12950                 << ULE->getName() << Fn->getSourceRange()),
12951         SemaRef, OCD_AllCandidates, Args);
12952     break;
12953   }
12954 
12955   case OR_Ambiguous:
12956     CandidateSet->NoteCandidates(
12957         PartialDiagnosticAt(Fn->getBeginLoc(),
12958                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12959                                 << ULE->getName() << Fn->getSourceRange()),
12960         SemaRef, OCD_AmbiguousCandidates, Args);
12961     break;
12962 
12963   case OR_Deleted: {
12964     CandidateSet->NoteCandidates(
12965         PartialDiagnosticAt(Fn->getBeginLoc(),
12966                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12967                                 << ULE->getName() << Fn->getSourceRange()),
12968         SemaRef, OCD_AllCandidates, Args);
12969 
12970     // We emitted an error for the unavailable/deleted function call but keep
12971     // the call in the AST.
12972     FunctionDecl *FDecl = (*Best)->Function;
12973     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12974     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12975                                          ExecConfig, /*IsExecConfig=*/false,
12976                                          (*Best)->IsADLCandidate);
12977   }
12978   }
12979 
12980   // Overload resolution failed, try to recover.
12981   SmallVector<Expr *, 8> SubExprs = {Fn};
12982   SubExprs.append(Args.begin(), Args.end());
12983   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12984                                     chooseRecoveryType(*CandidateSet, Best));
12985 }
12986 
12987 static void markUnaddressableCandidatesUnviable(Sema &S,
12988                                                 OverloadCandidateSet &CS) {
12989   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12990     if (I->Viable &&
12991         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12992       I->Viable = false;
12993       I->FailureKind = ovl_fail_addr_not_available;
12994     }
12995   }
12996 }
12997 
12998 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12999 /// (which eventually refers to the declaration Func) and the call
13000 /// arguments Args/NumArgs, attempt to resolve the function call down
13001 /// to a specific function. If overload resolution succeeds, returns
13002 /// the call expression produced by overload resolution.
13003 /// Otherwise, emits diagnostics and returns ExprError.
13004 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
13005                                          UnresolvedLookupExpr *ULE,
13006                                          SourceLocation LParenLoc,
13007                                          MultiExprArg Args,
13008                                          SourceLocation RParenLoc,
13009                                          Expr *ExecConfig,
13010                                          bool AllowTypoCorrection,
13011                                          bool CalleesAddressIsTaken) {
13012   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
13013                                     OverloadCandidateSet::CSK_Normal);
13014   ExprResult result;
13015 
13016   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
13017                              &result))
13018     return result;
13019 
13020   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13021   // functions that aren't addressible are considered unviable.
13022   if (CalleesAddressIsTaken)
13023     markUnaddressableCandidatesUnviable(*this, CandidateSet);
13024 
13025   OverloadCandidateSet::iterator Best;
13026   OverloadingResult OverloadResult =
13027       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
13028 
13029   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
13030                                   ExecConfig, &CandidateSet, &Best,
13031                                   OverloadResult, AllowTypoCorrection);
13032 }
13033 
13034 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
13035   return Functions.size() > 1 ||
13036          (Functions.size() == 1 &&
13037           isa<FunctionTemplateDecl>((*Functions.begin())->getUnderlyingDecl()));
13038 }
13039 
13040 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
13041                                             NestedNameSpecifierLoc NNSLoc,
13042                                             DeclarationNameInfo DNI,
13043                                             const UnresolvedSetImpl &Fns,
13044                                             bool PerformADL) {
13045   return UnresolvedLookupExpr::Create(Context, NamingClass, NNSLoc, DNI,
13046                                       PerformADL, IsOverloaded(Fns),
13047                                       Fns.begin(), Fns.end());
13048 }
13049 
13050 /// Create a unary operation that may resolve to an overloaded
13051 /// operator.
13052 ///
13053 /// \param OpLoc The location of the operator itself (e.g., '*').
13054 ///
13055 /// \param Opc The UnaryOperatorKind that describes this operator.
13056 ///
13057 /// \param Fns The set of non-member functions that will be
13058 /// considered by overload resolution. The caller needs to build this
13059 /// set based on the context using, e.g.,
13060 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13061 /// set should not contain any member functions; those will be added
13062 /// by CreateOverloadedUnaryOp().
13063 ///
13064 /// \param Input The input argument.
13065 ExprResult
13066 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13067                               const UnresolvedSetImpl &Fns,
13068                               Expr *Input, bool PerformADL) {
13069   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13070   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13071   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13072   // TODO: provide better source location info.
13073   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13074 
13075   if (checkPlaceholderForOverload(*this, Input))
13076     return ExprError();
13077 
13078   Expr *Args[2] = { Input, nullptr };
13079   unsigned NumArgs = 1;
13080 
13081   // For post-increment and post-decrement, add the implicit '0' as
13082   // the second argument, so that we know this is a post-increment or
13083   // post-decrement.
13084   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13085     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13086     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13087                                      SourceLocation());
13088     NumArgs = 2;
13089   }
13090 
13091   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13092 
13093   if (Input->isTypeDependent()) {
13094     if (Fns.empty())
13095       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13096                                    VK_RValue, OK_Ordinary, OpLoc, false,
13097                                    CurFPFeatureOverrides());
13098 
13099     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13100     ExprResult Fn = CreateUnresolvedLookupExpr(
13101         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
13102     if (Fn.isInvalid())
13103       return ExprError();
13104     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
13105                                        Context.DependentTy, VK_RValue, OpLoc,
13106                                        CurFPFeatureOverrides());
13107   }
13108 
13109   // Build an empty overload set.
13110   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13111 
13112   // Add the candidates from the given function set.
13113   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13114 
13115   // Add operator candidates that are member functions.
13116   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13117 
13118   // Add candidates from ADL.
13119   if (PerformADL) {
13120     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13121                                          /*ExplicitTemplateArgs*/nullptr,
13122                                          CandidateSet);
13123   }
13124 
13125   // Add builtin operator candidates.
13126   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13127 
13128   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13129 
13130   // Perform overload resolution.
13131   OverloadCandidateSet::iterator Best;
13132   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13133   case OR_Success: {
13134     // We found a built-in operator or an overloaded operator.
13135     FunctionDecl *FnDecl = Best->Function;
13136 
13137     if (FnDecl) {
13138       Expr *Base = nullptr;
13139       // We matched an overloaded operator. Build a call to that
13140       // operator.
13141 
13142       // Convert the arguments.
13143       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13144         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13145 
13146         ExprResult InputRes =
13147           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13148                                               Best->FoundDecl, Method);
13149         if (InputRes.isInvalid())
13150           return ExprError();
13151         Base = Input = InputRes.get();
13152       } else {
13153         // Convert the arguments.
13154         ExprResult InputInit
13155           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13156                                                       Context,
13157                                                       FnDecl->getParamDecl(0)),
13158                                       SourceLocation(),
13159                                       Input);
13160         if (InputInit.isInvalid())
13161           return ExprError();
13162         Input = InputInit.get();
13163       }
13164 
13165       // Build the actual expression node.
13166       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13167                                                 Base, HadMultipleCandidates,
13168                                                 OpLoc);
13169       if (FnExpr.isInvalid())
13170         return ExprError();
13171 
13172       // Determine the result type.
13173       QualType ResultTy = FnDecl->getReturnType();
13174       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13175       ResultTy = ResultTy.getNonLValueExprType(Context);
13176 
13177       Args[0] = Input;
13178       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13179           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13180           CurFPFeatureOverrides(), Best->IsADLCandidate);
13181 
13182       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13183         return ExprError();
13184 
13185       if (CheckFunctionCall(FnDecl, TheCall,
13186                             FnDecl->getType()->castAs<FunctionProtoType>()))
13187         return ExprError();
13188       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13189     } else {
13190       // We matched a built-in operator. Convert the arguments, then
13191       // break out so that we will build the appropriate built-in
13192       // operator node.
13193       ExprResult InputRes = PerformImplicitConversion(
13194           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13195           CCK_ForBuiltinOverloadedOp);
13196       if (InputRes.isInvalid())
13197         return ExprError();
13198       Input = InputRes.get();
13199       break;
13200     }
13201   }
13202 
13203   case OR_No_Viable_Function:
13204     // This is an erroneous use of an operator which can be overloaded by
13205     // a non-member function. Check for non-member operators which were
13206     // defined too late to be candidates.
13207     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13208       // FIXME: Recover by calling the found function.
13209       return ExprError();
13210 
13211     // No viable function; fall through to handling this as a
13212     // built-in operator, which will produce an error message for us.
13213     break;
13214 
13215   case OR_Ambiguous:
13216     CandidateSet.NoteCandidates(
13217         PartialDiagnosticAt(OpLoc,
13218                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13219                                 << UnaryOperator::getOpcodeStr(Opc)
13220                                 << Input->getType() << Input->getSourceRange()),
13221         *this, OCD_AmbiguousCandidates, ArgsArray,
13222         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13223     return ExprError();
13224 
13225   case OR_Deleted:
13226     CandidateSet.NoteCandidates(
13227         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13228                                        << UnaryOperator::getOpcodeStr(Opc)
13229                                        << Input->getSourceRange()),
13230         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13231         OpLoc);
13232     return ExprError();
13233   }
13234 
13235   // Either we found no viable overloaded operator or we matched a
13236   // built-in operator. In either case, fall through to trying to
13237   // build a built-in operation.
13238   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13239 }
13240 
13241 /// Perform lookup for an overloaded binary operator.
13242 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13243                                  OverloadedOperatorKind Op,
13244                                  const UnresolvedSetImpl &Fns,
13245                                  ArrayRef<Expr *> Args, bool PerformADL) {
13246   SourceLocation OpLoc = CandidateSet.getLocation();
13247 
13248   OverloadedOperatorKind ExtraOp =
13249       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13250           ? getRewrittenOverloadedOperator(Op)
13251           : OO_None;
13252 
13253   // Add the candidates from the given function set. This also adds the
13254   // rewritten candidates using these functions if necessary.
13255   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13256 
13257   // Add operator candidates that are member functions.
13258   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13259   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13260     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13261                                 OverloadCandidateParamOrder::Reversed);
13262 
13263   // In C++20, also add any rewritten member candidates.
13264   if (ExtraOp) {
13265     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13266     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13267       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13268                                   CandidateSet,
13269                                   OverloadCandidateParamOrder::Reversed);
13270   }
13271 
13272   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13273   // performed for an assignment operator (nor for operator[] nor operator->,
13274   // which don't get here).
13275   if (Op != OO_Equal && PerformADL) {
13276     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13277     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13278                                          /*ExplicitTemplateArgs*/ nullptr,
13279                                          CandidateSet);
13280     if (ExtraOp) {
13281       DeclarationName ExtraOpName =
13282           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13283       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13284                                            /*ExplicitTemplateArgs*/ nullptr,
13285                                            CandidateSet);
13286     }
13287   }
13288 
13289   // Add builtin operator candidates.
13290   //
13291   // FIXME: We don't add any rewritten candidates here. This is strictly
13292   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13293   // resulting in our selecting a rewritten builtin candidate. For example:
13294   //
13295   //   enum class E { e };
13296   //   bool operator!=(E, E) requires false;
13297   //   bool k = E::e != E::e;
13298   //
13299   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13300   // it seems unreasonable to consider rewritten builtin candidates. A core
13301   // issue has been filed proposing to removed this requirement.
13302   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13303 }
13304 
13305 /// Create a binary operation that may resolve to an overloaded
13306 /// operator.
13307 ///
13308 /// \param OpLoc The location of the operator itself (e.g., '+').
13309 ///
13310 /// \param Opc The BinaryOperatorKind that describes this operator.
13311 ///
13312 /// \param Fns The set of non-member functions that will be
13313 /// considered by overload resolution. The caller needs to build this
13314 /// set based on the context using, e.g.,
13315 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13316 /// set should not contain any member functions; those will be added
13317 /// by CreateOverloadedBinOp().
13318 ///
13319 /// \param LHS Left-hand argument.
13320 /// \param RHS Right-hand argument.
13321 /// \param PerformADL Whether to consider operator candidates found by ADL.
13322 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13323 ///        C++20 operator rewrites.
13324 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13325 ///        the function in question. Such a function is never a candidate in
13326 ///        our overload resolution. This also enables synthesizing a three-way
13327 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13328 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13329                                        BinaryOperatorKind Opc,
13330                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13331                                        Expr *RHS, bool PerformADL,
13332                                        bool AllowRewrittenCandidates,
13333                                        FunctionDecl *DefaultedFn) {
13334   Expr *Args[2] = { LHS, RHS };
13335   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13336 
13337   if (!getLangOpts().CPlusPlus20)
13338     AllowRewrittenCandidates = false;
13339 
13340   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13341 
13342   // If either side is type-dependent, create an appropriate dependent
13343   // expression.
13344   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13345     if (Fns.empty()) {
13346       // If there are no functions to store, just build a dependent
13347       // BinaryOperator or CompoundAssignment.
13348       if (BinaryOperator::isCompoundAssignmentOp(Opc))
13349         return CompoundAssignOperator::Create(
13350             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13351             OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13352             Context.DependentTy);
13353       return BinaryOperator::Create(Context, Args[0], Args[1], Opc,
13354                                     Context.DependentTy, VK_RValue, OK_Ordinary,
13355                                     OpLoc, CurFPFeatureOverrides());
13356     }
13357 
13358     // FIXME: save results of ADL from here?
13359     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13360     // TODO: provide better source location info in DNLoc component.
13361     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13362     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13363     ExprResult Fn = CreateUnresolvedLookupExpr(
13364         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
13365     if (Fn.isInvalid())
13366       return ExprError();
13367     return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
13368                                        Context.DependentTy, VK_RValue, OpLoc,
13369                                        CurFPFeatureOverrides());
13370   }
13371 
13372   // Always do placeholder-like conversions on the RHS.
13373   if (checkPlaceholderForOverload(*this, Args[1]))
13374     return ExprError();
13375 
13376   // Do placeholder-like conversion on the LHS; note that we should
13377   // not get here with a PseudoObject LHS.
13378   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13379   if (checkPlaceholderForOverload(*this, Args[0]))
13380     return ExprError();
13381 
13382   // If this is the assignment operator, we only perform overload resolution
13383   // if the left-hand side is a class or enumeration type. This is actually
13384   // a hack. The standard requires that we do overload resolution between the
13385   // various built-in candidates, but as DR507 points out, this can lead to
13386   // problems. So we do it this way, which pretty much follows what GCC does.
13387   // Note that we go the traditional code path for compound assignment forms.
13388   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13389     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13390 
13391   // If this is the .* operator, which is not overloadable, just
13392   // create a built-in binary operator.
13393   if (Opc == BO_PtrMemD)
13394     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13395 
13396   // Build the overload set.
13397   OverloadCandidateSet CandidateSet(
13398       OpLoc, OverloadCandidateSet::CSK_Operator,
13399       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13400   if (DefaultedFn)
13401     CandidateSet.exclude(DefaultedFn);
13402   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13403 
13404   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13405 
13406   // Perform overload resolution.
13407   OverloadCandidateSet::iterator Best;
13408   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13409     case OR_Success: {
13410       // We found a built-in operator or an overloaded operator.
13411       FunctionDecl *FnDecl = Best->Function;
13412 
13413       bool IsReversed = Best->isReversed();
13414       if (IsReversed)
13415         std::swap(Args[0], Args[1]);
13416 
13417       if (FnDecl) {
13418         Expr *Base = nullptr;
13419         // We matched an overloaded operator. Build a call to that
13420         // operator.
13421 
13422         OverloadedOperatorKind ChosenOp =
13423             FnDecl->getDeclName().getCXXOverloadedOperator();
13424 
13425         // C++2a [over.match.oper]p9:
13426         //   If a rewritten operator== candidate is selected by overload
13427         //   resolution for an operator@, its return type shall be cv bool
13428         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13429             !FnDecl->getReturnType()->isBooleanType()) {
13430           bool IsExtension =
13431               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13432           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13433                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13434               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13435               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13436           Diag(FnDecl->getLocation(), diag::note_declared_at);
13437           if (!IsExtension)
13438             return ExprError();
13439         }
13440 
13441         if (AllowRewrittenCandidates && !IsReversed &&
13442             CandidateSet.getRewriteInfo().isReversible()) {
13443           // We could have reversed this operator, but didn't. Check if some
13444           // reversed form was a viable candidate, and if so, if it had a
13445           // better conversion for either parameter. If so, this call is
13446           // formally ambiguous, and allowing it is an extension.
13447           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13448           for (OverloadCandidate &Cand : CandidateSet) {
13449             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13450                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13451               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13452                 if (CompareImplicitConversionSequences(
13453                         *this, OpLoc, Cand.Conversions[ArgIdx],
13454                         Best->Conversions[ArgIdx]) ==
13455                     ImplicitConversionSequence::Better) {
13456                   AmbiguousWith.push_back(Cand.Function);
13457                   break;
13458                 }
13459               }
13460             }
13461           }
13462 
13463           if (!AmbiguousWith.empty()) {
13464             bool AmbiguousWithSelf =
13465                 AmbiguousWith.size() == 1 &&
13466                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13467             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13468                 << BinaryOperator::getOpcodeStr(Opc)
13469                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13470                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13471             if (AmbiguousWithSelf) {
13472               Diag(FnDecl->getLocation(),
13473                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13474             } else {
13475               Diag(FnDecl->getLocation(),
13476                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13477               for (auto *F : AmbiguousWith)
13478                 Diag(F->getLocation(),
13479                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13480             }
13481           }
13482         }
13483 
13484         // Convert the arguments.
13485         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13486           // Best->Access is only meaningful for class members.
13487           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13488 
13489           ExprResult Arg1 =
13490             PerformCopyInitialization(
13491               InitializedEntity::InitializeParameter(Context,
13492                                                      FnDecl->getParamDecl(0)),
13493               SourceLocation(), Args[1]);
13494           if (Arg1.isInvalid())
13495             return ExprError();
13496 
13497           ExprResult Arg0 =
13498             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13499                                                 Best->FoundDecl, Method);
13500           if (Arg0.isInvalid())
13501             return ExprError();
13502           Base = Args[0] = Arg0.getAs<Expr>();
13503           Args[1] = RHS = Arg1.getAs<Expr>();
13504         } else {
13505           // Convert the arguments.
13506           ExprResult Arg0 = PerformCopyInitialization(
13507             InitializedEntity::InitializeParameter(Context,
13508                                                    FnDecl->getParamDecl(0)),
13509             SourceLocation(), Args[0]);
13510           if (Arg0.isInvalid())
13511             return ExprError();
13512 
13513           ExprResult Arg1 =
13514             PerformCopyInitialization(
13515               InitializedEntity::InitializeParameter(Context,
13516                                                      FnDecl->getParamDecl(1)),
13517               SourceLocation(), Args[1]);
13518           if (Arg1.isInvalid())
13519             return ExprError();
13520           Args[0] = LHS = Arg0.getAs<Expr>();
13521           Args[1] = RHS = Arg1.getAs<Expr>();
13522         }
13523 
13524         // Build the actual expression node.
13525         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13526                                                   Best->FoundDecl, Base,
13527                                                   HadMultipleCandidates, OpLoc);
13528         if (FnExpr.isInvalid())
13529           return ExprError();
13530 
13531         // Determine the result type.
13532         QualType ResultTy = FnDecl->getReturnType();
13533         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13534         ResultTy = ResultTy.getNonLValueExprType(Context);
13535 
13536         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13537             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13538             CurFPFeatureOverrides(), Best->IsADLCandidate);
13539 
13540         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13541                                 FnDecl))
13542           return ExprError();
13543 
13544         ArrayRef<const Expr *> ArgsArray(Args, 2);
13545         const Expr *ImplicitThis = nullptr;
13546         // Cut off the implicit 'this'.
13547         if (isa<CXXMethodDecl>(FnDecl)) {
13548           ImplicitThis = ArgsArray[0];
13549           ArgsArray = ArgsArray.slice(1);
13550         }
13551 
13552         // Check for a self move.
13553         if (Op == OO_Equal)
13554           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13555 
13556         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13557                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13558                   VariadicDoesNotApply);
13559 
13560         ExprResult R = MaybeBindToTemporary(TheCall);
13561         if (R.isInvalid())
13562           return ExprError();
13563 
13564         R = CheckForImmediateInvocation(R, FnDecl);
13565         if (R.isInvalid())
13566           return ExprError();
13567 
13568         // For a rewritten candidate, we've already reversed the arguments
13569         // if needed. Perform the rest of the rewrite now.
13570         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13571             (Op == OO_Spaceship && IsReversed)) {
13572           if (Op == OO_ExclaimEqual) {
13573             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13574             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13575           } else {
13576             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13577             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13578             Expr *ZeroLiteral =
13579                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13580 
13581             Sema::CodeSynthesisContext Ctx;
13582             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13583             Ctx.Entity = FnDecl;
13584             pushCodeSynthesisContext(Ctx);
13585 
13586             R = CreateOverloadedBinOp(
13587                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13588                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13589                 /*AllowRewrittenCandidates=*/false);
13590 
13591             popCodeSynthesisContext();
13592           }
13593           if (R.isInvalid())
13594             return ExprError();
13595         } else {
13596           assert(ChosenOp == Op && "unexpected operator name");
13597         }
13598 
13599         // Make a note in the AST if we did any rewriting.
13600         if (Best->RewriteKind != CRK_None)
13601           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13602 
13603         return R;
13604       } else {
13605         // We matched a built-in operator. Convert the arguments, then
13606         // break out so that we will build the appropriate built-in
13607         // operator node.
13608         ExprResult ArgsRes0 = PerformImplicitConversion(
13609             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13610             AA_Passing, CCK_ForBuiltinOverloadedOp);
13611         if (ArgsRes0.isInvalid())
13612           return ExprError();
13613         Args[0] = ArgsRes0.get();
13614 
13615         ExprResult ArgsRes1 = PerformImplicitConversion(
13616             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13617             AA_Passing, CCK_ForBuiltinOverloadedOp);
13618         if (ArgsRes1.isInvalid())
13619           return ExprError();
13620         Args[1] = ArgsRes1.get();
13621         break;
13622       }
13623     }
13624 
13625     case OR_No_Viable_Function: {
13626       // C++ [over.match.oper]p9:
13627       //   If the operator is the operator , [...] and there are no
13628       //   viable functions, then the operator is assumed to be the
13629       //   built-in operator and interpreted according to clause 5.
13630       if (Opc == BO_Comma)
13631         break;
13632 
13633       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13634       // compare result using '==' and '<'.
13635       if (DefaultedFn && Opc == BO_Cmp) {
13636         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13637                                                           Args[1], DefaultedFn);
13638         if (E.isInvalid() || E.isUsable())
13639           return E;
13640       }
13641 
13642       // For class as left operand for assignment or compound assignment
13643       // operator do not fall through to handling in built-in, but report that
13644       // no overloaded assignment operator found
13645       ExprResult Result = ExprError();
13646       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13647       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13648                                                    Args, OpLoc);
13649       if (Args[0]->getType()->isRecordType() &&
13650           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13651         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13652              << BinaryOperator::getOpcodeStr(Opc)
13653              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13654         if (Args[0]->getType()->isIncompleteType()) {
13655           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13656             << Args[0]->getType()
13657             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13658         }
13659       } else {
13660         // This is an erroneous use of an operator which can be overloaded by
13661         // a non-member function. Check for non-member operators which were
13662         // defined too late to be candidates.
13663         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13664           // FIXME: Recover by calling the found function.
13665           return ExprError();
13666 
13667         // No viable function; try to create a built-in operation, which will
13668         // produce an error. Then, show the non-viable candidates.
13669         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13670       }
13671       assert(Result.isInvalid() &&
13672              "C++ binary operator overloading is missing candidates!");
13673       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13674       return Result;
13675     }
13676 
13677     case OR_Ambiguous:
13678       CandidateSet.NoteCandidates(
13679           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13680                                          << BinaryOperator::getOpcodeStr(Opc)
13681                                          << Args[0]->getType()
13682                                          << Args[1]->getType()
13683                                          << Args[0]->getSourceRange()
13684                                          << Args[1]->getSourceRange()),
13685           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13686           OpLoc);
13687       return ExprError();
13688 
13689     case OR_Deleted:
13690       if (isImplicitlyDeleted(Best->Function)) {
13691         FunctionDecl *DeletedFD = Best->Function;
13692         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13693         if (DFK.isSpecialMember()) {
13694           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13695             << Args[0]->getType() << DFK.asSpecialMember();
13696         } else {
13697           assert(DFK.isComparison());
13698           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13699             << Args[0]->getType() << DeletedFD;
13700         }
13701 
13702         // The user probably meant to call this special member. Just
13703         // explain why it's deleted.
13704         NoteDeletedFunction(DeletedFD);
13705         return ExprError();
13706       }
13707       CandidateSet.NoteCandidates(
13708           PartialDiagnosticAt(
13709               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13710                          << getOperatorSpelling(Best->Function->getDeclName()
13711                                                     .getCXXOverloadedOperator())
13712                          << Args[0]->getSourceRange()
13713                          << Args[1]->getSourceRange()),
13714           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13715           OpLoc);
13716       return ExprError();
13717   }
13718 
13719   // We matched a built-in operator; build it.
13720   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13721 }
13722 
13723 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13724     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13725     FunctionDecl *DefaultedFn) {
13726   const ComparisonCategoryInfo *Info =
13727       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13728   // If we're not producing a known comparison category type, we can't
13729   // synthesize a three-way comparison. Let the caller diagnose this.
13730   if (!Info)
13731     return ExprResult((Expr*)nullptr);
13732 
13733   // If we ever want to perform this synthesis more generally, we will need to
13734   // apply the temporary materialization conversion to the operands.
13735   assert(LHS->isGLValue() && RHS->isGLValue() &&
13736          "cannot use prvalue expressions more than once");
13737   Expr *OrigLHS = LHS;
13738   Expr *OrigRHS = RHS;
13739 
13740   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13741   // each of them multiple times below.
13742   LHS = new (Context)
13743       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13744                       LHS->getObjectKind(), LHS);
13745   RHS = new (Context)
13746       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13747                       RHS->getObjectKind(), RHS);
13748 
13749   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13750                                         DefaultedFn);
13751   if (Eq.isInvalid())
13752     return ExprError();
13753 
13754   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13755                                           true, DefaultedFn);
13756   if (Less.isInvalid())
13757     return ExprError();
13758 
13759   ExprResult Greater;
13760   if (Info->isPartial()) {
13761     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13762                                     DefaultedFn);
13763     if (Greater.isInvalid())
13764       return ExprError();
13765   }
13766 
13767   // Form the list of comparisons we're going to perform.
13768   struct Comparison {
13769     ExprResult Cmp;
13770     ComparisonCategoryResult Result;
13771   } Comparisons[4] =
13772   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13773                           : ComparisonCategoryResult::Equivalent},
13774     {Less, ComparisonCategoryResult::Less},
13775     {Greater, ComparisonCategoryResult::Greater},
13776     {ExprResult(), ComparisonCategoryResult::Unordered},
13777   };
13778 
13779   int I = Info->isPartial() ? 3 : 2;
13780 
13781   // Combine the comparisons with suitable conditional expressions.
13782   ExprResult Result;
13783   for (; I >= 0; --I) {
13784     // Build a reference to the comparison category constant.
13785     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13786     // FIXME: Missing a constant for a comparison category. Diagnose this?
13787     if (!VI)
13788       return ExprResult((Expr*)nullptr);
13789     ExprResult ThisResult =
13790         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13791     if (ThisResult.isInvalid())
13792       return ExprError();
13793 
13794     // Build a conditional unless this is the final case.
13795     if (Result.get()) {
13796       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13797                                   ThisResult.get(), Result.get());
13798       if (Result.isInvalid())
13799         return ExprError();
13800     } else {
13801       Result = ThisResult;
13802     }
13803   }
13804 
13805   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13806   // bind the OpaqueValueExprs before they're (repeatedly) used.
13807   Expr *SyntacticForm = BinaryOperator::Create(
13808       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13809       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13810       CurFPFeatureOverrides());
13811   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13812   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13813 }
13814 
13815 ExprResult
13816 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13817                                          SourceLocation RLoc,
13818                                          Expr *Base, Expr *Idx) {
13819   Expr *Args[2] = { Base, Idx };
13820   DeclarationName OpName =
13821       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13822 
13823   // If either side is type-dependent, create an appropriate dependent
13824   // expression.
13825   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13826 
13827     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13828     // CHECKME: no 'operator' keyword?
13829     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13830     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13831     ExprResult Fn = CreateUnresolvedLookupExpr(
13832         NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
13833     if (Fn.isInvalid())
13834       return ExprError();
13835     // Can't add any actual overloads yet
13836 
13837     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
13838                                        Context.DependentTy, VK_RValue, RLoc,
13839                                        CurFPFeatureOverrides());
13840   }
13841 
13842   // Handle placeholders on both operands.
13843   if (checkPlaceholderForOverload(*this, Args[0]))
13844     return ExprError();
13845   if (checkPlaceholderForOverload(*this, Args[1]))
13846     return ExprError();
13847 
13848   // Build an empty overload set.
13849   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13850 
13851   // Subscript can only be overloaded as a member function.
13852 
13853   // Add operator candidates that are member functions.
13854   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13855 
13856   // Add builtin operator candidates.
13857   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13858 
13859   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13860 
13861   // Perform overload resolution.
13862   OverloadCandidateSet::iterator Best;
13863   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13864     case OR_Success: {
13865       // We found a built-in operator or an overloaded operator.
13866       FunctionDecl *FnDecl = Best->Function;
13867 
13868       if (FnDecl) {
13869         // We matched an overloaded operator. Build a call to that
13870         // operator.
13871 
13872         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13873 
13874         // Convert the arguments.
13875         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13876         ExprResult Arg0 =
13877           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13878                                               Best->FoundDecl, Method);
13879         if (Arg0.isInvalid())
13880           return ExprError();
13881         Args[0] = Arg0.get();
13882 
13883         // Convert the arguments.
13884         ExprResult InputInit
13885           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13886                                                       Context,
13887                                                       FnDecl->getParamDecl(0)),
13888                                       SourceLocation(),
13889                                       Args[1]);
13890         if (InputInit.isInvalid())
13891           return ExprError();
13892 
13893         Args[1] = InputInit.getAs<Expr>();
13894 
13895         // Build the actual expression node.
13896         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13897         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13898         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13899                                                   Best->FoundDecl,
13900                                                   Base,
13901                                                   HadMultipleCandidates,
13902                                                   OpLocInfo.getLoc(),
13903                                                   OpLocInfo.getInfo());
13904         if (FnExpr.isInvalid())
13905           return ExprError();
13906 
13907         // Determine the result type
13908         QualType ResultTy = FnDecl->getReturnType();
13909         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13910         ResultTy = ResultTy.getNonLValueExprType(Context);
13911 
13912         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13913             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13914             CurFPFeatureOverrides());
13915         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13916           return ExprError();
13917 
13918         if (CheckFunctionCall(Method, TheCall,
13919                               Method->getType()->castAs<FunctionProtoType>()))
13920           return ExprError();
13921 
13922         return MaybeBindToTemporary(TheCall);
13923       } else {
13924         // We matched a built-in operator. Convert the arguments, then
13925         // break out so that we will build the appropriate built-in
13926         // operator node.
13927         ExprResult ArgsRes0 = PerformImplicitConversion(
13928             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13929             AA_Passing, CCK_ForBuiltinOverloadedOp);
13930         if (ArgsRes0.isInvalid())
13931           return ExprError();
13932         Args[0] = ArgsRes0.get();
13933 
13934         ExprResult ArgsRes1 = PerformImplicitConversion(
13935             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13936             AA_Passing, CCK_ForBuiltinOverloadedOp);
13937         if (ArgsRes1.isInvalid())
13938           return ExprError();
13939         Args[1] = ArgsRes1.get();
13940 
13941         break;
13942       }
13943     }
13944 
13945     case OR_No_Viable_Function: {
13946       PartialDiagnostic PD = CandidateSet.empty()
13947           ? (PDiag(diag::err_ovl_no_oper)
13948              << Args[0]->getType() << /*subscript*/ 0
13949              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13950           : (PDiag(diag::err_ovl_no_viable_subscript)
13951              << Args[0]->getType() << Args[0]->getSourceRange()
13952              << Args[1]->getSourceRange());
13953       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13954                                   OCD_AllCandidates, Args, "[]", LLoc);
13955       return ExprError();
13956     }
13957 
13958     case OR_Ambiguous:
13959       CandidateSet.NoteCandidates(
13960           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13961                                         << "[]" << Args[0]->getType()
13962                                         << Args[1]->getType()
13963                                         << Args[0]->getSourceRange()
13964                                         << Args[1]->getSourceRange()),
13965           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13966       return ExprError();
13967 
13968     case OR_Deleted:
13969       CandidateSet.NoteCandidates(
13970           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13971                                         << "[]" << Args[0]->getSourceRange()
13972                                         << Args[1]->getSourceRange()),
13973           *this, OCD_AllCandidates, Args, "[]", LLoc);
13974       return ExprError();
13975     }
13976 
13977   // We matched a built-in operator; build it.
13978   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13979 }
13980 
13981 /// BuildCallToMemberFunction - Build a call to a member
13982 /// function. MemExpr is the expression that refers to the member
13983 /// function (and includes the object parameter), Args/NumArgs are the
13984 /// arguments to the function call (not including the object
13985 /// parameter). The caller needs to validate that the member
13986 /// expression refers to a non-static member function or an overloaded
13987 /// member function.
13988 ExprResult
13989 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13990                                 SourceLocation LParenLoc,
13991                                 MultiExprArg Args,
13992                                 SourceLocation RParenLoc) {
13993   assert(MemExprE->getType() == Context.BoundMemberTy ||
13994          MemExprE->getType() == Context.OverloadTy);
13995 
13996   // Dig out the member expression. This holds both the object
13997   // argument and the member function we're referring to.
13998   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13999 
14000   // Determine whether this is a call to a pointer-to-member function.
14001   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
14002     assert(op->getType() == Context.BoundMemberTy);
14003     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
14004 
14005     QualType fnType =
14006       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
14007 
14008     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
14009     QualType resultType = proto->getCallResultType(Context);
14010     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
14011 
14012     // Check that the object type isn't more qualified than the
14013     // member function we're calling.
14014     Qualifiers funcQuals = proto->getMethodQuals();
14015 
14016     QualType objectType = op->getLHS()->getType();
14017     if (op->getOpcode() == BO_PtrMemI)
14018       objectType = objectType->castAs<PointerType>()->getPointeeType();
14019     Qualifiers objectQuals = objectType.getQualifiers();
14020 
14021     Qualifiers difference = objectQuals - funcQuals;
14022     difference.removeObjCGCAttr();
14023     difference.removeAddressSpace();
14024     if (difference) {
14025       std::string qualsString = difference.getAsString();
14026       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
14027         << fnType.getUnqualifiedType()
14028         << qualsString
14029         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
14030     }
14031 
14032     CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
14033         Context, MemExprE, Args, resultType, valueKind, RParenLoc,
14034         CurFPFeatureOverrides(), proto->getNumParams());
14035 
14036     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
14037                             call, nullptr))
14038       return ExprError();
14039 
14040     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
14041       return ExprError();
14042 
14043     if (CheckOtherCall(call, proto))
14044       return ExprError();
14045 
14046     return MaybeBindToTemporary(call);
14047   }
14048 
14049   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
14050     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
14051                             RParenLoc, CurFPFeatureOverrides());
14052 
14053   UnbridgedCastsSet UnbridgedCasts;
14054   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14055     return ExprError();
14056 
14057   MemberExpr *MemExpr;
14058   CXXMethodDecl *Method = nullptr;
14059   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14060   NestedNameSpecifier *Qualifier = nullptr;
14061   if (isa<MemberExpr>(NakedMemExpr)) {
14062     MemExpr = cast<MemberExpr>(NakedMemExpr);
14063     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14064     FoundDecl = MemExpr->getFoundDecl();
14065     Qualifier = MemExpr->getQualifier();
14066     UnbridgedCasts.restore();
14067   } else {
14068     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14069     Qualifier = UnresExpr->getQualifier();
14070 
14071     QualType ObjectType = UnresExpr->getBaseType();
14072     Expr::Classification ObjectClassification
14073       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14074                             : UnresExpr->getBase()->Classify(Context);
14075 
14076     // Add overload candidates
14077     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14078                                       OverloadCandidateSet::CSK_Normal);
14079 
14080     // FIXME: avoid copy.
14081     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14082     if (UnresExpr->hasExplicitTemplateArgs()) {
14083       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14084       TemplateArgs = &TemplateArgsBuffer;
14085     }
14086 
14087     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14088            E = UnresExpr->decls_end(); I != E; ++I) {
14089 
14090       NamedDecl *Func = *I;
14091       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14092       if (isa<UsingShadowDecl>(Func))
14093         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14094 
14095 
14096       // Microsoft supports direct constructor calls.
14097       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14098         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14099                              CandidateSet,
14100                              /*SuppressUserConversions*/ false);
14101       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14102         // If explicit template arguments were provided, we can't call a
14103         // non-template member function.
14104         if (TemplateArgs)
14105           continue;
14106 
14107         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14108                            ObjectClassification, Args, CandidateSet,
14109                            /*SuppressUserConversions=*/false);
14110       } else {
14111         AddMethodTemplateCandidate(
14112             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14113             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14114             /*SuppressUserConversions=*/false);
14115       }
14116     }
14117 
14118     DeclarationName DeclName = UnresExpr->getMemberName();
14119 
14120     UnbridgedCasts.restore();
14121 
14122     OverloadCandidateSet::iterator Best;
14123     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14124                                             Best)) {
14125     case OR_Success:
14126       Method = cast<CXXMethodDecl>(Best->Function);
14127       FoundDecl = Best->FoundDecl;
14128       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14129       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14130         return ExprError();
14131       // If FoundDecl is different from Method (such as if one is a template
14132       // and the other a specialization), make sure DiagnoseUseOfDecl is
14133       // called on both.
14134       // FIXME: This would be more comprehensively addressed by modifying
14135       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14136       // being used.
14137       if (Method != FoundDecl.getDecl() &&
14138                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14139         return ExprError();
14140       break;
14141 
14142     case OR_No_Viable_Function:
14143       CandidateSet.NoteCandidates(
14144           PartialDiagnosticAt(
14145               UnresExpr->getMemberLoc(),
14146               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14147                   << DeclName << MemExprE->getSourceRange()),
14148           *this, OCD_AllCandidates, Args);
14149       // FIXME: Leaking incoming expressions!
14150       return ExprError();
14151 
14152     case OR_Ambiguous:
14153       CandidateSet.NoteCandidates(
14154           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14155                               PDiag(diag::err_ovl_ambiguous_member_call)
14156                                   << DeclName << MemExprE->getSourceRange()),
14157           *this, OCD_AmbiguousCandidates, Args);
14158       // FIXME: Leaking incoming expressions!
14159       return ExprError();
14160 
14161     case OR_Deleted:
14162       CandidateSet.NoteCandidates(
14163           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14164                               PDiag(diag::err_ovl_deleted_member_call)
14165                                   << DeclName << MemExprE->getSourceRange()),
14166           *this, OCD_AllCandidates, Args);
14167       // FIXME: Leaking incoming expressions!
14168       return ExprError();
14169     }
14170 
14171     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14172 
14173     // If overload resolution picked a static member, build a
14174     // non-member call based on that function.
14175     if (Method->isStatic()) {
14176       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14177                                    RParenLoc);
14178     }
14179 
14180     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14181   }
14182 
14183   QualType ResultType = Method->getReturnType();
14184   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14185   ResultType = ResultType.getNonLValueExprType(Context);
14186 
14187   assert(Method && "Member call to something that isn't a method?");
14188   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14189   CXXMemberCallExpr *TheCall = CXXMemberCallExpr::Create(
14190       Context, MemExprE, Args, ResultType, VK, RParenLoc,
14191       CurFPFeatureOverrides(), Proto->getNumParams());
14192 
14193   // Check for a valid return type.
14194   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14195                           TheCall, Method))
14196     return ExprError();
14197 
14198   // Convert the object argument (for a non-static member function call).
14199   // We only need to do this if there was actually an overload; otherwise
14200   // it was done at lookup.
14201   if (!Method->isStatic()) {
14202     ExprResult ObjectArg =
14203       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14204                                           FoundDecl, Method);
14205     if (ObjectArg.isInvalid())
14206       return ExprError();
14207     MemExpr->setBase(ObjectArg.get());
14208   }
14209 
14210   // Convert the rest of the arguments
14211   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14212                               RParenLoc))
14213     return ExprError();
14214 
14215   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14216 
14217   if (CheckFunctionCall(Method, TheCall, Proto))
14218     return ExprError();
14219 
14220   // In the case the method to call was not selected by the overloading
14221   // resolution process, we still need to handle the enable_if attribute. Do
14222   // that here, so it will not hide previous -- and more relevant -- errors.
14223   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14224     if (const EnableIfAttr *Attr =
14225             CheckEnableIf(Method, LParenLoc, Args, true)) {
14226       Diag(MemE->getMemberLoc(),
14227            diag::err_ovl_no_viable_member_function_in_call)
14228           << Method << Method->getSourceRange();
14229       Diag(Method->getLocation(),
14230            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14231           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14232       return ExprError();
14233     }
14234   }
14235 
14236   if ((isa<CXXConstructorDecl>(CurContext) ||
14237        isa<CXXDestructorDecl>(CurContext)) &&
14238       TheCall->getMethodDecl()->isPure()) {
14239     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14240 
14241     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14242         MemExpr->performsVirtualDispatch(getLangOpts())) {
14243       Diag(MemExpr->getBeginLoc(),
14244            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14245           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14246           << MD->getParent();
14247 
14248       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14249       if (getLangOpts().AppleKext)
14250         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14251             << MD->getParent() << MD->getDeclName();
14252     }
14253   }
14254 
14255   if (CXXDestructorDecl *DD =
14256           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14257     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14258     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14259     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14260                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14261                          MemExpr->getMemberLoc());
14262   }
14263 
14264   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14265                                      TheCall->getMethodDecl());
14266 }
14267 
14268 /// BuildCallToObjectOfClassType - Build a call to an object of class
14269 /// type (C++ [over.call.object]), which can end up invoking an
14270 /// overloaded function call operator (@c operator()) or performing a
14271 /// user-defined conversion on the object argument.
14272 ExprResult
14273 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14274                                    SourceLocation LParenLoc,
14275                                    MultiExprArg Args,
14276                                    SourceLocation RParenLoc) {
14277   if (checkPlaceholderForOverload(*this, Obj))
14278     return ExprError();
14279   ExprResult Object = Obj;
14280 
14281   UnbridgedCastsSet UnbridgedCasts;
14282   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14283     return ExprError();
14284 
14285   assert(Object.get()->getType()->isRecordType() &&
14286          "Requires object type argument");
14287 
14288   // C++ [over.call.object]p1:
14289   //  If the primary-expression E in the function call syntax
14290   //  evaluates to a class object of type "cv T", then the set of
14291   //  candidate functions includes at least the function call
14292   //  operators of T. The function call operators of T are obtained by
14293   //  ordinary lookup of the name operator() in the context of
14294   //  (E).operator().
14295   OverloadCandidateSet CandidateSet(LParenLoc,
14296                                     OverloadCandidateSet::CSK_Operator);
14297   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14298 
14299   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14300                           diag::err_incomplete_object_call, Object.get()))
14301     return true;
14302 
14303   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14304   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14305   LookupQualifiedName(R, Record->getDecl());
14306   R.suppressDiagnostics();
14307 
14308   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14309        Oper != OperEnd; ++Oper) {
14310     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14311                        Object.get()->Classify(Context), Args, CandidateSet,
14312                        /*SuppressUserConversion=*/false);
14313   }
14314 
14315   // C++ [over.call.object]p2:
14316   //   In addition, for each (non-explicit in C++0x) conversion function
14317   //   declared in T of the form
14318   //
14319   //        operator conversion-type-id () cv-qualifier;
14320   //
14321   //   where cv-qualifier is the same cv-qualification as, or a
14322   //   greater cv-qualification than, cv, and where conversion-type-id
14323   //   denotes the type "pointer to function of (P1,...,Pn) returning
14324   //   R", or the type "reference to pointer to function of
14325   //   (P1,...,Pn) returning R", or the type "reference to function
14326   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14327   //   is also considered as a candidate function. Similarly,
14328   //   surrogate call functions are added to the set of candidate
14329   //   functions for each conversion function declared in an
14330   //   accessible base class provided the function is not hidden
14331   //   within T by another intervening declaration.
14332   const auto &Conversions =
14333       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14334   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14335     NamedDecl *D = *I;
14336     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14337     if (isa<UsingShadowDecl>(D))
14338       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14339 
14340     // Skip over templated conversion functions; they aren't
14341     // surrogates.
14342     if (isa<FunctionTemplateDecl>(D))
14343       continue;
14344 
14345     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14346     if (!Conv->isExplicit()) {
14347       // Strip the reference type (if any) and then the pointer type (if
14348       // any) to get down to what might be a function type.
14349       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14350       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14351         ConvType = ConvPtrType->getPointeeType();
14352 
14353       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14354       {
14355         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14356                               Object.get(), Args, CandidateSet);
14357       }
14358     }
14359   }
14360 
14361   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14362 
14363   // Perform overload resolution.
14364   OverloadCandidateSet::iterator Best;
14365   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14366                                           Best)) {
14367   case OR_Success:
14368     // Overload resolution succeeded; we'll build the appropriate call
14369     // below.
14370     break;
14371 
14372   case OR_No_Viable_Function: {
14373     PartialDiagnostic PD =
14374         CandidateSet.empty()
14375             ? (PDiag(diag::err_ovl_no_oper)
14376                << Object.get()->getType() << /*call*/ 1
14377                << Object.get()->getSourceRange())
14378             : (PDiag(diag::err_ovl_no_viable_object_call)
14379                << Object.get()->getType() << Object.get()->getSourceRange());
14380     CandidateSet.NoteCandidates(
14381         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14382         OCD_AllCandidates, Args);
14383     break;
14384   }
14385   case OR_Ambiguous:
14386     CandidateSet.NoteCandidates(
14387         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14388                             PDiag(diag::err_ovl_ambiguous_object_call)
14389                                 << Object.get()->getType()
14390                                 << Object.get()->getSourceRange()),
14391         *this, OCD_AmbiguousCandidates, Args);
14392     break;
14393 
14394   case OR_Deleted:
14395     CandidateSet.NoteCandidates(
14396         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14397                             PDiag(diag::err_ovl_deleted_object_call)
14398                                 << Object.get()->getType()
14399                                 << Object.get()->getSourceRange()),
14400         *this, OCD_AllCandidates, Args);
14401     break;
14402   }
14403 
14404   if (Best == CandidateSet.end())
14405     return true;
14406 
14407   UnbridgedCasts.restore();
14408 
14409   if (Best->Function == nullptr) {
14410     // Since there is no function declaration, this is one of the
14411     // surrogate candidates. Dig out the conversion function.
14412     CXXConversionDecl *Conv
14413       = cast<CXXConversionDecl>(
14414                          Best->Conversions[0].UserDefined.ConversionFunction);
14415 
14416     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14417                               Best->FoundDecl);
14418     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14419       return ExprError();
14420     assert(Conv == Best->FoundDecl.getDecl() &&
14421              "Found Decl & conversion-to-functionptr should be same, right?!");
14422     // We selected one of the surrogate functions that converts the
14423     // object parameter to a function pointer. Perform the conversion
14424     // on the object argument, then let BuildCallExpr finish the job.
14425 
14426     // Create an implicit member expr to refer to the conversion operator.
14427     // and then call it.
14428     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14429                                              Conv, HadMultipleCandidates);
14430     if (Call.isInvalid())
14431       return ExprError();
14432     // Record usage of conversion in an implicit cast.
14433     Call = ImplicitCastExpr::Create(
14434         Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
14435         nullptr, VK_RValue, CurFPFeatureOverrides());
14436 
14437     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14438   }
14439 
14440   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14441 
14442   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14443   // that calls this method, using Object for the implicit object
14444   // parameter and passing along the remaining arguments.
14445   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14446 
14447   // An error diagnostic has already been printed when parsing the declaration.
14448   if (Method->isInvalidDecl())
14449     return ExprError();
14450 
14451   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14452   unsigned NumParams = Proto->getNumParams();
14453 
14454   DeclarationNameInfo OpLocInfo(
14455                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14456   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14457   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14458                                            Obj, HadMultipleCandidates,
14459                                            OpLocInfo.getLoc(),
14460                                            OpLocInfo.getInfo());
14461   if (NewFn.isInvalid())
14462     return true;
14463 
14464   // The number of argument slots to allocate in the call. If we have default
14465   // arguments we need to allocate space for them as well. We additionally
14466   // need one more slot for the object parameter.
14467   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14468 
14469   // Build the full argument list for the method call (the implicit object
14470   // parameter is placed at the beginning of the list).
14471   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14472 
14473   bool IsError = false;
14474 
14475   // Initialize the implicit object parameter.
14476   ExprResult ObjRes =
14477     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14478                                         Best->FoundDecl, Method);
14479   if (ObjRes.isInvalid())
14480     IsError = true;
14481   else
14482     Object = ObjRes;
14483   MethodArgs[0] = Object.get();
14484 
14485   // Check the argument types.
14486   for (unsigned i = 0; i != NumParams; i++) {
14487     Expr *Arg;
14488     if (i < Args.size()) {
14489       Arg = Args[i];
14490 
14491       // Pass the argument.
14492 
14493       ExprResult InputInit
14494         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14495                                                     Context,
14496                                                     Method->getParamDecl(i)),
14497                                     SourceLocation(), Arg);
14498 
14499       IsError |= InputInit.isInvalid();
14500       Arg = InputInit.getAs<Expr>();
14501     } else {
14502       ExprResult DefArg
14503         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14504       if (DefArg.isInvalid()) {
14505         IsError = true;
14506         break;
14507       }
14508 
14509       Arg = DefArg.getAs<Expr>();
14510     }
14511 
14512     MethodArgs[i + 1] = Arg;
14513   }
14514 
14515   // If this is a variadic call, handle args passed through "...".
14516   if (Proto->isVariadic()) {
14517     // Promote the arguments (C99 6.5.2.2p7).
14518     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14519       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14520                                                         nullptr);
14521       IsError |= Arg.isInvalid();
14522       MethodArgs[i + 1] = Arg.get();
14523     }
14524   }
14525 
14526   if (IsError)
14527     return true;
14528 
14529   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14530 
14531   // Once we've built TheCall, all of the expressions are properly owned.
14532   QualType ResultTy = Method->getReturnType();
14533   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14534   ResultTy = ResultTy.getNonLValueExprType(Context);
14535 
14536   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14537       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14538       CurFPFeatureOverrides());
14539 
14540   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14541     return true;
14542 
14543   if (CheckFunctionCall(Method, TheCall, Proto))
14544     return true;
14545 
14546   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14547 }
14548 
14549 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14550 ///  (if one exists), where @c Base is an expression of class type and
14551 /// @c Member is the name of the member we're trying to find.
14552 ExprResult
14553 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14554                                bool *NoArrowOperatorFound) {
14555   assert(Base->getType()->isRecordType() &&
14556          "left-hand side must have class type");
14557 
14558   if (checkPlaceholderForOverload(*this, Base))
14559     return ExprError();
14560 
14561   SourceLocation Loc = Base->getExprLoc();
14562 
14563   // C++ [over.ref]p1:
14564   //
14565   //   [...] An expression x->m is interpreted as (x.operator->())->m
14566   //   for a class object x of type T if T::operator->() exists and if
14567   //   the operator is selected as the best match function by the
14568   //   overload resolution mechanism (13.3).
14569   DeclarationName OpName =
14570     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14571   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14572 
14573   if (RequireCompleteType(Loc, Base->getType(),
14574                           diag::err_typecheck_incomplete_tag, Base))
14575     return ExprError();
14576 
14577   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14578   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14579   R.suppressDiagnostics();
14580 
14581   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14582        Oper != OperEnd; ++Oper) {
14583     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14584                        None, CandidateSet, /*SuppressUserConversion=*/false);
14585   }
14586 
14587   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14588 
14589   // Perform overload resolution.
14590   OverloadCandidateSet::iterator Best;
14591   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14592   case OR_Success:
14593     // Overload resolution succeeded; we'll build the call below.
14594     break;
14595 
14596   case OR_No_Viable_Function: {
14597     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14598     if (CandidateSet.empty()) {
14599       QualType BaseType = Base->getType();
14600       if (NoArrowOperatorFound) {
14601         // Report this specific error to the caller instead of emitting a
14602         // diagnostic, as requested.
14603         *NoArrowOperatorFound = true;
14604         return ExprError();
14605       }
14606       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14607         << BaseType << Base->getSourceRange();
14608       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14609         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14610           << FixItHint::CreateReplacement(OpLoc, ".");
14611       }
14612     } else
14613       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14614         << "operator->" << Base->getSourceRange();
14615     CandidateSet.NoteCandidates(*this, Base, Cands);
14616     return ExprError();
14617   }
14618   case OR_Ambiguous:
14619     CandidateSet.NoteCandidates(
14620         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14621                                        << "->" << Base->getType()
14622                                        << Base->getSourceRange()),
14623         *this, OCD_AmbiguousCandidates, Base);
14624     return ExprError();
14625 
14626   case OR_Deleted:
14627     CandidateSet.NoteCandidates(
14628         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14629                                        << "->" << Base->getSourceRange()),
14630         *this, OCD_AllCandidates, Base);
14631     return ExprError();
14632   }
14633 
14634   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14635 
14636   // Convert the object parameter.
14637   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14638   ExprResult BaseResult =
14639     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14640                                         Best->FoundDecl, Method);
14641   if (BaseResult.isInvalid())
14642     return ExprError();
14643   Base = BaseResult.get();
14644 
14645   // Build the operator call.
14646   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14647                                             Base, HadMultipleCandidates, OpLoc);
14648   if (FnExpr.isInvalid())
14649     return ExprError();
14650 
14651   QualType ResultTy = Method->getReturnType();
14652   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14653   ResultTy = ResultTy.getNonLValueExprType(Context);
14654   CXXOperatorCallExpr *TheCall =
14655       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14656                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14657 
14658   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14659     return ExprError();
14660 
14661   if (CheckFunctionCall(Method, TheCall,
14662                         Method->getType()->castAs<FunctionProtoType>()))
14663     return ExprError();
14664 
14665   return MaybeBindToTemporary(TheCall);
14666 }
14667 
14668 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14669 /// a literal operator described by the provided lookup results.
14670 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14671                                           DeclarationNameInfo &SuffixInfo,
14672                                           ArrayRef<Expr*> Args,
14673                                           SourceLocation LitEndLoc,
14674                                        TemplateArgumentListInfo *TemplateArgs) {
14675   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14676 
14677   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14678                                     OverloadCandidateSet::CSK_Normal);
14679   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14680                                  TemplateArgs);
14681 
14682   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14683 
14684   // Perform overload resolution. This will usually be trivial, but might need
14685   // to perform substitutions for a literal operator template.
14686   OverloadCandidateSet::iterator Best;
14687   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14688   case OR_Success:
14689   case OR_Deleted:
14690     break;
14691 
14692   case OR_No_Viable_Function:
14693     CandidateSet.NoteCandidates(
14694         PartialDiagnosticAt(UDSuffixLoc,
14695                             PDiag(diag::err_ovl_no_viable_function_in_call)
14696                                 << R.getLookupName()),
14697         *this, OCD_AllCandidates, Args);
14698     return ExprError();
14699 
14700   case OR_Ambiguous:
14701     CandidateSet.NoteCandidates(
14702         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14703                                                 << R.getLookupName()),
14704         *this, OCD_AmbiguousCandidates, Args);
14705     return ExprError();
14706   }
14707 
14708   FunctionDecl *FD = Best->Function;
14709   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14710                                         nullptr, HadMultipleCandidates,
14711                                         SuffixInfo.getLoc(),
14712                                         SuffixInfo.getInfo());
14713   if (Fn.isInvalid())
14714     return true;
14715 
14716   // Check the argument types. This should almost always be a no-op, except
14717   // that array-to-pointer decay is applied to string literals.
14718   Expr *ConvArgs[2];
14719   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14720     ExprResult InputInit = PerformCopyInitialization(
14721       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14722       SourceLocation(), Args[ArgIdx]);
14723     if (InputInit.isInvalid())
14724       return true;
14725     ConvArgs[ArgIdx] = InputInit.get();
14726   }
14727 
14728   QualType ResultTy = FD->getReturnType();
14729   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14730   ResultTy = ResultTy.getNonLValueExprType(Context);
14731 
14732   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14733       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14734       VK, LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
14735 
14736   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14737     return ExprError();
14738 
14739   if (CheckFunctionCall(FD, UDL, nullptr))
14740     return ExprError();
14741 
14742   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14743 }
14744 
14745 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14746 /// given LookupResult is non-empty, it is assumed to describe a member which
14747 /// will be invoked. Otherwise, the function will be found via argument
14748 /// dependent lookup.
14749 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14750 /// otherwise CallExpr is set to ExprError() and some non-success value
14751 /// is returned.
14752 Sema::ForRangeStatus
14753 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14754                                 SourceLocation RangeLoc,
14755                                 const DeclarationNameInfo &NameInfo,
14756                                 LookupResult &MemberLookup,
14757                                 OverloadCandidateSet *CandidateSet,
14758                                 Expr *Range, ExprResult *CallExpr) {
14759   Scope *S = nullptr;
14760 
14761   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14762   if (!MemberLookup.empty()) {
14763     ExprResult MemberRef =
14764         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14765                                  /*IsPtr=*/false, CXXScopeSpec(),
14766                                  /*TemplateKWLoc=*/SourceLocation(),
14767                                  /*FirstQualifierInScope=*/nullptr,
14768                                  MemberLookup,
14769                                  /*TemplateArgs=*/nullptr, S);
14770     if (MemberRef.isInvalid()) {
14771       *CallExpr = ExprError();
14772       return FRS_DiagnosticIssued;
14773     }
14774     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14775     if (CallExpr->isInvalid()) {
14776       *CallExpr = ExprError();
14777       return FRS_DiagnosticIssued;
14778     }
14779   } else {
14780     ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
14781                                                 NestedNameSpecifierLoc(),
14782                                                 NameInfo, UnresolvedSet<0>());
14783     if (FnR.isInvalid())
14784       return FRS_DiagnosticIssued;
14785     UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
14786 
14787     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14788                                                     CandidateSet, CallExpr);
14789     if (CandidateSet->empty() || CandidateSetError) {
14790       *CallExpr = ExprError();
14791       return FRS_NoViableFunction;
14792     }
14793     OverloadCandidateSet::iterator Best;
14794     OverloadingResult OverloadResult =
14795         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14796 
14797     if (OverloadResult == OR_No_Viable_Function) {
14798       *CallExpr = ExprError();
14799       return FRS_NoViableFunction;
14800     }
14801     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14802                                          Loc, nullptr, CandidateSet, &Best,
14803                                          OverloadResult,
14804                                          /*AllowTypoCorrection=*/false);
14805     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14806       *CallExpr = ExprError();
14807       return FRS_DiagnosticIssued;
14808     }
14809   }
14810   return FRS_Success;
14811 }
14812 
14813 
14814 /// FixOverloadedFunctionReference - E is an expression that refers to
14815 /// a C++ overloaded function (possibly with some parentheses and
14816 /// perhaps a '&' around it). We have resolved the overloaded function
14817 /// to the function declaration Fn, so patch up the expression E to
14818 /// refer (possibly indirectly) to Fn. Returns the new expr.
14819 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14820                                            FunctionDecl *Fn) {
14821   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14822     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14823                                                    Found, Fn);
14824     if (SubExpr == PE->getSubExpr())
14825       return PE;
14826 
14827     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14828   }
14829 
14830   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14831     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14832                                                    Found, Fn);
14833     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14834                                SubExpr->getType()) &&
14835            "Implicit cast type cannot be determined from overload");
14836     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14837     if (SubExpr == ICE->getSubExpr())
14838       return ICE;
14839 
14840     return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
14841                                     SubExpr, nullptr, ICE->getValueKind(),
14842                                     CurFPFeatureOverrides());
14843   }
14844 
14845   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14846     if (!GSE->isResultDependent()) {
14847       Expr *SubExpr =
14848           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14849       if (SubExpr == GSE->getResultExpr())
14850         return GSE;
14851 
14852       // Replace the resulting type information before rebuilding the generic
14853       // selection expression.
14854       ArrayRef<Expr *> A = GSE->getAssocExprs();
14855       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14856       unsigned ResultIdx = GSE->getResultIndex();
14857       AssocExprs[ResultIdx] = SubExpr;
14858 
14859       return GenericSelectionExpr::Create(
14860           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14861           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14862           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14863           ResultIdx);
14864     }
14865     // Rather than fall through to the unreachable, return the original generic
14866     // selection expression.
14867     return GSE;
14868   }
14869 
14870   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14871     assert(UnOp->getOpcode() == UO_AddrOf &&
14872            "Can only take the address of an overloaded function");
14873     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14874       if (Method->isStatic()) {
14875         // Do nothing: static member functions aren't any different
14876         // from non-member functions.
14877       } else {
14878         // Fix the subexpression, which really has to be an
14879         // UnresolvedLookupExpr holding an overloaded member function
14880         // or template.
14881         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14882                                                        Found, Fn);
14883         if (SubExpr == UnOp->getSubExpr())
14884           return UnOp;
14885 
14886         assert(isa<DeclRefExpr>(SubExpr)
14887                && "fixed to something other than a decl ref");
14888         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14889                && "fixed to a member ref with no nested name qualifier");
14890 
14891         // We have taken the address of a pointer to member
14892         // function. Perform the computation here so that we get the
14893         // appropriate pointer to member type.
14894         QualType ClassType
14895           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14896         QualType MemPtrType
14897           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14898         // Under the MS ABI, lock down the inheritance model now.
14899         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14900           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14901 
14902         return UnaryOperator::Create(
14903             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14904             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14905       }
14906     }
14907     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14908                                                    Found, Fn);
14909     if (SubExpr == UnOp->getSubExpr())
14910       return UnOp;
14911 
14912     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14913                                  Context.getPointerType(SubExpr->getType()),
14914                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14915                                  false, CurFPFeatureOverrides());
14916   }
14917 
14918   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14919     // FIXME: avoid copy.
14920     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14921     if (ULE->hasExplicitTemplateArgs()) {
14922       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14923       TemplateArgs = &TemplateArgsBuffer;
14924     }
14925 
14926     DeclRefExpr *DRE =
14927         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14928                          ULE->getQualifierLoc(), Found.getDecl(),
14929                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14930     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14931     return DRE;
14932   }
14933 
14934   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14935     // FIXME: avoid copy.
14936     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14937     if (MemExpr->hasExplicitTemplateArgs()) {
14938       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14939       TemplateArgs = &TemplateArgsBuffer;
14940     }
14941 
14942     Expr *Base;
14943 
14944     // If we're filling in a static method where we used to have an
14945     // implicit member access, rewrite to a simple decl ref.
14946     if (MemExpr->isImplicitAccess()) {
14947       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14948         DeclRefExpr *DRE = BuildDeclRefExpr(
14949             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14950             MemExpr->getQualifierLoc(), Found.getDecl(),
14951             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14952         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14953         return DRE;
14954       } else {
14955         SourceLocation Loc = MemExpr->getMemberLoc();
14956         if (MemExpr->getQualifier())
14957           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14958         Base =
14959             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14960       }
14961     } else
14962       Base = MemExpr->getBase();
14963 
14964     ExprValueKind valueKind;
14965     QualType type;
14966     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14967       valueKind = VK_LValue;
14968       type = Fn->getType();
14969     } else {
14970       valueKind = VK_RValue;
14971       type = Context.BoundMemberTy;
14972     }
14973 
14974     return BuildMemberExpr(
14975         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14976         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14977         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14978         type, valueKind, OK_Ordinary, TemplateArgs);
14979   }
14980 
14981   llvm_unreachable("Invalid reference to overloaded function");
14982 }
14983 
14984 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14985                                                 DeclAccessPair Found,
14986                                                 FunctionDecl *Fn) {
14987   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14988 }
14989