xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaOverload.cpp (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
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_OCL_Scalar_Widening,
141     ICR_Complex_Real_Conversion,
142     ICR_Conversion,
143     ICR_Conversion,
144     ICR_Writeback_Conversion,
145     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
146                      // it was omitted by the patch that added
147                      // ICK_Zero_Event_Conversion
148     ICR_C_Conversion,
149     ICR_C_Conversion_Extension
150   };
151   return Rank[(int)Kind];
152 }
153 
154 /// GetImplicitConversionName - Return the name of this kind of
155 /// implicit conversion.
156 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
157   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158     "No conversion",
159     "Lvalue-to-rvalue",
160     "Array-to-pointer",
161     "Function-to-pointer",
162     "Function pointer conversion",
163     "Qualification",
164     "Integral promotion",
165     "Floating point promotion",
166     "Complex promotion",
167     "Integral conversion",
168     "Floating conversion",
169     "Complex conversion",
170     "Floating-integral conversion",
171     "Pointer conversion",
172     "Pointer-to-member conversion",
173     "Boolean conversion",
174     "Compatible-types conversion",
175     "Derived-to-base conversion",
176     "Vector conversion",
177     "Vector splat",
178     "Complex-real conversion",
179     "Block Pointer conversion",
180     "Transparent Union Conversion",
181     "Writeback conversion",
182     "OpenCL Zero Event Conversion",
183     "C specific type conversion",
184     "Incompatible pointer conversion"
185   };
186   return Name[Kind];
187 }
188 
189 /// StandardConversionSequence - Set the standard conversion
190 /// sequence to the identity conversion.
191 void StandardConversionSequence::setAsIdentityConversion() {
192   First = ICK_Identity;
193   Second = ICK_Identity;
194   Third = ICK_Identity;
195   DeprecatedStringLiteralToCharPtr = false;
196   QualificationIncludesObjCLifetime = false;
197   ReferenceBinding = false;
198   DirectBinding = false;
199   IsLvalueReference = true;
200   BindsToFunctionLvalue = false;
201   BindsToRvalue = false;
202   BindsImplicitObjectArgumentWithoutRefQualifier = false;
203   ObjCLifetimeConversionBinding = false;
204   CopyConstructor = nullptr;
205 }
206 
207 /// getRank - Retrieve the rank of this standard conversion sequence
208 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
209 /// implicit conversions.
210 ImplicitConversionRank StandardConversionSequence::getRank() const {
211   ImplicitConversionRank Rank = ICR_Exact_Match;
212   if  (GetConversionRank(First) > Rank)
213     Rank = GetConversionRank(First);
214   if  (GetConversionRank(Second) > Rank)
215     Rank = GetConversionRank(Second);
216   if  (GetConversionRank(Third) > Rank)
217     Rank = GetConversionRank(Third);
218   return Rank;
219 }
220 
221 /// isPointerConversionToBool - Determines whether this conversion is
222 /// a conversion of a pointer or pointer-to-member to bool. This is
223 /// used as part of the ranking of standard conversion sequences
224 /// (C++ 13.3.3.2p4).
225 bool StandardConversionSequence::isPointerConversionToBool() const {
226   // Note that FromType has not necessarily been transformed by the
227   // array-to-pointer or function-to-pointer implicit conversions, so
228   // check for their presence as well as checking whether FromType is
229   // a pointer.
230   if (getToType(1)->isBooleanType() &&
231       (getFromType()->isPointerType() ||
232        getFromType()->isMemberPointerType() ||
233        getFromType()->isObjCObjectPointerType() ||
234        getFromType()->isBlockPointerType() ||
235        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
236     return true;
237 
238   return false;
239 }
240 
241 /// isPointerConversionToVoidPointer - Determines whether this
242 /// conversion is a conversion of a pointer to a void pointer. This is
243 /// used as part of the ranking of standard conversion sequences (C++
244 /// 13.3.3.2p4).
245 bool
246 StandardConversionSequence::
247 isPointerConversionToVoidPointer(ASTContext& Context) const {
248   QualType FromType = getFromType();
249   QualType ToType = getToType(1);
250 
251   // Note that FromType has not necessarily been transformed by the
252   // array-to-pointer implicit conversion, so check for its presence
253   // and redo the conversion to get a pointer.
254   if (First == ICK_Array_To_Pointer)
255     FromType = Context.getArrayDecayedType(FromType);
256 
257   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
258     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
259       return ToPtrType->getPointeeType()->isVoidType();
260 
261   return false;
262 }
263 
264 /// Skip any implicit casts which could be either part of a narrowing conversion
265 /// or after one in an implicit conversion.
266 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
267                                              const Expr *Converted) {
268   // We can have cleanups wrapping the converted expression; these need to be
269   // preserved so that destructors run if necessary.
270   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
271     Expr *Inner =
272         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
273     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
274                                     EWC->getObjects());
275   }
276 
277   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
278     switch (ICE->getCastKind()) {
279     case CK_NoOp:
280     case CK_IntegralCast:
281     case CK_IntegralToBoolean:
282     case CK_IntegralToFloating:
283     case CK_BooleanToSignedIntegral:
284     case CK_FloatingToIntegral:
285     case CK_FloatingToBoolean:
286     case CK_FloatingCast:
287       Converted = ICE->getSubExpr();
288       continue;
289 
290     default:
291       return Converted;
292     }
293   }
294 
295   return Converted;
296 }
297 
298 /// Check if this standard conversion sequence represents a narrowing
299 /// conversion, according to C++11 [dcl.init.list]p7.
300 ///
301 /// \param Ctx  The AST context.
302 /// \param Converted  The result of applying this standard conversion sequence.
303 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
304 ///        value of the expression prior to the narrowing conversion.
305 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
306 ///        type of the expression prior to the narrowing conversion.
307 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
308 ///        from floating point types to integral types should be ignored.
309 NarrowingKind StandardConversionSequence::getNarrowingKind(
310     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
311     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
312   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
313 
314   // C++11 [dcl.init.list]p7:
315   //   A narrowing conversion is an implicit conversion ...
316   QualType FromType = getToType(0);
317   QualType ToType = getToType(1);
318 
319   // A conversion to an enumeration type is narrowing if the conversion to
320   // the underlying type is narrowing. This only arises for expressions of
321   // the form 'Enum{init}'.
322   if (auto *ET = ToType->getAs<EnumType>())
323     ToType = ET->getDecl()->getIntegerType();
324 
325   switch (Second) {
326   // 'bool' is an integral type; dispatch to the right place to handle it.
327   case ICK_Boolean_Conversion:
328     if (FromType->isRealFloatingType())
329       goto FloatingIntegralConversion;
330     if (FromType->isIntegralOrUnscopedEnumerationType())
331       goto IntegralConversion;
332     // -- from a pointer type or pointer-to-member type to bool, or
333     return NK_Type_Narrowing;
334 
335   // -- from a floating-point type to an integer type, or
336   //
337   // -- from an integer type or unscoped enumeration type to a floating-point
338   //    type, except where the source is a constant expression and the actual
339   //    value after conversion will fit into the target type and will produce
340   //    the original value when converted back to the original type, or
341   case ICK_Floating_Integral:
342   FloatingIntegralConversion:
343     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
344       return NK_Type_Narrowing;
345     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
346                ToType->isRealFloatingType()) {
347       if (IgnoreFloatToIntegralConversion)
348         return NK_Not_Narrowing;
349       llvm::APSInt IntConstantValue;
350       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
351       assert(Initializer && "Unknown conversion expression");
352 
353       // If it's value-dependent, we can't tell whether it's narrowing.
354       if (Initializer->isValueDependent())
355         return NK_Dependent_Narrowing;
356 
357       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
358         // Convert the integer to the floating type.
359         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
360         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
361                                 llvm::APFloat::rmNearestTiesToEven);
362         // And back.
363         llvm::APSInt ConvertedValue = IntConstantValue;
364         bool ignored;
365         Result.convertToInteger(ConvertedValue,
366                                 llvm::APFloat::rmTowardZero, &ignored);
367         // If the resulting value is different, this was a narrowing conversion.
368         if (IntConstantValue != ConvertedValue) {
369           ConstantValue = APValue(IntConstantValue);
370           ConstantType = Initializer->getType();
371           return NK_Constant_Narrowing;
372         }
373       } else {
374         // Variables are always narrowings.
375         return NK_Variable_Narrowing;
376       }
377     }
378     return NK_Not_Narrowing;
379 
380   // -- from long double to double or float, or from double to float, except
381   //    where the source is a constant expression and the actual value after
382   //    conversion is within the range of values that can be represented (even
383   //    if it cannot be represented exactly), or
384   case ICK_Floating_Conversion:
385     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
386         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
387       // FromType is larger than ToType.
388       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
389 
390       // If it's value-dependent, we can't tell whether it's narrowing.
391       if (Initializer->isValueDependent())
392         return NK_Dependent_Narrowing;
393 
394       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
395         // Constant!
396         assert(ConstantValue.isFloat());
397         llvm::APFloat FloatVal = ConstantValue.getFloat();
398         // Convert the source value into the target type.
399         bool ignored;
400         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
401           Ctx.getFloatTypeSemantics(ToType),
402           llvm::APFloat::rmNearestTiesToEven, &ignored);
403         // If there was no overflow, the source value is within the range of
404         // values that can be represented.
405         if (ConvertStatus & llvm::APFloat::opOverflow) {
406           ConstantType = Initializer->getType();
407           return NK_Constant_Narrowing;
408         }
409       } else {
410         return NK_Variable_Narrowing;
411       }
412     }
413     return NK_Not_Narrowing;
414 
415   // -- from an integer type or unscoped enumeration type to an integer type
416   //    that cannot represent all the values of the original type, except where
417   //    the source is a constant expression and the actual value after
418   //    conversion will fit into the target type and will produce the original
419   //    value when converted back to the original type.
420   case ICK_Integral_Conversion:
421   IntegralConversion: {
422     assert(FromType->isIntegralOrUnscopedEnumerationType());
423     assert(ToType->isIntegralOrUnscopedEnumerationType());
424     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
425     const unsigned FromWidth = Ctx.getIntWidth(FromType);
426     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
427     const unsigned ToWidth = Ctx.getIntWidth(ToType);
428 
429     if (FromWidth > ToWidth ||
430         (FromWidth == ToWidth && FromSigned != ToSigned) ||
431         (FromSigned && !ToSigned)) {
432       // Not all values of FromType can be represented in ToType.
433       llvm::APSInt InitializerValue;
434       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 
436       // If it's value-dependent, we can't tell whether it's narrowing.
437       if (Initializer->isValueDependent())
438         return NK_Dependent_Narrowing;
439 
440       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
441         // Such conversions on variables are always narrowing.
442         return NK_Variable_Narrowing;
443       }
444       bool Narrowing = false;
445       if (FromWidth < ToWidth) {
446         // Negative -> unsigned is narrowing. Otherwise, more bits is never
447         // narrowing.
448         if (InitializerValue.isSigned() && InitializerValue.isNegative())
449           Narrowing = true;
450       } else {
451         // Add a bit to the InitializerValue so we don't have to worry about
452         // signed vs. unsigned comparisons.
453         InitializerValue = InitializerValue.extend(
454           InitializerValue.getBitWidth() + 1);
455         // Convert the initializer to and from the target width and signed-ness.
456         llvm::APSInt ConvertedValue = InitializerValue;
457         ConvertedValue = ConvertedValue.trunc(ToWidth);
458         ConvertedValue.setIsSigned(ToSigned);
459         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
460         ConvertedValue.setIsSigned(InitializerValue.isSigned());
461         // If the result is different, this was a narrowing conversion.
462         if (ConvertedValue != InitializerValue)
463           Narrowing = true;
464       }
465       if (Narrowing) {
466         ConstantType = Initializer->getType();
467         ConstantValue = APValue(InitializerValue);
468         return NK_Constant_Narrowing;
469       }
470     }
471     return NK_Not_Narrowing;
472   }
473 
474   default:
475     // Other kinds of conversions are not narrowings.
476     return NK_Not_Narrowing;
477   }
478 }
479 
480 /// dump - Print this standard conversion sequence to standard
481 /// error. Useful for debugging overloading issues.
482 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
483   raw_ostream &OS = llvm::errs();
484   bool PrintedSomething = false;
485   if (First != ICK_Identity) {
486     OS << GetImplicitConversionName(First);
487     PrintedSomething = true;
488   }
489 
490   if (Second != ICK_Identity) {
491     if (PrintedSomething) {
492       OS << " -> ";
493     }
494     OS << GetImplicitConversionName(Second);
495 
496     if (CopyConstructor) {
497       OS << " (by copy constructor)";
498     } else if (DirectBinding) {
499       OS << " (direct reference binding)";
500     } else if (ReferenceBinding) {
501       OS << " (reference binding)";
502     }
503     PrintedSomething = true;
504   }
505 
506   if (Third != ICK_Identity) {
507     if (PrintedSomething) {
508       OS << " -> ";
509     }
510     OS << GetImplicitConversionName(Third);
511     PrintedSomething = true;
512   }
513 
514   if (!PrintedSomething) {
515     OS << "No conversions required";
516   }
517 }
518 
519 /// dump - Print this user-defined conversion sequence to standard
520 /// error. Useful for debugging overloading issues.
521 void UserDefinedConversionSequence::dump() const {
522   raw_ostream &OS = llvm::errs();
523   if (Before.First || Before.Second || Before.Third) {
524     Before.dump();
525     OS << " -> ";
526   }
527   if (ConversionFunction)
528     OS << '\'' << *ConversionFunction << '\'';
529   else
530     OS << "aggregate initialization";
531   if (After.First || After.Second || After.Third) {
532     OS << " -> ";
533     After.dump();
534   }
535 }
536 
537 /// dump - Print this implicit conversion sequence to standard
538 /// error. Useful for debugging overloading issues.
539 void ImplicitConversionSequence::dump() const {
540   raw_ostream &OS = llvm::errs();
541   if (isStdInitializerListElement())
542     OS << "Worst std::initializer_list element conversion: ";
543   switch (ConversionKind) {
544   case StandardConversion:
545     OS << "Standard conversion: ";
546     Standard.dump();
547     break;
548   case UserDefinedConversion:
549     OS << "User-defined conversion: ";
550     UserDefined.dump();
551     break;
552   case EllipsisConversion:
553     OS << "Ellipsis conversion";
554     break;
555   case AmbiguousConversion:
556     OS << "Ambiguous conversion";
557     break;
558   case BadConversion:
559     OS << "Bad conversion";
560     break;
561   }
562 
563   OS << "\n";
564 }
565 
566 void AmbiguousConversionSequence::construct() {
567   new (&conversions()) ConversionSet();
568 }
569 
570 void AmbiguousConversionSequence::destruct() {
571   conversions().~ConversionSet();
572 }
573 
574 void
575 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
576   FromTypePtr = O.FromTypePtr;
577   ToTypePtr = O.ToTypePtr;
578   new (&conversions()) ConversionSet(O.conversions());
579 }
580 
581 namespace {
582   // Structure used by DeductionFailureInfo to store
583   // template argument information.
584   struct DFIArguments {
585     TemplateArgument FirstArg;
586     TemplateArgument SecondArg;
587   };
588   // Structure used by DeductionFailureInfo to store
589   // template parameter and template argument information.
590   struct DFIParamWithArguments : DFIArguments {
591     TemplateParameter Param;
592   };
593   // Structure used by DeductionFailureInfo to store template argument
594   // information and the index of the problematic call argument.
595   struct DFIDeducedMismatchArgs : DFIArguments {
596     TemplateArgumentList *TemplateArgs;
597     unsigned CallArgIndex;
598   };
599   // Structure used by DeductionFailureInfo to store information about
600   // unsatisfied constraints.
601   struct CNSInfo {
602     TemplateArgumentList *TemplateArgs;
603     ConstraintSatisfaction Satisfaction;
604   };
605 }
606 
607 /// Convert from Sema's representation of template deduction information
608 /// to the form used in overload-candidate information.
609 DeductionFailureInfo
610 clang::MakeDeductionFailureInfo(ASTContext &Context,
611                                 Sema::TemplateDeductionResult TDK,
612                                 TemplateDeductionInfo &Info) {
613   DeductionFailureInfo Result;
614   Result.Result = static_cast<unsigned>(TDK);
615   Result.HasDiagnostic = false;
616   switch (TDK) {
617   case Sema::TDK_Invalid:
618   case Sema::TDK_InstantiationDepth:
619   case Sema::TDK_TooManyArguments:
620   case Sema::TDK_TooFewArguments:
621   case Sema::TDK_MiscellaneousDeductionFailure:
622   case Sema::TDK_CUDATargetMismatch:
623     Result.Data = nullptr;
624     break;
625 
626   case Sema::TDK_Incomplete:
627   case Sema::TDK_InvalidExplicitArguments:
628     Result.Data = Info.Param.getOpaqueValue();
629     break;
630 
631   case Sema::TDK_DeducedMismatch:
632   case Sema::TDK_DeducedMismatchNested: {
633     // FIXME: Should allocate from normal heap so that we can free this later.
634     auto *Saved = new (Context) DFIDeducedMismatchArgs;
635     Saved->FirstArg = Info.FirstArg;
636     Saved->SecondArg = Info.SecondArg;
637     Saved->TemplateArgs = Info.take();
638     Saved->CallArgIndex = Info.CallArgIndex;
639     Result.Data = Saved;
640     break;
641   }
642 
643   case Sema::TDK_NonDeducedMismatch: {
644     // FIXME: Should allocate from normal heap so that we can free this later.
645     DFIArguments *Saved = new (Context) DFIArguments;
646     Saved->FirstArg = Info.FirstArg;
647     Saved->SecondArg = Info.SecondArg;
648     Result.Data = Saved;
649     break;
650   }
651 
652   case Sema::TDK_IncompletePack:
653     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
654   case Sema::TDK_Inconsistent:
655   case Sema::TDK_Underqualified: {
656     // FIXME: Should allocate from normal heap so that we can free this later.
657     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
658     Saved->Param = Info.Param;
659     Saved->FirstArg = Info.FirstArg;
660     Saved->SecondArg = Info.SecondArg;
661     Result.Data = Saved;
662     break;
663   }
664 
665   case Sema::TDK_SubstitutionFailure:
666     Result.Data = Info.take();
667     if (Info.hasSFINAEDiagnostic()) {
668       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
669           SourceLocation(), PartialDiagnostic::NullDiagnostic());
670       Info.takeSFINAEDiagnostic(*Diag);
671       Result.HasDiagnostic = true;
672     }
673     break;
674 
675   case Sema::TDK_ConstraintsNotSatisfied: {
676     CNSInfo *Saved = new (Context) CNSInfo;
677     Saved->TemplateArgs = Info.take();
678     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
679     Result.Data = Saved;
680     break;
681   }
682 
683   case Sema::TDK_Success:
684   case Sema::TDK_NonDependentConversionFailure:
685     llvm_unreachable("not a deduction failure");
686   }
687 
688   return Result;
689 }
690 
691 void DeductionFailureInfo::Destroy() {
692   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
693   case Sema::TDK_Success:
694   case Sema::TDK_Invalid:
695   case Sema::TDK_InstantiationDepth:
696   case Sema::TDK_Incomplete:
697   case Sema::TDK_TooManyArguments:
698   case Sema::TDK_TooFewArguments:
699   case Sema::TDK_InvalidExplicitArguments:
700   case Sema::TDK_CUDATargetMismatch:
701   case Sema::TDK_NonDependentConversionFailure:
702     break;
703 
704   case Sema::TDK_IncompletePack:
705   case Sema::TDK_Inconsistent:
706   case Sema::TDK_Underqualified:
707   case Sema::TDK_DeducedMismatch:
708   case Sema::TDK_DeducedMismatchNested:
709   case Sema::TDK_NonDeducedMismatch:
710     // FIXME: Destroy the data?
711     Data = nullptr;
712     break;
713 
714   case Sema::TDK_SubstitutionFailure:
715     // FIXME: Destroy the template argument list?
716     Data = nullptr;
717     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
718       Diag->~PartialDiagnosticAt();
719       HasDiagnostic = false;
720     }
721     break;
722 
723   case Sema::TDK_ConstraintsNotSatisfied:
724     // FIXME: Destroy the template argument list?
725     Data = nullptr;
726     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
727       Diag->~PartialDiagnosticAt();
728       HasDiagnostic = false;
729     }
730     break;
731 
732   // Unhandled
733   case Sema::TDK_MiscellaneousDeductionFailure:
734     break;
735   }
736 }
737 
738 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
739   if (HasDiagnostic)
740     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
741   return nullptr;
742 }
743 
744 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
745   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
746   case Sema::TDK_Success:
747   case Sema::TDK_Invalid:
748   case Sema::TDK_InstantiationDepth:
749   case Sema::TDK_TooManyArguments:
750   case Sema::TDK_TooFewArguments:
751   case Sema::TDK_SubstitutionFailure:
752   case Sema::TDK_DeducedMismatch:
753   case Sema::TDK_DeducedMismatchNested:
754   case Sema::TDK_NonDeducedMismatch:
755   case Sema::TDK_CUDATargetMismatch:
756   case Sema::TDK_NonDependentConversionFailure:
757   case Sema::TDK_ConstraintsNotSatisfied:
758     return TemplateParameter();
759 
760   case Sema::TDK_Incomplete:
761   case Sema::TDK_InvalidExplicitArguments:
762     return TemplateParameter::getFromOpaqueValue(Data);
763 
764   case Sema::TDK_IncompletePack:
765   case Sema::TDK_Inconsistent:
766   case Sema::TDK_Underqualified:
767     return static_cast<DFIParamWithArguments*>(Data)->Param;
768 
769   // Unhandled
770   case Sema::TDK_MiscellaneousDeductionFailure:
771     break;
772   }
773 
774   return TemplateParameter();
775 }
776 
777 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
778   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
779   case Sema::TDK_Success:
780   case Sema::TDK_Invalid:
781   case Sema::TDK_InstantiationDepth:
782   case Sema::TDK_TooManyArguments:
783   case Sema::TDK_TooFewArguments:
784   case Sema::TDK_Incomplete:
785   case Sema::TDK_IncompletePack:
786   case Sema::TDK_InvalidExplicitArguments:
787   case Sema::TDK_Inconsistent:
788   case Sema::TDK_Underqualified:
789   case Sema::TDK_NonDeducedMismatch:
790   case Sema::TDK_CUDATargetMismatch:
791   case Sema::TDK_NonDependentConversionFailure:
792     return nullptr;
793 
794   case Sema::TDK_DeducedMismatch:
795   case Sema::TDK_DeducedMismatchNested:
796     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
797 
798   case Sema::TDK_SubstitutionFailure:
799     return static_cast<TemplateArgumentList*>(Data);
800 
801   case Sema::TDK_ConstraintsNotSatisfied:
802     return static_cast<CNSInfo*>(Data)->TemplateArgs;
803 
804   // Unhandled
805   case Sema::TDK_MiscellaneousDeductionFailure:
806     break;
807   }
808 
809   return nullptr;
810 }
811 
812 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
813   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
814   case Sema::TDK_Success:
815   case Sema::TDK_Invalid:
816   case Sema::TDK_InstantiationDepth:
817   case Sema::TDK_Incomplete:
818   case Sema::TDK_TooManyArguments:
819   case Sema::TDK_TooFewArguments:
820   case Sema::TDK_InvalidExplicitArguments:
821   case Sema::TDK_SubstitutionFailure:
822   case Sema::TDK_CUDATargetMismatch:
823   case Sema::TDK_NonDependentConversionFailure:
824   case Sema::TDK_ConstraintsNotSatisfied:
825     return nullptr;
826 
827   case Sema::TDK_IncompletePack:
828   case Sema::TDK_Inconsistent:
829   case Sema::TDK_Underqualified:
830   case Sema::TDK_DeducedMismatch:
831   case Sema::TDK_DeducedMismatchNested:
832   case Sema::TDK_NonDeducedMismatch:
833     return &static_cast<DFIArguments*>(Data)->FirstArg;
834 
835   // Unhandled
836   case Sema::TDK_MiscellaneousDeductionFailure:
837     break;
838   }
839 
840   return nullptr;
841 }
842 
843 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
844   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
845   case Sema::TDK_Success:
846   case Sema::TDK_Invalid:
847   case Sema::TDK_InstantiationDepth:
848   case Sema::TDK_Incomplete:
849   case Sema::TDK_IncompletePack:
850   case Sema::TDK_TooManyArguments:
851   case Sema::TDK_TooFewArguments:
852   case Sema::TDK_InvalidExplicitArguments:
853   case Sema::TDK_SubstitutionFailure:
854   case Sema::TDK_CUDATargetMismatch:
855   case Sema::TDK_NonDependentConversionFailure:
856   case Sema::TDK_ConstraintsNotSatisfied:
857     return nullptr;
858 
859   case Sema::TDK_Inconsistent:
860   case Sema::TDK_Underqualified:
861   case Sema::TDK_DeducedMismatch:
862   case Sema::TDK_DeducedMismatchNested:
863   case Sema::TDK_NonDeducedMismatch:
864     return &static_cast<DFIArguments*>(Data)->SecondArg;
865 
866   // Unhandled
867   case Sema::TDK_MiscellaneousDeductionFailure:
868     break;
869   }
870 
871   return nullptr;
872 }
873 
874 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
875   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
876   case Sema::TDK_DeducedMismatch:
877   case Sema::TDK_DeducedMismatchNested:
878     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
879 
880   default:
881     return llvm::None;
882   }
883 }
884 
885 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
886     OverloadedOperatorKind Op) {
887   if (!AllowRewrittenCandidates)
888     return false;
889   return Op == OO_EqualEqual || Op == OO_Spaceship;
890 }
891 
892 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
893     ASTContext &Ctx, const FunctionDecl *FD) {
894   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
895     return false;
896   // Don't bother adding a reversed candidate that can never be a better
897   // match than the non-reversed version.
898   return FD->getNumParams() != 2 ||
899          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
900                                      FD->getParamDecl(1)->getType()) ||
901          FD->hasAttr<EnableIfAttr>();
902 }
903 
904 void OverloadCandidateSet::destroyCandidates() {
905   for (iterator i = begin(), e = end(); i != e; ++i) {
906     for (auto &C : i->Conversions)
907       C.~ImplicitConversionSequence();
908     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
909       i->DeductionFailure.Destroy();
910   }
911 }
912 
913 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
914   destroyCandidates();
915   SlabAllocator.Reset();
916   NumInlineBytesUsed = 0;
917   Candidates.clear();
918   Functions.clear();
919   Kind = CSK;
920 }
921 
922 namespace {
923   class UnbridgedCastsSet {
924     struct Entry {
925       Expr **Addr;
926       Expr *Saved;
927     };
928     SmallVector<Entry, 2> Entries;
929 
930   public:
931     void save(Sema &S, Expr *&E) {
932       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
933       Entry entry = { &E, E };
934       Entries.push_back(entry);
935       E = S.stripARCUnbridgedCast(E);
936     }
937 
938     void restore() {
939       for (SmallVectorImpl<Entry>::iterator
940              i = Entries.begin(), e = Entries.end(); i != e; ++i)
941         *i->Addr = i->Saved;
942     }
943   };
944 }
945 
946 /// checkPlaceholderForOverload - Do any interesting placeholder-like
947 /// preprocessing on the given expression.
948 ///
949 /// \param unbridgedCasts a collection to which to add unbridged casts;
950 ///   without this, they will be immediately diagnosed as errors
951 ///
952 /// Return true on unrecoverable error.
953 static bool
954 checkPlaceholderForOverload(Sema &S, Expr *&E,
955                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
956   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
957     // We can't handle overloaded expressions here because overload
958     // resolution might reasonably tweak them.
959     if (placeholder->getKind() == BuiltinType::Overload) return false;
960 
961     // If the context potentially accepts unbridged ARC casts, strip
962     // the unbridged cast and add it to the collection for later restoration.
963     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
964         unbridgedCasts) {
965       unbridgedCasts->save(S, E);
966       return false;
967     }
968 
969     // Go ahead and check everything else.
970     ExprResult result = S.CheckPlaceholderExpr(E);
971     if (result.isInvalid())
972       return true;
973 
974     E = result.get();
975     return false;
976   }
977 
978   // Nothing to do.
979   return false;
980 }
981 
982 /// checkArgPlaceholdersForOverload - Check a set of call operands for
983 /// placeholders.
984 static bool checkArgPlaceholdersForOverload(Sema &S,
985                                             MultiExprArg Args,
986                                             UnbridgedCastsSet &unbridged) {
987   for (unsigned i = 0, e = Args.size(); i != e; ++i)
988     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
989       return true;
990 
991   return false;
992 }
993 
994 /// Determine whether the given New declaration is an overload of the
995 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
996 /// New and Old cannot be overloaded, e.g., if New has the same signature as
997 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
998 /// functions (or function templates) at all. When it does return Ovl_Match or
999 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1000 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1001 /// declaration.
1002 ///
1003 /// Example: Given the following input:
1004 ///
1005 ///   void f(int, float); // #1
1006 ///   void f(int, int); // #2
1007 ///   int f(int, int); // #3
1008 ///
1009 /// When we process #1, there is no previous declaration of "f", so IsOverload
1010 /// will not be used.
1011 ///
1012 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1013 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1014 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1015 /// unchanged.
1016 ///
1017 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1018 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1019 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1020 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1021 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1022 ///
1023 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1024 /// by a using declaration. The rules for whether to hide shadow declarations
1025 /// ignore some properties which otherwise figure into a function template's
1026 /// signature.
1027 Sema::OverloadKind
1028 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1029                     NamedDecl *&Match, bool NewIsUsingDecl) {
1030   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1031          I != E; ++I) {
1032     NamedDecl *OldD = *I;
1033 
1034     bool OldIsUsingDecl = false;
1035     if (isa<UsingShadowDecl>(OldD)) {
1036       OldIsUsingDecl = true;
1037 
1038       // We can always introduce two using declarations into the same
1039       // context, even if they have identical signatures.
1040       if (NewIsUsingDecl) continue;
1041 
1042       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1043     }
1044 
1045     // A using-declaration does not conflict with another declaration
1046     // if one of them is hidden.
1047     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1048       continue;
1049 
1050     // If either declaration was introduced by a using declaration,
1051     // we'll need to use slightly different rules for matching.
1052     // Essentially, these rules are the normal rules, except that
1053     // function templates hide function templates with different
1054     // return types or template parameter lists.
1055     bool UseMemberUsingDeclRules =
1056       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1057       !New->getFriendObjectKind();
1058 
1059     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1060       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1061         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1062           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1063           continue;
1064         }
1065 
1066         if (!isa<FunctionTemplateDecl>(OldD) &&
1067             !shouldLinkPossiblyHiddenDecl(*I, New))
1068           continue;
1069 
1070         Match = *I;
1071         return Ovl_Match;
1072       }
1073 
1074       // Builtins that have custom typechecking or have a reference should
1075       // not be overloadable or redeclarable.
1076       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1077         Match = *I;
1078         return Ovl_NonFunction;
1079       }
1080     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1081       // We can overload with these, which can show up when doing
1082       // redeclaration checks for UsingDecls.
1083       assert(Old.getLookupKind() == LookupUsingDeclName);
1084     } else if (isa<TagDecl>(OldD)) {
1085       // We can always overload with tags by hiding them.
1086     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1087       // Optimistically assume that an unresolved using decl will
1088       // overload; if it doesn't, we'll have to diagnose during
1089       // template instantiation.
1090       //
1091       // Exception: if the scope is dependent and this is not a class
1092       // member, the using declaration can only introduce an enumerator.
1093       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1094         Match = *I;
1095         return Ovl_NonFunction;
1096       }
1097     } else {
1098       // (C++ 13p1):
1099       //   Only function declarations can be overloaded; object and type
1100       //   declarations cannot be overloaded.
1101       Match = *I;
1102       return Ovl_NonFunction;
1103     }
1104   }
1105 
1106   // C++ [temp.friend]p1:
1107   //   For a friend function declaration that is not a template declaration:
1108   //    -- if the name of the friend is a qualified or unqualified template-id,
1109   //       [...], otherwise
1110   //    -- if the name of the friend is a qualified-id and a matching
1111   //       non-template function is found in the specified class or namespace,
1112   //       the friend declaration refers to that function, otherwise,
1113   //    -- if the name of the friend is a qualified-id and a matching function
1114   //       template is found in the specified class or namespace, the friend
1115   //       declaration refers to the deduced specialization of that function
1116   //       template, otherwise
1117   //    -- the name shall be an unqualified-id [...]
1118   // If we get here for a qualified friend declaration, we've just reached the
1119   // third bullet. If the type of the friend is dependent, skip this lookup
1120   // until instantiation.
1121   if (New->getFriendObjectKind() && New->getQualifier() &&
1122       !New->getDescribedFunctionTemplate() &&
1123       !New->getDependentSpecializationInfo() &&
1124       !New->getType()->isDependentType()) {
1125     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1126     TemplateSpecResult.addAllDecls(Old);
1127     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1128                                             /*QualifiedFriend*/true)) {
1129       New->setInvalidDecl();
1130       return Ovl_Overload;
1131     }
1132 
1133     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1134     return Ovl_Match;
1135   }
1136 
1137   return Ovl_Overload;
1138 }
1139 
1140 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1141                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1142                       bool ConsiderRequiresClauses) {
1143   // C++ [basic.start.main]p2: This function shall not be overloaded.
1144   if (New->isMain())
1145     return false;
1146 
1147   // MSVCRT user defined entry points cannot be overloaded.
1148   if (New->isMSVCRTEntryPoint())
1149     return false;
1150 
1151   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1152   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1153 
1154   // C++ [temp.fct]p2:
1155   //   A function template can be overloaded with other function templates
1156   //   and with normal (non-template) functions.
1157   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1158     return true;
1159 
1160   // Is the function New an overload of the function Old?
1161   QualType OldQType = Context.getCanonicalType(Old->getType());
1162   QualType NewQType = Context.getCanonicalType(New->getType());
1163 
1164   // Compare the signatures (C++ 1.3.10) of the two functions to
1165   // determine whether they are overloads. If we find any mismatch
1166   // in the signature, they are overloads.
1167 
1168   // If either of these functions is a K&R-style function (no
1169   // prototype), then we consider them to have matching signatures.
1170   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1171       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1172     return false;
1173 
1174   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1175   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1176 
1177   // The signature of a function includes the types of its
1178   // parameters (C++ 1.3.10), which includes the presence or absence
1179   // of the ellipsis; see C++ DR 357).
1180   if (OldQType != NewQType &&
1181       (OldType->getNumParams() != NewType->getNumParams() ||
1182        OldType->isVariadic() != NewType->isVariadic() ||
1183        !FunctionParamTypesAreEqual(OldType, NewType)))
1184     return true;
1185 
1186   // C++ [temp.over.link]p4:
1187   //   The signature of a function template consists of its function
1188   //   signature, its return type and its template parameter list. The names
1189   //   of the template parameters are significant only for establishing the
1190   //   relationship between the template parameters and the rest of the
1191   //   signature.
1192   //
1193   // We check the return type and template parameter lists for function
1194   // templates first; the remaining checks follow.
1195   //
1196   // However, we don't consider either of these when deciding whether
1197   // a member introduced by a shadow declaration is hidden.
1198   if (!UseMemberUsingDeclRules && NewTemplate &&
1199       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1200                                        OldTemplate->getTemplateParameters(),
1201                                        false, TPL_TemplateMatch) ||
1202        !Context.hasSameType(Old->getDeclaredReturnType(),
1203                             New->getDeclaredReturnType())))
1204     return true;
1205 
1206   // If the function is a class member, its signature includes the
1207   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1208   //
1209   // As part of this, also check whether one of the member functions
1210   // is static, in which case they are not overloads (C++
1211   // 13.1p2). While not part of the definition of the signature,
1212   // this check is important to determine whether these functions
1213   // can be overloaded.
1214   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1215   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1216   if (OldMethod && NewMethod &&
1217       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1218     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1219       if (!UseMemberUsingDeclRules &&
1220           (OldMethod->getRefQualifier() == RQ_None ||
1221            NewMethod->getRefQualifier() == RQ_None)) {
1222         // C++0x [over.load]p2:
1223         //   - Member function declarations with the same name and the same
1224         //     parameter-type-list as well as member function template
1225         //     declarations with the same name, the same parameter-type-list, and
1226         //     the same template parameter lists cannot be overloaded if any of
1227         //     them, but not all, have a ref-qualifier (8.3.5).
1228         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1229           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1230         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1231       }
1232       return true;
1233     }
1234 
1235     // We may not have applied the implicit const for a constexpr member
1236     // function yet (because we haven't yet resolved whether this is a static
1237     // or non-static member function). Add it now, on the assumption that this
1238     // is a redeclaration of OldMethod.
1239     auto OldQuals = OldMethod->getMethodQualifiers();
1240     auto NewQuals = NewMethod->getMethodQualifiers();
1241     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1242         !isa<CXXConstructorDecl>(NewMethod))
1243       NewQuals.addConst();
1244     // We do not allow overloading based off of '__restrict'.
1245     OldQuals.removeRestrict();
1246     NewQuals.removeRestrict();
1247     if (OldQuals != NewQuals)
1248       return true;
1249   }
1250 
1251   // Though pass_object_size is placed on parameters and takes an argument, we
1252   // consider it to be a function-level modifier for the sake of function
1253   // identity. Either the function has one or more parameters with
1254   // pass_object_size or it doesn't.
1255   if (functionHasPassObjectSizeParams(New) !=
1256       functionHasPassObjectSizeParams(Old))
1257     return true;
1258 
1259   // enable_if attributes are an order-sensitive part of the signature.
1260   for (specific_attr_iterator<EnableIfAttr>
1261          NewI = New->specific_attr_begin<EnableIfAttr>(),
1262          NewE = New->specific_attr_end<EnableIfAttr>(),
1263          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1264          OldE = Old->specific_attr_end<EnableIfAttr>();
1265        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1266     if (NewI == NewE || OldI == OldE)
1267       return true;
1268     llvm::FoldingSetNodeID NewID, OldID;
1269     NewI->getCond()->Profile(NewID, Context, true);
1270     OldI->getCond()->Profile(OldID, Context, true);
1271     if (NewID != OldID)
1272       return true;
1273   }
1274 
1275   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1276     // Don't allow overloading of destructors.  (In theory we could, but it
1277     // would be a giant change to clang.)
1278     if (!isa<CXXDestructorDecl>(New)) {
1279       CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1280                          OldTarget = IdentifyCUDATarget(Old);
1281       if (NewTarget != CFT_InvalidTarget) {
1282         assert((OldTarget != CFT_InvalidTarget) &&
1283                "Unexpected invalid target.");
1284 
1285         // Allow overloading of functions with same signature and different CUDA
1286         // target attributes.
1287         if (NewTarget != OldTarget)
1288           return true;
1289       }
1290     }
1291   }
1292 
1293   if (ConsiderRequiresClauses) {
1294     Expr *NewRC = New->getTrailingRequiresClause(),
1295          *OldRC = Old->getTrailingRequiresClause();
1296     if ((NewRC != nullptr) != (OldRC != nullptr))
1297       // RC are most certainly different - these are overloads.
1298       return true;
1299 
1300     if (NewRC) {
1301       llvm::FoldingSetNodeID NewID, OldID;
1302       NewRC->Profile(NewID, Context, /*Canonical=*/true);
1303       OldRC->Profile(OldID, Context, /*Canonical=*/true);
1304       if (NewID != OldID)
1305         // RCs are not equivalent - these are overloads.
1306         return true;
1307     }
1308   }
1309 
1310   // The signatures match; this is not an overload.
1311   return false;
1312 }
1313 
1314 /// Tries a user-defined conversion from From to ToType.
1315 ///
1316 /// Produces an implicit conversion sequence for when a standard conversion
1317 /// is not an option. See TryImplicitConversion for more information.
1318 static ImplicitConversionSequence
1319 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1320                          bool SuppressUserConversions,
1321                          AllowedExplicit AllowExplicit,
1322                          bool InOverloadResolution,
1323                          bool CStyle,
1324                          bool AllowObjCWritebackConversion,
1325                          bool AllowObjCConversionOnExplicit) {
1326   ImplicitConversionSequence ICS;
1327 
1328   if (SuppressUserConversions) {
1329     // We're not in the case above, so there is no conversion that
1330     // we can perform.
1331     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1332     return ICS;
1333   }
1334 
1335   // Attempt user-defined conversion.
1336   OverloadCandidateSet Conversions(From->getExprLoc(),
1337                                    OverloadCandidateSet::CSK_Normal);
1338   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1339                                   Conversions, AllowExplicit,
1340                                   AllowObjCConversionOnExplicit)) {
1341   case OR_Success:
1342   case OR_Deleted:
1343     ICS.setUserDefined();
1344     // C++ [over.ics.user]p4:
1345     //   A conversion of an expression of class type to the same class
1346     //   type is given Exact Match rank, and a conversion of an
1347     //   expression of class type to a base class of that type is
1348     //   given Conversion rank, in spite of the fact that a copy
1349     //   constructor (i.e., a user-defined conversion function) is
1350     //   called for those cases.
1351     if (CXXConstructorDecl *Constructor
1352           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1353       QualType FromCanon
1354         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1355       QualType ToCanon
1356         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1357       if (Constructor->isCopyConstructor() &&
1358           (FromCanon == ToCanon ||
1359            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1360         // Turn this into a "standard" conversion sequence, so that it
1361         // gets ranked with standard conversion sequences.
1362         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1363         ICS.setStandard();
1364         ICS.Standard.setAsIdentityConversion();
1365         ICS.Standard.setFromType(From->getType());
1366         ICS.Standard.setAllToTypes(ToType);
1367         ICS.Standard.CopyConstructor = Constructor;
1368         ICS.Standard.FoundCopyConstructor = Found;
1369         if (ToCanon != FromCanon)
1370           ICS.Standard.Second = ICK_Derived_To_Base;
1371       }
1372     }
1373     break;
1374 
1375   case OR_Ambiguous:
1376     ICS.setAmbiguous();
1377     ICS.Ambiguous.setFromType(From->getType());
1378     ICS.Ambiguous.setToType(ToType);
1379     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1380          Cand != Conversions.end(); ++Cand)
1381       if (Cand->Best)
1382         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1383     break;
1384 
1385     // Fall through.
1386   case OR_No_Viable_Function:
1387     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1388     break;
1389   }
1390 
1391   return ICS;
1392 }
1393 
1394 /// TryImplicitConversion - Attempt to perform an implicit conversion
1395 /// from the given expression (Expr) to the given type (ToType). This
1396 /// function returns an implicit conversion sequence that can be used
1397 /// to perform the initialization. Given
1398 ///
1399 ///   void f(float f);
1400 ///   void g(int i) { f(i); }
1401 ///
1402 /// this routine would produce an implicit conversion sequence to
1403 /// describe the initialization of f from i, which will be a standard
1404 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1405 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1406 //
1407 /// Note that this routine only determines how the conversion can be
1408 /// performed; it does not actually perform the conversion. As such,
1409 /// it will not produce any diagnostics if no conversion is available,
1410 /// but will instead return an implicit conversion sequence of kind
1411 /// "BadConversion".
1412 ///
1413 /// If @p SuppressUserConversions, then user-defined conversions are
1414 /// not permitted.
1415 /// If @p AllowExplicit, then explicit user-defined conversions are
1416 /// permitted.
1417 ///
1418 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1419 /// writeback conversion, which allows __autoreleasing id* parameters to
1420 /// be initialized with __strong id* or __weak id* arguments.
1421 static ImplicitConversionSequence
1422 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1423                       bool SuppressUserConversions,
1424                       AllowedExplicit AllowExplicit,
1425                       bool InOverloadResolution,
1426                       bool CStyle,
1427                       bool AllowObjCWritebackConversion,
1428                       bool AllowObjCConversionOnExplicit) {
1429   ImplicitConversionSequence ICS;
1430   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1431                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1432     ICS.setStandard();
1433     return ICS;
1434   }
1435 
1436   if (!S.getLangOpts().CPlusPlus) {
1437     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1438     return ICS;
1439   }
1440 
1441   // C++ [over.ics.user]p4:
1442   //   A conversion of an expression of class type to the same class
1443   //   type is given Exact Match rank, and a conversion of an
1444   //   expression of class type to a base class of that type is
1445   //   given Conversion rank, in spite of the fact that a copy/move
1446   //   constructor (i.e., a user-defined conversion function) is
1447   //   called for those cases.
1448   QualType FromType = From->getType();
1449   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1450       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1451        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1452     ICS.setStandard();
1453     ICS.Standard.setAsIdentityConversion();
1454     ICS.Standard.setFromType(FromType);
1455     ICS.Standard.setAllToTypes(ToType);
1456 
1457     // We don't actually check at this point whether there is a valid
1458     // copy/move constructor, since overloading just assumes that it
1459     // exists. When we actually perform initialization, we'll find the
1460     // appropriate constructor to copy the returned object, if needed.
1461     ICS.Standard.CopyConstructor = nullptr;
1462 
1463     // Determine whether this is considered a derived-to-base conversion.
1464     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1465       ICS.Standard.Second = ICK_Derived_To_Base;
1466 
1467     return ICS;
1468   }
1469 
1470   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1471                                   AllowExplicit, InOverloadResolution, CStyle,
1472                                   AllowObjCWritebackConversion,
1473                                   AllowObjCConversionOnExplicit);
1474 }
1475 
1476 ImplicitConversionSequence
1477 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1478                             bool SuppressUserConversions,
1479                             AllowedExplicit AllowExplicit,
1480                             bool InOverloadResolution,
1481                             bool CStyle,
1482                             bool AllowObjCWritebackConversion) {
1483   return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1484                                  AllowExplicit, InOverloadResolution, CStyle,
1485                                  AllowObjCWritebackConversion,
1486                                  /*AllowObjCConversionOnExplicit=*/false);
1487 }
1488 
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1494 ExprResult
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496                                 AssignmentAction Action, bool AllowExplicit) {
1497   ImplicitConversionSequence ICS;
1498   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1499 }
1500 
1501 ExprResult
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503                                 AssignmentAction Action, bool AllowExplicit,
1504                                 ImplicitConversionSequence& ICS) {
1505   if (checkPlaceholderForOverload(*this, From))
1506     return ExprError();
1507 
1508   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509   bool AllowObjCWritebackConversion
1510     = getLangOpts().ObjCAutoRefCount &&
1511       (Action == AA_Passing || Action == AA_Sending);
1512   if (getLangOpts().ObjC)
1513     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514                                       From->getType(), From);
1515   ICS = ::TryImplicitConversion(*this, From, ToType,
1516                                 /*SuppressUserConversions=*/false,
1517                                 AllowExplicit ? AllowedExplicit::All
1518                                               : AllowedExplicit::None,
1519                                 /*InOverloadResolution=*/false,
1520                                 /*CStyle=*/false, AllowObjCWritebackConversion,
1521                                 /*AllowObjCConversionOnExplicit=*/false);
1522   return PerformImplicitConversion(From, ToType, ICS, Action);
1523 }
1524 
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1527 /// type.
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529                                 QualType &ResultTy) {
1530   if (Context.hasSameUnqualifiedType(FromType, ToType))
1531     return false;
1532 
1533   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534   //                    or F(t noexcept) -> F(t)
1535   // where F adds one of the following at most once:
1536   //   - a pointer
1537   //   - a member pointer
1538   //   - a block pointer
1539   // Changes here need matching changes in FindCompositePointerType.
1540   CanQualType CanTo = Context.getCanonicalType(ToType);
1541   CanQualType CanFrom = Context.getCanonicalType(FromType);
1542   Type::TypeClass TyClass = CanTo->getTypeClass();
1543   if (TyClass != CanFrom->getTypeClass()) return false;
1544   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545     if (TyClass == Type::Pointer) {
1546       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548     } else if (TyClass == Type::BlockPointer) {
1549       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551     } else if (TyClass == Type::MemberPointer) {
1552       auto ToMPT = CanTo.castAs<MemberPointerType>();
1553       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554       // A function pointer conversion cannot change the class of the function.
1555       if (ToMPT->getClass() != FromMPT->getClass())
1556         return false;
1557       CanTo = ToMPT->getPointeeType();
1558       CanFrom = FromMPT->getPointeeType();
1559     } else {
1560       return false;
1561     }
1562 
1563     TyClass = CanTo->getTypeClass();
1564     if (TyClass != CanFrom->getTypeClass()) return false;
1565     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1566       return false;
1567   }
1568 
1569   const auto *FromFn = cast<FunctionType>(CanFrom);
1570   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1571 
1572   const auto *ToFn = cast<FunctionType>(CanTo);
1573   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1574 
1575   bool Changed = false;
1576 
1577   // Drop 'noreturn' if not present in target type.
1578   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1580     Changed = true;
1581   }
1582 
1583   // Drop 'noexcept' if not present in target type.
1584   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587       FromFn = cast<FunctionType>(
1588           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1589                                                    EST_None)
1590                  .getTypePtr());
1591       Changed = true;
1592     }
1593 
1594     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595     // only if the ExtParameterInfo lists of the two function prototypes can be
1596     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598     bool CanUseToFPT, CanUseFromFPT;
1599     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600                                       CanUseFromFPT, NewParamInfos) &&
1601         CanUseToFPT && !CanUseFromFPT) {
1602       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603       ExtInfo.ExtParameterInfos =
1604           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606                                             FromFPT->getParamTypes(), ExtInfo);
1607       FromFn = QT->getAs<FunctionType>();
1608       Changed = true;
1609     }
1610   }
1611 
1612   if (!Changed)
1613     return false;
1614 
1615   assert(QualType(FromFn, 0).isCanonical());
1616   if (QualType(FromFn, 0) != CanTo) return false;
1617 
1618   ResultTy = ToType;
1619   return true;
1620 }
1621 
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1624 ///
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1626 /// conversion.
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628                                QualType ToType, ImplicitConversionKind &ICK) {
1629   // We need at least one of these types to be a vector type to have a vector
1630   // conversion.
1631   if (!ToType->isVectorType() && !FromType->isVectorType())
1632     return false;
1633 
1634   // Identical types require no conversions.
1635   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1636     return false;
1637 
1638   // There are no conversions between extended vector types, only identity.
1639   if (ToType->isExtVectorType()) {
1640     // There are no conversions between extended vector types other than the
1641     // identity conversion.
1642     if (FromType->isExtVectorType())
1643       return false;
1644 
1645     // Vector splat from any arithmetic type to a vector.
1646     if (FromType->isArithmeticType()) {
1647       ICK = ICK_Vector_Splat;
1648       return true;
1649     }
1650   }
1651 
1652   // We can perform the conversion between vector types in the following cases:
1653   // 1)vector types are equivalent AltiVec and GCC vector types
1654   // 2)lax vector conversions are permitted and the vector types are of the
1655   //   same size
1656   // 3)the destination type does not have the ARM MVE strict-polymorphism
1657   //   attribute, which inhibits lax vector conversion for overload resolution
1658   //   only
1659   if (ToType->isVectorType() && FromType->isVectorType()) {
1660     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1661         (S.isLaxVectorConversion(FromType, ToType) &&
1662          !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
1663       ICK = ICK_Vector_Conversion;
1664       return true;
1665     }
1666   }
1667 
1668   return false;
1669 }
1670 
1671 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1672                                 bool InOverloadResolution,
1673                                 StandardConversionSequence &SCS,
1674                                 bool CStyle);
1675 
1676 /// IsStandardConversion - Determines whether there is a standard
1677 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1678 /// expression From to the type ToType. Standard conversion sequences
1679 /// only consider non-class types; for conversions that involve class
1680 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1681 /// contain the standard conversion sequence required to perform this
1682 /// conversion and this routine will return true. Otherwise, this
1683 /// routine will return false and the value of SCS is unspecified.
1684 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1685                                  bool InOverloadResolution,
1686                                  StandardConversionSequence &SCS,
1687                                  bool CStyle,
1688                                  bool AllowObjCWritebackConversion) {
1689   QualType FromType = From->getType();
1690 
1691   // Standard conversions (C++ [conv])
1692   SCS.setAsIdentityConversion();
1693   SCS.IncompatibleObjC = false;
1694   SCS.setFromType(FromType);
1695   SCS.CopyConstructor = nullptr;
1696 
1697   // There are no standard conversions for class types in C++, so
1698   // abort early. When overloading in C, however, we do permit them.
1699   if (S.getLangOpts().CPlusPlus &&
1700       (FromType->isRecordType() || ToType->isRecordType()))
1701     return false;
1702 
1703   // The first conversion can be an lvalue-to-rvalue conversion,
1704   // array-to-pointer conversion, or function-to-pointer conversion
1705   // (C++ 4p1).
1706 
1707   if (FromType == S.Context.OverloadTy) {
1708     DeclAccessPair AccessPair;
1709     if (FunctionDecl *Fn
1710           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1711                                                  AccessPair)) {
1712       // We were able to resolve the address of the overloaded function,
1713       // so we can convert to the type of that function.
1714       FromType = Fn->getType();
1715       SCS.setFromType(FromType);
1716 
1717       // we can sometimes resolve &foo<int> regardless of ToType, so check
1718       // if the type matches (identity) or we are converting to bool
1719       if (!S.Context.hasSameUnqualifiedType(
1720                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1721         QualType resultTy;
1722         // if the function type matches except for [[noreturn]], it's ok
1723         if (!S.IsFunctionConversion(FromType,
1724               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1725           // otherwise, only a boolean conversion is standard
1726           if (!ToType->isBooleanType())
1727             return false;
1728       }
1729 
1730       // Check if the "from" expression is taking the address of an overloaded
1731       // function and recompute the FromType accordingly. Take advantage of the
1732       // fact that non-static member functions *must* have such an address-of
1733       // expression.
1734       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1735       if (Method && !Method->isStatic()) {
1736         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1737                "Non-unary operator on non-static member address");
1738         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1739                == UO_AddrOf &&
1740                "Non-address-of operator on non-static member address");
1741         const Type *ClassType
1742           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1743         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1744       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1745         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1746                UO_AddrOf &&
1747                "Non-address-of operator for overloaded function expression");
1748         FromType = S.Context.getPointerType(FromType);
1749       }
1750 
1751       // Check that we've computed the proper type after overload resolution.
1752       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1753       // be calling it from within an NDEBUG block.
1754       assert(S.Context.hasSameType(
1755         FromType,
1756         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757     } else {
1758       return false;
1759     }
1760   }
1761   // Lvalue-to-rvalue conversion (C++11 4.1):
1762   //   A glvalue (3.10) of a non-function, non-array type T can
1763   //   be converted to a prvalue.
1764   bool argIsLValue = From->isGLValue();
1765   if (argIsLValue &&
1766       !FromType->isFunctionType() && !FromType->isArrayType() &&
1767       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1768     SCS.First = ICK_Lvalue_To_Rvalue;
1769 
1770     // C11 6.3.2.1p2:
1771     //   ... if the lvalue has atomic type, the value has the non-atomic version
1772     //   of the type of the lvalue ...
1773     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1774       FromType = Atomic->getValueType();
1775 
1776     // If T is a non-class type, the type of the rvalue is the
1777     // cv-unqualified version of T. Otherwise, the type of the rvalue
1778     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1779     // just strip the qualifiers because they don't matter.
1780     FromType = FromType.getUnqualifiedType();
1781   } else if (FromType->isArrayType()) {
1782     // Array-to-pointer conversion (C++ 4.2)
1783     SCS.First = ICK_Array_To_Pointer;
1784 
1785     // An lvalue or rvalue of type "array of N T" or "array of unknown
1786     // bound of T" can be converted to an rvalue of type "pointer to
1787     // T" (C++ 4.2p1).
1788     FromType = S.Context.getArrayDecayedType(FromType);
1789 
1790     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1791       // This conversion is deprecated in C++03 (D.4)
1792       SCS.DeprecatedStringLiteralToCharPtr = true;
1793 
1794       // For the purpose of ranking in overload resolution
1795       // (13.3.3.1.1), this conversion is considered an
1796       // array-to-pointer conversion followed by a qualification
1797       // conversion (4.4). (C++ 4.2p2)
1798       SCS.Second = ICK_Identity;
1799       SCS.Third = ICK_Qualification;
1800       SCS.QualificationIncludesObjCLifetime = false;
1801       SCS.setAllToTypes(FromType);
1802       return true;
1803     }
1804   } else if (FromType->isFunctionType() && argIsLValue) {
1805     // Function-to-pointer conversion (C++ 4.3).
1806     SCS.First = ICK_Function_To_Pointer;
1807 
1808     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1809       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1810         if (!S.checkAddressOfFunctionIsAvailable(FD))
1811           return false;
1812 
1813     // An lvalue of function type T can be converted to an rvalue of
1814     // type "pointer to T." The result is a pointer to the
1815     // function. (C++ 4.3p1).
1816     FromType = S.Context.getPointerType(FromType);
1817   } else {
1818     // We don't require any conversions for the first step.
1819     SCS.First = ICK_Identity;
1820   }
1821   SCS.setToType(0, FromType);
1822 
1823   // The second conversion can be an integral promotion, floating
1824   // point promotion, integral conversion, floating point conversion,
1825   // floating-integral conversion, pointer conversion,
1826   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1827   // For overloading in C, this can also be a "compatible-type"
1828   // conversion.
1829   bool IncompatibleObjC = false;
1830   ImplicitConversionKind SecondICK = ICK_Identity;
1831   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1832     // The unqualified versions of the types are the same: there's no
1833     // conversion to do.
1834     SCS.Second = ICK_Identity;
1835   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1836     // Integral promotion (C++ 4.5).
1837     SCS.Second = ICK_Integral_Promotion;
1838     FromType = ToType.getUnqualifiedType();
1839   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1840     // Floating point promotion (C++ 4.6).
1841     SCS.Second = ICK_Floating_Promotion;
1842     FromType = ToType.getUnqualifiedType();
1843   } else if (S.IsComplexPromotion(FromType, ToType)) {
1844     // Complex promotion (Clang extension)
1845     SCS.Second = ICK_Complex_Promotion;
1846     FromType = ToType.getUnqualifiedType();
1847   } else if (ToType->isBooleanType() &&
1848              (FromType->isArithmeticType() ||
1849               FromType->isAnyPointerType() ||
1850               FromType->isBlockPointerType() ||
1851               FromType->isMemberPointerType())) {
1852     // Boolean conversions (C++ 4.12).
1853     SCS.Second = ICK_Boolean_Conversion;
1854     FromType = S.Context.BoolTy;
1855   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1856              ToType->isIntegralType(S.Context)) {
1857     // Integral conversions (C++ 4.7).
1858     SCS.Second = ICK_Integral_Conversion;
1859     FromType = ToType.getUnqualifiedType();
1860   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1861     // Complex conversions (C99 6.3.1.6)
1862     SCS.Second = ICK_Complex_Conversion;
1863     FromType = ToType.getUnqualifiedType();
1864   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1865              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1866     // Complex-real conversions (C99 6.3.1.7)
1867     SCS.Second = ICK_Complex_Real;
1868     FromType = ToType.getUnqualifiedType();
1869   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1870     // FIXME: disable conversions between long double and __float128 if
1871     // their representation is different until there is back end support
1872     // We of course allow this conversion if long double is really double.
1873 
1874     // Conversions between bfloat and other floats are not permitted.
1875     if (FromType == S.Context.BFloat16Ty || ToType == S.Context.BFloat16Ty)
1876       return false;
1877     if (&S.Context.getFloatTypeSemantics(FromType) !=
1878         &S.Context.getFloatTypeSemantics(ToType)) {
1879       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1880                                     ToType == S.Context.LongDoubleTy) ||
1881                                    (FromType == S.Context.LongDoubleTy &&
1882                                     ToType == S.Context.Float128Ty));
1883       if (Float128AndLongDouble &&
1884           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1885            &llvm::APFloat::PPCDoubleDouble()))
1886         return false;
1887     }
1888     // Floating point conversions (C++ 4.8).
1889     SCS.Second = ICK_Floating_Conversion;
1890     FromType = ToType.getUnqualifiedType();
1891   } else if ((FromType->isRealFloatingType() &&
1892               ToType->isIntegralType(S.Context)) ||
1893              (FromType->isIntegralOrUnscopedEnumerationType() &&
1894               ToType->isRealFloatingType())) {
1895     // Conversions between bfloat and int are not permitted.
1896     if (FromType->isBFloat16Type() || ToType->isBFloat16Type())
1897       return false;
1898 
1899     // Floating-integral conversions (C++ 4.9).
1900     SCS.Second = ICK_Floating_Integral;
1901     FromType = ToType.getUnqualifiedType();
1902   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1903     SCS.Second = ICK_Block_Pointer_Conversion;
1904   } else if (AllowObjCWritebackConversion &&
1905              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1906     SCS.Second = ICK_Writeback_Conversion;
1907   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1908                                    FromType, IncompatibleObjC)) {
1909     // Pointer conversions (C++ 4.10).
1910     SCS.Second = ICK_Pointer_Conversion;
1911     SCS.IncompatibleObjC = IncompatibleObjC;
1912     FromType = FromType.getUnqualifiedType();
1913   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1914                                          InOverloadResolution, FromType)) {
1915     // Pointer to member conversions (4.11).
1916     SCS.Second = ICK_Pointer_Member;
1917   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1918     SCS.Second = SecondICK;
1919     FromType = ToType.getUnqualifiedType();
1920   } else if (!S.getLangOpts().CPlusPlus &&
1921              S.Context.typesAreCompatible(ToType, FromType)) {
1922     // Compatible conversions (Clang extension for C function overloading)
1923     SCS.Second = ICK_Compatible_Conversion;
1924     FromType = ToType.getUnqualifiedType();
1925   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1926                                              InOverloadResolution,
1927                                              SCS, CStyle)) {
1928     SCS.Second = ICK_TransparentUnionConversion;
1929     FromType = ToType;
1930   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1931                                  CStyle)) {
1932     // tryAtomicConversion has updated the standard conversion sequence
1933     // appropriately.
1934     return true;
1935   } else if (ToType->isEventT() &&
1936              From->isIntegerConstantExpr(S.getASTContext()) &&
1937              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1938     SCS.Second = ICK_Zero_Event_Conversion;
1939     FromType = ToType;
1940   } else if (ToType->isQueueT() &&
1941              From->isIntegerConstantExpr(S.getASTContext()) &&
1942              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1943     SCS.Second = ICK_Zero_Queue_Conversion;
1944     FromType = ToType;
1945   } else if (ToType->isSamplerT() &&
1946              From->isIntegerConstantExpr(S.getASTContext())) {
1947     SCS.Second = ICK_Compatible_Conversion;
1948     FromType = ToType;
1949   } else {
1950     // No second conversion required.
1951     SCS.Second = ICK_Identity;
1952   }
1953   SCS.setToType(1, FromType);
1954 
1955   // The third conversion can be a function pointer conversion or a
1956   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1957   bool ObjCLifetimeConversion;
1958   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1959     // Function pointer conversions (removing 'noexcept') including removal of
1960     // 'noreturn' (Clang extension).
1961     SCS.Third = ICK_Function_Conversion;
1962   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1963                                          ObjCLifetimeConversion)) {
1964     SCS.Third = ICK_Qualification;
1965     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1966     FromType = ToType;
1967   } else {
1968     // No conversion required
1969     SCS.Third = ICK_Identity;
1970   }
1971 
1972   // C++ [over.best.ics]p6:
1973   //   [...] Any difference in top-level cv-qualification is
1974   //   subsumed by the initialization itself and does not constitute
1975   //   a conversion. [...]
1976   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1977   QualType CanonTo = S.Context.getCanonicalType(ToType);
1978   if (CanonFrom.getLocalUnqualifiedType()
1979                                      == CanonTo.getLocalUnqualifiedType() &&
1980       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1981     FromType = ToType;
1982     CanonFrom = CanonTo;
1983   }
1984 
1985   SCS.setToType(2, FromType);
1986 
1987   if (CanonFrom == CanonTo)
1988     return true;
1989 
1990   // If we have not converted the argument type to the parameter type,
1991   // this is a bad conversion sequence, unless we're resolving an overload in C.
1992   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1993     return false;
1994 
1995   ExprResult ER = ExprResult{From};
1996   Sema::AssignConvertType Conv =
1997       S.CheckSingleAssignmentConstraints(ToType, ER,
1998                                          /*Diagnose=*/false,
1999                                          /*DiagnoseCFAudited=*/false,
2000                                          /*ConvertRHS=*/false);
2001   ImplicitConversionKind SecondConv;
2002   switch (Conv) {
2003   case Sema::Compatible:
2004     SecondConv = ICK_C_Only_Conversion;
2005     break;
2006   // For our purposes, discarding qualifiers is just as bad as using an
2007   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2008   // qualifiers, as well.
2009   case Sema::CompatiblePointerDiscardsQualifiers:
2010   case Sema::IncompatiblePointer:
2011   case Sema::IncompatiblePointerSign:
2012     SecondConv = ICK_Incompatible_Pointer_Conversion;
2013     break;
2014   default:
2015     return false;
2016   }
2017 
2018   // First can only be an lvalue conversion, so we pretend that this was the
2019   // second conversion. First should already be valid from earlier in the
2020   // function.
2021   SCS.Second = SecondConv;
2022   SCS.setToType(1, ToType);
2023 
2024   // Third is Identity, because Second should rank us worse than any other
2025   // conversion. This could also be ICK_Qualification, but it's simpler to just
2026   // lump everything in with the second conversion, and we don't gain anything
2027   // from making this ICK_Qualification.
2028   SCS.Third = ICK_Identity;
2029   SCS.setToType(2, ToType);
2030   return true;
2031 }
2032 
2033 static bool
2034 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2035                                      QualType &ToType,
2036                                      bool InOverloadResolution,
2037                                      StandardConversionSequence &SCS,
2038                                      bool CStyle) {
2039 
2040   const RecordType *UT = ToType->getAsUnionType();
2041   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2042     return false;
2043   // The field to initialize within the transparent union.
2044   RecordDecl *UD = UT->getDecl();
2045   // It's compatible if the expression matches any of the fields.
2046   for (const auto *it : UD->fields()) {
2047     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2048                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2049       ToType = it->getType();
2050       return true;
2051     }
2052   }
2053   return false;
2054 }
2055 
2056 /// IsIntegralPromotion - Determines whether the conversion from the
2057 /// expression From (whose potentially-adjusted type is FromType) to
2058 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2059 /// sets PromotedType to the promoted type.
2060 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2061   const BuiltinType *To = ToType->getAs<BuiltinType>();
2062   // All integers are built-in.
2063   if (!To) {
2064     return false;
2065   }
2066 
2067   // An rvalue of type char, signed char, unsigned char, short int, or
2068   // unsigned short int can be converted to an rvalue of type int if
2069   // int can represent all the values of the source type; otherwise,
2070   // the source rvalue can be converted to an rvalue of type unsigned
2071   // int (C++ 4.5p1).
2072   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2073       !FromType->isEnumeralType()) {
2074     if (// We can promote any signed, promotable integer type to an int
2075         (FromType->isSignedIntegerType() ||
2076          // We can promote any unsigned integer type whose size is
2077          // less than int to an int.
2078          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2079       return To->getKind() == BuiltinType::Int;
2080     }
2081 
2082     return To->getKind() == BuiltinType::UInt;
2083   }
2084 
2085   // C++11 [conv.prom]p3:
2086   //   A prvalue of an unscoped enumeration type whose underlying type is not
2087   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2088   //   following types that can represent all the values of the enumeration
2089   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2090   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2091   //   long long int. If none of the types in that list can represent all the
2092   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2093   //   type can be converted to an rvalue a prvalue of the extended integer type
2094   //   with lowest integer conversion rank (4.13) greater than the rank of long
2095   //   long in which all the values of the enumeration can be represented. If
2096   //   there are two such extended types, the signed one is chosen.
2097   // C++11 [conv.prom]p4:
2098   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2099   //   can be converted to a prvalue of its underlying type. Moreover, if
2100   //   integral promotion can be applied to its underlying type, a prvalue of an
2101   //   unscoped enumeration type whose underlying type is fixed can also be
2102   //   converted to a prvalue of the promoted underlying type.
2103   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2104     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2105     // provided for a scoped enumeration.
2106     if (FromEnumType->getDecl()->isScoped())
2107       return false;
2108 
2109     // We can perform an integral promotion to the underlying type of the enum,
2110     // even if that's not the promoted type. Note that the check for promoting
2111     // the underlying type is based on the type alone, and does not consider
2112     // the bitfield-ness of the actual source expression.
2113     if (FromEnumType->getDecl()->isFixed()) {
2114       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2115       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2116              IsIntegralPromotion(nullptr, Underlying, ToType);
2117     }
2118 
2119     // We have already pre-calculated the promotion type, so this is trivial.
2120     if (ToType->isIntegerType() &&
2121         isCompleteType(From->getBeginLoc(), FromType))
2122       return Context.hasSameUnqualifiedType(
2123           ToType, FromEnumType->getDecl()->getPromotionType());
2124 
2125     // C++ [conv.prom]p5:
2126     //   If the bit-field has an enumerated type, it is treated as any other
2127     //   value of that type for promotion purposes.
2128     //
2129     // ... so do not fall through into the bit-field checks below in C++.
2130     if (getLangOpts().CPlusPlus)
2131       return false;
2132   }
2133 
2134   // C++0x [conv.prom]p2:
2135   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2136   //   to an rvalue a prvalue of the first of the following types that can
2137   //   represent all the values of its underlying type: int, unsigned int,
2138   //   long int, unsigned long int, long long int, or unsigned long long int.
2139   //   If none of the types in that list can represent all the values of its
2140   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2141   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2142   //   type.
2143   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2144       ToType->isIntegerType()) {
2145     // Determine whether the type we're converting from is signed or
2146     // unsigned.
2147     bool FromIsSigned = FromType->isSignedIntegerType();
2148     uint64_t FromSize = Context.getTypeSize(FromType);
2149 
2150     // The types we'll try to promote to, in the appropriate
2151     // order. Try each of these types.
2152     QualType PromoteTypes[6] = {
2153       Context.IntTy, Context.UnsignedIntTy,
2154       Context.LongTy, Context.UnsignedLongTy ,
2155       Context.LongLongTy, Context.UnsignedLongLongTy
2156     };
2157     for (int Idx = 0; Idx < 6; ++Idx) {
2158       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2159       if (FromSize < ToSize ||
2160           (FromSize == ToSize &&
2161            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2162         // We found the type that we can promote to. If this is the
2163         // type we wanted, we have a promotion. Otherwise, no
2164         // promotion.
2165         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2166       }
2167     }
2168   }
2169 
2170   // An rvalue for an integral bit-field (9.6) can be converted to an
2171   // rvalue of type int if int can represent all the values of the
2172   // bit-field; otherwise, it can be converted to unsigned int if
2173   // unsigned int can represent all the values of the bit-field. If
2174   // the bit-field is larger yet, no integral promotion applies to
2175   // it. If the bit-field has an enumerated type, it is treated as any
2176   // other value of that type for promotion purposes (C++ 4.5p3).
2177   // FIXME: We should delay checking of bit-fields until we actually perform the
2178   // conversion.
2179   //
2180   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2181   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2182   // bit-fields and those whose underlying type is larger than int) for GCC
2183   // compatibility.
2184   if (From) {
2185     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2186       llvm::APSInt BitWidth;
2187       if (FromType->isIntegralType(Context) &&
2188           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2189         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2190         ToSize = Context.getTypeSize(ToType);
2191 
2192         // Are we promoting to an int from a bitfield that fits in an int?
2193         if (BitWidth < ToSize ||
2194             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2195           return To->getKind() == BuiltinType::Int;
2196         }
2197 
2198         // Are we promoting to an unsigned int from an unsigned bitfield
2199         // that fits into an unsigned int?
2200         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2201           return To->getKind() == BuiltinType::UInt;
2202         }
2203 
2204         return false;
2205       }
2206     }
2207   }
2208 
2209   // An rvalue of type bool can be converted to an rvalue of type int,
2210   // with false becoming zero and true becoming one (C++ 4.5p4).
2211   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2212     return true;
2213   }
2214 
2215   return false;
2216 }
2217 
2218 /// IsFloatingPointPromotion - Determines whether the conversion from
2219 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2220 /// returns true and sets PromotedType to the promoted type.
2221 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2222   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2223     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2224       /// An rvalue of type float can be converted to an rvalue of type
2225       /// double. (C++ 4.6p1).
2226       if (FromBuiltin->getKind() == BuiltinType::Float &&
2227           ToBuiltin->getKind() == BuiltinType::Double)
2228         return true;
2229 
2230       // C99 6.3.1.5p1:
2231       //   When a float is promoted to double or long double, or a
2232       //   double is promoted to long double [...].
2233       if (!getLangOpts().CPlusPlus &&
2234           (FromBuiltin->getKind() == BuiltinType::Float ||
2235            FromBuiltin->getKind() == BuiltinType::Double) &&
2236           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2237            ToBuiltin->getKind() == BuiltinType::Float128))
2238         return true;
2239 
2240       // Half can be promoted to float.
2241       if (!getLangOpts().NativeHalfType &&
2242            FromBuiltin->getKind() == BuiltinType::Half &&
2243           ToBuiltin->getKind() == BuiltinType::Float)
2244         return true;
2245     }
2246 
2247   return false;
2248 }
2249 
2250 /// Determine if a conversion is a complex promotion.
2251 ///
2252 /// A complex promotion is defined as a complex -> complex conversion
2253 /// where the conversion between the underlying real types is a
2254 /// floating-point or integral promotion.
2255 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2256   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2257   if (!FromComplex)
2258     return false;
2259 
2260   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2261   if (!ToComplex)
2262     return false;
2263 
2264   return IsFloatingPointPromotion(FromComplex->getElementType(),
2265                                   ToComplex->getElementType()) ||
2266     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2267                         ToComplex->getElementType());
2268 }
2269 
2270 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2271 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2272 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2273 /// if non-empty, will be a pointer to ToType that may or may not have
2274 /// the right set of qualifiers on its pointee.
2275 ///
2276 static QualType
2277 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2278                                    QualType ToPointee, QualType ToType,
2279                                    ASTContext &Context,
2280                                    bool StripObjCLifetime = false) {
2281   assert((FromPtr->getTypeClass() == Type::Pointer ||
2282           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2283          "Invalid similarly-qualified pointer type");
2284 
2285   /// Conversions to 'id' subsume cv-qualifier conversions.
2286   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2287     return ToType.getUnqualifiedType();
2288 
2289   QualType CanonFromPointee
2290     = Context.getCanonicalType(FromPtr->getPointeeType());
2291   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2292   Qualifiers Quals = CanonFromPointee.getQualifiers();
2293 
2294   if (StripObjCLifetime)
2295     Quals.removeObjCLifetime();
2296 
2297   // Exact qualifier match -> return the pointer type we're converting to.
2298   if (CanonToPointee.getLocalQualifiers() == Quals) {
2299     // ToType is exactly what we need. Return it.
2300     if (!ToType.isNull())
2301       return ToType.getUnqualifiedType();
2302 
2303     // Build a pointer to ToPointee. It has the right qualifiers
2304     // already.
2305     if (isa<ObjCObjectPointerType>(ToType))
2306       return Context.getObjCObjectPointerType(ToPointee);
2307     return Context.getPointerType(ToPointee);
2308   }
2309 
2310   // Just build a canonical type that has the right qualifiers.
2311   QualType QualifiedCanonToPointee
2312     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2313 
2314   if (isa<ObjCObjectPointerType>(ToType))
2315     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2316   return Context.getPointerType(QualifiedCanonToPointee);
2317 }
2318 
2319 static bool isNullPointerConstantForConversion(Expr *Expr,
2320                                                bool InOverloadResolution,
2321                                                ASTContext &Context) {
2322   // Handle value-dependent integral null pointer constants correctly.
2323   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2324   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2325       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2326     return !InOverloadResolution;
2327 
2328   return Expr->isNullPointerConstant(Context,
2329                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2330                                         : Expr::NPC_ValueDependentIsNull);
2331 }
2332 
2333 /// IsPointerConversion - Determines whether the conversion of the
2334 /// expression From, which has the (possibly adjusted) type FromType,
2335 /// can be converted to the type ToType via a pointer conversion (C++
2336 /// 4.10). If so, returns true and places the converted type (that
2337 /// might differ from ToType in its cv-qualifiers at some level) into
2338 /// ConvertedType.
2339 ///
2340 /// This routine also supports conversions to and from block pointers
2341 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2342 /// pointers to interfaces. FIXME: Once we've determined the
2343 /// appropriate overloading rules for Objective-C, we may want to
2344 /// split the Objective-C checks into a different routine; however,
2345 /// GCC seems to consider all of these conversions to be pointer
2346 /// conversions, so for now they live here. IncompatibleObjC will be
2347 /// set if the conversion is an allowed Objective-C conversion that
2348 /// should result in a warning.
2349 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2350                                bool InOverloadResolution,
2351                                QualType& ConvertedType,
2352                                bool &IncompatibleObjC) {
2353   IncompatibleObjC = false;
2354   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2355                               IncompatibleObjC))
2356     return true;
2357 
2358   // Conversion from a null pointer constant to any Objective-C pointer type.
2359   if (ToType->isObjCObjectPointerType() &&
2360       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2361     ConvertedType = ToType;
2362     return true;
2363   }
2364 
2365   // Blocks: Block pointers can be converted to void*.
2366   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2367       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2368     ConvertedType = ToType;
2369     return true;
2370   }
2371   // Blocks: A null pointer constant can be converted to a block
2372   // pointer type.
2373   if (ToType->isBlockPointerType() &&
2374       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2375     ConvertedType = ToType;
2376     return true;
2377   }
2378 
2379   // If the left-hand-side is nullptr_t, the right side can be a null
2380   // pointer constant.
2381   if (ToType->isNullPtrType() &&
2382       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2383     ConvertedType = ToType;
2384     return true;
2385   }
2386 
2387   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2388   if (!ToTypePtr)
2389     return false;
2390 
2391   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2392   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2393     ConvertedType = ToType;
2394     return true;
2395   }
2396 
2397   // Beyond this point, both types need to be pointers
2398   // , including objective-c pointers.
2399   QualType ToPointeeType = ToTypePtr->getPointeeType();
2400   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2401       !getLangOpts().ObjCAutoRefCount) {
2402     ConvertedType = BuildSimilarlyQualifiedPointerType(
2403                                       FromType->getAs<ObjCObjectPointerType>(),
2404                                                        ToPointeeType,
2405                                                        ToType, Context);
2406     return true;
2407   }
2408   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2409   if (!FromTypePtr)
2410     return false;
2411 
2412   QualType FromPointeeType = FromTypePtr->getPointeeType();
2413 
2414   // If the unqualified pointee types are the same, this can't be a
2415   // pointer conversion, so don't do all of the work below.
2416   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2417     return false;
2418 
2419   // An rvalue of type "pointer to cv T," where T is an object type,
2420   // can be converted to an rvalue of type "pointer to cv void" (C++
2421   // 4.10p2).
2422   if (FromPointeeType->isIncompleteOrObjectType() &&
2423       ToPointeeType->isVoidType()) {
2424     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2425                                                        ToPointeeType,
2426                                                        ToType, Context,
2427                                                    /*StripObjCLifetime=*/true);
2428     return true;
2429   }
2430 
2431   // MSVC allows implicit function to void* type conversion.
2432   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2433       ToPointeeType->isVoidType()) {
2434     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2435                                                        ToPointeeType,
2436                                                        ToType, Context);
2437     return true;
2438   }
2439 
2440   // When we're overloading in C, we allow a special kind of pointer
2441   // conversion for compatible-but-not-identical pointee types.
2442   if (!getLangOpts().CPlusPlus &&
2443       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2444     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2445                                                        ToPointeeType,
2446                                                        ToType, Context);
2447     return true;
2448   }
2449 
2450   // C++ [conv.ptr]p3:
2451   //
2452   //   An rvalue of type "pointer to cv D," where D is a class type,
2453   //   can be converted to an rvalue of type "pointer to cv B," where
2454   //   B is a base class (clause 10) of D. If B is an inaccessible
2455   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2456   //   necessitates this conversion is ill-formed. The result of the
2457   //   conversion is a pointer to the base class sub-object of the
2458   //   derived class object. The null pointer value is converted to
2459   //   the null pointer value of the destination type.
2460   //
2461   // Note that we do not check for ambiguity or inaccessibility
2462   // here. That is handled by CheckPointerConversion.
2463   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2464       ToPointeeType->isRecordType() &&
2465       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2466       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2467     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2468                                                        ToPointeeType,
2469                                                        ToType, Context);
2470     return true;
2471   }
2472 
2473   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2474       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2475     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2476                                                        ToPointeeType,
2477                                                        ToType, Context);
2478     return true;
2479   }
2480 
2481   return false;
2482 }
2483 
2484 /// Adopt the given qualifiers for the given type.
2485 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2486   Qualifiers TQs = T.getQualifiers();
2487 
2488   // Check whether qualifiers already match.
2489   if (TQs == Qs)
2490     return T;
2491 
2492   if (Qs.compatiblyIncludes(TQs))
2493     return Context.getQualifiedType(T, Qs);
2494 
2495   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2496 }
2497 
2498 /// isObjCPointerConversion - Determines whether this is an
2499 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2500 /// with the same arguments and return values.
2501 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2502                                    QualType& ConvertedType,
2503                                    bool &IncompatibleObjC) {
2504   if (!getLangOpts().ObjC)
2505     return false;
2506 
2507   // The set of qualifiers on the type we're converting from.
2508   Qualifiers FromQualifiers = FromType.getQualifiers();
2509 
2510   // First, we handle all conversions on ObjC object pointer types.
2511   const ObjCObjectPointerType* ToObjCPtr =
2512     ToType->getAs<ObjCObjectPointerType>();
2513   const ObjCObjectPointerType *FromObjCPtr =
2514     FromType->getAs<ObjCObjectPointerType>();
2515 
2516   if (ToObjCPtr && FromObjCPtr) {
2517     // If the pointee types are the same (ignoring qualifications),
2518     // then this is not a pointer conversion.
2519     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2520                                        FromObjCPtr->getPointeeType()))
2521       return false;
2522 
2523     // Conversion between Objective-C pointers.
2524     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2525       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2526       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2527       if (getLangOpts().CPlusPlus && LHS && RHS &&
2528           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2529                                                 FromObjCPtr->getPointeeType()))
2530         return false;
2531       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2532                                                    ToObjCPtr->getPointeeType(),
2533                                                          ToType, Context);
2534       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2535       return true;
2536     }
2537 
2538     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2539       // Okay: this is some kind of implicit downcast of Objective-C
2540       // interfaces, which is permitted. However, we're going to
2541       // complain about it.
2542       IncompatibleObjC = true;
2543       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2544                                                    ToObjCPtr->getPointeeType(),
2545                                                          ToType, Context);
2546       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2547       return true;
2548     }
2549   }
2550   // Beyond this point, both types need to be C pointers or block pointers.
2551   QualType ToPointeeType;
2552   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2553     ToPointeeType = ToCPtr->getPointeeType();
2554   else if (const BlockPointerType *ToBlockPtr =
2555             ToType->getAs<BlockPointerType>()) {
2556     // Objective C++: We're able to convert from a pointer to any object
2557     // to a block pointer type.
2558     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2559       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2560       return true;
2561     }
2562     ToPointeeType = ToBlockPtr->getPointeeType();
2563   }
2564   else if (FromType->getAs<BlockPointerType>() &&
2565            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2566     // Objective C++: We're able to convert from a block pointer type to a
2567     // pointer to any object.
2568     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2569     return true;
2570   }
2571   else
2572     return false;
2573 
2574   QualType FromPointeeType;
2575   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2576     FromPointeeType = FromCPtr->getPointeeType();
2577   else if (const BlockPointerType *FromBlockPtr =
2578            FromType->getAs<BlockPointerType>())
2579     FromPointeeType = FromBlockPtr->getPointeeType();
2580   else
2581     return false;
2582 
2583   // If we have pointers to pointers, recursively check whether this
2584   // is an Objective-C conversion.
2585   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2586       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2587                               IncompatibleObjC)) {
2588     // We always complain about this conversion.
2589     IncompatibleObjC = true;
2590     ConvertedType = Context.getPointerType(ConvertedType);
2591     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2592     return true;
2593   }
2594   // Allow conversion of pointee being objective-c pointer to another one;
2595   // as in I* to id.
2596   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2597       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2598       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2599                               IncompatibleObjC)) {
2600 
2601     ConvertedType = Context.getPointerType(ConvertedType);
2602     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2603     return true;
2604   }
2605 
2606   // If we have pointers to functions or blocks, check whether the only
2607   // differences in the argument and result types are in Objective-C
2608   // pointer conversions. If so, we permit the conversion (but
2609   // complain about it).
2610   const FunctionProtoType *FromFunctionType
2611     = FromPointeeType->getAs<FunctionProtoType>();
2612   const FunctionProtoType *ToFunctionType
2613     = ToPointeeType->getAs<FunctionProtoType>();
2614   if (FromFunctionType && ToFunctionType) {
2615     // If the function types are exactly the same, this isn't an
2616     // Objective-C pointer conversion.
2617     if (Context.getCanonicalType(FromPointeeType)
2618           == Context.getCanonicalType(ToPointeeType))
2619       return false;
2620 
2621     // Perform the quick checks that will tell us whether these
2622     // function types are obviously different.
2623     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2624         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2625         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2626       return false;
2627 
2628     bool HasObjCConversion = false;
2629     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2630         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2631       // Okay, the types match exactly. Nothing to do.
2632     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2633                                        ToFunctionType->getReturnType(),
2634                                        ConvertedType, IncompatibleObjC)) {
2635       // Okay, we have an Objective-C pointer conversion.
2636       HasObjCConversion = true;
2637     } else {
2638       // Function types are too different. Abort.
2639       return false;
2640     }
2641 
2642     // Check argument types.
2643     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2644          ArgIdx != NumArgs; ++ArgIdx) {
2645       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2646       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2647       if (Context.getCanonicalType(FromArgType)
2648             == Context.getCanonicalType(ToArgType)) {
2649         // Okay, the types match exactly. Nothing to do.
2650       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2651                                          ConvertedType, IncompatibleObjC)) {
2652         // Okay, we have an Objective-C pointer conversion.
2653         HasObjCConversion = true;
2654       } else {
2655         // Argument types are too different. Abort.
2656         return false;
2657       }
2658     }
2659 
2660     if (HasObjCConversion) {
2661       // We had an Objective-C conversion. Allow this pointer
2662       // conversion, but complain about it.
2663       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2664       IncompatibleObjC = true;
2665       return true;
2666     }
2667   }
2668 
2669   return false;
2670 }
2671 
2672 /// Determine whether this is an Objective-C writeback conversion,
2673 /// used for parameter passing when performing automatic reference counting.
2674 ///
2675 /// \param FromType The type we're converting form.
2676 ///
2677 /// \param ToType The type we're converting to.
2678 ///
2679 /// \param ConvertedType The type that will be produced after applying
2680 /// this conversion.
2681 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2682                                      QualType &ConvertedType) {
2683   if (!getLangOpts().ObjCAutoRefCount ||
2684       Context.hasSameUnqualifiedType(FromType, ToType))
2685     return false;
2686 
2687   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2688   QualType ToPointee;
2689   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2690     ToPointee = ToPointer->getPointeeType();
2691   else
2692     return false;
2693 
2694   Qualifiers ToQuals = ToPointee.getQualifiers();
2695   if (!ToPointee->isObjCLifetimeType() ||
2696       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2697       !ToQuals.withoutObjCLifetime().empty())
2698     return false;
2699 
2700   // Argument must be a pointer to __strong to __weak.
2701   QualType FromPointee;
2702   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2703     FromPointee = FromPointer->getPointeeType();
2704   else
2705     return false;
2706 
2707   Qualifiers FromQuals = FromPointee.getQualifiers();
2708   if (!FromPointee->isObjCLifetimeType() ||
2709       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2710        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2711     return false;
2712 
2713   // Make sure that we have compatible qualifiers.
2714   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2715   if (!ToQuals.compatiblyIncludes(FromQuals))
2716     return false;
2717 
2718   // Remove qualifiers from the pointee type we're converting from; they
2719   // aren't used in the compatibility check belong, and we'll be adding back
2720   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2721   FromPointee = FromPointee.getUnqualifiedType();
2722 
2723   // The unqualified form of the pointee types must be compatible.
2724   ToPointee = ToPointee.getUnqualifiedType();
2725   bool IncompatibleObjC;
2726   if (Context.typesAreCompatible(FromPointee, ToPointee))
2727     FromPointee = ToPointee;
2728   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2729                                     IncompatibleObjC))
2730     return false;
2731 
2732   /// Construct the type we're converting to, which is a pointer to
2733   /// __autoreleasing pointee.
2734   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2735   ConvertedType = Context.getPointerType(FromPointee);
2736   return true;
2737 }
2738 
2739 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2740                                     QualType& ConvertedType) {
2741   QualType ToPointeeType;
2742   if (const BlockPointerType *ToBlockPtr =
2743         ToType->getAs<BlockPointerType>())
2744     ToPointeeType = ToBlockPtr->getPointeeType();
2745   else
2746     return false;
2747 
2748   QualType FromPointeeType;
2749   if (const BlockPointerType *FromBlockPtr =
2750       FromType->getAs<BlockPointerType>())
2751     FromPointeeType = FromBlockPtr->getPointeeType();
2752   else
2753     return false;
2754   // We have pointer to blocks, check whether the only
2755   // differences in the argument and result types are in Objective-C
2756   // pointer conversions. If so, we permit the conversion.
2757 
2758   const FunctionProtoType *FromFunctionType
2759     = FromPointeeType->getAs<FunctionProtoType>();
2760   const FunctionProtoType *ToFunctionType
2761     = ToPointeeType->getAs<FunctionProtoType>();
2762 
2763   if (!FromFunctionType || !ToFunctionType)
2764     return false;
2765 
2766   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2767     return true;
2768 
2769   // Perform the quick checks that will tell us whether these
2770   // function types are obviously different.
2771   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2772       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2773     return false;
2774 
2775   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2776   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2777   if (FromEInfo != ToEInfo)
2778     return false;
2779 
2780   bool IncompatibleObjC = false;
2781   if (Context.hasSameType(FromFunctionType->getReturnType(),
2782                           ToFunctionType->getReturnType())) {
2783     // Okay, the types match exactly. Nothing to do.
2784   } else {
2785     QualType RHS = FromFunctionType->getReturnType();
2786     QualType LHS = ToFunctionType->getReturnType();
2787     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2788         !RHS.hasQualifiers() && LHS.hasQualifiers())
2789        LHS = LHS.getUnqualifiedType();
2790 
2791      if (Context.hasSameType(RHS,LHS)) {
2792        // OK exact match.
2793      } else if (isObjCPointerConversion(RHS, LHS,
2794                                         ConvertedType, IncompatibleObjC)) {
2795      if (IncompatibleObjC)
2796        return false;
2797      // Okay, we have an Objective-C pointer conversion.
2798      }
2799      else
2800        return false;
2801    }
2802 
2803    // Check argument types.
2804    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2805         ArgIdx != NumArgs; ++ArgIdx) {
2806      IncompatibleObjC = false;
2807      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2808      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2809      if (Context.hasSameType(FromArgType, ToArgType)) {
2810        // Okay, the types match exactly. Nothing to do.
2811      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2812                                         ConvertedType, IncompatibleObjC)) {
2813        if (IncompatibleObjC)
2814          return false;
2815        // Okay, we have an Objective-C pointer conversion.
2816      } else
2817        // Argument types are too different. Abort.
2818        return false;
2819    }
2820 
2821    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2822    bool CanUseToFPT, CanUseFromFPT;
2823    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2824                                       CanUseToFPT, CanUseFromFPT,
2825                                       NewParamInfos))
2826      return false;
2827 
2828    ConvertedType = ToType;
2829    return true;
2830 }
2831 
2832 enum {
2833   ft_default,
2834   ft_different_class,
2835   ft_parameter_arity,
2836   ft_parameter_mismatch,
2837   ft_return_type,
2838   ft_qualifer_mismatch,
2839   ft_noexcept
2840 };
2841 
2842 /// Attempts to get the FunctionProtoType from a Type. Handles
2843 /// MemberFunctionPointers properly.
2844 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2845   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2846     return FPT;
2847 
2848   if (auto *MPT = FromType->getAs<MemberPointerType>())
2849     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2850 
2851   return nullptr;
2852 }
2853 
2854 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2855 /// function types.  Catches different number of parameter, mismatch in
2856 /// parameter types, and different return types.
2857 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2858                                       QualType FromType, QualType ToType) {
2859   // If either type is not valid, include no extra info.
2860   if (FromType.isNull() || ToType.isNull()) {
2861     PDiag << ft_default;
2862     return;
2863   }
2864 
2865   // Get the function type from the pointers.
2866   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2867     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2868                *ToMember = ToType->castAs<MemberPointerType>();
2869     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2870       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2871             << QualType(FromMember->getClass(), 0);
2872       return;
2873     }
2874     FromType = FromMember->getPointeeType();
2875     ToType = ToMember->getPointeeType();
2876   }
2877 
2878   if (FromType->isPointerType())
2879     FromType = FromType->getPointeeType();
2880   if (ToType->isPointerType())
2881     ToType = ToType->getPointeeType();
2882 
2883   // Remove references.
2884   FromType = FromType.getNonReferenceType();
2885   ToType = ToType.getNonReferenceType();
2886 
2887   // Don't print extra info for non-specialized template functions.
2888   if (FromType->isInstantiationDependentType() &&
2889       !FromType->getAs<TemplateSpecializationType>()) {
2890     PDiag << ft_default;
2891     return;
2892   }
2893 
2894   // No extra info for same types.
2895   if (Context.hasSameType(FromType, ToType)) {
2896     PDiag << ft_default;
2897     return;
2898   }
2899 
2900   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2901                           *ToFunction = tryGetFunctionProtoType(ToType);
2902 
2903   // Both types need to be function types.
2904   if (!FromFunction || !ToFunction) {
2905     PDiag << ft_default;
2906     return;
2907   }
2908 
2909   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2910     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2911           << FromFunction->getNumParams();
2912     return;
2913   }
2914 
2915   // Handle different parameter types.
2916   unsigned ArgPos;
2917   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2918     PDiag << ft_parameter_mismatch << ArgPos + 1
2919           << ToFunction->getParamType(ArgPos)
2920           << FromFunction->getParamType(ArgPos);
2921     return;
2922   }
2923 
2924   // Handle different return type.
2925   if (!Context.hasSameType(FromFunction->getReturnType(),
2926                            ToFunction->getReturnType())) {
2927     PDiag << ft_return_type << ToFunction->getReturnType()
2928           << FromFunction->getReturnType();
2929     return;
2930   }
2931 
2932   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2933     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2934           << FromFunction->getMethodQuals();
2935     return;
2936   }
2937 
2938   // Handle exception specification differences on canonical type (in C++17
2939   // onwards).
2940   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2941           ->isNothrow() !=
2942       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2943           ->isNothrow()) {
2944     PDiag << ft_noexcept;
2945     return;
2946   }
2947 
2948   // Unable to find a difference, so add no extra info.
2949   PDiag << ft_default;
2950 }
2951 
2952 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2953 /// for equality of their argument types. Caller has already checked that
2954 /// they have same number of arguments.  If the parameters are different,
2955 /// ArgPos will have the parameter index of the first different parameter.
2956 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2957                                       const FunctionProtoType *NewType,
2958                                       unsigned *ArgPos) {
2959   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2960                                               N = NewType->param_type_begin(),
2961                                               E = OldType->param_type_end();
2962        O && (O != E); ++O, ++N) {
2963     // Ignore address spaces in pointee type. This is to disallow overloading
2964     // on __ptr32/__ptr64 address spaces.
2965     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2966     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2967 
2968     if (!Context.hasSameType(Old, New)) {
2969       if (ArgPos)
2970         *ArgPos = O - OldType->param_type_begin();
2971       return false;
2972     }
2973   }
2974   return true;
2975 }
2976 
2977 /// CheckPointerConversion - Check the pointer conversion from the
2978 /// expression From to the type ToType. This routine checks for
2979 /// ambiguous or inaccessible derived-to-base pointer
2980 /// conversions for which IsPointerConversion has already returned
2981 /// true. It returns true and produces a diagnostic if there was an
2982 /// error, or returns false otherwise.
2983 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2984                                   CastKind &Kind,
2985                                   CXXCastPath& BasePath,
2986                                   bool IgnoreBaseAccess,
2987                                   bool Diagnose) {
2988   QualType FromType = From->getType();
2989   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2990 
2991   Kind = CK_BitCast;
2992 
2993   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2994       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2995           Expr::NPCK_ZeroExpression) {
2996     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2997       DiagRuntimeBehavior(From->getExprLoc(), From,
2998                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2999                             << ToType << From->getSourceRange());
3000     else if (!isUnevaluatedContext())
3001       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3002         << ToType << From->getSourceRange();
3003   }
3004   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3005     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3006       QualType FromPointeeType = FromPtrType->getPointeeType(),
3007                ToPointeeType   = ToPtrType->getPointeeType();
3008 
3009       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3010           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3011         // We must have a derived-to-base conversion. Check an
3012         // ambiguous or inaccessible conversion.
3013         unsigned InaccessibleID = 0;
3014         unsigned AmbiguousID = 0;
3015         if (Diagnose) {
3016           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3017           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3018         }
3019         if (CheckDerivedToBaseConversion(
3020                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3021                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3022                 &BasePath, IgnoreBaseAccess))
3023           return true;
3024 
3025         // The conversion was successful.
3026         Kind = CK_DerivedToBase;
3027       }
3028 
3029       if (Diagnose && !IsCStyleOrFunctionalCast &&
3030           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3031         assert(getLangOpts().MSVCCompat &&
3032                "this should only be possible with MSVCCompat!");
3033         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3034             << From->getSourceRange();
3035       }
3036     }
3037   } else if (const ObjCObjectPointerType *ToPtrType =
3038                ToType->getAs<ObjCObjectPointerType>()) {
3039     if (const ObjCObjectPointerType *FromPtrType =
3040           FromType->getAs<ObjCObjectPointerType>()) {
3041       // Objective-C++ conversions are always okay.
3042       // FIXME: We should have a different class of conversions for the
3043       // Objective-C++ implicit conversions.
3044       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3045         return false;
3046     } else if (FromType->isBlockPointerType()) {
3047       Kind = CK_BlockPointerToObjCPointerCast;
3048     } else {
3049       Kind = CK_CPointerToObjCPointerCast;
3050     }
3051   } else if (ToType->isBlockPointerType()) {
3052     if (!FromType->isBlockPointerType())
3053       Kind = CK_AnyPointerToBlockPointerCast;
3054   }
3055 
3056   // We shouldn't fall into this case unless it's valid for other
3057   // reasons.
3058   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3059     Kind = CK_NullToPointer;
3060 
3061   return false;
3062 }
3063 
3064 /// IsMemberPointerConversion - Determines whether the conversion of the
3065 /// expression From, which has the (possibly adjusted) type FromType, can be
3066 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3067 /// If so, returns true and places the converted type (that might differ from
3068 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3069 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3070                                      QualType ToType,
3071                                      bool InOverloadResolution,
3072                                      QualType &ConvertedType) {
3073   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3074   if (!ToTypePtr)
3075     return false;
3076 
3077   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3078   if (From->isNullPointerConstant(Context,
3079                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3080                                         : Expr::NPC_ValueDependentIsNull)) {
3081     ConvertedType = ToType;
3082     return true;
3083   }
3084 
3085   // Otherwise, both types have to be member pointers.
3086   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3087   if (!FromTypePtr)
3088     return false;
3089 
3090   // A pointer to member of B can be converted to a pointer to member of D,
3091   // where D is derived from B (C++ 4.11p2).
3092   QualType FromClass(FromTypePtr->getClass(), 0);
3093   QualType ToClass(ToTypePtr->getClass(), 0);
3094 
3095   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3096       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3097     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3098                                                  ToClass.getTypePtr());
3099     return true;
3100   }
3101 
3102   return false;
3103 }
3104 
3105 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3106 /// expression From to the type ToType. This routine checks for ambiguous or
3107 /// virtual or inaccessible base-to-derived member pointer conversions
3108 /// for which IsMemberPointerConversion has already returned true. It returns
3109 /// true and produces a diagnostic if there was an error, or returns false
3110 /// otherwise.
3111 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3112                                         CastKind &Kind,
3113                                         CXXCastPath &BasePath,
3114                                         bool IgnoreBaseAccess) {
3115   QualType FromType = From->getType();
3116   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3117   if (!FromPtrType) {
3118     // This must be a null pointer to member pointer conversion
3119     assert(From->isNullPointerConstant(Context,
3120                                        Expr::NPC_ValueDependentIsNull) &&
3121            "Expr must be null pointer constant!");
3122     Kind = CK_NullToMemberPointer;
3123     return false;
3124   }
3125 
3126   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3127   assert(ToPtrType && "No member pointer cast has a target type "
3128                       "that is not a member pointer.");
3129 
3130   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3131   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3132 
3133   // FIXME: What about dependent types?
3134   assert(FromClass->isRecordType() && "Pointer into non-class.");
3135   assert(ToClass->isRecordType() && "Pointer into non-class.");
3136 
3137   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3138                      /*DetectVirtual=*/true);
3139   bool DerivationOkay =
3140       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3141   assert(DerivationOkay &&
3142          "Should not have been called if derivation isn't OK.");
3143   (void)DerivationOkay;
3144 
3145   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3146                                   getUnqualifiedType())) {
3147     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3148     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3149       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3150     return true;
3151   }
3152 
3153   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3154     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3155       << FromClass << ToClass << QualType(VBase, 0)
3156       << From->getSourceRange();
3157     return true;
3158   }
3159 
3160   if (!IgnoreBaseAccess)
3161     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3162                          Paths.front(),
3163                          diag::err_downcast_from_inaccessible_base);
3164 
3165   // Must be a base to derived member conversion.
3166   BuildBasePathArray(Paths, BasePath);
3167   Kind = CK_BaseToDerivedMemberPointer;
3168   return false;
3169 }
3170 
3171 /// Determine whether the lifetime conversion between the two given
3172 /// qualifiers sets is nontrivial.
3173 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3174                                                Qualifiers ToQuals) {
3175   // Converting anything to const __unsafe_unretained is trivial.
3176   if (ToQuals.hasConst() &&
3177       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3178     return false;
3179 
3180   return true;
3181 }
3182 
3183 /// Perform a single iteration of the loop for checking if a qualification
3184 /// conversion is valid.
3185 ///
3186 /// Specifically, check whether any change between the qualifiers of \p
3187 /// FromType and \p ToType is permissible, given knowledge about whether every
3188 /// outer layer is const-qualified.
3189 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3190                                           bool CStyle, bool IsTopLevel,
3191                                           bool &PreviousToQualsIncludeConst,
3192                                           bool &ObjCLifetimeConversion) {
3193   Qualifiers FromQuals = FromType.getQualifiers();
3194   Qualifiers ToQuals = ToType.getQualifiers();
3195 
3196   // Ignore __unaligned qualifier if this type is void.
3197   if (ToType.getUnqualifiedType()->isVoidType())
3198     FromQuals.removeUnaligned();
3199 
3200   // Objective-C ARC:
3201   //   Check Objective-C lifetime conversions.
3202   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3203     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3204       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3205         ObjCLifetimeConversion = true;
3206       FromQuals.removeObjCLifetime();
3207       ToQuals.removeObjCLifetime();
3208     } else {
3209       // Qualification conversions cannot cast between different
3210       // Objective-C lifetime qualifiers.
3211       return false;
3212     }
3213   }
3214 
3215   // Allow addition/removal of GC attributes but not changing GC attributes.
3216   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3217       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3218     FromQuals.removeObjCGCAttr();
3219     ToQuals.removeObjCGCAttr();
3220   }
3221 
3222   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3223   //      2,j, and similarly for volatile.
3224   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3225     return false;
3226 
3227   // If address spaces mismatch:
3228   //  - in top level it is only valid to convert to addr space that is a
3229   //    superset in all cases apart from C-style casts where we allow
3230   //    conversions between overlapping address spaces.
3231   //  - in non-top levels it is not a valid conversion.
3232   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3233       (!IsTopLevel ||
3234        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3235          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3236     return false;
3237 
3238   //   -- if the cv 1,j and cv 2,j are different, then const is in
3239   //      every cv for 0 < k < j.
3240   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3241       !PreviousToQualsIncludeConst)
3242     return false;
3243 
3244   // Keep track of whether all prior cv-qualifiers in the "to" type
3245   // include const.
3246   PreviousToQualsIncludeConst =
3247       PreviousToQualsIncludeConst && ToQuals.hasConst();
3248   return true;
3249 }
3250 
3251 /// IsQualificationConversion - Determines whether the conversion from
3252 /// an rvalue of type FromType to ToType is a qualification conversion
3253 /// (C++ 4.4).
3254 ///
3255 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3256 /// when the qualification conversion involves a change in the Objective-C
3257 /// object lifetime.
3258 bool
3259 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3260                                 bool CStyle, bool &ObjCLifetimeConversion) {
3261   FromType = Context.getCanonicalType(FromType);
3262   ToType = Context.getCanonicalType(ToType);
3263   ObjCLifetimeConversion = false;
3264 
3265   // If FromType and ToType are the same type, this is not a
3266   // qualification conversion.
3267   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3268     return false;
3269 
3270   // (C++ 4.4p4):
3271   //   A conversion can add cv-qualifiers at levels other than the first
3272   //   in multi-level pointers, subject to the following rules: [...]
3273   bool PreviousToQualsIncludeConst = true;
3274   bool UnwrappedAnyPointer = false;
3275   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3276     if (!isQualificationConversionStep(
3277             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3278             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3279       return false;
3280     UnwrappedAnyPointer = true;
3281   }
3282 
3283   // We are left with FromType and ToType being the pointee types
3284   // after unwrapping the original FromType and ToType the same number
3285   // of times. If we unwrapped any pointers, and if FromType and
3286   // ToType have the same unqualified type (since we checked
3287   // qualifiers above), then this is a qualification conversion.
3288   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3289 }
3290 
3291 /// - Determine whether this is a conversion from a scalar type to an
3292 /// atomic type.
3293 ///
3294 /// If successful, updates \c SCS's second and third steps in the conversion
3295 /// sequence to finish the conversion.
3296 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3297                                 bool InOverloadResolution,
3298                                 StandardConversionSequence &SCS,
3299                                 bool CStyle) {
3300   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3301   if (!ToAtomic)
3302     return false;
3303 
3304   StandardConversionSequence InnerSCS;
3305   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3306                             InOverloadResolution, InnerSCS,
3307                             CStyle, /*AllowObjCWritebackConversion=*/false))
3308     return false;
3309 
3310   SCS.Second = InnerSCS.Second;
3311   SCS.setToType(1, InnerSCS.getToType(1));
3312   SCS.Third = InnerSCS.Third;
3313   SCS.QualificationIncludesObjCLifetime
3314     = InnerSCS.QualificationIncludesObjCLifetime;
3315   SCS.setToType(2, InnerSCS.getToType(2));
3316   return true;
3317 }
3318 
3319 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3320                                               CXXConstructorDecl *Constructor,
3321                                               QualType Type) {
3322   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3323   if (CtorType->getNumParams() > 0) {
3324     QualType FirstArg = CtorType->getParamType(0);
3325     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3326       return true;
3327   }
3328   return false;
3329 }
3330 
3331 static OverloadingResult
3332 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3333                                        CXXRecordDecl *To,
3334                                        UserDefinedConversionSequence &User,
3335                                        OverloadCandidateSet &CandidateSet,
3336                                        bool AllowExplicit) {
3337   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3338   for (auto *D : S.LookupConstructors(To)) {
3339     auto Info = getConstructorInfo(D);
3340     if (!Info)
3341       continue;
3342 
3343     bool Usable = !Info.Constructor->isInvalidDecl() &&
3344                   S.isInitListConstructor(Info.Constructor);
3345     if (Usable) {
3346       // If the first argument is (a reference to) the target type,
3347       // suppress conversions.
3348       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3349           S.Context, Info.Constructor, ToType);
3350       if (Info.ConstructorTmpl)
3351         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3352                                        /*ExplicitArgs*/ nullptr, From,
3353                                        CandidateSet, SuppressUserConversions,
3354                                        /*PartialOverloading*/ false,
3355                                        AllowExplicit);
3356       else
3357         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3358                                CandidateSet, SuppressUserConversions,
3359                                /*PartialOverloading*/ false, AllowExplicit);
3360     }
3361   }
3362 
3363   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3364 
3365   OverloadCandidateSet::iterator Best;
3366   switch (auto Result =
3367               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3368   case OR_Deleted:
3369   case OR_Success: {
3370     // Record the standard conversion we used and the conversion function.
3371     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3372     QualType ThisType = Constructor->getThisType();
3373     // Initializer lists don't have conversions as such.
3374     User.Before.setAsIdentityConversion();
3375     User.HadMultipleCandidates = HadMultipleCandidates;
3376     User.ConversionFunction = Constructor;
3377     User.FoundConversionFunction = Best->FoundDecl;
3378     User.After.setAsIdentityConversion();
3379     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3380     User.After.setAllToTypes(ToType);
3381     return Result;
3382   }
3383 
3384   case OR_No_Viable_Function:
3385     return OR_No_Viable_Function;
3386   case OR_Ambiguous:
3387     return OR_Ambiguous;
3388   }
3389 
3390   llvm_unreachable("Invalid OverloadResult!");
3391 }
3392 
3393 /// Determines whether there is a user-defined conversion sequence
3394 /// (C++ [over.ics.user]) that converts expression From to the type
3395 /// ToType. If such a conversion exists, User will contain the
3396 /// user-defined conversion sequence that performs such a conversion
3397 /// and this routine will return true. Otherwise, this routine returns
3398 /// false and User is unspecified.
3399 ///
3400 /// \param AllowExplicit  true if the conversion should consider C++0x
3401 /// "explicit" conversion functions as well as non-explicit conversion
3402 /// functions (C++0x [class.conv.fct]p2).
3403 ///
3404 /// \param AllowObjCConversionOnExplicit true if the conversion should
3405 /// allow an extra Objective-C pointer conversion on uses of explicit
3406 /// constructors. Requires \c AllowExplicit to also be set.
3407 static OverloadingResult
3408 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3409                         UserDefinedConversionSequence &User,
3410                         OverloadCandidateSet &CandidateSet,
3411                         AllowedExplicit AllowExplicit,
3412                         bool AllowObjCConversionOnExplicit) {
3413   assert(AllowExplicit != AllowedExplicit::None ||
3414          !AllowObjCConversionOnExplicit);
3415   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3416 
3417   // Whether we will only visit constructors.
3418   bool ConstructorsOnly = false;
3419 
3420   // If the type we are conversion to is a class type, enumerate its
3421   // constructors.
3422   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3423     // C++ [over.match.ctor]p1:
3424     //   When objects of class type are direct-initialized (8.5), or
3425     //   copy-initialized from an expression of the same or a
3426     //   derived class type (8.5), overload resolution selects the
3427     //   constructor. [...] For copy-initialization, the candidate
3428     //   functions are all the converting constructors (12.3.1) of
3429     //   that class. The argument list is the expression-list within
3430     //   the parentheses of the initializer.
3431     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3432         (From->getType()->getAs<RecordType>() &&
3433          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3434       ConstructorsOnly = true;
3435 
3436     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3437       // We're not going to find any constructors.
3438     } else if (CXXRecordDecl *ToRecordDecl
3439                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3440 
3441       Expr **Args = &From;
3442       unsigned NumArgs = 1;
3443       bool ListInitializing = false;
3444       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3445         // But first, see if there is an init-list-constructor that will work.
3446         OverloadingResult Result = IsInitializerListConstructorConversion(
3447             S, From, ToType, ToRecordDecl, User, CandidateSet,
3448             AllowExplicit == AllowedExplicit::All);
3449         if (Result != OR_No_Viable_Function)
3450           return Result;
3451         // Never mind.
3452         CandidateSet.clear(
3453             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3454 
3455         // If we're list-initializing, we pass the individual elements as
3456         // arguments, not the entire list.
3457         Args = InitList->getInits();
3458         NumArgs = InitList->getNumInits();
3459         ListInitializing = true;
3460       }
3461 
3462       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3463         auto Info = getConstructorInfo(D);
3464         if (!Info)
3465           continue;
3466 
3467         bool Usable = !Info.Constructor->isInvalidDecl();
3468         if (!ListInitializing)
3469           Usable = Usable && Info.Constructor->isConvertingConstructor(
3470                                  /*AllowExplicit*/ true);
3471         if (Usable) {
3472           bool SuppressUserConversions = !ConstructorsOnly;
3473           if (SuppressUserConversions && ListInitializing) {
3474             SuppressUserConversions = false;
3475             if (NumArgs == 1) {
3476               // If the first argument is (a reference to) the target type,
3477               // suppress conversions.
3478               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3479                   S.Context, Info.Constructor, ToType);
3480             }
3481           }
3482           if (Info.ConstructorTmpl)
3483             S.AddTemplateOverloadCandidate(
3484                 Info.ConstructorTmpl, Info.FoundDecl,
3485                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3486                 CandidateSet, SuppressUserConversions,
3487                 /*PartialOverloading*/ false,
3488                 AllowExplicit == AllowedExplicit::All);
3489           else
3490             // Allow one user-defined conversion when user specifies a
3491             // From->ToType conversion via an static cast (c-style, etc).
3492             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3493                                    llvm::makeArrayRef(Args, NumArgs),
3494                                    CandidateSet, SuppressUserConversions,
3495                                    /*PartialOverloading*/ false,
3496                                    AllowExplicit == AllowedExplicit::All);
3497         }
3498       }
3499     }
3500   }
3501 
3502   // Enumerate conversion functions, if we're allowed to.
3503   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3504   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3505     // No conversion functions from incomplete types.
3506   } else if (const RecordType *FromRecordType =
3507                  From->getType()->getAs<RecordType>()) {
3508     if (CXXRecordDecl *FromRecordDecl
3509          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3510       // Add all of the conversion functions as candidates.
3511       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3512       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3513         DeclAccessPair FoundDecl = I.getPair();
3514         NamedDecl *D = FoundDecl.getDecl();
3515         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3516         if (isa<UsingShadowDecl>(D))
3517           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3518 
3519         CXXConversionDecl *Conv;
3520         FunctionTemplateDecl *ConvTemplate;
3521         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3522           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3523         else
3524           Conv = cast<CXXConversionDecl>(D);
3525 
3526         if (ConvTemplate)
3527           S.AddTemplateConversionCandidate(
3528               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3529               CandidateSet, AllowObjCConversionOnExplicit,
3530               AllowExplicit != AllowedExplicit::None);
3531         else
3532           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3533                                    CandidateSet, AllowObjCConversionOnExplicit,
3534                                    AllowExplicit != AllowedExplicit::None);
3535       }
3536     }
3537   }
3538 
3539   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3540 
3541   OverloadCandidateSet::iterator Best;
3542   switch (auto Result =
3543               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3544   case OR_Success:
3545   case OR_Deleted:
3546     // Record the standard conversion we used and the conversion function.
3547     if (CXXConstructorDecl *Constructor
3548           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3549       // C++ [over.ics.user]p1:
3550       //   If the user-defined conversion is specified by a
3551       //   constructor (12.3.1), the initial standard conversion
3552       //   sequence converts the source type to the type required by
3553       //   the argument of the constructor.
3554       //
3555       QualType ThisType = Constructor->getThisType();
3556       if (isa<InitListExpr>(From)) {
3557         // Initializer lists don't have conversions as such.
3558         User.Before.setAsIdentityConversion();
3559       } else {
3560         if (Best->Conversions[0].isEllipsis())
3561           User.EllipsisConversion = true;
3562         else {
3563           User.Before = Best->Conversions[0].Standard;
3564           User.EllipsisConversion = false;
3565         }
3566       }
3567       User.HadMultipleCandidates = HadMultipleCandidates;
3568       User.ConversionFunction = Constructor;
3569       User.FoundConversionFunction = Best->FoundDecl;
3570       User.After.setAsIdentityConversion();
3571       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3572       User.After.setAllToTypes(ToType);
3573       return Result;
3574     }
3575     if (CXXConversionDecl *Conversion
3576                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3577       // C++ [over.ics.user]p1:
3578       //
3579       //   [...] If the user-defined conversion is specified by a
3580       //   conversion function (12.3.2), the initial standard
3581       //   conversion sequence converts the source type to the
3582       //   implicit object parameter of the conversion function.
3583       User.Before = Best->Conversions[0].Standard;
3584       User.HadMultipleCandidates = HadMultipleCandidates;
3585       User.ConversionFunction = Conversion;
3586       User.FoundConversionFunction = Best->FoundDecl;
3587       User.EllipsisConversion = false;
3588 
3589       // C++ [over.ics.user]p2:
3590       //   The second standard conversion sequence converts the
3591       //   result of the user-defined conversion to the target type
3592       //   for the sequence. Since an implicit conversion sequence
3593       //   is an initialization, the special rules for
3594       //   initialization by user-defined conversion apply when
3595       //   selecting the best user-defined conversion for a
3596       //   user-defined conversion sequence (see 13.3.3 and
3597       //   13.3.3.1).
3598       User.After = Best->FinalConversion;
3599       return Result;
3600     }
3601     llvm_unreachable("Not a constructor or conversion function?");
3602 
3603   case OR_No_Viable_Function:
3604     return OR_No_Viable_Function;
3605 
3606   case OR_Ambiguous:
3607     return OR_Ambiguous;
3608   }
3609 
3610   llvm_unreachable("Invalid OverloadResult!");
3611 }
3612 
3613 bool
3614 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3615   ImplicitConversionSequence ICS;
3616   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3617                                     OverloadCandidateSet::CSK_Normal);
3618   OverloadingResult OvResult =
3619     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3620                             CandidateSet, AllowedExplicit::None, false);
3621 
3622   if (!(OvResult == OR_Ambiguous ||
3623         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3624     return false;
3625 
3626   auto Cands = CandidateSet.CompleteCandidates(
3627       *this,
3628       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3629       From);
3630   if (OvResult == OR_Ambiguous)
3631     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3632         << From->getType() << ToType << From->getSourceRange();
3633   else { // OR_No_Viable_Function && !CandidateSet.empty()
3634     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3635                              diag::err_typecheck_nonviable_condition_incomplete,
3636                              From->getType(), From->getSourceRange()))
3637       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3638           << false << From->getType() << From->getSourceRange() << ToType;
3639   }
3640 
3641   CandidateSet.NoteCandidates(
3642                               *this, From, Cands);
3643   return true;
3644 }
3645 
3646 /// Compare the user-defined conversion functions or constructors
3647 /// of two user-defined conversion sequences to determine whether any ordering
3648 /// is possible.
3649 static ImplicitConversionSequence::CompareKind
3650 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3651                            FunctionDecl *Function2) {
3652   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3653     return ImplicitConversionSequence::Indistinguishable;
3654 
3655   // Objective-C++:
3656   //   If both conversion functions are implicitly-declared conversions from
3657   //   a lambda closure type to a function pointer and a block pointer,
3658   //   respectively, always prefer the conversion to a function pointer,
3659   //   because the function pointer is more lightweight and is more likely
3660   //   to keep code working.
3661   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3662   if (!Conv1)
3663     return ImplicitConversionSequence::Indistinguishable;
3664 
3665   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3666   if (!Conv2)
3667     return ImplicitConversionSequence::Indistinguishable;
3668 
3669   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3670     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3671     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3672     if (Block1 != Block2)
3673       return Block1 ? ImplicitConversionSequence::Worse
3674                     : ImplicitConversionSequence::Better;
3675   }
3676 
3677   return ImplicitConversionSequence::Indistinguishable;
3678 }
3679 
3680 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3681     const ImplicitConversionSequence &ICS) {
3682   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3683          (ICS.isUserDefined() &&
3684           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3685 }
3686 
3687 /// CompareImplicitConversionSequences - Compare two implicit
3688 /// conversion sequences to determine whether one is better than the
3689 /// other or if they are indistinguishable (C++ 13.3.3.2).
3690 static ImplicitConversionSequence::CompareKind
3691 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3692                                    const ImplicitConversionSequence& ICS1,
3693                                    const ImplicitConversionSequence& ICS2)
3694 {
3695   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3696   // conversion sequences (as defined in 13.3.3.1)
3697   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3698   //      conversion sequence than a user-defined conversion sequence or
3699   //      an ellipsis conversion sequence, and
3700   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3701   //      conversion sequence than an ellipsis conversion sequence
3702   //      (13.3.3.1.3).
3703   //
3704   // C++0x [over.best.ics]p10:
3705   //   For the purpose of ranking implicit conversion sequences as
3706   //   described in 13.3.3.2, the ambiguous conversion sequence is
3707   //   treated as a user-defined sequence that is indistinguishable
3708   //   from any other user-defined conversion sequence.
3709 
3710   // String literal to 'char *' conversion has been deprecated in C++03. It has
3711   // been removed from C++11. We still accept this conversion, if it happens at
3712   // the best viable function. Otherwise, this conversion is considered worse
3713   // than ellipsis conversion. Consider this as an extension; this is not in the
3714   // standard. For example:
3715   //
3716   // int &f(...);    // #1
3717   // void f(char*);  // #2
3718   // void g() { int &r = f("foo"); }
3719   //
3720   // In C++03, we pick #2 as the best viable function.
3721   // In C++11, we pick #1 as the best viable function, because ellipsis
3722   // conversion is better than string-literal to char* conversion (since there
3723   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3724   // convert arguments, #2 would be the best viable function in C++11.
3725   // If the best viable function has this conversion, a warning will be issued
3726   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3727 
3728   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3729       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3730       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3731     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3732                ? ImplicitConversionSequence::Worse
3733                : ImplicitConversionSequence::Better;
3734 
3735   if (ICS1.getKindRank() < ICS2.getKindRank())
3736     return ImplicitConversionSequence::Better;
3737   if (ICS2.getKindRank() < ICS1.getKindRank())
3738     return ImplicitConversionSequence::Worse;
3739 
3740   // The following checks require both conversion sequences to be of
3741   // the same kind.
3742   if (ICS1.getKind() != ICS2.getKind())
3743     return ImplicitConversionSequence::Indistinguishable;
3744 
3745   ImplicitConversionSequence::CompareKind Result =
3746       ImplicitConversionSequence::Indistinguishable;
3747 
3748   // Two implicit conversion sequences of the same form are
3749   // indistinguishable conversion sequences unless one of the
3750   // following rules apply: (C++ 13.3.3.2p3):
3751 
3752   // List-initialization sequence L1 is a better conversion sequence than
3753   // list-initialization sequence L2 if:
3754   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3755   //   if not that,
3756   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3757   //   and N1 is smaller than N2.,
3758   // even if one of the other rules in this paragraph would otherwise apply.
3759   if (!ICS1.isBad()) {
3760     if (ICS1.isStdInitializerListElement() &&
3761         !ICS2.isStdInitializerListElement())
3762       return ImplicitConversionSequence::Better;
3763     if (!ICS1.isStdInitializerListElement() &&
3764         ICS2.isStdInitializerListElement())
3765       return ImplicitConversionSequence::Worse;
3766   }
3767 
3768   if (ICS1.isStandard())
3769     // Standard conversion sequence S1 is a better conversion sequence than
3770     // standard conversion sequence S2 if [...]
3771     Result = CompareStandardConversionSequences(S, Loc,
3772                                                 ICS1.Standard, ICS2.Standard);
3773   else if (ICS1.isUserDefined()) {
3774     // User-defined conversion sequence U1 is a better conversion
3775     // sequence than another user-defined conversion sequence U2 if
3776     // they contain the same user-defined conversion function or
3777     // constructor and if the second standard conversion sequence of
3778     // U1 is better than the second standard conversion sequence of
3779     // U2 (C++ 13.3.3.2p3).
3780     if (ICS1.UserDefined.ConversionFunction ==
3781           ICS2.UserDefined.ConversionFunction)
3782       Result = CompareStandardConversionSequences(S, Loc,
3783                                                   ICS1.UserDefined.After,
3784                                                   ICS2.UserDefined.After);
3785     else
3786       Result = compareConversionFunctions(S,
3787                                           ICS1.UserDefined.ConversionFunction,
3788                                           ICS2.UserDefined.ConversionFunction);
3789   }
3790 
3791   return Result;
3792 }
3793 
3794 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3795 // determine if one is a proper subset of the other.
3796 static ImplicitConversionSequence::CompareKind
3797 compareStandardConversionSubsets(ASTContext &Context,
3798                                  const StandardConversionSequence& SCS1,
3799                                  const StandardConversionSequence& SCS2) {
3800   ImplicitConversionSequence::CompareKind Result
3801     = ImplicitConversionSequence::Indistinguishable;
3802 
3803   // the identity conversion sequence is considered to be a subsequence of
3804   // any non-identity conversion sequence
3805   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3806     return ImplicitConversionSequence::Better;
3807   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3808     return ImplicitConversionSequence::Worse;
3809 
3810   if (SCS1.Second != SCS2.Second) {
3811     if (SCS1.Second == ICK_Identity)
3812       Result = ImplicitConversionSequence::Better;
3813     else if (SCS2.Second == ICK_Identity)
3814       Result = ImplicitConversionSequence::Worse;
3815     else
3816       return ImplicitConversionSequence::Indistinguishable;
3817   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3818     return ImplicitConversionSequence::Indistinguishable;
3819 
3820   if (SCS1.Third == SCS2.Third) {
3821     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3822                              : ImplicitConversionSequence::Indistinguishable;
3823   }
3824 
3825   if (SCS1.Third == ICK_Identity)
3826     return Result == ImplicitConversionSequence::Worse
3827              ? ImplicitConversionSequence::Indistinguishable
3828              : ImplicitConversionSequence::Better;
3829 
3830   if (SCS2.Third == ICK_Identity)
3831     return Result == ImplicitConversionSequence::Better
3832              ? ImplicitConversionSequence::Indistinguishable
3833              : ImplicitConversionSequence::Worse;
3834 
3835   return ImplicitConversionSequence::Indistinguishable;
3836 }
3837 
3838 /// Determine whether one of the given reference bindings is better
3839 /// than the other based on what kind of bindings they are.
3840 static bool
3841 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3842                              const StandardConversionSequence &SCS2) {
3843   // C++0x [over.ics.rank]p3b4:
3844   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3845   //      implicit object parameter of a non-static member function declared
3846   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3847   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3848   //      lvalue reference to a function lvalue and S2 binds an rvalue
3849   //      reference*.
3850   //
3851   // FIXME: Rvalue references. We're going rogue with the above edits,
3852   // because the semantics in the current C++0x working paper (N3225 at the
3853   // time of this writing) break the standard definition of std::forward
3854   // and std::reference_wrapper when dealing with references to functions.
3855   // Proposed wording changes submitted to CWG for consideration.
3856   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3857       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3858     return false;
3859 
3860   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3861           SCS2.IsLvalueReference) ||
3862          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3863           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3864 }
3865 
3866 enum class FixedEnumPromotion {
3867   None,
3868   ToUnderlyingType,
3869   ToPromotedUnderlyingType
3870 };
3871 
3872 /// Returns kind of fixed enum promotion the \a SCS uses.
3873 static FixedEnumPromotion
3874 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3875 
3876   if (SCS.Second != ICK_Integral_Promotion)
3877     return FixedEnumPromotion::None;
3878 
3879   QualType FromType = SCS.getFromType();
3880   if (!FromType->isEnumeralType())
3881     return FixedEnumPromotion::None;
3882 
3883   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3884   if (!Enum->isFixed())
3885     return FixedEnumPromotion::None;
3886 
3887   QualType UnderlyingType = Enum->getIntegerType();
3888   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3889     return FixedEnumPromotion::ToUnderlyingType;
3890 
3891   return FixedEnumPromotion::ToPromotedUnderlyingType;
3892 }
3893 
3894 /// CompareStandardConversionSequences - Compare two standard
3895 /// conversion sequences to determine whether one is better than the
3896 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3897 static ImplicitConversionSequence::CompareKind
3898 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3899                                    const StandardConversionSequence& SCS1,
3900                                    const StandardConversionSequence& SCS2)
3901 {
3902   // Standard conversion sequence S1 is a better conversion sequence
3903   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3904 
3905   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3906   //     sequences in the canonical form defined by 13.3.3.1.1,
3907   //     excluding any Lvalue Transformation; the identity conversion
3908   //     sequence is considered to be a subsequence of any
3909   //     non-identity conversion sequence) or, if not that,
3910   if (ImplicitConversionSequence::CompareKind CK
3911         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3912     return CK;
3913 
3914   //  -- the rank of S1 is better than the rank of S2 (by the rules
3915   //     defined below), or, if not that,
3916   ImplicitConversionRank Rank1 = SCS1.getRank();
3917   ImplicitConversionRank Rank2 = SCS2.getRank();
3918   if (Rank1 < Rank2)
3919     return ImplicitConversionSequence::Better;
3920   else if (Rank2 < Rank1)
3921     return ImplicitConversionSequence::Worse;
3922 
3923   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3924   // are indistinguishable unless one of the following rules
3925   // applies:
3926 
3927   //   A conversion that is not a conversion of a pointer, or
3928   //   pointer to member, to bool is better than another conversion
3929   //   that is such a conversion.
3930   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3931     return SCS2.isPointerConversionToBool()
3932              ? ImplicitConversionSequence::Better
3933              : ImplicitConversionSequence::Worse;
3934 
3935   // C++14 [over.ics.rank]p4b2:
3936   // This is retroactively applied to C++11 by CWG 1601.
3937   //
3938   //   A conversion that promotes an enumeration whose underlying type is fixed
3939   //   to its underlying type is better than one that promotes to the promoted
3940   //   underlying type, if the two are different.
3941   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3942   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3943   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3944       FEP1 != FEP2)
3945     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3946                ? ImplicitConversionSequence::Better
3947                : ImplicitConversionSequence::Worse;
3948 
3949   // C++ [over.ics.rank]p4b2:
3950   //
3951   //   If class B is derived directly or indirectly from class A,
3952   //   conversion of B* to A* is better than conversion of B* to
3953   //   void*, and conversion of A* to void* is better than conversion
3954   //   of B* to void*.
3955   bool SCS1ConvertsToVoid
3956     = SCS1.isPointerConversionToVoidPointer(S.Context);
3957   bool SCS2ConvertsToVoid
3958     = SCS2.isPointerConversionToVoidPointer(S.Context);
3959   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3960     // Exactly one of the conversion sequences is a conversion to
3961     // a void pointer; it's the worse conversion.
3962     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3963                               : ImplicitConversionSequence::Worse;
3964   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3965     // Neither conversion sequence converts to a void pointer; compare
3966     // their derived-to-base conversions.
3967     if (ImplicitConversionSequence::CompareKind DerivedCK
3968           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3969       return DerivedCK;
3970   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3971              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3972     // Both conversion sequences are conversions to void
3973     // pointers. Compare the source types to determine if there's an
3974     // inheritance relationship in their sources.
3975     QualType FromType1 = SCS1.getFromType();
3976     QualType FromType2 = SCS2.getFromType();
3977 
3978     // Adjust the types we're converting from via the array-to-pointer
3979     // conversion, if we need to.
3980     if (SCS1.First == ICK_Array_To_Pointer)
3981       FromType1 = S.Context.getArrayDecayedType(FromType1);
3982     if (SCS2.First == ICK_Array_To_Pointer)
3983       FromType2 = S.Context.getArrayDecayedType(FromType2);
3984 
3985     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3986     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3987 
3988     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3989       return ImplicitConversionSequence::Better;
3990     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3991       return ImplicitConversionSequence::Worse;
3992 
3993     // Objective-C++: If one interface is more specific than the
3994     // other, it is the better one.
3995     const ObjCObjectPointerType* FromObjCPtr1
3996       = FromType1->getAs<ObjCObjectPointerType>();
3997     const ObjCObjectPointerType* FromObjCPtr2
3998       = FromType2->getAs<ObjCObjectPointerType>();
3999     if (FromObjCPtr1 && FromObjCPtr2) {
4000       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4001                                                           FromObjCPtr2);
4002       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4003                                                            FromObjCPtr1);
4004       if (AssignLeft != AssignRight) {
4005         return AssignLeft? ImplicitConversionSequence::Better
4006                          : ImplicitConversionSequence::Worse;
4007       }
4008     }
4009   }
4010 
4011   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4012     // Check for a better reference binding based on the kind of bindings.
4013     if (isBetterReferenceBindingKind(SCS1, SCS2))
4014       return ImplicitConversionSequence::Better;
4015     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4016       return ImplicitConversionSequence::Worse;
4017   }
4018 
4019   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4020   // bullet 3).
4021   if (ImplicitConversionSequence::CompareKind QualCK
4022         = CompareQualificationConversions(S, SCS1, SCS2))
4023     return QualCK;
4024 
4025   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4026     // C++ [over.ics.rank]p3b4:
4027     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4028     //      which the references refer are the same type except for
4029     //      top-level cv-qualifiers, and the type to which the reference
4030     //      initialized by S2 refers is more cv-qualified than the type
4031     //      to which the reference initialized by S1 refers.
4032     QualType T1 = SCS1.getToType(2);
4033     QualType T2 = SCS2.getToType(2);
4034     T1 = S.Context.getCanonicalType(T1);
4035     T2 = S.Context.getCanonicalType(T2);
4036     Qualifiers T1Quals, T2Quals;
4037     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4038     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4039     if (UnqualT1 == UnqualT2) {
4040       // Objective-C++ ARC: If the references refer to objects with different
4041       // lifetimes, prefer bindings that don't change lifetime.
4042       if (SCS1.ObjCLifetimeConversionBinding !=
4043                                           SCS2.ObjCLifetimeConversionBinding) {
4044         return SCS1.ObjCLifetimeConversionBinding
4045                                            ? ImplicitConversionSequence::Worse
4046                                            : ImplicitConversionSequence::Better;
4047       }
4048 
4049       // If the type is an array type, promote the element qualifiers to the
4050       // type for comparison.
4051       if (isa<ArrayType>(T1) && T1Quals)
4052         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4053       if (isa<ArrayType>(T2) && T2Quals)
4054         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4055       if (T2.isMoreQualifiedThan(T1))
4056         return ImplicitConversionSequence::Better;
4057       if (T1.isMoreQualifiedThan(T2))
4058         return ImplicitConversionSequence::Worse;
4059     }
4060   }
4061 
4062   // In Microsoft mode, prefer an integral conversion to a
4063   // floating-to-integral conversion if the integral conversion
4064   // is between types of the same size.
4065   // For example:
4066   // void f(float);
4067   // void f(int);
4068   // int main {
4069   //    long a;
4070   //    f(a);
4071   // }
4072   // Here, MSVC will call f(int) instead of generating a compile error
4073   // as clang will do in standard mode.
4074   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4075       SCS2.Second == ICK_Floating_Integral &&
4076       S.Context.getTypeSize(SCS1.getFromType()) ==
4077           S.Context.getTypeSize(SCS1.getToType(2)))
4078     return ImplicitConversionSequence::Better;
4079 
4080   // Prefer a compatible vector conversion over a lax vector conversion
4081   // For example:
4082   //
4083   // typedef float __v4sf __attribute__((__vector_size__(16)));
4084   // void f(vector float);
4085   // void f(vector signed int);
4086   // int main() {
4087   //   __v4sf a;
4088   //   f(a);
4089   // }
4090   // Here, we'd like to choose f(vector float) and not
4091   // report an ambiguous call error
4092   if (SCS1.Second == ICK_Vector_Conversion &&
4093       SCS2.Second == ICK_Vector_Conversion) {
4094     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4095         SCS1.getFromType(), SCS1.getToType(2));
4096     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4097         SCS2.getFromType(), SCS2.getToType(2));
4098 
4099     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4100       return SCS1IsCompatibleVectorConversion
4101                  ? ImplicitConversionSequence::Better
4102                  : ImplicitConversionSequence::Worse;
4103   }
4104 
4105   return ImplicitConversionSequence::Indistinguishable;
4106 }
4107 
4108 /// CompareQualificationConversions - Compares two standard conversion
4109 /// sequences to determine whether they can be ranked based on their
4110 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4111 static ImplicitConversionSequence::CompareKind
4112 CompareQualificationConversions(Sema &S,
4113                                 const StandardConversionSequence& SCS1,
4114                                 const StandardConversionSequence& SCS2) {
4115   // C++ 13.3.3.2p3:
4116   //  -- S1 and S2 differ only in their qualification conversion and
4117   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4118   //     cv-qualification signature of type T1 is a proper subset of
4119   //     the cv-qualification signature of type T2, and S1 is not the
4120   //     deprecated string literal array-to-pointer conversion (4.2).
4121   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4122       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4123     return ImplicitConversionSequence::Indistinguishable;
4124 
4125   // FIXME: the example in the standard doesn't use a qualification
4126   // conversion (!)
4127   QualType T1 = SCS1.getToType(2);
4128   QualType T2 = SCS2.getToType(2);
4129   T1 = S.Context.getCanonicalType(T1);
4130   T2 = S.Context.getCanonicalType(T2);
4131   assert(!T1->isReferenceType() && !T2->isReferenceType());
4132   Qualifiers T1Quals, T2Quals;
4133   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4134   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4135 
4136   // If the types are the same, we won't learn anything by unwrapping
4137   // them.
4138   if (UnqualT1 == UnqualT2)
4139     return ImplicitConversionSequence::Indistinguishable;
4140 
4141   ImplicitConversionSequence::CompareKind Result
4142     = ImplicitConversionSequence::Indistinguishable;
4143 
4144   // Objective-C++ ARC:
4145   //   Prefer qualification conversions not involving a change in lifetime
4146   //   to qualification conversions that do not change lifetime.
4147   if (SCS1.QualificationIncludesObjCLifetime !=
4148                                       SCS2.QualificationIncludesObjCLifetime) {
4149     Result = SCS1.QualificationIncludesObjCLifetime
4150                ? ImplicitConversionSequence::Worse
4151                : ImplicitConversionSequence::Better;
4152   }
4153 
4154   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4155     // Within each iteration of the loop, we check the qualifiers to
4156     // determine if this still looks like a qualification
4157     // conversion. Then, if all is well, we unwrap one more level of
4158     // pointers or pointers-to-members and do it all again
4159     // until there are no more pointers or pointers-to-members left
4160     // to unwrap. This essentially mimics what
4161     // IsQualificationConversion does, but here we're checking for a
4162     // strict subset of qualifiers.
4163     if (T1.getQualifiers().withoutObjCLifetime() ==
4164         T2.getQualifiers().withoutObjCLifetime())
4165       // The qualifiers are the same, so this doesn't tell us anything
4166       // about how the sequences rank.
4167       // ObjC ownership quals are omitted above as they interfere with
4168       // the ARC overload rule.
4169       ;
4170     else if (T2.isMoreQualifiedThan(T1)) {
4171       // T1 has fewer qualifiers, so it could be the better sequence.
4172       if (Result == ImplicitConversionSequence::Worse)
4173         // Neither has qualifiers that are a subset of the other's
4174         // qualifiers.
4175         return ImplicitConversionSequence::Indistinguishable;
4176 
4177       Result = ImplicitConversionSequence::Better;
4178     } else if (T1.isMoreQualifiedThan(T2)) {
4179       // T2 has fewer qualifiers, so it could be the better sequence.
4180       if (Result == ImplicitConversionSequence::Better)
4181         // Neither has qualifiers that are a subset of the other's
4182         // qualifiers.
4183         return ImplicitConversionSequence::Indistinguishable;
4184 
4185       Result = ImplicitConversionSequence::Worse;
4186     } else {
4187       // Qualifiers are disjoint.
4188       return ImplicitConversionSequence::Indistinguishable;
4189     }
4190 
4191     // If the types after this point are equivalent, we're done.
4192     if (S.Context.hasSameUnqualifiedType(T1, T2))
4193       break;
4194   }
4195 
4196   // Check that the winning standard conversion sequence isn't using
4197   // the deprecated string literal array to pointer conversion.
4198   switch (Result) {
4199   case ImplicitConversionSequence::Better:
4200     if (SCS1.DeprecatedStringLiteralToCharPtr)
4201       Result = ImplicitConversionSequence::Indistinguishable;
4202     break;
4203 
4204   case ImplicitConversionSequence::Indistinguishable:
4205     break;
4206 
4207   case ImplicitConversionSequence::Worse:
4208     if (SCS2.DeprecatedStringLiteralToCharPtr)
4209       Result = ImplicitConversionSequence::Indistinguishable;
4210     break;
4211   }
4212 
4213   return Result;
4214 }
4215 
4216 /// CompareDerivedToBaseConversions - Compares two standard conversion
4217 /// sequences to determine whether they can be ranked based on their
4218 /// various kinds of derived-to-base conversions (C++
4219 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4220 /// conversions between Objective-C interface types.
4221 static ImplicitConversionSequence::CompareKind
4222 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4223                                 const StandardConversionSequence& SCS1,
4224                                 const StandardConversionSequence& SCS2) {
4225   QualType FromType1 = SCS1.getFromType();
4226   QualType ToType1 = SCS1.getToType(1);
4227   QualType FromType2 = SCS2.getFromType();
4228   QualType ToType2 = SCS2.getToType(1);
4229 
4230   // Adjust the types we're converting from via the array-to-pointer
4231   // conversion, if we need to.
4232   if (SCS1.First == ICK_Array_To_Pointer)
4233     FromType1 = S.Context.getArrayDecayedType(FromType1);
4234   if (SCS2.First == ICK_Array_To_Pointer)
4235     FromType2 = S.Context.getArrayDecayedType(FromType2);
4236 
4237   // Canonicalize all of the types.
4238   FromType1 = S.Context.getCanonicalType(FromType1);
4239   ToType1 = S.Context.getCanonicalType(ToType1);
4240   FromType2 = S.Context.getCanonicalType(FromType2);
4241   ToType2 = S.Context.getCanonicalType(ToType2);
4242 
4243   // C++ [over.ics.rank]p4b3:
4244   //
4245   //   If class B is derived directly or indirectly from class A and
4246   //   class C is derived directly or indirectly from B,
4247   //
4248   // Compare based on pointer conversions.
4249   if (SCS1.Second == ICK_Pointer_Conversion &&
4250       SCS2.Second == ICK_Pointer_Conversion &&
4251       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4252       FromType1->isPointerType() && FromType2->isPointerType() &&
4253       ToType1->isPointerType() && ToType2->isPointerType()) {
4254     QualType FromPointee1 =
4255         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4256     QualType ToPointee1 =
4257         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4258     QualType FromPointee2 =
4259         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4260     QualType ToPointee2 =
4261         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4262 
4263     //   -- conversion of C* to B* is better than conversion of C* to A*,
4264     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4265       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4266         return ImplicitConversionSequence::Better;
4267       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4268         return ImplicitConversionSequence::Worse;
4269     }
4270 
4271     //   -- conversion of B* to A* is better than conversion of C* to A*,
4272     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4273       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4274         return ImplicitConversionSequence::Better;
4275       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4276         return ImplicitConversionSequence::Worse;
4277     }
4278   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4279              SCS2.Second == ICK_Pointer_Conversion) {
4280     const ObjCObjectPointerType *FromPtr1
4281       = FromType1->getAs<ObjCObjectPointerType>();
4282     const ObjCObjectPointerType *FromPtr2
4283       = FromType2->getAs<ObjCObjectPointerType>();
4284     const ObjCObjectPointerType *ToPtr1
4285       = ToType1->getAs<ObjCObjectPointerType>();
4286     const ObjCObjectPointerType *ToPtr2
4287       = ToType2->getAs<ObjCObjectPointerType>();
4288 
4289     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4290       // Apply the same conversion ranking rules for Objective-C pointer types
4291       // that we do for C++ pointers to class types. However, we employ the
4292       // Objective-C pseudo-subtyping relationship used for assignment of
4293       // Objective-C pointer types.
4294       bool FromAssignLeft
4295         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4296       bool FromAssignRight
4297         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4298       bool ToAssignLeft
4299         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4300       bool ToAssignRight
4301         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4302 
4303       // A conversion to an a non-id object pointer type or qualified 'id'
4304       // type is better than a conversion to 'id'.
4305       if (ToPtr1->isObjCIdType() &&
4306           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4307         return ImplicitConversionSequence::Worse;
4308       if (ToPtr2->isObjCIdType() &&
4309           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4310         return ImplicitConversionSequence::Better;
4311 
4312       // A conversion to a non-id object pointer type is better than a
4313       // conversion to a qualified 'id' type
4314       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4315         return ImplicitConversionSequence::Worse;
4316       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4317         return ImplicitConversionSequence::Better;
4318 
4319       // A conversion to an a non-Class object pointer type or qualified 'Class'
4320       // type is better than a conversion to 'Class'.
4321       if (ToPtr1->isObjCClassType() &&
4322           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4323         return ImplicitConversionSequence::Worse;
4324       if (ToPtr2->isObjCClassType() &&
4325           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4326         return ImplicitConversionSequence::Better;
4327 
4328       // A conversion to a non-Class object pointer type is better than a
4329       // conversion to a qualified 'Class' type.
4330       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4331         return ImplicitConversionSequence::Worse;
4332       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4333         return ImplicitConversionSequence::Better;
4334 
4335       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4336       if (S.Context.hasSameType(FromType1, FromType2) &&
4337           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4338           (ToAssignLeft != ToAssignRight)) {
4339         if (FromPtr1->isSpecialized()) {
4340           // "conversion of B<A> * to B * is better than conversion of B * to
4341           // C *.
4342           bool IsFirstSame =
4343               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4344           bool IsSecondSame =
4345               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4346           if (IsFirstSame) {
4347             if (!IsSecondSame)
4348               return ImplicitConversionSequence::Better;
4349           } else if (IsSecondSame)
4350             return ImplicitConversionSequence::Worse;
4351         }
4352         return ToAssignLeft? ImplicitConversionSequence::Worse
4353                            : ImplicitConversionSequence::Better;
4354       }
4355 
4356       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4357       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4358           (FromAssignLeft != FromAssignRight))
4359         return FromAssignLeft? ImplicitConversionSequence::Better
4360         : ImplicitConversionSequence::Worse;
4361     }
4362   }
4363 
4364   // Ranking of member-pointer types.
4365   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4366       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4367       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4368     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4369     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4370     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4371     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4372     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4373     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4374     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4375     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4376     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4377     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4378     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4379     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4380     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4381     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4382       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4383         return ImplicitConversionSequence::Worse;
4384       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4385         return ImplicitConversionSequence::Better;
4386     }
4387     // conversion of B::* to C::* is better than conversion of A::* to C::*
4388     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4389       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4390         return ImplicitConversionSequence::Better;
4391       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4392         return ImplicitConversionSequence::Worse;
4393     }
4394   }
4395 
4396   if (SCS1.Second == ICK_Derived_To_Base) {
4397     //   -- conversion of C to B is better than conversion of C to A,
4398     //   -- binding of an expression of type C to a reference of type
4399     //      B& is better than binding an expression of type C to a
4400     //      reference of type A&,
4401     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4402         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4403       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4404         return ImplicitConversionSequence::Better;
4405       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4406         return ImplicitConversionSequence::Worse;
4407     }
4408 
4409     //   -- conversion of B to A is better than conversion of C to A.
4410     //   -- binding of an expression of type B to a reference of type
4411     //      A& is better than binding an expression of type C to a
4412     //      reference of type A&,
4413     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4414         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4415       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4416         return ImplicitConversionSequence::Better;
4417       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4418         return ImplicitConversionSequence::Worse;
4419     }
4420   }
4421 
4422   return ImplicitConversionSequence::Indistinguishable;
4423 }
4424 
4425 /// Determine whether the given type is valid, e.g., it is not an invalid
4426 /// C++ class.
4427 static bool isTypeValid(QualType T) {
4428   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4429     return !Record->isInvalidDecl();
4430 
4431   return true;
4432 }
4433 
4434 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4435   if (!T.getQualifiers().hasUnaligned())
4436     return T;
4437 
4438   Qualifiers Q;
4439   T = Ctx.getUnqualifiedArrayType(T, Q);
4440   Q.removeUnaligned();
4441   return Ctx.getQualifiedType(T, Q);
4442 }
4443 
4444 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4445 /// determine whether they are reference-compatible,
4446 /// reference-related, or incompatible, for use in C++ initialization by
4447 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4448 /// type, and the first type (T1) is the pointee type of the reference
4449 /// type being initialized.
4450 Sema::ReferenceCompareResult
4451 Sema::CompareReferenceRelationship(SourceLocation Loc,
4452                                    QualType OrigT1, QualType OrigT2,
4453                                    ReferenceConversions *ConvOut) {
4454   assert(!OrigT1->isReferenceType() &&
4455     "T1 must be the pointee type of the reference type");
4456   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4457 
4458   QualType T1 = Context.getCanonicalType(OrigT1);
4459   QualType T2 = Context.getCanonicalType(OrigT2);
4460   Qualifiers T1Quals, T2Quals;
4461   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4462   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4463 
4464   ReferenceConversions ConvTmp;
4465   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4466   Conv = ReferenceConversions();
4467 
4468   // C++2a [dcl.init.ref]p4:
4469   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4470   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4471   //   T1 is a base class of T2.
4472   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4473   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4474   //   "pointer to cv1 T1" via a standard conversion sequence.
4475 
4476   // Check for standard conversions we can apply to pointers: derived-to-base
4477   // conversions, ObjC pointer conversions, and function pointer conversions.
4478   // (Qualification conversions are checked last.)
4479   QualType ConvertedT2;
4480   if (UnqualT1 == UnqualT2) {
4481     // Nothing to do.
4482   } else if (isCompleteType(Loc, OrigT2) &&
4483              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4484              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4485     Conv |= ReferenceConversions::DerivedToBase;
4486   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4487            UnqualT2->isObjCObjectOrInterfaceType() &&
4488            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4489     Conv |= ReferenceConversions::ObjC;
4490   else if (UnqualT2->isFunctionType() &&
4491            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4492     Conv |= ReferenceConversions::Function;
4493     // No need to check qualifiers; function types don't have them.
4494     return Ref_Compatible;
4495   }
4496   bool ConvertedReferent = Conv != 0;
4497 
4498   // We can have a qualification conversion. Compute whether the types are
4499   // similar at the same time.
4500   bool PreviousToQualsIncludeConst = true;
4501   bool TopLevel = true;
4502   do {
4503     if (T1 == T2)
4504       break;
4505 
4506     // We will need a qualification conversion.
4507     Conv |= ReferenceConversions::Qualification;
4508 
4509     // Track whether we performed a qualification conversion anywhere other
4510     // than the top level. This matters for ranking reference bindings in
4511     // overload resolution.
4512     if (!TopLevel)
4513       Conv |= ReferenceConversions::NestedQualification;
4514 
4515     // MS compiler ignores __unaligned qualifier for references; do the same.
4516     T1 = withoutUnaligned(Context, T1);
4517     T2 = withoutUnaligned(Context, T2);
4518 
4519     // If we find a qualifier mismatch, the types are not reference-compatible,
4520     // but are still be reference-related if they're similar.
4521     bool ObjCLifetimeConversion = false;
4522     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4523                                        PreviousToQualsIncludeConst,
4524                                        ObjCLifetimeConversion))
4525       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4526                  ? Ref_Related
4527                  : Ref_Incompatible;
4528 
4529     // FIXME: Should we track this for any level other than the first?
4530     if (ObjCLifetimeConversion)
4531       Conv |= ReferenceConversions::ObjCLifetime;
4532 
4533     TopLevel = false;
4534   } while (Context.UnwrapSimilarTypes(T1, T2));
4535 
4536   // At this point, if the types are reference-related, we must either have the
4537   // same inner type (ignoring qualifiers), or must have already worked out how
4538   // to convert the referent.
4539   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4540              ? Ref_Compatible
4541              : Ref_Incompatible;
4542 }
4543 
4544 /// Look for a user-defined conversion to a value reference-compatible
4545 ///        with DeclType. Return true if something definite is found.
4546 static bool
4547 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4548                          QualType DeclType, SourceLocation DeclLoc,
4549                          Expr *Init, QualType T2, bool AllowRvalues,
4550                          bool AllowExplicit) {
4551   assert(T2->isRecordType() && "Can only find conversions of record types.");
4552   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4553 
4554   OverloadCandidateSet CandidateSet(
4555       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4556   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4557   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4558     NamedDecl *D = *I;
4559     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4560     if (isa<UsingShadowDecl>(D))
4561       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4562 
4563     FunctionTemplateDecl *ConvTemplate
4564       = dyn_cast<FunctionTemplateDecl>(D);
4565     CXXConversionDecl *Conv;
4566     if (ConvTemplate)
4567       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4568     else
4569       Conv = cast<CXXConversionDecl>(D);
4570 
4571     if (AllowRvalues) {
4572       // If we are initializing an rvalue reference, don't permit conversion
4573       // functions that return lvalues.
4574       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4575         const ReferenceType *RefType
4576           = Conv->getConversionType()->getAs<LValueReferenceType>();
4577         if (RefType && !RefType->getPointeeType()->isFunctionType())
4578           continue;
4579       }
4580 
4581       if (!ConvTemplate &&
4582           S.CompareReferenceRelationship(
4583               DeclLoc,
4584               Conv->getConversionType()
4585                   .getNonReferenceType()
4586                   .getUnqualifiedType(),
4587               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4588               Sema::Ref_Incompatible)
4589         continue;
4590     } else {
4591       // If the conversion function doesn't return a reference type,
4592       // it can't be considered for this conversion. An rvalue reference
4593       // is only acceptable if its referencee is a function type.
4594 
4595       const ReferenceType *RefType =
4596         Conv->getConversionType()->getAs<ReferenceType>();
4597       if (!RefType ||
4598           (!RefType->isLValueReferenceType() &&
4599            !RefType->getPointeeType()->isFunctionType()))
4600         continue;
4601     }
4602 
4603     if (ConvTemplate)
4604       S.AddTemplateConversionCandidate(
4605           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4606           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4607     else
4608       S.AddConversionCandidate(
4609           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4610           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4611   }
4612 
4613   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4614 
4615   OverloadCandidateSet::iterator Best;
4616   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4617   case OR_Success:
4618     // C++ [over.ics.ref]p1:
4619     //
4620     //   [...] If the parameter binds directly to the result of
4621     //   applying a conversion function to the argument
4622     //   expression, the implicit conversion sequence is a
4623     //   user-defined conversion sequence (13.3.3.1.2), with the
4624     //   second standard conversion sequence either an identity
4625     //   conversion or, if the conversion function returns an
4626     //   entity of a type that is a derived class of the parameter
4627     //   type, a derived-to-base Conversion.
4628     if (!Best->FinalConversion.DirectBinding)
4629       return false;
4630 
4631     ICS.setUserDefined();
4632     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4633     ICS.UserDefined.After = Best->FinalConversion;
4634     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4635     ICS.UserDefined.ConversionFunction = Best->Function;
4636     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4637     ICS.UserDefined.EllipsisConversion = false;
4638     assert(ICS.UserDefined.After.ReferenceBinding &&
4639            ICS.UserDefined.After.DirectBinding &&
4640            "Expected a direct reference binding!");
4641     return true;
4642 
4643   case OR_Ambiguous:
4644     ICS.setAmbiguous();
4645     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4646          Cand != CandidateSet.end(); ++Cand)
4647       if (Cand->Best)
4648         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4649     return true;
4650 
4651   case OR_No_Viable_Function:
4652   case OR_Deleted:
4653     // There was no suitable conversion, or we found a deleted
4654     // conversion; continue with other checks.
4655     return false;
4656   }
4657 
4658   llvm_unreachable("Invalid OverloadResult!");
4659 }
4660 
4661 /// Compute an implicit conversion sequence for reference
4662 /// initialization.
4663 static ImplicitConversionSequence
4664 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4665                  SourceLocation DeclLoc,
4666                  bool SuppressUserConversions,
4667                  bool AllowExplicit) {
4668   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4669 
4670   // Most paths end in a failed conversion.
4671   ImplicitConversionSequence ICS;
4672   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4673 
4674   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4675   QualType T2 = Init->getType();
4676 
4677   // If the initializer is the address of an overloaded function, try
4678   // to resolve the overloaded function. If all goes well, T2 is the
4679   // type of the resulting function.
4680   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4681     DeclAccessPair Found;
4682     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4683                                                                 false, Found))
4684       T2 = Fn->getType();
4685   }
4686 
4687   // Compute some basic properties of the types and the initializer.
4688   bool isRValRef = DeclType->isRValueReferenceType();
4689   Expr::Classification InitCategory = Init->Classify(S.Context);
4690 
4691   Sema::ReferenceConversions RefConv;
4692   Sema::ReferenceCompareResult RefRelationship =
4693       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4694 
4695   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4696     ICS.setStandard();
4697     ICS.Standard.First = ICK_Identity;
4698     // FIXME: A reference binding can be a function conversion too. We should
4699     // consider that when ordering reference-to-function bindings.
4700     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4701                               ? ICK_Derived_To_Base
4702                               : (RefConv & Sema::ReferenceConversions::ObjC)
4703                                     ? ICK_Compatible_Conversion
4704                                     : ICK_Identity;
4705     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4706     // a reference binding that performs a non-top-level qualification
4707     // conversion as a qualification conversion, not as an identity conversion.
4708     ICS.Standard.Third = (RefConv &
4709                               Sema::ReferenceConversions::NestedQualification)
4710                              ? ICK_Qualification
4711                              : ICK_Identity;
4712     ICS.Standard.setFromType(T2);
4713     ICS.Standard.setToType(0, T2);
4714     ICS.Standard.setToType(1, T1);
4715     ICS.Standard.setToType(2, T1);
4716     ICS.Standard.ReferenceBinding = true;
4717     ICS.Standard.DirectBinding = BindsDirectly;
4718     ICS.Standard.IsLvalueReference = !isRValRef;
4719     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4720     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4721     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4722     ICS.Standard.ObjCLifetimeConversionBinding =
4723         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4724     ICS.Standard.CopyConstructor = nullptr;
4725     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4726   };
4727 
4728   // C++0x [dcl.init.ref]p5:
4729   //   A reference to type "cv1 T1" is initialized by an expression
4730   //   of type "cv2 T2" as follows:
4731 
4732   //     -- If reference is an lvalue reference and the initializer expression
4733   if (!isRValRef) {
4734     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4735     //        reference-compatible with "cv2 T2," or
4736     //
4737     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4738     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4739       // C++ [over.ics.ref]p1:
4740       //   When a parameter of reference type binds directly (8.5.3)
4741       //   to an argument expression, the implicit conversion sequence
4742       //   is the identity conversion, unless the argument expression
4743       //   has a type that is a derived class of the parameter type,
4744       //   in which case the implicit conversion sequence is a
4745       //   derived-to-base Conversion (13.3.3.1).
4746       SetAsReferenceBinding(/*BindsDirectly=*/true);
4747 
4748       // Nothing more to do: the inaccessibility/ambiguity check for
4749       // derived-to-base conversions is suppressed when we're
4750       // computing the implicit conversion sequence (C++
4751       // [over.best.ics]p2).
4752       return ICS;
4753     }
4754 
4755     //       -- has a class type (i.e., T2 is a class type), where T1 is
4756     //          not reference-related to T2, and can be implicitly
4757     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4758     //          is reference-compatible with "cv3 T3" 92) (this
4759     //          conversion is selected by enumerating the applicable
4760     //          conversion functions (13.3.1.6) and choosing the best
4761     //          one through overload resolution (13.3)),
4762     if (!SuppressUserConversions && T2->isRecordType() &&
4763         S.isCompleteType(DeclLoc, T2) &&
4764         RefRelationship == Sema::Ref_Incompatible) {
4765       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4766                                    Init, T2, /*AllowRvalues=*/false,
4767                                    AllowExplicit))
4768         return ICS;
4769     }
4770   }
4771 
4772   //     -- Otherwise, the reference shall be an lvalue reference to a
4773   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4774   //        shall be an rvalue reference.
4775   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4776     return ICS;
4777 
4778   //       -- If the initializer expression
4779   //
4780   //            -- is an xvalue, class prvalue, array prvalue or function
4781   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4782   if (RefRelationship == Sema::Ref_Compatible &&
4783       (InitCategory.isXValue() ||
4784        (InitCategory.isPRValue() &&
4785           (T2->isRecordType() || T2->isArrayType())) ||
4786        (InitCategory.isLValue() && T2->isFunctionType()))) {
4787     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4788     // binding unless we're binding to a class prvalue.
4789     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4790     // allow the use of rvalue references in C++98/03 for the benefit of
4791     // standard library implementors; therefore, we need the xvalue check here.
4792     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4793                           !(InitCategory.isPRValue() || T2->isRecordType()));
4794     return ICS;
4795   }
4796 
4797   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4798   //               reference-related to T2, and can be implicitly converted to
4799   //               an xvalue, class prvalue, or function lvalue of type
4800   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4801   //               "cv3 T3",
4802   //
4803   //          then the reference is bound to the value of the initializer
4804   //          expression in the first case and to the result of the conversion
4805   //          in the second case (or, in either case, to an appropriate base
4806   //          class subobject).
4807   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4808       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4809       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4810                                Init, T2, /*AllowRvalues=*/true,
4811                                AllowExplicit)) {
4812     // In the second case, if the reference is an rvalue reference
4813     // and the second standard conversion sequence of the
4814     // user-defined conversion sequence includes an lvalue-to-rvalue
4815     // conversion, the program is ill-formed.
4816     if (ICS.isUserDefined() && isRValRef &&
4817         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4818       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4819 
4820     return ICS;
4821   }
4822 
4823   // A temporary of function type cannot be created; don't even try.
4824   if (T1->isFunctionType())
4825     return ICS;
4826 
4827   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4828   //          initialized from the initializer expression using the
4829   //          rules for a non-reference copy initialization (8.5). The
4830   //          reference is then bound to the temporary. If T1 is
4831   //          reference-related to T2, cv1 must be the same
4832   //          cv-qualification as, or greater cv-qualification than,
4833   //          cv2; otherwise, the program is ill-formed.
4834   if (RefRelationship == Sema::Ref_Related) {
4835     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4836     // we would be reference-compatible or reference-compatible with
4837     // added qualification. But that wasn't the case, so the reference
4838     // initialization fails.
4839     //
4840     // Note that we only want to check address spaces and cvr-qualifiers here.
4841     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4842     Qualifiers T1Quals = T1.getQualifiers();
4843     Qualifiers T2Quals = T2.getQualifiers();
4844     T1Quals.removeObjCGCAttr();
4845     T1Quals.removeObjCLifetime();
4846     T2Quals.removeObjCGCAttr();
4847     T2Quals.removeObjCLifetime();
4848     // MS compiler ignores __unaligned qualifier for references; do the same.
4849     T1Quals.removeUnaligned();
4850     T2Quals.removeUnaligned();
4851     if (!T1Quals.compatiblyIncludes(T2Quals))
4852       return ICS;
4853   }
4854 
4855   // If at least one of the types is a class type, the types are not
4856   // related, and we aren't allowed any user conversions, the
4857   // reference binding fails. This case is important for breaking
4858   // recursion, since TryImplicitConversion below will attempt to
4859   // create a temporary through the use of a copy constructor.
4860   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4861       (T1->isRecordType() || T2->isRecordType()))
4862     return ICS;
4863 
4864   // If T1 is reference-related to T2 and the reference is an rvalue
4865   // reference, the initializer expression shall not be an lvalue.
4866   if (RefRelationship >= Sema::Ref_Related &&
4867       isRValRef && Init->Classify(S.Context).isLValue())
4868     return ICS;
4869 
4870   // C++ [over.ics.ref]p2:
4871   //   When a parameter of reference type is not bound directly to
4872   //   an argument expression, the conversion sequence is the one
4873   //   required to convert the argument expression to the
4874   //   underlying type of the reference according to
4875   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4876   //   to copy-initializing a temporary of the underlying type with
4877   //   the argument expression. Any difference in top-level
4878   //   cv-qualification is subsumed by the initialization itself
4879   //   and does not constitute a conversion.
4880   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4881                               AllowedExplicit::None,
4882                               /*InOverloadResolution=*/false,
4883                               /*CStyle=*/false,
4884                               /*AllowObjCWritebackConversion=*/false,
4885                               /*AllowObjCConversionOnExplicit=*/false);
4886 
4887   // Of course, that's still a reference binding.
4888   if (ICS.isStandard()) {
4889     ICS.Standard.ReferenceBinding = true;
4890     ICS.Standard.IsLvalueReference = !isRValRef;
4891     ICS.Standard.BindsToFunctionLvalue = false;
4892     ICS.Standard.BindsToRvalue = true;
4893     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4894     ICS.Standard.ObjCLifetimeConversionBinding = false;
4895   } else if (ICS.isUserDefined()) {
4896     const ReferenceType *LValRefType =
4897         ICS.UserDefined.ConversionFunction->getReturnType()
4898             ->getAs<LValueReferenceType>();
4899 
4900     // C++ [over.ics.ref]p3:
4901     //   Except for an implicit object parameter, for which see 13.3.1, a
4902     //   standard conversion sequence cannot be formed if it requires [...]
4903     //   binding an rvalue reference to an lvalue other than a function
4904     //   lvalue.
4905     // Note that the function case is not possible here.
4906     if (DeclType->isRValueReferenceType() && LValRefType) {
4907       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4908       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4909       // reference to an rvalue!
4910       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4911       return ICS;
4912     }
4913 
4914     ICS.UserDefined.After.ReferenceBinding = true;
4915     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4916     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4917     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4918     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4919     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4920   }
4921 
4922   return ICS;
4923 }
4924 
4925 static ImplicitConversionSequence
4926 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4927                       bool SuppressUserConversions,
4928                       bool InOverloadResolution,
4929                       bool AllowObjCWritebackConversion,
4930                       bool AllowExplicit = false);
4931 
4932 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4933 /// initializer list From.
4934 static ImplicitConversionSequence
4935 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4936                   bool SuppressUserConversions,
4937                   bool InOverloadResolution,
4938                   bool AllowObjCWritebackConversion) {
4939   // C++11 [over.ics.list]p1:
4940   //   When an argument is an initializer list, it is not an expression and
4941   //   special rules apply for converting it to a parameter type.
4942 
4943   ImplicitConversionSequence Result;
4944   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4945 
4946   // We need a complete type for what follows. Incomplete types can never be
4947   // initialized from init lists.
4948   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4949     return Result;
4950 
4951   // Per DR1467:
4952   //   If the parameter type is a class X and the initializer list has a single
4953   //   element of type cv U, where U is X or a class derived from X, the
4954   //   implicit conversion sequence is the one required to convert the element
4955   //   to the parameter type.
4956   //
4957   //   Otherwise, if the parameter type is a character array [... ]
4958   //   and the initializer list has a single element that is an
4959   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4960   //   implicit conversion sequence is the identity conversion.
4961   if (From->getNumInits() == 1) {
4962     if (ToType->isRecordType()) {
4963       QualType InitType = From->getInit(0)->getType();
4964       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4965           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4966         return TryCopyInitialization(S, From->getInit(0), ToType,
4967                                      SuppressUserConversions,
4968                                      InOverloadResolution,
4969                                      AllowObjCWritebackConversion);
4970     }
4971     // FIXME: Check the other conditions here: array of character type,
4972     // initializer is a string literal.
4973     if (ToType->isArrayType()) {
4974       InitializedEntity Entity =
4975         InitializedEntity::InitializeParameter(S.Context, ToType,
4976                                                /*Consumed=*/false);
4977       if (S.CanPerformCopyInitialization(Entity, From)) {
4978         Result.setStandard();
4979         Result.Standard.setAsIdentityConversion();
4980         Result.Standard.setFromType(ToType);
4981         Result.Standard.setAllToTypes(ToType);
4982         return Result;
4983       }
4984     }
4985   }
4986 
4987   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4988   // C++11 [over.ics.list]p2:
4989   //   If the parameter type is std::initializer_list<X> or "array of X" and
4990   //   all the elements can be implicitly converted to X, the implicit
4991   //   conversion sequence is the worst conversion necessary to convert an
4992   //   element of the list to X.
4993   //
4994   // C++14 [over.ics.list]p3:
4995   //   Otherwise, if the parameter type is "array of N X", if the initializer
4996   //   list has exactly N elements or if it has fewer than N elements and X is
4997   //   default-constructible, and if all the elements of the initializer list
4998   //   can be implicitly converted to X, the implicit conversion sequence is
4999   //   the worst conversion necessary to convert an element of the list to X.
5000   //
5001   // FIXME: We're missing a lot of these checks.
5002   bool toStdInitializerList = false;
5003   QualType X;
5004   if (ToType->isArrayType())
5005     X = S.Context.getAsArrayType(ToType)->getElementType();
5006   else
5007     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5008   if (!X.isNull()) {
5009     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5010       Expr *Init = From->getInit(i);
5011       ImplicitConversionSequence ICS =
5012           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5013                                 InOverloadResolution,
5014                                 AllowObjCWritebackConversion);
5015       // If a single element isn't convertible, fail.
5016       if (ICS.isBad()) {
5017         Result = ICS;
5018         break;
5019       }
5020       // Otherwise, look for the worst conversion.
5021       if (Result.isBad() || CompareImplicitConversionSequences(
5022                                 S, From->getBeginLoc(), ICS, Result) ==
5023                                 ImplicitConversionSequence::Worse)
5024         Result = ICS;
5025     }
5026 
5027     // For an empty list, we won't have computed any conversion sequence.
5028     // Introduce the identity conversion sequence.
5029     if (From->getNumInits() == 0) {
5030       Result.setStandard();
5031       Result.Standard.setAsIdentityConversion();
5032       Result.Standard.setFromType(ToType);
5033       Result.Standard.setAllToTypes(ToType);
5034     }
5035 
5036     Result.setStdInitializerListElement(toStdInitializerList);
5037     return Result;
5038   }
5039 
5040   // C++14 [over.ics.list]p4:
5041   // C++11 [over.ics.list]p3:
5042   //   Otherwise, if the parameter is a non-aggregate class X and overload
5043   //   resolution chooses a single best constructor [...] the implicit
5044   //   conversion sequence is a user-defined conversion sequence. If multiple
5045   //   constructors are viable but none is better than the others, the
5046   //   implicit conversion sequence is a user-defined conversion sequence.
5047   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5048     // This function can deal with initializer lists.
5049     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5050                                     AllowedExplicit::None,
5051                                     InOverloadResolution, /*CStyle=*/false,
5052                                     AllowObjCWritebackConversion,
5053                                     /*AllowObjCConversionOnExplicit=*/false);
5054   }
5055 
5056   // C++14 [over.ics.list]p5:
5057   // C++11 [over.ics.list]p4:
5058   //   Otherwise, if the parameter has an aggregate type which can be
5059   //   initialized from the initializer list [...] the implicit conversion
5060   //   sequence is a user-defined conversion sequence.
5061   if (ToType->isAggregateType()) {
5062     // Type is an aggregate, argument is an init list. At this point it comes
5063     // down to checking whether the initialization works.
5064     // FIXME: Find out whether this parameter is consumed or not.
5065     InitializedEntity Entity =
5066         InitializedEntity::InitializeParameter(S.Context, ToType,
5067                                                /*Consumed=*/false);
5068     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5069                                                                  From)) {
5070       Result.setUserDefined();
5071       Result.UserDefined.Before.setAsIdentityConversion();
5072       // Initializer lists don't have a type.
5073       Result.UserDefined.Before.setFromType(QualType());
5074       Result.UserDefined.Before.setAllToTypes(QualType());
5075 
5076       Result.UserDefined.After.setAsIdentityConversion();
5077       Result.UserDefined.After.setFromType(ToType);
5078       Result.UserDefined.After.setAllToTypes(ToType);
5079       Result.UserDefined.ConversionFunction = nullptr;
5080     }
5081     return Result;
5082   }
5083 
5084   // C++14 [over.ics.list]p6:
5085   // C++11 [over.ics.list]p5:
5086   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5087   if (ToType->isReferenceType()) {
5088     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5089     // mention initializer lists in any way. So we go by what list-
5090     // initialization would do and try to extrapolate from that.
5091 
5092     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5093 
5094     // If the initializer list has a single element that is reference-related
5095     // to the parameter type, we initialize the reference from that.
5096     if (From->getNumInits() == 1) {
5097       Expr *Init = From->getInit(0);
5098 
5099       QualType T2 = Init->getType();
5100 
5101       // If the initializer is the address of an overloaded function, try
5102       // to resolve the overloaded function. If all goes well, T2 is the
5103       // type of the resulting function.
5104       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5105         DeclAccessPair Found;
5106         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5107                                    Init, ToType, false, Found))
5108           T2 = Fn->getType();
5109       }
5110 
5111       // Compute some basic properties of the types and the initializer.
5112       Sema::ReferenceCompareResult RefRelationship =
5113           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5114 
5115       if (RefRelationship >= Sema::Ref_Related) {
5116         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5117                                 SuppressUserConversions,
5118                                 /*AllowExplicit=*/false);
5119       }
5120     }
5121 
5122     // Otherwise, we bind the reference to a temporary created from the
5123     // initializer list.
5124     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5125                                InOverloadResolution,
5126                                AllowObjCWritebackConversion);
5127     if (Result.isFailure())
5128       return Result;
5129     assert(!Result.isEllipsis() &&
5130            "Sub-initialization cannot result in ellipsis conversion.");
5131 
5132     // Can we even bind to a temporary?
5133     if (ToType->isRValueReferenceType() ||
5134         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5135       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5136                                             Result.UserDefined.After;
5137       SCS.ReferenceBinding = true;
5138       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5139       SCS.BindsToRvalue = true;
5140       SCS.BindsToFunctionLvalue = false;
5141       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5142       SCS.ObjCLifetimeConversionBinding = false;
5143     } else
5144       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5145                     From, ToType);
5146     return Result;
5147   }
5148 
5149   // C++14 [over.ics.list]p7:
5150   // C++11 [over.ics.list]p6:
5151   //   Otherwise, if the parameter type is not a class:
5152   if (!ToType->isRecordType()) {
5153     //    - if the initializer list has one element that is not itself an
5154     //      initializer list, the implicit conversion sequence is the one
5155     //      required to convert the element to the parameter type.
5156     unsigned NumInits = From->getNumInits();
5157     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5158       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5159                                      SuppressUserConversions,
5160                                      InOverloadResolution,
5161                                      AllowObjCWritebackConversion);
5162     //    - if the initializer list has no elements, the implicit conversion
5163     //      sequence is the identity conversion.
5164     else if (NumInits == 0) {
5165       Result.setStandard();
5166       Result.Standard.setAsIdentityConversion();
5167       Result.Standard.setFromType(ToType);
5168       Result.Standard.setAllToTypes(ToType);
5169     }
5170     return Result;
5171   }
5172 
5173   // C++14 [over.ics.list]p8:
5174   // C++11 [over.ics.list]p7:
5175   //   In all cases other than those enumerated above, no conversion is possible
5176   return Result;
5177 }
5178 
5179 /// TryCopyInitialization - Try to copy-initialize a value of type
5180 /// ToType from the expression From. Return the implicit conversion
5181 /// sequence required to pass this argument, which may be a bad
5182 /// conversion sequence (meaning that the argument cannot be passed to
5183 /// a parameter of this type). If @p SuppressUserConversions, then we
5184 /// do not permit any user-defined conversion sequences.
5185 static ImplicitConversionSequence
5186 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5187                       bool SuppressUserConversions,
5188                       bool InOverloadResolution,
5189                       bool AllowObjCWritebackConversion,
5190                       bool AllowExplicit) {
5191   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5192     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5193                              InOverloadResolution,AllowObjCWritebackConversion);
5194 
5195   if (ToType->isReferenceType())
5196     return TryReferenceInit(S, From, ToType,
5197                             /*FIXME:*/ From->getBeginLoc(),
5198                             SuppressUserConversions, AllowExplicit);
5199 
5200   return TryImplicitConversion(S, From, ToType,
5201                                SuppressUserConversions,
5202                                AllowedExplicit::None,
5203                                InOverloadResolution,
5204                                /*CStyle=*/false,
5205                                AllowObjCWritebackConversion,
5206                                /*AllowObjCConversionOnExplicit=*/false);
5207 }
5208 
5209 static bool TryCopyInitialization(const CanQualType FromQTy,
5210                                   const CanQualType ToQTy,
5211                                   Sema &S,
5212                                   SourceLocation Loc,
5213                                   ExprValueKind FromVK) {
5214   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5215   ImplicitConversionSequence ICS =
5216     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5217 
5218   return !ICS.isBad();
5219 }
5220 
5221 /// TryObjectArgumentInitialization - Try to initialize the object
5222 /// parameter of the given member function (@c Method) from the
5223 /// expression @p From.
5224 static ImplicitConversionSequence
5225 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5226                                 Expr::Classification FromClassification,
5227                                 CXXMethodDecl *Method,
5228                                 CXXRecordDecl *ActingContext) {
5229   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5230   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5231   //                 const volatile object.
5232   Qualifiers Quals = Method->getMethodQualifiers();
5233   if (isa<CXXDestructorDecl>(Method)) {
5234     Quals.addConst();
5235     Quals.addVolatile();
5236   }
5237 
5238   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5239 
5240   // Set up the conversion sequence as a "bad" conversion, to allow us
5241   // to exit early.
5242   ImplicitConversionSequence ICS;
5243 
5244   // We need to have an object of class type.
5245   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5246     FromType = PT->getPointeeType();
5247 
5248     // When we had a pointer, it's implicitly dereferenced, so we
5249     // better have an lvalue.
5250     assert(FromClassification.isLValue());
5251   }
5252 
5253   assert(FromType->isRecordType());
5254 
5255   // C++0x [over.match.funcs]p4:
5256   //   For non-static member functions, the type of the implicit object
5257   //   parameter is
5258   //
5259   //     - "lvalue reference to cv X" for functions declared without a
5260   //        ref-qualifier or with the & ref-qualifier
5261   //     - "rvalue reference to cv X" for functions declared with the &&
5262   //        ref-qualifier
5263   //
5264   // where X is the class of which the function is a member and cv is the
5265   // cv-qualification on the member function declaration.
5266   //
5267   // However, when finding an implicit conversion sequence for the argument, we
5268   // are not allowed to perform user-defined conversions
5269   // (C++ [over.match.funcs]p5). We perform a simplified version of
5270   // reference binding here, that allows class rvalues to bind to
5271   // non-constant references.
5272 
5273   // First check the qualifiers.
5274   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5275   if (ImplicitParamType.getCVRQualifiers()
5276                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5277       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5278     ICS.setBad(BadConversionSequence::bad_qualifiers,
5279                FromType, ImplicitParamType);
5280     return ICS;
5281   }
5282 
5283   if (FromTypeCanon.hasAddressSpace()) {
5284     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5285     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5286     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5287       ICS.setBad(BadConversionSequence::bad_qualifiers,
5288                  FromType, ImplicitParamType);
5289       return ICS;
5290     }
5291   }
5292 
5293   // Check that we have either the same type or a derived type. It
5294   // affects the conversion rank.
5295   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5296   ImplicitConversionKind SecondKind;
5297   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5298     SecondKind = ICK_Identity;
5299   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5300     SecondKind = ICK_Derived_To_Base;
5301   else {
5302     ICS.setBad(BadConversionSequence::unrelated_class,
5303                FromType, ImplicitParamType);
5304     return ICS;
5305   }
5306 
5307   // Check the ref-qualifier.
5308   switch (Method->getRefQualifier()) {
5309   case RQ_None:
5310     // Do nothing; we don't care about lvalueness or rvalueness.
5311     break;
5312 
5313   case RQ_LValue:
5314     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5315       // non-const lvalue reference cannot bind to an rvalue
5316       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5317                  ImplicitParamType);
5318       return ICS;
5319     }
5320     break;
5321 
5322   case RQ_RValue:
5323     if (!FromClassification.isRValue()) {
5324       // rvalue reference cannot bind to an lvalue
5325       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5326                  ImplicitParamType);
5327       return ICS;
5328     }
5329     break;
5330   }
5331 
5332   // Success. Mark this as a reference binding.
5333   ICS.setStandard();
5334   ICS.Standard.setAsIdentityConversion();
5335   ICS.Standard.Second = SecondKind;
5336   ICS.Standard.setFromType(FromType);
5337   ICS.Standard.setAllToTypes(ImplicitParamType);
5338   ICS.Standard.ReferenceBinding = true;
5339   ICS.Standard.DirectBinding = true;
5340   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5341   ICS.Standard.BindsToFunctionLvalue = false;
5342   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5343   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5344     = (Method->getRefQualifier() == RQ_None);
5345   return ICS;
5346 }
5347 
5348 /// PerformObjectArgumentInitialization - Perform initialization of
5349 /// the implicit object parameter for the given Method with the given
5350 /// expression.
5351 ExprResult
5352 Sema::PerformObjectArgumentInitialization(Expr *From,
5353                                           NestedNameSpecifier *Qualifier,
5354                                           NamedDecl *FoundDecl,
5355                                           CXXMethodDecl *Method) {
5356   QualType FromRecordType, DestType;
5357   QualType ImplicitParamRecordType  =
5358     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5359 
5360   Expr::Classification FromClassification;
5361   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5362     FromRecordType = PT->getPointeeType();
5363     DestType = Method->getThisType();
5364     FromClassification = Expr::Classification::makeSimpleLValue();
5365   } else {
5366     FromRecordType = From->getType();
5367     DestType = ImplicitParamRecordType;
5368     FromClassification = From->Classify(Context);
5369 
5370     // When performing member access on an rvalue, materialize a temporary.
5371     if (From->isRValue()) {
5372       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5373                                             Method->getRefQualifier() !=
5374                                                 RefQualifierKind::RQ_RValue);
5375     }
5376   }
5377 
5378   // Note that we always use the true parent context when performing
5379   // the actual argument initialization.
5380   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5381       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5382       Method->getParent());
5383   if (ICS.isBad()) {
5384     switch (ICS.Bad.Kind) {
5385     case BadConversionSequence::bad_qualifiers: {
5386       Qualifiers FromQs = FromRecordType.getQualifiers();
5387       Qualifiers ToQs = DestType.getQualifiers();
5388       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5389       if (CVR) {
5390         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5391             << Method->getDeclName() << FromRecordType << (CVR - 1)
5392             << From->getSourceRange();
5393         Diag(Method->getLocation(), diag::note_previous_decl)
5394           << Method->getDeclName();
5395         return ExprError();
5396       }
5397       break;
5398     }
5399 
5400     case BadConversionSequence::lvalue_ref_to_rvalue:
5401     case BadConversionSequence::rvalue_ref_to_lvalue: {
5402       bool IsRValueQualified =
5403         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5404       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5405           << Method->getDeclName() << FromClassification.isRValue()
5406           << IsRValueQualified;
5407       Diag(Method->getLocation(), diag::note_previous_decl)
5408         << Method->getDeclName();
5409       return ExprError();
5410     }
5411 
5412     case BadConversionSequence::no_conversion:
5413     case BadConversionSequence::unrelated_class:
5414       break;
5415     }
5416 
5417     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5418            << ImplicitParamRecordType << FromRecordType
5419            << From->getSourceRange();
5420   }
5421 
5422   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5423     ExprResult FromRes =
5424       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5425     if (FromRes.isInvalid())
5426       return ExprError();
5427     From = FromRes.get();
5428   }
5429 
5430   if (!Context.hasSameType(From->getType(), DestType)) {
5431     CastKind CK;
5432     QualType PteeTy = DestType->getPointeeType();
5433     LangAS DestAS =
5434         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5435     if (FromRecordType.getAddressSpace() != DestAS)
5436       CK = CK_AddressSpaceConversion;
5437     else
5438       CK = CK_NoOp;
5439     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5440   }
5441   return From;
5442 }
5443 
5444 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5445 /// expression From to bool (C++0x [conv]p3).
5446 static ImplicitConversionSequence
5447 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5448   // C++ [dcl.init]/17.8:
5449   //   - Otherwise, if the initialization is direct-initialization, the source
5450   //     type is std::nullptr_t, and the destination type is bool, the initial
5451   //     value of the object being initialized is false.
5452   if (From->getType()->isNullPtrType())
5453     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5454                                                         S.Context.BoolTy,
5455                                                         From->isGLValue());
5456 
5457   // All other direct-initialization of bool is equivalent to an implicit
5458   // conversion to bool in which explicit conversions are permitted.
5459   return TryImplicitConversion(S, From, S.Context.BoolTy,
5460                                /*SuppressUserConversions=*/false,
5461                                AllowedExplicit::Conversions,
5462                                /*InOverloadResolution=*/false,
5463                                /*CStyle=*/false,
5464                                /*AllowObjCWritebackConversion=*/false,
5465                                /*AllowObjCConversionOnExplicit=*/false);
5466 }
5467 
5468 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5469 /// of the expression From to bool (C++0x [conv]p3).
5470 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5471   if (checkPlaceholderForOverload(*this, From))
5472     return ExprError();
5473 
5474   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5475   if (!ICS.isBad())
5476     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5477 
5478   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5479     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5480            << From->getType() << From->getSourceRange();
5481   return ExprError();
5482 }
5483 
5484 /// Check that the specified conversion is permitted in a converted constant
5485 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5486 /// is acceptable.
5487 static bool CheckConvertedConstantConversions(Sema &S,
5488                                               StandardConversionSequence &SCS) {
5489   // Since we know that the target type is an integral or unscoped enumeration
5490   // type, most conversion kinds are impossible. All possible First and Third
5491   // conversions are fine.
5492   switch (SCS.Second) {
5493   case ICK_Identity:
5494   case ICK_Function_Conversion:
5495   case ICK_Integral_Promotion:
5496   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5497   case ICK_Zero_Queue_Conversion:
5498     return true;
5499 
5500   case ICK_Boolean_Conversion:
5501     // Conversion from an integral or unscoped enumeration type to bool is
5502     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5503     // conversion, so we allow it in a converted constant expression.
5504     //
5505     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5506     // a lot of popular code. We should at least add a warning for this
5507     // (non-conforming) extension.
5508     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5509            SCS.getToType(2)->isBooleanType();
5510 
5511   case ICK_Pointer_Conversion:
5512   case ICK_Pointer_Member:
5513     // C++1z: null pointer conversions and null member pointer conversions are
5514     // only permitted if the source type is std::nullptr_t.
5515     return SCS.getFromType()->isNullPtrType();
5516 
5517   case ICK_Floating_Promotion:
5518   case ICK_Complex_Promotion:
5519   case ICK_Floating_Conversion:
5520   case ICK_Complex_Conversion:
5521   case ICK_Floating_Integral:
5522   case ICK_Compatible_Conversion:
5523   case ICK_Derived_To_Base:
5524   case ICK_Vector_Conversion:
5525   case ICK_Vector_Splat:
5526   case ICK_Complex_Real:
5527   case ICK_Block_Pointer_Conversion:
5528   case ICK_TransparentUnionConversion:
5529   case ICK_Writeback_Conversion:
5530   case ICK_Zero_Event_Conversion:
5531   case ICK_C_Only_Conversion:
5532   case ICK_Incompatible_Pointer_Conversion:
5533     return false;
5534 
5535   case ICK_Lvalue_To_Rvalue:
5536   case ICK_Array_To_Pointer:
5537   case ICK_Function_To_Pointer:
5538     llvm_unreachable("found a first conversion kind in Second");
5539 
5540   case ICK_Qualification:
5541     llvm_unreachable("found a third conversion kind in Second");
5542 
5543   case ICK_Num_Conversion_Kinds:
5544     break;
5545   }
5546 
5547   llvm_unreachable("unknown conversion kind");
5548 }
5549 
5550 /// CheckConvertedConstantExpression - Check that the expression From is a
5551 /// converted constant expression of type T, perform the conversion and produce
5552 /// the converted expression, per C++11 [expr.const]p3.
5553 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5554                                                    QualType T, APValue &Value,
5555                                                    Sema::CCEKind CCE,
5556                                                    bool RequireInt) {
5557   assert(S.getLangOpts().CPlusPlus11 &&
5558          "converted constant expression outside C++11");
5559 
5560   if (checkPlaceholderForOverload(S, From))
5561     return ExprError();
5562 
5563   // C++1z [expr.const]p3:
5564   //  A converted constant expression of type T is an expression,
5565   //  implicitly converted to type T, where the converted
5566   //  expression is a constant expression and the implicit conversion
5567   //  sequence contains only [... list of conversions ...].
5568   // C++1z [stmt.if]p2:
5569   //  If the if statement is of the form if constexpr, the value of the
5570   //  condition shall be a contextually converted constant expression of type
5571   //  bool.
5572   ImplicitConversionSequence ICS =
5573       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5574           ? TryContextuallyConvertToBool(S, From)
5575           : TryCopyInitialization(S, From, T,
5576                                   /*SuppressUserConversions=*/false,
5577                                   /*InOverloadResolution=*/false,
5578                                   /*AllowObjCWritebackConversion=*/false,
5579                                   /*AllowExplicit=*/false);
5580   StandardConversionSequence *SCS = nullptr;
5581   switch (ICS.getKind()) {
5582   case ImplicitConversionSequence::StandardConversion:
5583     SCS = &ICS.Standard;
5584     break;
5585   case ImplicitConversionSequence::UserDefinedConversion:
5586     // We are converting to a non-class type, so the Before sequence
5587     // must be trivial.
5588     SCS = &ICS.UserDefined.After;
5589     break;
5590   case ImplicitConversionSequence::AmbiguousConversion:
5591   case ImplicitConversionSequence::BadConversion:
5592     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5593       return S.Diag(From->getBeginLoc(),
5594                     diag::err_typecheck_converted_constant_expression)
5595              << From->getType() << From->getSourceRange() << T;
5596     return ExprError();
5597 
5598   case ImplicitConversionSequence::EllipsisConversion:
5599     llvm_unreachable("ellipsis conversion in converted constant expression");
5600   }
5601 
5602   // Check that we would only use permitted conversions.
5603   if (!CheckConvertedConstantConversions(S, *SCS)) {
5604     return S.Diag(From->getBeginLoc(),
5605                   diag::err_typecheck_converted_constant_expression_disallowed)
5606            << From->getType() << From->getSourceRange() << T;
5607   }
5608   // [...] and where the reference binding (if any) binds directly.
5609   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5610     return S.Diag(From->getBeginLoc(),
5611                   diag::err_typecheck_converted_constant_expression_indirect)
5612            << From->getType() << From->getSourceRange() << T;
5613   }
5614 
5615   ExprResult Result =
5616       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5617   if (Result.isInvalid())
5618     return Result;
5619 
5620   // C++2a [intro.execution]p5:
5621   //   A full-expression is [...] a constant-expression [...]
5622   Result =
5623       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5624                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5625   if (Result.isInvalid())
5626     return Result;
5627 
5628   // Check for a narrowing implicit conversion.
5629   APValue PreNarrowingValue;
5630   QualType PreNarrowingType;
5631   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5632                                 PreNarrowingType)) {
5633   case NK_Dependent_Narrowing:
5634     // Implicit conversion to a narrower type, but the expression is
5635     // value-dependent so we can't tell whether it's actually narrowing.
5636   case NK_Variable_Narrowing:
5637     // Implicit conversion to a narrower type, and the value is not a constant
5638     // expression. We'll diagnose this in a moment.
5639   case NK_Not_Narrowing:
5640     break;
5641 
5642   case NK_Constant_Narrowing:
5643     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5644         << CCE << /*Constant*/ 1
5645         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5646     break;
5647 
5648   case NK_Type_Narrowing:
5649     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5650         << CCE << /*Constant*/ 0 << From->getType() << T;
5651     break;
5652   }
5653 
5654   if (Result.get()->isValueDependent()) {
5655     Value = APValue();
5656     return Result;
5657   }
5658 
5659   // Check the expression is a constant expression.
5660   SmallVector<PartialDiagnosticAt, 8> Notes;
5661   Expr::EvalResult Eval;
5662   Eval.Diag = &Notes;
5663   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5664                                    ? Expr::EvaluateForMangling
5665                                    : Expr::EvaluateForCodeGen;
5666 
5667   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5668       (RequireInt && !Eval.Val.isInt())) {
5669     // The expression can't be folded, so we can't keep it at this position in
5670     // the AST.
5671     Result = ExprError();
5672   } else {
5673     Value = Eval.Val;
5674 
5675     if (Notes.empty()) {
5676       // It's a constant expression.
5677       return ConstantExpr::Create(S.Context, Result.get(), Value);
5678     }
5679   }
5680 
5681   // It's not a constant expression. Produce an appropriate diagnostic.
5682   if (Notes.size() == 1 &&
5683       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5684     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5685   else {
5686     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5687         << CCE << From->getSourceRange();
5688     for (unsigned I = 0; I < Notes.size(); ++I)
5689       S.Diag(Notes[I].first, Notes[I].second);
5690   }
5691   return ExprError();
5692 }
5693 
5694 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5695                                                   APValue &Value, CCEKind CCE) {
5696   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5697 }
5698 
5699 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5700                                                   llvm::APSInt &Value,
5701                                                   CCEKind CCE) {
5702   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5703 
5704   APValue V;
5705   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5706   if (!R.isInvalid() && !R.get()->isValueDependent())
5707     Value = V.getInt();
5708   return R;
5709 }
5710 
5711 
5712 /// dropPointerConversions - If the given standard conversion sequence
5713 /// involves any pointer conversions, remove them.  This may change
5714 /// the result type of the conversion sequence.
5715 static void dropPointerConversion(StandardConversionSequence &SCS) {
5716   if (SCS.Second == ICK_Pointer_Conversion) {
5717     SCS.Second = ICK_Identity;
5718     SCS.Third = ICK_Identity;
5719     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5720   }
5721 }
5722 
5723 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5724 /// convert the expression From to an Objective-C pointer type.
5725 static ImplicitConversionSequence
5726 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5727   // Do an implicit conversion to 'id'.
5728   QualType Ty = S.Context.getObjCIdType();
5729   ImplicitConversionSequence ICS
5730     = TryImplicitConversion(S, From, Ty,
5731                             // FIXME: Are these flags correct?
5732                             /*SuppressUserConversions=*/false,
5733                             AllowedExplicit::Conversions,
5734                             /*InOverloadResolution=*/false,
5735                             /*CStyle=*/false,
5736                             /*AllowObjCWritebackConversion=*/false,
5737                             /*AllowObjCConversionOnExplicit=*/true);
5738 
5739   // Strip off any final conversions to 'id'.
5740   switch (ICS.getKind()) {
5741   case ImplicitConversionSequence::BadConversion:
5742   case ImplicitConversionSequence::AmbiguousConversion:
5743   case ImplicitConversionSequence::EllipsisConversion:
5744     break;
5745 
5746   case ImplicitConversionSequence::UserDefinedConversion:
5747     dropPointerConversion(ICS.UserDefined.After);
5748     break;
5749 
5750   case ImplicitConversionSequence::StandardConversion:
5751     dropPointerConversion(ICS.Standard);
5752     break;
5753   }
5754 
5755   return ICS;
5756 }
5757 
5758 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5759 /// conversion of the expression From to an Objective-C pointer type.
5760 /// Returns a valid but null ExprResult if no conversion sequence exists.
5761 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5762   if (checkPlaceholderForOverload(*this, From))
5763     return ExprError();
5764 
5765   QualType Ty = Context.getObjCIdType();
5766   ImplicitConversionSequence ICS =
5767     TryContextuallyConvertToObjCPointer(*this, From);
5768   if (!ICS.isBad())
5769     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5770   return ExprResult();
5771 }
5772 
5773 /// Determine whether the provided type is an integral type, or an enumeration
5774 /// type of a permitted flavor.
5775 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5776   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5777                                  : T->isIntegralOrUnscopedEnumerationType();
5778 }
5779 
5780 static ExprResult
5781 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5782                             Sema::ContextualImplicitConverter &Converter,
5783                             QualType T, UnresolvedSetImpl &ViableConversions) {
5784 
5785   if (Converter.Suppress)
5786     return ExprError();
5787 
5788   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5789   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5790     CXXConversionDecl *Conv =
5791         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5792     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5793     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5794   }
5795   return From;
5796 }
5797 
5798 static bool
5799 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5800                            Sema::ContextualImplicitConverter &Converter,
5801                            QualType T, bool HadMultipleCandidates,
5802                            UnresolvedSetImpl &ExplicitConversions) {
5803   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5804     DeclAccessPair Found = ExplicitConversions[0];
5805     CXXConversionDecl *Conversion =
5806         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5807 
5808     // The user probably meant to invoke the given explicit
5809     // conversion; use it.
5810     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5811     std::string TypeStr;
5812     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5813 
5814     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5815         << FixItHint::CreateInsertion(From->getBeginLoc(),
5816                                       "static_cast<" + TypeStr + ">(")
5817         << FixItHint::CreateInsertion(
5818                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5819     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5820 
5821     // If we aren't in a SFINAE context, build a call to the
5822     // explicit conversion function.
5823     if (SemaRef.isSFINAEContext())
5824       return true;
5825 
5826     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5827     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5828                                                        HadMultipleCandidates);
5829     if (Result.isInvalid())
5830       return true;
5831     // Record usage of conversion in an implicit cast.
5832     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5833                                     CK_UserDefinedConversion, Result.get(),
5834                                     nullptr, Result.get()->getValueKind());
5835   }
5836   return false;
5837 }
5838 
5839 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5840                              Sema::ContextualImplicitConverter &Converter,
5841                              QualType T, bool HadMultipleCandidates,
5842                              DeclAccessPair &Found) {
5843   CXXConversionDecl *Conversion =
5844       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5845   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5846 
5847   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5848   if (!Converter.SuppressConversion) {
5849     if (SemaRef.isSFINAEContext())
5850       return true;
5851 
5852     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5853         << From->getSourceRange();
5854   }
5855 
5856   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5857                                                      HadMultipleCandidates);
5858   if (Result.isInvalid())
5859     return true;
5860   // Record usage of conversion in an implicit cast.
5861   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5862                                   CK_UserDefinedConversion, Result.get(),
5863                                   nullptr, Result.get()->getValueKind());
5864   return false;
5865 }
5866 
5867 static ExprResult finishContextualImplicitConversion(
5868     Sema &SemaRef, SourceLocation Loc, Expr *From,
5869     Sema::ContextualImplicitConverter &Converter) {
5870   if (!Converter.match(From->getType()) && !Converter.Suppress)
5871     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5872         << From->getSourceRange();
5873 
5874   return SemaRef.DefaultLvalueConversion(From);
5875 }
5876 
5877 static void
5878 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5879                                   UnresolvedSetImpl &ViableConversions,
5880                                   OverloadCandidateSet &CandidateSet) {
5881   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5882     DeclAccessPair FoundDecl = ViableConversions[I];
5883     NamedDecl *D = FoundDecl.getDecl();
5884     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5885     if (isa<UsingShadowDecl>(D))
5886       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5887 
5888     CXXConversionDecl *Conv;
5889     FunctionTemplateDecl *ConvTemplate;
5890     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5891       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5892     else
5893       Conv = cast<CXXConversionDecl>(D);
5894 
5895     if (ConvTemplate)
5896       SemaRef.AddTemplateConversionCandidate(
5897           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5898           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5899     else
5900       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5901                                      ToType, CandidateSet,
5902                                      /*AllowObjCConversionOnExplicit=*/false,
5903                                      /*AllowExplicit*/ true);
5904   }
5905 }
5906 
5907 /// Attempt to convert the given expression to a type which is accepted
5908 /// by the given converter.
5909 ///
5910 /// This routine will attempt to convert an expression of class type to a
5911 /// type accepted by the specified converter. In C++11 and before, the class
5912 /// must have a single non-explicit conversion function converting to a matching
5913 /// type. In C++1y, there can be multiple such conversion functions, but only
5914 /// one target type.
5915 ///
5916 /// \param Loc The source location of the construct that requires the
5917 /// conversion.
5918 ///
5919 /// \param From The expression we're converting from.
5920 ///
5921 /// \param Converter Used to control and diagnose the conversion process.
5922 ///
5923 /// \returns The expression, converted to an integral or enumeration type if
5924 /// successful.
5925 ExprResult Sema::PerformContextualImplicitConversion(
5926     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5927   // We can't perform any more checking for type-dependent expressions.
5928   if (From->isTypeDependent())
5929     return From;
5930 
5931   // Process placeholders immediately.
5932   if (From->hasPlaceholderType()) {
5933     ExprResult result = CheckPlaceholderExpr(From);
5934     if (result.isInvalid())
5935       return result;
5936     From = result.get();
5937   }
5938 
5939   // If the expression already has a matching type, we're golden.
5940   QualType T = From->getType();
5941   if (Converter.match(T))
5942     return DefaultLvalueConversion(From);
5943 
5944   // FIXME: Check for missing '()' if T is a function type?
5945 
5946   // We can only perform contextual implicit conversions on objects of class
5947   // type.
5948   const RecordType *RecordTy = T->getAs<RecordType>();
5949   if (!RecordTy || !getLangOpts().CPlusPlus) {
5950     if (!Converter.Suppress)
5951       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5952     return From;
5953   }
5954 
5955   // We must have a complete class type.
5956   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5957     ContextualImplicitConverter &Converter;
5958     Expr *From;
5959 
5960     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5961         : Converter(Converter), From(From) {}
5962 
5963     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5964       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5965     }
5966   } IncompleteDiagnoser(Converter, From);
5967 
5968   if (Converter.Suppress ? !isCompleteType(Loc, T)
5969                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5970     return From;
5971 
5972   // Look for a conversion to an integral or enumeration type.
5973   UnresolvedSet<4>
5974       ViableConversions; // These are *potentially* viable in C++1y.
5975   UnresolvedSet<4> ExplicitConversions;
5976   const auto &Conversions =
5977       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5978 
5979   bool HadMultipleCandidates =
5980       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5981 
5982   // To check that there is only one target type, in C++1y:
5983   QualType ToType;
5984   bool HasUniqueTargetType = true;
5985 
5986   // Collect explicit or viable (potentially in C++1y) conversions.
5987   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5988     NamedDecl *D = (*I)->getUnderlyingDecl();
5989     CXXConversionDecl *Conversion;
5990     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5991     if (ConvTemplate) {
5992       if (getLangOpts().CPlusPlus14)
5993         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5994       else
5995         continue; // C++11 does not consider conversion operator templates(?).
5996     } else
5997       Conversion = cast<CXXConversionDecl>(D);
5998 
5999     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6000            "Conversion operator templates are considered potentially "
6001            "viable in C++1y");
6002 
6003     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6004     if (Converter.match(CurToType) || ConvTemplate) {
6005 
6006       if (Conversion->isExplicit()) {
6007         // FIXME: For C++1y, do we need this restriction?
6008         // cf. diagnoseNoViableConversion()
6009         if (!ConvTemplate)
6010           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6011       } else {
6012         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6013           if (ToType.isNull())
6014             ToType = CurToType.getUnqualifiedType();
6015           else if (HasUniqueTargetType &&
6016                    (CurToType.getUnqualifiedType() != ToType))
6017             HasUniqueTargetType = false;
6018         }
6019         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6020       }
6021     }
6022   }
6023 
6024   if (getLangOpts().CPlusPlus14) {
6025     // C++1y [conv]p6:
6026     // ... An expression e of class type E appearing in such a context
6027     // is said to be contextually implicitly converted to a specified
6028     // type T and is well-formed if and only if e can be implicitly
6029     // converted to a type T that is determined as follows: E is searched
6030     // for conversion functions whose return type is cv T or reference to
6031     // cv T such that T is allowed by the context. There shall be
6032     // exactly one such T.
6033 
6034     // If no unique T is found:
6035     if (ToType.isNull()) {
6036       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6037                                      HadMultipleCandidates,
6038                                      ExplicitConversions))
6039         return ExprError();
6040       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6041     }
6042 
6043     // If more than one unique Ts are found:
6044     if (!HasUniqueTargetType)
6045       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6046                                          ViableConversions);
6047 
6048     // If one unique T is found:
6049     // First, build a candidate set from the previously recorded
6050     // potentially viable conversions.
6051     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6052     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6053                                       CandidateSet);
6054 
6055     // Then, perform overload resolution over the candidate set.
6056     OverloadCandidateSet::iterator Best;
6057     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6058     case OR_Success: {
6059       // Apply this conversion.
6060       DeclAccessPair Found =
6061           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6062       if (recordConversion(*this, Loc, From, Converter, T,
6063                            HadMultipleCandidates, Found))
6064         return ExprError();
6065       break;
6066     }
6067     case OR_Ambiguous:
6068       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6069                                          ViableConversions);
6070     case OR_No_Viable_Function:
6071       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6072                                      HadMultipleCandidates,
6073                                      ExplicitConversions))
6074         return ExprError();
6075       LLVM_FALLTHROUGH;
6076     case OR_Deleted:
6077       // We'll complain below about a non-integral condition type.
6078       break;
6079     }
6080   } else {
6081     switch (ViableConversions.size()) {
6082     case 0: {
6083       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6084                                      HadMultipleCandidates,
6085                                      ExplicitConversions))
6086         return ExprError();
6087 
6088       // We'll complain below about a non-integral condition type.
6089       break;
6090     }
6091     case 1: {
6092       // Apply this conversion.
6093       DeclAccessPair Found = ViableConversions[0];
6094       if (recordConversion(*this, Loc, From, Converter, T,
6095                            HadMultipleCandidates, Found))
6096         return ExprError();
6097       break;
6098     }
6099     default:
6100       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6101                                          ViableConversions);
6102     }
6103   }
6104 
6105   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6106 }
6107 
6108 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6109 /// an acceptable non-member overloaded operator for a call whose
6110 /// arguments have types T1 (and, if non-empty, T2). This routine
6111 /// implements the check in C++ [over.match.oper]p3b2 concerning
6112 /// enumeration types.
6113 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6114                                                    FunctionDecl *Fn,
6115                                                    ArrayRef<Expr *> Args) {
6116   QualType T1 = Args[0]->getType();
6117   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6118 
6119   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6120     return true;
6121 
6122   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6123     return true;
6124 
6125   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6126   if (Proto->getNumParams() < 1)
6127     return false;
6128 
6129   if (T1->isEnumeralType()) {
6130     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6131     if (Context.hasSameUnqualifiedType(T1, ArgType))
6132       return true;
6133   }
6134 
6135   if (Proto->getNumParams() < 2)
6136     return false;
6137 
6138   if (!T2.isNull() && T2->isEnumeralType()) {
6139     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6140     if (Context.hasSameUnqualifiedType(T2, ArgType))
6141       return true;
6142   }
6143 
6144   return false;
6145 }
6146 
6147 /// AddOverloadCandidate - Adds the given function to the set of
6148 /// candidate functions, using the given function call arguments.  If
6149 /// @p SuppressUserConversions, then don't allow user-defined
6150 /// conversions via constructors or conversion operators.
6151 ///
6152 /// \param PartialOverloading true if we are performing "partial" overloading
6153 /// based on an incomplete set of function arguments. This feature is used by
6154 /// code completion.
6155 void Sema::AddOverloadCandidate(
6156     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6157     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6158     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6159     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6160     OverloadCandidateParamOrder PO) {
6161   const FunctionProtoType *Proto
6162     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6163   assert(Proto && "Functions without a prototype cannot be overloaded");
6164   assert(!Function->getDescribedFunctionTemplate() &&
6165          "Use AddTemplateOverloadCandidate for function templates");
6166 
6167   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6168     if (!isa<CXXConstructorDecl>(Method)) {
6169       // If we get here, it's because we're calling a member function
6170       // that is named without a member access expression (e.g.,
6171       // "this->f") that was either written explicitly or created
6172       // implicitly. This can happen with a qualified call to a member
6173       // function, e.g., X::f(). We use an empty type for the implied
6174       // object argument (C++ [over.call.func]p3), and the acting context
6175       // is irrelevant.
6176       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6177                          Expr::Classification::makeSimpleLValue(), Args,
6178                          CandidateSet, SuppressUserConversions,
6179                          PartialOverloading, EarlyConversions, PO);
6180       return;
6181     }
6182     // We treat a constructor like a non-member function, since its object
6183     // argument doesn't participate in overload resolution.
6184   }
6185 
6186   if (!CandidateSet.isNewCandidate(Function, PO))
6187     return;
6188 
6189   // C++11 [class.copy]p11: [DR1402]
6190   //   A defaulted move constructor that is defined as deleted is ignored by
6191   //   overload resolution.
6192   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6193   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6194       Constructor->isMoveConstructor())
6195     return;
6196 
6197   // Overload resolution is always an unevaluated context.
6198   EnterExpressionEvaluationContext Unevaluated(
6199       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6200 
6201   // C++ [over.match.oper]p3:
6202   //   if no operand has a class type, only those non-member functions in the
6203   //   lookup set that have a first parameter of type T1 or "reference to
6204   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6205   //   is a right operand) a second parameter of type T2 or "reference to
6206   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6207   //   candidate functions.
6208   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6209       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6210     return;
6211 
6212   // Add this candidate
6213   OverloadCandidate &Candidate =
6214       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6215   Candidate.FoundDecl = FoundDecl;
6216   Candidate.Function = Function;
6217   Candidate.Viable = true;
6218   Candidate.RewriteKind =
6219       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6220   Candidate.IsSurrogate = false;
6221   Candidate.IsADLCandidate = IsADLCandidate;
6222   Candidate.IgnoreObjectArgument = false;
6223   Candidate.ExplicitCallArguments = Args.size();
6224 
6225   // Explicit functions are not actually candidates at all if we're not
6226   // allowing them in this context, but keep them around so we can point
6227   // to them in diagnostics.
6228   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6229     Candidate.Viable = false;
6230     Candidate.FailureKind = ovl_fail_explicit;
6231     return;
6232   }
6233 
6234   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6235       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6236     Candidate.Viable = false;
6237     Candidate.FailureKind = ovl_non_default_multiversion_function;
6238     return;
6239   }
6240 
6241   if (Constructor) {
6242     // C++ [class.copy]p3:
6243     //   A member function template is never instantiated to perform the copy
6244     //   of a class object to an object of its class type.
6245     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6246     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6247         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6248          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6249                        ClassType))) {
6250       Candidate.Viable = false;
6251       Candidate.FailureKind = ovl_fail_illegal_constructor;
6252       return;
6253     }
6254 
6255     // C++ [over.match.funcs]p8: (proposed DR resolution)
6256     //   A constructor inherited from class type C that has a first parameter
6257     //   of type "reference to P" (including such a constructor instantiated
6258     //   from a template) is excluded from the set of candidate functions when
6259     //   constructing an object of type cv D if the argument list has exactly
6260     //   one argument and D is reference-related to P and P is reference-related
6261     //   to C.
6262     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6263     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6264         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6265       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6266       QualType C = Context.getRecordType(Constructor->getParent());
6267       QualType D = Context.getRecordType(Shadow->getParent());
6268       SourceLocation Loc = Args.front()->getExprLoc();
6269       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6270           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6271         Candidate.Viable = false;
6272         Candidate.FailureKind = ovl_fail_inhctor_slice;
6273         return;
6274       }
6275     }
6276 
6277     // Check that the constructor is capable of constructing an object in the
6278     // destination address space.
6279     if (!Qualifiers::isAddressSpaceSupersetOf(
6280             Constructor->getMethodQualifiers().getAddressSpace(),
6281             CandidateSet.getDestAS())) {
6282       Candidate.Viable = false;
6283       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6284     }
6285   }
6286 
6287   unsigned NumParams = Proto->getNumParams();
6288 
6289   // (C++ 13.3.2p2): A candidate function having fewer than m
6290   // parameters is viable only if it has an ellipsis in its parameter
6291   // list (8.3.5).
6292   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6293       !Proto->isVariadic()) {
6294     Candidate.Viable = false;
6295     Candidate.FailureKind = ovl_fail_too_many_arguments;
6296     return;
6297   }
6298 
6299   // (C++ 13.3.2p2): A candidate function having more than m parameters
6300   // is viable only if the (m+1)st parameter has a default argument
6301   // (8.3.6). For the purposes of overload resolution, the
6302   // parameter list is truncated on the right, so that there are
6303   // exactly m parameters.
6304   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6305   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6306     // Not enough arguments.
6307     Candidate.Viable = false;
6308     Candidate.FailureKind = ovl_fail_too_few_arguments;
6309     return;
6310   }
6311 
6312   // (CUDA B.1): Check for invalid calls between targets.
6313   if (getLangOpts().CUDA)
6314     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6315       // Skip the check for callers that are implicit members, because in this
6316       // case we may not yet know what the member's target is; the target is
6317       // inferred for the member automatically, based on the bases and fields of
6318       // the class.
6319       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6320         Candidate.Viable = false;
6321         Candidate.FailureKind = ovl_fail_bad_target;
6322         return;
6323       }
6324 
6325   if (Function->getTrailingRequiresClause()) {
6326     ConstraintSatisfaction Satisfaction;
6327     if (CheckFunctionConstraints(Function, Satisfaction) ||
6328         !Satisfaction.IsSatisfied) {
6329       Candidate.Viable = false;
6330       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6331       return;
6332     }
6333   }
6334 
6335   // Determine the implicit conversion sequences for each of the
6336   // arguments.
6337   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6338     unsigned ConvIdx =
6339         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6340     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6341       // We already formed a conversion sequence for this parameter during
6342       // template argument deduction.
6343     } else if (ArgIdx < NumParams) {
6344       // (C++ 13.3.2p3): for F to be a viable function, there shall
6345       // exist for each argument an implicit conversion sequence
6346       // (13.3.3.1) that converts that argument to the corresponding
6347       // parameter of F.
6348       QualType ParamType = Proto->getParamType(ArgIdx);
6349       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6350           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6351           /*InOverloadResolution=*/true,
6352           /*AllowObjCWritebackConversion=*/
6353           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6354       if (Candidate.Conversions[ConvIdx].isBad()) {
6355         Candidate.Viable = false;
6356         Candidate.FailureKind = ovl_fail_bad_conversion;
6357         return;
6358       }
6359     } else {
6360       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6361       // argument for which there is no corresponding parameter is
6362       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6363       Candidate.Conversions[ConvIdx].setEllipsis();
6364     }
6365   }
6366 
6367   if (EnableIfAttr *FailedAttr =
6368           CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
6369     Candidate.Viable = false;
6370     Candidate.FailureKind = ovl_fail_enable_if;
6371     Candidate.DeductionFailure.Data = FailedAttr;
6372     return;
6373   }
6374 
6375   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6376     Candidate.Viable = false;
6377     Candidate.FailureKind = ovl_fail_ext_disabled;
6378     return;
6379   }
6380 }
6381 
6382 ObjCMethodDecl *
6383 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6384                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6385   if (Methods.size() <= 1)
6386     return nullptr;
6387 
6388   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6389     bool Match = true;
6390     ObjCMethodDecl *Method = Methods[b];
6391     unsigned NumNamedArgs = Sel.getNumArgs();
6392     // Method might have more arguments than selector indicates. This is due
6393     // to addition of c-style arguments in method.
6394     if (Method->param_size() > NumNamedArgs)
6395       NumNamedArgs = Method->param_size();
6396     if (Args.size() < NumNamedArgs)
6397       continue;
6398 
6399     for (unsigned i = 0; i < NumNamedArgs; i++) {
6400       // We can't do any type-checking on a type-dependent argument.
6401       if (Args[i]->isTypeDependent()) {
6402         Match = false;
6403         break;
6404       }
6405 
6406       ParmVarDecl *param = Method->parameters()[i];
6407       Expr *argExpr = Args[i];
6408       assert(argExpr && "SelectBestMethod(): missing expression");
6409 
6410       // Strip the unbridged-cast placeholder expression off unless it's
6411       // a consumed argument.
6412       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6413           !param->hasAttr<CFConsumedAttr>())
6414         argExpr = stripARCUnbridgedCast(argExpr);
6415 
6416       // If the parameter is __unknown_anytype, move on to the next method.
6417       if (param->getType() == Context.UnknownAnyTy) {
6418         Match = false;
6419         break;
6420       }
6421 
6422       ImplicitConversionSequence ConversionState
6423         = TryCopyInitialization(*this, argExpr, param->getType(),
6424                                 /*SuppressUserConversions*/false,
6425                                 /*InOverloadResolution=*/true,
6426                                 /*AllowObjCWritebackConversion=*/
6427                                 getLangOpts().ObjCAutoRefCount,
6428                                 /*AllowExplicit*/false);
6429       // This function looks for a reasonably-exact match, so we consider
6430       // incompatible pointer conversions to be a failure here.
6431       if (ConversionState.isBad() ||
6432           (ConversionState.isStandard() &&
6433            ConversionState.Standard.Second ==
6434                ICK_Incompatible_Pointer_Conversion)) {
6435         Match = false;
6436         break;
6437       }
6438     }
6439     // Promote additional arguments to variadic methods.
6440     if (Match && Method->isVariadic()) {
6441       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6442         if (Args[i]->isTypeDependent()) {
6443           Match = false;
6444           break;
6445         }
6446         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6447                                                           nullptr);
6448         if (Arg.isInvalid()) {
6449           Match = false;
6450           break;
6451         }
6452       }
6453     } else {
6454       // Check for extra arguments to non-variadic methods.
6455       if (Args.size() != NumNamedArgs)
6456         Match = false;
6457       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6458         // Special case when selectors have no argument. In this case, select
6459         // one with the most general result type of 'id'.
6460         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6461           QualType ReturnT = Methods[b]->getReturnType();
6462           if (ReturnT->isObjCIdType())
6463             return Methods[b];
6464         }
6465       }
6466     }
6467 
6468     if (Match)
6469       return Method;
6470   }
6471   return nullptr;
6472 }
6473 
6474 static bool convertArgsForAvailabilityChecks(
6475     Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
6476     ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
6477     Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
6478   if (ThisArg) {
6479     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6480     assert(!isa<CXXConstructorDecl>(Method) &&
6481            "Shouldn't have `this` for ctors!");
6482     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6483     ExprResult R = S.PerformObjectArgumentInitialization(
6484         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6485     if (R.isInvalid())
6486       return false;
6487     ConvertedThis = R.get();
6488   } else {
6489     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6490       (void)MD;
6491       assert((MissingImplicitThis || MD->isStatic() ||
6492               isa<CXXConstructorDecl>(MD)) &&
6493              "Expected `this` for non-ctor instance methods");
6494     }
6495     ConvertedThis = nullptr;
6496   }
6497 
6498   // Ignore any variadic arguments. Converting them is pointless, since the
6499   // user can't refer to them in the function condition.
6500   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6501 
6502   // Convert the arguments.
6503   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6504     ExprResult R;
6505     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6506                                         S.Context, Function->getParamDecl(I)),
6507                                     SourceLocation(), Args[I]);
6508 
6509     if (R.isInvalid())
6510       return false;
6511 
6512     ConvertedArgs.push_back(R.get());
6513   }
6514 
6515   if (Trap.hasErrorOccurred())
6516     return false;
6517 
6518   // Push default arguments if needed.
6519   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6520     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6521       ParmVarDecl *P = Function->getParamDecl(i);
6522       if (!P->hasDefaultArg())
6523         return false;
6524       ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
6525       if (R.isInvalid())
6526         return false;
6527       ConvertedArgs.push_back(R.get());
6528     }
6529 
6530     if (Trap.hasErrorOccurred())
6531       return false;
6532   }
6533   return true;
6534 }
6535 
6536 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
6537                                   SourceLocation CallLoc,
6538                                   ArrayRef<Expr *> Args,
6539                                   bool MissingImplicitThis) {
6540   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6541   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6542     return nullptr;
6543 
6544   SFINAETrap Trap(*this);
6545   SmallVector<Expr *, 16> ConvertedArgs;
6546   // FIXME: We should look into making enable_if late-parsed.
6547   Expr *DiscardedThis;
6548   if (!convertArgsForAvailabilityChecks(
6549           *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
6550           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6551     return *EnableIfAttrs.begin();
6552 
6553   for (auto *EIA : EnableIfAttrs) {
6554     APValue Result;
6555     // FIXME: This doesn't consider value-dependent cases, because doing so is
6556     // very difficult. Ideally, we should handle them more gracefully.
6557     if (EIA->getCond()->isValueDependent() ||
6558         !EIA->getCond()->EvaluateWithSubstitution(
6559             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6560       return EIA;
6561 
6562     if (!Result.isInt() || !Result.getInt().getBoolValue())
6563       return EIA;
6564   }
6565   return nullptr;
6566 }
6567 
6568 template <typename CheckFn>
6569 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6570                                         bool ArgDependent, SourceLocation Loc,
6571                                         CheckFn &&IsSuccessful) {
6572   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6573   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6574     if (ArgDependent == DIA->getArgDependent())
6575       Attrs.push_back(DIA);
6576   }
6577 
6578   // Common case: No diagnose_if attributes, so we can quit early.
6579   if (Attrs.empty())
6580     return false;
6581 
6582   auto WarningBegin = std::stable_partition(
6583       Attrs.begin(), Attrs.end(),
6584       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6585 
6586   // Note that diagnose_if attributes are late-parsed, so they appear in the
6587   // correct order (unlike enable_if attributes).
6588   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6589                                IsSuccessful);
6590   if (ErrAttr != WarningBegin) {
6591     const DiagnoseIfAttr *DIA = *ErrAttr;
6592     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6593     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6594         << DIA->getParent() << DIA->getCond()->getSourceRange();
6595     return true;
6596   }
6597 
6598   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6599     if (IsSuccessful(DIA)) {
6600       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6601       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6602           << DIA->getParent() << DIA->getCond()->getSourceRange();
6603     }
6604 
6605   return false;
6606 }
6607 
6608 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6609                                                const Expr *ThisArg,
6610                                                ArrayRef<const Expr *> Args,
6611                                                SourceLocation Loc) {
6612   return diagnoseDiagnoseIfAttrsWith(
6613       *this, Function, /*ArgDependent=*/true, Loc,
6614       [&](const DiagnoseIfAttr *DIA) {
6615         APValue Result;
6616         // It's sane to use the same Args for any redecl of this function, since
6617         // EvaluateWithSubstitution only cares about the position of each
6618         // argument in the arg list, not the ParmVarDecl* it maps to.
6619         if (!DIA->getCond()->EvaluateWithSubstitution(
6620                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6621           return false;
6622         return Result.isInt() && Result.getInt().getBoolValue();
6623       });
6624 }
6625 
6626 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6627                                                  SourceLocation Loc) {
6628   return diagnoseDiagnoseIfAttrsWith(
6629       *this, ND, /*ArgDependent=*/false, Loc,
6630       [&](const DiagnoseIfAttr *DIA) {
6631         bool Result;
6632         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6633                Result;
6634       });
6635 }
6636 
6637 /// Add all of the function declarations in the given function set to
6638 /// the overload candidate set.
6639 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6640                                  ArrayRef<Expr *> Args,
6641                                  OverloadCandidateSet &CandidateSet,
6642                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6643                                  bool SuppressUserConversions,
6644                                  bool PartialOverloading,
6645                                  bool FirstArgumentIsBase) {
6646   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6647     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6648     ArrayRef<Expr *> FunctionArgs = Args;
6649 
6650     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6651     FunctionDecl *FD =
6652         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6653 
6654     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6655       QualType ObjectType;
6656       Expr::Classification ObjectClassification;
6657       if (Args.size() > 0) {
6658         if (Expr *E = Args[0]) {
6659           // Use the explicit base to restrict the lookup:
6660           ObjectType = E->getType();
6661           // Pointers in the object arguments are implicitly dereferenced, so we
6662           // always classify them as l-values.
6663           if (!ObjectType.isNull() && ObjectType->isPointerType())
6664             ObjectClassification = Expr::Classification::makeSimpleLValue();
6665           else
6666             ObjectClassification = E->Classify(Context);
6667         } // .. else there is an implicit base.
6668         FunctionArgs = Args.slice(1);
6669       }
6670       if (FunTmpl) {
6671         AddMethodTemplateCandidate(
6672             FunTmpl, F.getPair(),
6673             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6674             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6675             FunctionArgs, CandidateSet, SuppressUserConversions,
6676             PartialOverloading);
6677       } else {
6678         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6679                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6680                            ObjectClassification, FunctionArgs, CandidateSet,
6681                            SuppressUserConversions, PartialOverloading);
6682       }
6683     } else {
6684       // This branch handles both standalone functions and static methods.
6685 
6686       // Slice the first argument (which is the base) when we access
6687       // static method as non-static.
6688       if (Args.size() > 0 &&
6689           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6690                         !isa<CXXConstructorDecl>(FD)))) {
6691         assert(cast<CXXMethodDecl>(FD)->isStatic());
6692         FunctionArgs = Args.slice(1);
6693       }
6694       if (FunTmpl) {
6695         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6696                                      ExplicitTemplateArgs, FunctionArgs,
6697                                      CandidateSet, SuppressUserConversions,
6698                                      PartialOverloading);
6699       } else {
6700         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6701                              SuppressUserConversions, PartialOverloading);
6702       }
6703     }
6704   }
6705 }
6706 
6707 /// AddMethodCandidate - Adds a named decl (which is some kind of
6708 /// method) as a method candidate to the given overload set.
6709 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6710                               Expr::Classification ObjectClassification,
6711                               ArrayRef<Expr *> Args,
6712                               OverloadCandidateSet &CandidateSet,
6713                               bool SuppressUserConversions,
6714                               OverloadCandidateParamOrder PO) {
6715   NamedDecl *Decl = FoundDecl.getDecl();
6716   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6717 
6718   if (isa<UsingShadowDecl>(Decl))
6719     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6720 
6721   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6722     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6723            "Expected a member function template");
6724     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6725                                /*ExplicitArgs*/ nullptr, ObjectType,
6726                                ObjectClassification, Args, CandidateSet,
6727                                SuppressUserConversions, false, PO);
6728   } else {
6729     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6730                        ObjectType, ObjectClassification, Args, CandidateSet,
6731                        SuppressUserConversions, false, None, PO);
6732   }
6733 }
6734 
6735 /// AddMethodCandidate - Adds the given C++ member function to the set
6736 /// of candidate functions, using the given function call arguments
6737 /// and the object argument (@c Object). For example, in a call
6738 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6739 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6740 /// allow user-defined conversions via constructors or conversion
6741 /// operators.
6742 void
6743 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6744                          CXXRecordDecl *ActingContext, QualType ObjectType,
6745                          Expr::Classification ObjectClassification,
6746                          ArrayRef<Expr *> Args,
6747                          OverloadCandidateSet &CandidateSet,
6748                          bool SuppressUserConversions,
6749                          bool PartialOverloading,
6750                          ConversionSequenceList EarlyConversions,
6751                          OverloadCandidateParamOrder PO) {
6752   const FunctionProtoType *Proto
6753     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6754   assert(Proto && "Methods without a prototype cannot be overloaded");
6755   assert(!isa<CXXConstructorDecl>(Method) &&
6756          "Use AddOverloadCandidate for constructors");
6757 
6758   if (!CandidateSet.isNewCandidate(Method, PO))
6759     return;
6760 
6761   // C++11 [class.copy]p23: [DR1402]
6762   //   A defaulted move assignment operator that is defined as deleted is
6763   //   ignored by overload resolution.
6764   if (Method->isDefaulted() && Method->isDeleted() &&
6765       Method->isMoveAssignmentOperator())
6766     return;
6767 
6768   // Overload resolution is always an unevaluated context.
6769   EnterExpressionEvaluationContext Unevaluated(
6770       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6771 
6772   // Add this candidate
6773   OverloadCandidate &Candidate =
6774       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6775   Candidate.FoundDecl = FoundDecl;
6776   Candidate.Function = Method;
6777   Candidate.RewriteKind =
6778       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6779   Candidate.IsSurrogate = false;
6780   Candidate.IgnoreObjectArgument = false;
6781   Candidate.ExplicitCallArguments = Args.size();
6782 
6783   unsigned NumParams = Proto->getNumParams();
6784 
6785   // (C++ 13.3.2p2): A candidate function having fewer than m
6786   // parameters is viable only if it has an ellipsis in its parameter
6787   // list (8.3.5).
6788   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6789       !Proto->isVariadic()) {
6790     Candidate.Viable = false;
6791     Candidate.FailureKind = ovl_fail_too_many_arguments;
6792     return;
6793   }
6794 
6795   // (C++ 13.3.2p2): A candidate function having more than m parameters
6796   // is viable only if the (m+1)st parameter has a default argument
6797   // (8.3.6). For the purposes of overload resolution, the
6798   // parameter list is truncated on the right, so that there are
6799   // exactly m parameters.
6800   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6801   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6802     // Not enough arguments.
6803     Candidate.Viable = false;
6804     Candidate.FailureKind = ovl_fail_too_few_arguments;
6805     return;
6806   }
6807 
6808   Candidate.Viable = true;
6809 
6810   if (Method->isStatic() || ObjectType.isNull())
6811     // The implicit object argument is ignored.
6812     Candidate.IgnoreObjectArgument = true;
6813   else {
6814     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6815     // Determine the implicit conversion sequence for the object
6816     // parameter.
6817     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6818         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6819         Method, ActingContext);
6820     if (Candidate.Conversions[ConvIdx].isBad()) {
6821       Candidate.Viable = false;
6822       Candidate.FailureKind = ovl_fail_bad_conversion;
6823       return;
6824     }
6825   }
6826 
6827   // (CUDA B.1): Check for invalid calls between targets.
6828   if (getLangOpts().CUDA)
6829     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6830       if (!IsAllowedCUDACall(Caller, Method)) {
6831         Candidate.Viable = false;
6832         Candidate.FailureKind = ovl_fail_bad_target;
6833         return;
6834       }
6835 
6836   if (Method->getTrailingRequiresClause()) {
6837     ConstraintSatisfaction Satisfaction;
6838     if (CheckFunctionConstraints(Method, Satisfaction) ||
6839         !Satisfaction.IsSatisfied) {
6840       Candidate.Viable = false;
6841       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6842       return;
6843     }
6844   }
6845 
6846   // Determine the implicit conversion sequences for each of the
6847   // arguments.
6848   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6849     unsigned ConvIdx =
6850         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6851     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6852       // We already formed a conversion sequence for this parameter during
6853       // template argument deduction.
6854     } else if (ArgIdx < NumParams) {
6855       // (C++ 13.3.2p3): for F to be a viable function, there shall
6856       // exist for each argument an implicit conversion sequence
6857       // (13.3.3.1) that converts that argument to the corresponding
6858       // parameter of F.
6859       QualType ParamType = Proto->getParamType(ArgIdx);
6860       Candidate.Conversions[ConvIdx]
6861         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6862                                 SuppressUserConversions,
6863                                 /*InOverloadResolution=*/true,
6864                                 /*AllowObjCWritebackConversion=*/
6865                                   getLangOpts().ObjCAutoRefCount);
6866       if (Candidate.Conversions[ConvIdx].isBad()) {
6867         Candidate.Viable = false;
6868         Candidate.FailureKind = ovl_fail_bad_conversion;
6869         return;
6870       }
6871     } else {
6872       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6873       // argument for which there is no corresponding parameter is
6874       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6875       Candidate.Conversions[ConvIdx].setEllipsis();
6876     }
6877   }
6878 
6879   if (EnableIfAttr *FailedAttr =
6880           CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
6881     Candidate.Viable = false;
6882     Candidate.FailureKind = ovl_fail_enable_if;
6883     Candidate.DeductionFailure.Data = FailedAttr;
6884     return;
6885   }
6886 
6887   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6888       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6889     Candidate.Viable = false;
6890     Candidate.FailureKind = ovl_non_default_multiversion_function;
6891   }
6892 }
6893 
6894 /// Add a C++ member function template as a candidate to the candidate
6895 /// set, using template argument deduction to produce an appropriate member
6896 /// function template specialization.
6897 void Sema::AddMethodTemplateCandidate(
6898     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6899     CXXRecordDecl *ActingContext,
6900     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6901     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6902     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6903     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6904   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6905     return;
6906 
6907   // C++ [over.match.funcs]p7:
6908   //   In each case where a candidate is a function template, candidate
6909   //   function template specializations are generated using template argument
6910   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6911   //   candidate functions in the usual way.113) A given name can refer to one
6912   //   or more function templates and also to a set of overloaded non-template
6913   //   functions. In such a case, the candidate functions generated from each
6914   //   function template are combined with the set of non-template candidate
6915   //   functions.
6916   TemplateDeductionInfo Info(CandidateSet.getLocation());
6917   FunctionDecl *Specialization = nullptr;
6918   ConversionSequenceList Conversions;
6919   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6920           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6921           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6922             return CheckNonDependentConversions(
6923                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6924                 SuppressUserConversions, ActingContext, ObjectType,
6925                 ObjectClassification, PO);
6926           })) {
6927     OverloadCandidate &Candidate =
6928         CandidateSet.addCandidate(Conversions.size(), Conversions);
6929     Candidate.FoundDecl = FoundDecl;
6930     Candidate.Function = MethodTmpl->getTemplatedDecl();
6931     Candidate.Viable = false;
6932     Candidate.RewriteKind =
6933       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6934     Candidate.IsSurrogate = false;
6935     Candidate.IgnoreObjectArgument =
6936         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6937         ObjectType.isNull();
6938     Candidate.ExplicitCallArguments = Args.size();
6939     if (Result == TDK_NonDependentConversionFailure)
6940       Candidate.FailureKind = ovl_fail_bad_conversion;
6941     else {
6942       Candidate.FailureKind = ovl_fail_bad_deduction;
6943       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6944                                                             Info);
6945     }
6946     return;
6947   }
6948 
6949   // Add the function template specialization produced by template argument
6950   // deduction as a candidate.
6951   assert(Specialization && "Missing member function template specialization?");
6952   assert(isa<CXXMethodDecl>(Specialization) &&
6953          "Specialization is not a member function?");
6954   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6955                      ActingContext, ObjectType, ObjectClassification, Args,
6956                      CandidateSet, SuppressUserConversions, PartialOverloading,
6957                      Conversions, PO);
6958 }
6959 
6960 /// Determine whether a given function template has a simple explicit specifier
6961 /// or a non-value-dependent explicit-specification that evaluates to true.
6962 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6963   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6964 }
6965 
6966 /// Add a C++ function template specialization as a candidate
6967 /// in the candidate set, using template argument deduction to produce
6968 /// an appropriate function template specialization.
6969 void Sema::AddTemplateOverloadCandidate(
6970     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6971     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6972     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6973     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6974     OverloadCandidateParamOrder PO) {
6975   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6976     return;
6977 
6978   // If the function template has a non-dependent explicit specification,
6979   // exclude it now if appropriate; we are not permitted to perform deduction
6980   // and substitution in this case.
6981   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6982     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6983     Candidate.FoundDecl = FoundDecl;
6984     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6985     Candidate.Viable = false;
6986     Candidate.FailureKind = ovl_fail_explicit;
6987     return;
6988   }
6989 
6990   // C++ [over.match.funcs]p7:
6991   //   In each case where a candidate is a function template, candidate
6992   //   function template specializations are generated using template argument
6993   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6994   //   candidate functions in the usual way.113) A given name can refer to one
6995   //   or more function templates and also to a set of overloaded non-template
6996   //   functions. In such a case, the candidate functions generated from each
6997   //   function template are combined with the set of non-template candidate
6998   //   functions.
6999   TemplateDeductionInfo Info(CandidateSet.getLocation());
7000   FunctionDecl *Specialization = nullptr;
7001   ConversionSequenceList Conversions;
7002   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7003           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7004           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7005             return CheckNonDependentConversions(
7006                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7007                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7008           })) {
7009     OverloadCandidate &Candidate =
7010         CandidateSet.addCandidate(Conversions.size(), Conversions);
7011     Candidate.FoundDecl = FoundDecl;
7012     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7013     Candidate.Viable = false;
7014     Candidate.RewriteKind =
7015       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7016     Candidate.IsSurrogate = false;
7017     Candidate.IsADLCandidate = IsADLCandidate;
7018     // Ignore the object argument if there is one, since we don't have an object
7019     // type.
7020     Candidate.IgnoreObjectArgument =
7021         isa<CXXMethodDecl>(Candidate.Function) &&
7022         !isa<CXXConstructorDecl>(Candidate.Function);
7023     Candidate.ExplicitCallArguments = Args.size();
7024     if (Result == TDK_NonDependentConversionFailure)
7025       Candidate.FailureKind = ovl_fail_bad_conversion;
7026     else {
7027       Candidate.FailureKind = ovl_fail_bad_deduction;
7028       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7029                                                             Info);
7030     }
7031     return;
7032   }
7033 
7034   // Add the function template specialization produced by template argument
7035   // deduction as a candidate.
7036   assert(Specialization && "Missing function template specialization?");
7037   AddOverloadCandidate(
7038       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7039       PartialOverloading, AllowExplicit,
7040       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7041 }
7042 
7043 /// Check that implicit conversion sequences can be formed for each argument
7044 /// whose corresponding parameter has a non-dependent type, per DR1391's
7045 /// [temp.deduct.call]p10.
7046 bool Sema::CheckNonDependentConversions(
7047     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7048     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7049     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7050     CXXRecordDecl *ActingContext, QualType ObjectType,
7051     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7052   // FIXME: The cases in which we allow explicit conversions for constructor
7053   // arguments never consider calling a constructor template. It's not clear
7054   // that is correct.
7055   const bool AllowExplicit = false;
7056 
7057   auto *FD = FunctionTemplate->getTemplatedDecl();
7058   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7059   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7060   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7061 
7062   Conversions =
7063       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7064 
7065   // Overload resolution is always an unevaluated context.
7066   EnterExpressionEvaluationContext Unevaluated(
7067       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7068 
7069   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7070   // require that, but this check should never result in a hard error, and
7071   // overload resolution is permitted to sidestep instantiations.
7072   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7073       !ObjectType.isNull()) {
7074     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7075     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7076         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7077         Method, ActingContext);
7078     if (Conversions[ConvIdx].isBad())
7079       return true;
7080   }
7081 
7082   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7083        ++I) {
7084     QualType ParamType = ParamTypes[I];
7085     if (!ParamType->isDependentType()) {
7086       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7087                              ? 0
7088                              : (ThisConversions + I);
7089       Conversions[ConvIdx]
7090         = TryCopyInitialization(*this, Args[I], ParamType,
7091                                 SuppressUserConversions,
7092                                 /*InOverloadResolution=*/true,
7093                                 /*AllowObjCWritebackConversion=*/
7094                                   getLangOpts().ObjCAutoRefCount,
7095                                 AllowExplicit);
7096       if (Conversions[ConvIdx].isBad())
7097         return true;
7098     }
7099   }
7100 
7101   return false;
7102 }
7103 
7104 /// Determine whether this is an allowable conversion from the result
7105 /// of an explicit conversion operator to the expected type, per C++
7106 /// [over.match.conv]p1 and [over.match.ref]p1.
7107 ///
7108 /// \param ConvType The return type of the conversion function.
7109 ///
7110 /// \param ToType The type we are converting to.
7111 ///
7112 /// \param AllowObjCPointerConversion Allow a conversion from one
7113 /// Objective-C pointer to another.
7114 ///
7115 /// \returns true if the conversion is allowable, false otherwise.
7116 static bool isAllowableExplicitConversion(Sema &S,
7117                                           QualType ConvType, QualType ToType,
7118                                           bool AllowObjCPointerConversion) {
7119   QualType ToNonRefType = ToType.getNonReferenceType();
7120 
7121   // Easy case: the types are the same.
7122   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7123     return true;
7124 
7125   // Allow qualification conversions.
7126   bool ObjCLifetimeConversion;
7127   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7128                                   ObjCLifetimeConversion))
7129     return true;
7130 
7131   // If we're not allowed to consider Objective-C pointer conversions,
7132   // we're done.
7133   if (!AllowObjCPointerConversion)
7134     return false;
7135 
7136   // Is this an Objective-C pointer conversion?
7137   bool IncompatibleObjC = false;
7138   QualType ConvertedType;
7139   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7140                                    IncompatibleObjC);
7141 }
7142 
7143 /// AddConversionCandidate - Add a C++ conversion function as a
7144 /// candidate in the candidate set (C++ [over.match.conv],
7145 /// C++ [over.match.copy]). From is the expression we're converting from,
7146 /// and ToType is the type that we're eventually trying to convert to
7147 /// (which may or may not be the same type as the type that the
7148 /// conversion function produces).
7149 void Sema::AddConversionCandidate(
7150     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7151     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7152     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7153     bool AllowExplicit, bool AllowResultConversion) {
7154   assert(!Conversion->getDescribedFunctionTemplate() &&
7155          "Conversion function templates use AddTemplateConversionCandidate");
7156   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7157   if (!CandidateSet.isNewCandidate(Conversion))
7158     return;
7159 
7160   // If the conversion function has an undeduced return type, trigger its
7161   // deduction now.
7162   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7163     if (DeduceReturnType(Conversion, From->getExprLoc()))
7164       return;
7165     ConvType = Conversion->getConversionType().getNonReferenceType();
7166   }
7167 
7168   // If we don't allow any conversion of the result type, ignore conversion
7169   // functions that don't convert to exactly (possibly cv-qualified) T.
7170   if (!AllowResultConversion &&
7171       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7172     return;
7173 
7174   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7175   // operator is only a candidate if its return type is the target type or
7176   // can be converted to the target type with a qualification conversion.
7177   //
7178   // FIXME: Include such functions in the candidate list and explain why we
7179   // can't select them.
7180   if (Conversion->isExplicit() &&
7181       !isAllowableExplicitConversion(*this, ConvType, ToType,
7182                                      AllowObjCConversionOnExplicit))
7183     return;
7184 
7185   // Overload resolution is always an unevaluated context.
7186   EnterExpressionEvaluationContext Unevaluated(
7187       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7188 
7189   // Add this candidate
7190   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7191   Candidate.FoundDecl = FoundDecl;
7192   Candidate.Function = Conversion;
7193   Candidate.IsSurrogate = false;
7194   Candidate.IgnoreObjectArgument = false;
7195   Candidate.FinalConversion.setAsIdentityConversion();
7196   Candidate.FinalConversion.setFromType(ConvType);
7197   Candidate.FinalConversion.setAllToTypes(ToType);
7198   Candidate.Viable = true;
7199   Candidate.ExplicitCallArguments = 1;
7200 
7201   // Explicit functions are not actually candidates at all if we're not
7202   // allowing them in this context, but keep them around so we can point
7203   // to them in diagnostics.
7204   if (!AllowExplicit && Conversion->isExplicit()) {
7205     Candidate.Viable = false;
7206     Candidate.FailureKind = ovl_fail_explicit;
7207     return;
7208   }
7209 
7210   // C++ [over.match.funcs]p4:
7211   //   For conversion functions, the function is considered to be a member of
7212   //   the class of the implicit implied object argument for the purpose of
7213   //   defining the type of the implicit object parameter.
7214   //
7215   // Determine the implicit conversion sequence for the implicit
7216   // object parameter.
7217   QualType ImplicitParamType = From->getType();
7218   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7219     ImplicitParamType = FromPtrType->getPointeeType();
7220   CXXRecordDecl *ConversionContext
7221     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7222 
7223   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7224       *this, CandidateSet.getLocation(), From->getType(),
7225       From->Classify(Context), Conversion, ConversionContext);
7226 
7227   if (Candidate.Conversions[0].isBad()) {
7228     Candidate.Viable = false;
7229     Candidate.FailureKind = ovl_fail_bad_conversion;
7230     return;
7231   }
7232 
7233   if (Conversion->getTrailingRequiresClause()) {
7234     ConstraintSatisfaction Satisfaction;
7235     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7236         !Satisfaction.IsSatisfied) {
7237       Candidate.Viable = false;
7238       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7239       return;
7240     }
7241   }
7242 
7243   // We won't go through a user-defined type conversion function to convert a
7244   // derived to base as such conversions are given Conversion Rank. They only
7245   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7246   QualType FromCanon
7247     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7248   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7249   if (FromCanon == ToCanon ||
7250       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7251     Candidate.Viable = false;
7252     Candidate.FailureKind = ovl_fail_trivial_conversion;
7253     return;
7254   }
7255 
7256   // To determine what the conversion from the result of calling the
7257   // conversion function to the type we're eventually trying to
7258   // convert to (ToType), we need to synthesize a call to the
7259   // conversion function and attempt copy initialization from it. This
7260   // makes sure that we get the right semantics with respect to
7261   // lvalues/rvalues and the type. Fortunately, we can allocate this
7262   // call on the stack and we don't need its arguments to be
7263   // well-formed.
7264   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7265                             VK_LValue, From->getBeginLoc());
7266   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7267                                 Context.getPointerType(Conversion->getType()),
7268                                 CK_FunctionToPointerDecay,
7269                                 &ConversionRef, VK_RValue);
7270 
7271   QualType ConversionType = Conversion->getConversionType();
7272   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7273     Candidate.Viable = false;
7274     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7275     return;
7276   }
7277 
7278   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7279 
7280   // Note that it is safe to allocate CallExpr on the stack here because
7281   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7282   // allocator).
7283   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7284 
7285   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7286   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7287       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7288 
7289   ImplicitConversionSequence ICS =
7290       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7291                             /*SuppressUserConversions=*/true,
7292                             /*InOverloadResolution=*/false,
7293                             /*AllowObjCWritebackConversion=*/false);
7294 
7295   switch (ICS.getKind()) {
7296   case ImplicitConversionSequence::StandardConversion:
7297     Candidate.FinalConversion = ICS.Standard;
7298 
7299     // C++ [over.ics.user]p3:
7300     //   If the user-defined conversion is specified by a specialization of a
7301     //   conversion function template, the second standard conversion sequence
7302     //   shall have exact match rank.
7303     if (Conversion->getPrimaryTemplate() &&
7304         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7305       Candidate.Viable = false;
7306       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7307       return;
7308     }
7309 
7310     // C++0x [dcl.init.ref]p5:
7311     //    In the second case, if the reference is an rvalue reference and
7312     //    the second standard conversion sequence of the user-defined
7313     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7314     //    program is ill-formed.
7315     if (ToType->isRValueReferenceType() &&
7316         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7317       Candidate.Viable = false;
7318       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7319       return;
7320     }
7321     break;
7322 
7323   case ImplicitConversionSequence::BadConversion:
7324     Candidate.Viable = false;
7325     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7326     return;
7327 
7328   default:
7329     llvm_unreachable(
7330            "Can only end up with a standard conversion sequence or failure");
7331   }
7332 
7333   if (EnableIfAttr *FailedAttr =
7334           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7335     Candidate.Viable = false;
7336     Candidate.FailureKind = ovl_fail_enable_if;
7337     Candidate.DeductionFailure.Data = FailedAttr;
7338     return;
7339   }
7340 
7341   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7342       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7343     Candidate.Viable = false;
7344     Candidate.FailureKind = ovl_non_default_multiversion_function;
7345   }
7346 }
7347 
7348 /// Adds a conversion function template specialization
7349 /// candidate to the overload set, using template argument deduction
7350 /// to deduce the template arguments of the conversion function
7351 /// template from the type that we are converting to (C++
7352 /// [temp.deduct.conv]).
7353 void Sema::AddTemplateConversionCandidate(
7354     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7355     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7356     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7357     bool AllowExplicit, bool AllowResultConversion) {
7358   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7359          "Only conversion function templates permitted here");
7360 
7361   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7362     return;
7363 
7364   // If the function template has a non-dependent explicit specification,
7365   // exclude it now if appropriate; we are not permitted to perform deduction
7366   // and substitution in this case.
7367   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7368     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7369     Candidate.FoundDecl = FoundDecl;
7370     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7371     Candidate.Viable = false;
7372     Candidate.FailureKind = ovl_fail_explicit;
7373     return;
7374   }
7375 
7376   TemplateDeductionInfo Info(CandidateSet.getLocation());
7377   CXXConversionDecl *Specialization = nullptr;
7378   if (TemplateDeductionResult Result
7379         = DeduceTemplateArguments(FunctionTemplate, ToType,
7380                                   Specialization, Info)) {
7381     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7382     Candidate.FoundDecl = FoundDecl;
7383     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7384     Candidate.Viable = false;
7385     Candidate.FailureKind = ovl_fail_bad_deduction;
7386     Candidate.IsSurrogate = false;
7387     Candidate.IgnoreObjectArgument = false;
7388     Candidate.ExplicitCallArguments = 1;
7389     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7390                                                           Info);
7391     return;
7392   }
7393 
7394   // Add the conversion function template specialization produced by
7395   // template argument deduction as a candidate.
7396   assert(Specialization && "Missing function template specialization?");
7397   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7398                          CandidateSet, AllowObjCConversionOnExplicit,
7399                          AllowExplicit, AllowResultConversion);
7400 }
7401 
7402 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7403 /// converts the given @c Object to a function pointer via the
7404 /// conversion function @c Conversion, and then attempts to call it
7405 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7406 /// the type of function that we'll eventually be calling.
7407 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7408                                  DeclAccessPair FoundDecl,
7409                                  CXXRecordDecl *ActingContext,
7410                                  const FunctionProtoType *Proto,
7411                                  Expr *Object,
7412                                  ArrayRef<Expr *> Args,
7413                                  OverloadCandidateSet& CandidateSet) {
7414   if (!CandidateSet.isNewCandidate(Conversion))
7415     return;
7416 
7417   // Overload resolution is always an unevaluated context.
7418   EnterExpressionEvaluationContext Unevaluated(
7419       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7420 
7421   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7422   Candidate.FoundDecl = FoundDecl;
7423   Candidate.Function = nullptr;
7424   Candidate.Surrogate = Conversion;
7425   Candidate.Viable = true;
7426   Candidate.IsSurrogate = true;
7427   Candidate.IgnoreObjectArgument = false;
7428   Candidate.ExplicitCallArguments = Args.size();
7429 
7430   // Determine the implicit conversion sequence for the implicit
7431   // object parameter.
7432   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7433       *this, CandidateSet.getLocation(), Object->getType(),
7434       Object->Classify(Context), Conversion, ActingContext);
7435   if (ObjectInit.isBad()) {
7436     Candidate.Viable = false;
7437     Candidate.FailureKind = ovl_fail_bad_conversion;
7438     Candidate.Conversions[0] = ObjectInit;
7439     return;
7440   }
7441 
7442   // The first conversion is actually a user-defined conversion whose
7443   // first conversion is ObjectInit's standard conversion (which is
7444   // effectively a reference binding). Record it as such.
7445   Candidate.Conversions[0].setUserDefined();
7446   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7447   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7448   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7449   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7450   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7451   Candidate.Conversions[0].UserDefined.After
7452     = Candidate.Conversions[0].UserDefined.Before;
7453   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7454 
7455   // Find the
7456   unsigned NumParams = Proto->getNumParams();
7457 
7458   // (C++ 13.3.2p2): A candidate function having fewer than m
7459   // parameters is viable only if it has an ellipsis in its parameter
7460   // list (8.3.5).
7461   if (Args.size() > NumParams && !Proto->isVariadic()) {
7462     Candidate.Viable = false;
7463     Candidate.FailureKind = ovl_fail_too_many_arguments;
7464     return;
7465   }
7466 
7467   // Function types don't have any default arguments, so just check if
7468   // we have enough arguments.
7469   if (Args.size() < NumParams) {
7470     // Not enough arguments.
7471     Candidate.Viable = false;
7472     Candidate.FailureKind = ovl_fail_too_few_arguments;
7473     return;
7474   }
7475 
7476   // Determine the implicit conversion sequences for each of the
7477   // arguments.
7478   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7479     if (ArgIdx < NumParams) {
7480       // (C++ 13.3.2p3): for F to be a viable function, there shall
7481       // exist for each argument an implicit conversion sequence
7482       // (13.3.3.1) that converts that argument to the corresponding
7483       // parameter of F.
7484       QualType ParamType = Proto->getParamType(ArgIdx);
7485       Candidate.Conversions[ArgIdx + 1]
7486         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7487                                 /*SuppressUserConversions=*/false,
7488                                 /*InOverloadResolution=*/false,
7489                                 /*AllowObjCWritebackConversion=*/
7490                                   getLangOpts().ObjCAutoRefCount);
7491       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7492         Candidate.Viable = false;
7493         Candidate.FailureKind = ovl_fail_bad_conversion;
7494         return;
7495       }
7496     } else {
7497       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7498       // argument for which there is no corresponding parameter is
7499       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7500       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7501     }
7502   }
7503 
7504   if (EnableIfAttr *FailedAttr =
7505           CheckEnableIf(Conversion, CandidateSet.getLocation(), None)) {
7506     Candidate.Viable = false;
7507     Candidate.FailureKind = ovl_fail_enable_if;
7508     Candidate.DeductionFailure.Data = FailedAttr;
7509     return;
7510   }
7511 }
7512 
7513 /// Add all of the non-member operator function declarations in the given
7514 /// function set to the overload candidate set.
7515 void Sema::AddNonMemberOperatorCandidates(
7516     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7517     OverloadCandidateSet &CandidateSet,
7518     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7519   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7520     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7521     ArrayRef<Expr *> FunctionArgs = Args;
7522 
7523     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7524     FunctionDecl *FD =
7525         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7526 
7527     // Don't consider rewritten functions if we're not rewriting.
7528     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7529       continue;
7530 
7531     assert(!isa<CXXMethodDecl>(FD) &&
7532            "unqualified operator lookup found a member function");
7533 
7534     if (FunTmpl) {
7535       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7536                                    FunctionArgs, CandidateSet);
7537       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7538         AddTemplateOverloadCandidate(
7539             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7540             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7541             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7542     } else {
7543       if (ExplicitTemplateArgs)
7544         continue;
7545       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7546       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7547         AddOverloadCandidate(FD, F.getPair(),
7548                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7549                              false, false, true, false, ADLCallKind::NotADL,
7550                              None, OverloadCandidateParamOrder::Reversed);
7551     }
7552   }
7553 }
7554 
7555 /// Add overload candidates for overloaded operators that are
7556 /// member functions.
7557 ///
7558 /// Add the overloaded operator candidates that are member functions
7559 /// for the operator Op that was used in an operator expression such
7560 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7561 /// CandidateSet will store the added overload candidates. (C++
7562 /// [over.match.oper]).
7563 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7564                                        SourceLocation OpLoc,
7565                                        ArrayRef<Expr *> Args,
7566                                        OverloadCandidateSet &CandidateSet,
7567                                        OverloadCandidateParamOrder PO) {
7568   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7569 
7570   // C++ [over.match.oper]p3:
7571   //   For a unary operator @ with an operand of a type whose
7572   //   cv-unqualified version is T1, and for a binary operator @ with
7573   //   a left operand of a type whose cv-unqualified version is T1 and
7574   //   a right operand of a type whose cv-unqualified version is T2,
7575   //   three sets of candidate functions, designated member
7576   //   candidates, non-member candidates and built-in candidates, are
7577   //   constructed as follows:
7578   QualType T1 = Args[0]->getType();
7579 
7580   //     -- If T1 is a complete class type or a class currently being
7581   //        defined, the set of member candidates is the result of the
7582   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7583   //        the set of member candidates is empty.
7584   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7585     // Complete the type if it can be completed.
7586     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7587       return;
7588     // If the type is neither complete nor being defined, bail out now.
7589     if (!T1Rec->getDecl()->getDefinition())
7590       return;
7591 
7592     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7593     LookupQualifiedName(Operators, T1Rec->getDecl());
7594     Operators.suppressDiagnostics();
7595 
7596     for (LookupResult::iterator Oper = Operators.begin(),
7597                              OperEnd = Operators.end();
7598          Oper != OperEnd;
7599          ++Oper)
7600       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7601                          Args[0]->Classify(Context), Args.slice(1),
7602                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7603   }
7604 }
7605 
7606 /// AddBuiltinCandidate - Add a candidate for a built-in
7607 /// operator. ResultTy and ParamTys are the result and parameter types
7608 /// of the built-in candidate, respectively. Args and NumArgs are the
7609 /// arguments being passed to the candidate. IsAssignmentOperator
7610 /// should be true when this built-in candidate is an assignment
7611 /// operator. NumContextualBoolArguments is the number of arguments
7612 /// (at the beginning of the argument list) that will be contextually
7613 /// converted to bool.
7614 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7615                                OverloadCandidateSet& CandidateSet,
7616                                bool IsAssignmentOperator,
7617                                unsigned NumContextualBoolArguments) {
7618   // Overload resolution is always an unevaluated context.
7619   EnterExpressionEvaluationContext Unevaluated(
7620       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7621 
7622   // Add this candidate
7623   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7624   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7625   Candidate.Function = nullptr;
7626   Candidate.IsSurrogate = false;
7627   Candidate.IgnoreObjectArgument = false;
7628   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7629 
7630   // Determine the implicit conversion sequences for each of the
7631   // arguments.
7632   Candidate.Viable = true;
7633   Candidate.ExplicitCallArguments = Args.size();
7634   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7635     // C++ [over.match.oper]p4:
7636     //   For the built-in assignment operators, conversions of the
7637     //   left operand are restricted as follows:
7638     //     -- no temporaries are introduced to hold the left operand, and
7639     //     -- no user-defined conversions are applied to the left
7640     //        operand to achieve a type match with the left-most
7641     //        parameter of a built-in candidate.
7642     //
7643     // We block these conversions by turning off user-defined
7644     // conversions, since that is the only way that initialization of
7645     // a reference to a non-class type can occur from something that
7646     // is not of the same type.
7647     if (ArgIdx < NumContextualBoolArguments) {
7648       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7649              "Contextual conversion to bool requires bool type");
7650       Candidate.Conversions[ArgIdx]
7651         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7652     } else {
7653       Candidate.Conversions[ArgIdx]
7654         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7655                                 ArgIdx == 0 && IsAssignmentOperator,
7656                                 /*InOverloadResolution=*/false,
7657                                 /*AllowObjCWritebackConversion=*/
7658                                   getLangOpts().ObjCAutoRefCount);
7659     }
7660     if (Candidate.Conversions[ArgIdx].isBad()) {
7661       Candidate.Viable = false;
7662       Candidate.FailureKind = ovl_fail_bad_conversion;
7663       break;
7664     }
7665   }
7666 }
7667 
7668 namespace {
7669 
7670 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7671 /// candidate operator functions for built-in operators (C++
7672 /// [over.built]). The types are separated into pointer types and
7673 /// enumeration types.
7674 class BuiltinCandidateTypeSet  {
7675   /// TypeSet - A set of types.
7676   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7677                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7678 
7679   /// PointerTypes - The set of pointer types that will be used in the
7680   /// built-in candidates.
7681   TypeSet PointerTypes;
7682 
7683   /// MemberPointerTypes - The set of member pointer types that will be
7684   /// used in the built-in candidates.
7685   TypeSet MemberPointerTypes;
7686 
7687   /// EnumerationTypes - The set of enumeration types that will be
7688   /// used in the built-in candidates.
7689   TypeSet EnumerationTypes;
7690 
7691   /// The set of vector types that will be used in the built-in
7692   /// candidates.
7693   TypeSet VectorTypes;
7694 
7695   /// The set of matrix types that will be used in the built-in
7696   /// candidates.
7697   TypeSet MatrixTypes;
7698 
7699   /// A flag indicating non-record types are viable candidates
7700   bool HasNonRecordTypes;
7701 
7702   /// A flag indicating whether either arithmetic or enumeration types
7703   /// were present in the candidate set.
7704   bool HasArithmeticOrEnumeralTypes;
7705 
7706   /// A flag indicating whether the nullptr type was present in the
7707   /// candidate set.
7708   bool HasNullPtrType;
7709 
7710   /// Sema - The semantic analysis instance where we are building the
7711   /// candidate type set.
7712   Sema &SemaRef;
7713 
7714   /// Context - The AST context in which we will build the type sets.
7715   ASTContext &Context;
7716 
7717   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7718                                                const Qualifiers &VisibleQuals);
7719   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7720 
7721 public:
7722   /// iterator - Iterates through the types that are part of the set.
7723   typedef TypeSet::iterator iterator;
7724 
7725   BuiltinCandidateTypeSet(Sema &SemaRef)
7726     : HasNonRecordTypes(false),
7727       HasArithmeticOrEnumeralTypes(false),
7728       HasNullPtrType(false),
7729       SemaRef(SemaRef),
7730       Context(SemaRef.Context) { }
7731 
7732   void AddTypesConvertedFrom(QualType Ty,
7733                              SourceLocation Loc,
7734                              bool AllowUserConversions,
7735                              bool AllowExplicitConversions,
7736                              const Qualifiers &VisibleTypeConversionsQuals);
7737 
7738   /// pointer_begin - First pointer type found;
7739   iterator pointer_begin() { return PointerTypes.begin(); }
7740 
7741   /// pointer_end - Past the last pointer type found;
7742   iterator pointer_end() { return PointerTypes.end(); }
7743 
7744   /// member_pointer_begin - First member pointer type found;
7745   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7746 
7747   /// member_pointer_end - Past the last member pointer type found;
7748   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7749 
7750   /// enumeration_begin - First enumeration type found;
7751   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7752 
7753   /// enumeration_end - Past the last enumeration type found;
7754   iterator enumeration_end() { return EnumerationTypes.end(); }
7755 
7756   llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
7757 
7758   llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
7759 
7760   bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
7761   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7762   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7763   bool hasNullPtrType() const { return HasNullPtrType; }
7764 };
7765 
7766 } // end anonymous namespace
7767 
7768 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7769 /// the set of pointer types along with any more-qualified variants of
7770 /// that type. For example, if @p Ty is "int const *", this routine
7771 /// will add "int const *", "int const volatile *", "int const
7772 /// restrict *", and "int const volatile restrict *" to the set of
7773 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7774 /// false otherwise.
7775 ///
7776 /// FIXME: what to do about extended qualifiers?
7777 bool
7778 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7779                                              const Qualifiers &VisibleQuals) {
7780 
7781   // Insert this type.
7782   if (!PointerTypes.insert(Ty))
7783     return false;
7784 
7785   QualType PointeeTy;
7786   const PointerType *PointerTy = Ty->getAs<PointerType>();
7787   bool buildObjCPtr = false;
7788   if (!PointerTy) {
7789     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7790     PointeeTy = PTy->getPointeeType();
7791     buildObjCPtr = true;
7792   } else {
7793     PointeeTy = PointerTy->getPointeeType();
7794   }
7795 
7796   // Don't add qualified variants of arrays. For one, they're not allowed
7797   // (the qualifier would sink to the element type), and for another, the
7798   // only overload situation where it matters is subscript or pointer +- int,
7799   // and those shouldn't have qualifier variants anyway.
7800   if (PointeeTy->isArrayType())
7801     return true;
7802 
7803   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7804   bool hasVolatile = VisibleQuals.hasVolatile();
7805   bool hasRestrict = VisibleQuals.hasRestrict();
7806 
7807   // Iterate through all strict supersets of BaseCVR.
7808   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7809     if ((CVR | BaseCVR) != CVR) continue;
7810     // Skip over volatile if no volatile found anywhere in the types.
7811     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7812 
7813     // Skip over restrict if no restrict found anywhere in the types, or if
7814     // the type cannot be restrict-qualified.
7815     if ((CVR & Qualifiers::Restrict) &&
7816         (!hasRestrict ||
7817          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7818       continue;
7819 
7820     // Build qualified pointee type.
7821     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7822 
7823     // Build qualified pointer type.
7824     QualType QPointerTy;
7825     if (!buildObjCPtr)
7826       QPointerTy = Context.getPointerType(QPointeeTy);
7827     else
7828       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7829 
7830     // Insert qualified pointer type.
7831     PointerTypes.insert(QPointerTy);
7832   }
7833 
7834   return true;
7835 }
7836 
7837 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7838 /// to the set of pointer types along with any more-qualified variants of
7839 /// that type. For example, if @p Ty is "int const *", this routine
7840 /// will add "int const *", "int const volatile *", "int const
7841 /// restrict *", and "int const volatile restrict *" to the set of
7842 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7843 /// false otherwise.
7844 ///
7845 /// FIXME: what to do about extended qualifiers?
7846 bool
7847 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7848     QualType Ty) {
7849   // Insert this type.
7850   if (!MemberPointerTypes.insert(Ty))
7851     return false;
7852 
7853   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7854   assert(PointerTy && "type was not a member pointer type!");
7855 
7856   QualType PointeeTy = PointerTy->getPointeeType();
7857   // Don't add qualified variants of arrays. For one, they're not allowed
7858   // (the qualifier would sink to the element type), and for another, the
7859   // only overload situation where it matters is subscript or pointer +- int,
7860   // and those shouldn't have qualifier variants anyway.
7861   if (PointeeTy->isArrayType())
7862     return true;
7863   const Type *ClassTy = PointerTy->getClass();
7864 
7865   // Iterate through all strict supersets of the pointee type's CVR
7866   // qualifiers.
7867   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7868   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7869     if ((CVR | BaseCVR) != CVR) continue;
7870 
7871     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7872     MemberPointerTypes.insert(
7873       Context.getMemberPointerType(QPointeeTy, ClassTy));
7874   }
7875 
7876   return true;
7877 }
7878 
7879 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7880 /// Ty can be implicit converted to the given set of @p Types. We're
7881 /// primarily interested in pointer types and enumeration types. We also
7882 /// take member pointer types, for the conditional operator.
7883 /// AllowUserConversions is true if we should look at the conversion
7884 /// functions of a class type, and AllowExplicitConversions if we
7885 /// should also include the explicit conversion functions of a class
7886 /// type.
7887 void
7888 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7889                                                SourceLocation Loc,
7890                                                bool AllowUserConversions,
7891                                                bool AllowExplicitConversions,
7892                                                const Qualifiers &VisibleQuals) {
7893   // Only deal with canonical types.
7894   Ty = Context.getCanonicalType(Ty);
7895 
7896   // Look through reference types; they aren't part of the type of an
7897   // expression for the purposes of conversions.
7898   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7899     Ty = RefTy->getPointeeType();
7900 
7901   // If we're dealing with an array type, decay to the pointer.
7902   if (Ty->isArrayType())
7903     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7904 
7905   // Otherwise, we don't care about qualifiers on the type.
7906   Ty = Ty.getLocalUnqualifiedType();
7907 
7908   // Flag if we ever add a non-record type.
7909   const RecordType *TyRec = Ty->getAs<RecordType>();
7910   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7911 
7912   // Flag if we encounter an arithmetic type.
7913   HasArithmeticOrEnumeralTypes =
7914     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7915 
7916   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7917     PointerTypes.insert(Ty);
7918   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7919     // Insert our type, and its more-qualified variants, into the set
7920     // of types.
7921     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7922       return;
7923   } else if (Ty->isMemberPointerType()) {
7924     // Member pointers are far easier, since the pointee can't be converted.
7925     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7926       return;
7927   } else if (Ty->isEnumeralType()) {
7928     HasArithmeticOrEnumeralTypes = true;
7929     EnumerationTypes.insert(Ty);
7930   } else if (Ty->isVectorType()) {
7931     // We treat vector types as arithmetic types in many contexts as an
7932     // extension.
7933     HasArithmeticOrEnumeralTypes = true;
7934     VectorTypes.insert(Ty);
7935   } else if (Ty->isMatrixType()) {
7936     // Similar to vector types, we treat vector types as arithmetic types in
7937     // many contexts as an extension.
7938     HasArithmeticOrEnumeralTypes = true;
7939     MatrixTypes.insert(Ty);
7940   } else if (Ty->isNullPtrType()) {
7941     HasNullPtrType = true;
7942   } else if (AllowUserConversions && TyRec) {
7943     // No conversion functions in incomplete types.
7944     if (!SemaRef.isCompleteType(Loc, Ty))
7945       return;
7946 
7947     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7948     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7949       if (isa<UsingShadowDecl>(D))
7950         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7951 
7952       // Skip conversion function templates; they don't tell us anything
7953       // about which builtin types we can convert to.
7954       if (isa<FunctionTemplateDecl>(D))
7955         continue;
7956 
7957       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7958       if (AllowExplicitConversions || !Conv->isExplicit()) {
7959         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7960                               VisibleQuals);
7961       }
7962     }
7963   }
7964 }
7965 /// Helper function for adjusting address spaces for the pointer or reference
7966 /// operands of builtin operators depending on the argument.
7967 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7968                                                         Expr *Arg) {
7969   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7970 }
7971 
7972 /// Helper function for AddBuiltinOperatorCandidates() that adds
7973 /// the volatile- and non-volatile-qualified assignment operators for the
7974 /// given type to the candidate set.
7975 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7976                                                    QualType T,
7977                                                    ArrayRef<Expr *> Args,
7978                                     OverloadCandidateSet &CandidateSet) {
7979   QualType ParamTypes[2];
7980 
7981   // T& operator=(T&, T)
7982   ParamTypes[0] = S.Context.getLValueReferenceType(
7983       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7984   ParamTypes[1] = T;
7985   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7986                         /*IsAssignmentOperator=*/true);
7987 
7988   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7989     // volatile T& operator=(volatile T&, T)
7990     ParamTypes[0] = S.Context.getLValueReferenceType(
7991         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7992                                                 Args[0]));
7993     ParamTypes[1] = T;
7994     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7995                           /*IsAssignmentOperator=*/true);
7996   }
7997 }
7998 
7999 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8000 /// if any, found in visible type conversion functions found in ArgExpr's type.
8001 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8002     Qualifiers VRQuals;
8003     const RecordType *TyRec;
8004     if (const MemberPointerType *RHSMPType =
8005         ArgExpr->getType()->getAs<MemberPointerType>())
8006       TyRec = RHSMPType->getClass()->getAs<RecordType>();
8007     else
8008       TyRec = ArgExpr->getType()->getAs<RecordType>();
8009     if (!TyRec) {
8010       // Just to be safe, assume the worst case.
8011       VRQuals.addVolatile();
8012       VRQuals.addRestrict();
8013       return VRQuals;
8014     }
8015 
8016     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8017     if (!ClassDecl->hasDefinition())
8018       return VRQuals;
8019 
8020     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8021       if (isa<UsingShadowDecl>(D))
8022         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8023       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8024         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8025         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8026           CanTy = ResTypeRef->getPointeeType();
8027         // Need to go down the pointer/mempointer chain and add qualifiers
8028         // as see them.
8029         bool done = false;
8030         while (!done) {
8031           if (CanTy.isRestrictQualified())
8032             VRQuals.addRestrict();
8033           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8034             CanTy = ResTypePtr->getPointeeType();
8035           else if (const MemberPointerType *ResTypeMPtr =
8036                 CanTy->getAs<MemberPointerType>())
8037             CanTy = ResTypeMPtr->getPointeeType();
8038           else
8039             done = true;
8040           if (CanTy.isVolatileQualified())
8041             VRQuals.addVolatile();
8042           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8043             return VRQuals;
8044         }
8045       }
8046     }
8047     return VRQuals;
8048 }
8049 
8050 namespace {
8051 
8052 /// Helper class to manage the addition of builtin operator overload
8053 /// candidates. It provides shared state and utility methods used throughout
8054 /// the process, as well as a helper method to add each group of builtin
8055 /// operator overloads from the standard to a candidate set.
8056 class BuiltinOperatorOverloadBuilder {
8057   // Common instance state available to all overload candidate addition methods.
8058   Sema &S;
8059   ArrayRef<Expr *> Args;
8060   Qualifiers VisibleTypeConversionsQuals;
8061   bool HasArithmeticOrEnumeralCandidateType;
8062   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8063   OverloadCandidateSet &CandidateSet;
8064 
8065   static constexpr int ArithmeticTypesCap = 24;
8066   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8067 
8068   // Define some indices used to iterate over the arithmetic types in
8069   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8070   // types are that preserved by promotion (C++ [over.built]p2).
8071   unsigned FirstIntegralType,
8072            LastIntegralType;
8073   unsigned FirstPromotedIntegralType,
8074            LastPromotedIntegralType;
8075   unsigned FirstPromotedArithmeticType,
8076            LastPromotedArithmeticType;
8077   unsigned NumArithmeticTypes;
8078 
8079   void InitArithmeticTypes() {
8080     // Start of promoted types.
8081     FirstPromotedArithmeticType = 0;
8082     ArithmeticTypes.push_back(S.Context.FloatTy);
8083     ArithmeticTypes.push_back(S.Context.DoubleTy);
8084     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8085     if (S.Context.getTargetInfo().hasFloat128Type())
8086       ArithmeticTypes.push_back(S.Context.Float128Ty);
8087 
8088     // Start of integral types.
8089     FirstIntegralType = ArithmeticTypes.size();
8090     FirstPromotedIntegralType = ArithmeticTypes.size();
8091     ArithmeticTypes.push_back(S.Context.IntTy);
8092     ArithmeticTypes.push_back(S.Context.LongTy);
8093     ArithmeticTypes.push_back(S.Context.LongLongTy);
8094     if (S.Context.getTargetInfo().hasInt128Type())
8095       ArithmeticTypes.push_back(S.Context.Int128Ty);
8096     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8097     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8098     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8099     if (S.Context.getTargetInfo().hasInt128Type())
8100       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8101     LastPromotedIntegralType = ArithmeticTypes.size();
8102     LastPromotedArithmeticType = ArithmeticTypes.size();
8103     // End of promoted types.
8104 
8105     ArithmeticTypes.push_back(S.Context.BoolTy);
8106     ArithmeticTypes.push_back(S.Context.CharTy);
8107     ArithmeticTypes.push_back(S.Context.WCharTy);
8108     if (S.Context.getLangOpts().Char8)
8109       ArithmeticTypes.push_back(S.Context.Char8Ty);
8110     ArithmeticTypes.push_back(S.Context.Char16Ty);
8111     ArithmeticTypes.push_back(S.Context.Char32Ty);
8112     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8113     ArithmeticTypes.push_back(S.Context.ShortTy);
8114     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8115     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8116     LastIntegralType = ArithmeticTypes.size();
8117     NumArithmeticTypes = ArithmeticTypes.size();
8118     // End of integral types.
8119     // FIXME: What about complex? What about half?
8120 
8121     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8122            "Enough inline storage for all arithmetic types.");
8123   }
8124 
8125   /// Helper method to factor out the common pattern of adding overloads
8126   /// for '++' and '--' builtin operators.
8127   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8128                                            bool HasVolatile,
8129                                            bool HasRestrict) {
8130     QualType ParamTypes[2] = {
8131       S.Context.getLValueReferenceType(CandidateTy),
8132       S.Context.IntTy
8133     };
8134 
8135     // Non-volatile version.
8136     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8137 
8138     // Use a heuristic to reduce number of builtin candidates in the set:
8139     // add volatile version only if there are conversions to a volatile type.
8140     if (HasVolatile) {
8141       ParamTypes[0] =
8142         S.Context.getLValueReferenceType(
8143           S.Context.getVolatileType(CandidateTy));
8144       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8145     }
8146 
8147     // Add restrict version only if there are conversions to a restrict type
8148     // and our candidate type is a non-restrict-qualified pointer.
8149     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8150         !CandidateTy.isRestrictQualified()) {
8151       ParamTypes[0]
8152         = S.Context.getLValueReferenceType(
8153             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8154       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8155 
8156       if (HasVolatile) {
8157         ParamTypes[0]
8158           = S.Context.getLValueReferenceType(
8159               S.Context.getCVRQualifiedType(CandidateTy,
8160                                             (Qualifiers::Volatile |
8161                                              Qualifiers::Restrict)));
8162         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8163       }
8164     }
8165 
8166   }
8167 
8168   /// Helper to add an overload candidate for a binary builtin with types \p L
8169   /// and \p R.
8170   void AddCandidate(QualType L, QualType R) {
8171     QualType LandR[2] = {L, R};
8172     S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8173   }
8174 
8175 public:
8176   BuiltinOperatorOverloadBuilder(
8177     Sema &S, ArrayRef<Expr *> Args,
8178     Qualifiers VisibleTypeConversionsQuals,
8179     bool HasArithmeticOrEnumeralCandidateType,
8180     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8181     OverloadCandidateSet &CandidateSet)
8182     : S(S), Args(Args),
8183       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8184       HasArithmeticOrEnumeralCandidateType(
8185         HasArithmeticOrEnumeralCandidateType),
8186       CandidateTypes(CandidateTypes),
8187       CandidateSet(CandidateSet) {
8188 
8189     InitArithmeticTypes();
8190   }
8191 
8192   // Increment is deprecated for bool since C++17.
8193   //
8194   // C++ [over.built]p3:
8195   //
8196   //   For every pair (T, VQ), where T is an arithmetic type other
8197   //   than bool, and VQ is either volatile or empty, there exist
8198   //   candidate operator functions of the form
8199   //
8200   //       VQ T&      operator++(VQ T&);
8201   //       T          operator++(VQ T&, int);
8202   //
8203   // C++ [over.built]p4:
8204   //
8205   //   For every pair (T, VQ), where T is an arithmetic type other
8206   //   than bool, and VQ is either volatile or empty, there exist
8207   //   candidate operator functions of the form
8208   //
8209   //       VQ T&      operator--(VQ T&);
8210   //       T          operator--(VQ T&, int);
8211   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8212     if (!HasArithmeticOrEnumeralCandidateType)
8213       return;
8214 
8215     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8216       const auto TypeOfT = ArithmeticTypes[Arith];
8217       if (TypeOfT == S.Context.BoolTy) {
8218         if (Op == OO_MinusMinus)
8219           continue;
8220         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8221           continue;
8222       }
8223       addPlusPlusMinusMinusStyleOverloads(
8224         TypeOfT,
8225         VisibleTypeConversionsQuals.hasVolatile(),
8226         VisibleTypeConversionsQuals.hasRestrict());
8227     }
8228   }
8229 
8230   // C++ [over.built]p5:
8231   //
8232   //   For every pair (T, VQ), where T is a cv-qualified or
8233   //   cv-unqualified object type, and VQ is either volatile or
8234   //   empty, there exist candidate operator functions of the form
8235   //
8236   //       T*VQ&      operator++(T*VQ&);
8237   //       T*VQ&      operator--(T*VQ&);
8238   //       T*         operator++(T*VQ&, int);
8239   //       T*         operator--(T*VQ&, int);
8240   void addPlusPlusMinusMinusPointerOverloads() {
8241     for (BuiltinCandidateTypeSet::iterator
8242               Ptr = CandidateTypes[0].pointer_begin(),
8243            PtrEnd = CandidateTypes[0].pointer_end();
8244          Ptr != PtrEnd; ++Ptr) {
8245       // Skip pointer types that aren't pointers to object types.
8246       if (!(*Ptr)->getPointeeType()->isObjectType())
8247         continue;
8248 
8249       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8250         (!(*Ptr).isVolatileQualified() &&
8251          VisibleTypeConversionsQuals.hasVolatile()),
8252         (!(*Ptr).isRestrictQualified() &&
8253          VisibleTypeConversionsQuals.hasRestrict()));
8254     }
8255   }
8256 
8257   // C++ [over.built]p6:
8258   //   For every cv-qualified or cv-unqualified object type T, there
8259   //   exist candidate operator functions of the form
8260   //
8261   //       T&         operator*(T*);
8262   //
8263   // C++ [over.built]p7:
8264   //   For every function type T that does not have cv-qualifiers or a
8265   //   ref-qualifier, there exist candidate operator functions of the form
8266   //       T&         operator*(T*);
8267   void addUnaryStarPointerOverloads() {
8268     for (BuiltinCandidateTypeSet::iterator
8269               Ptr = CandidateTypes[0].pointer_begin(),
8270            PtrEnd = CandidateTypes[0].pointer_end();
8271          Ptr != PtrEnd; ++Ptr) {
8272       QualType ParamTy = *Ptr;
8273       QualType PointeeTy = ParamTy->getPointeeType();
8274       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8275         continue;
8276 
8277       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8278         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8279           continue;
8280 
8281       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8282     }
8283   }
8284 
8285   // C++ [over.built]p9:
8286   //  For every promoted arithmetic type T, there exist candidate
8287   //  operator functions of the form
8288   //
8289   //       T         operator+(T);
8290   //       T         operator-(T);
8291   void addUnaryPlusOrMinusArithmeticOverloads() {
8292     if (!HasArithmeticOrEnumeralCandidateType)
8293       return;
8294 
8295     for (unsigned Arith = FirstPromotedArithmeticType;
8296          Arith < LastPromotedArithmeticType; ++Arith) {
8297       QualType ArithTy = ArithmeticTypes[Arith];
8298       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8299     }
8300 
8301     // Extension: We also add these operators for vector types.
8302     for (QualType VecTy : CandidateTypes[0].vector_types())
8303       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8304   }
8305 
8306   // C++ [over.built]p8:
8307   //   For every type T, there exist candidate operator functions of
8308   //   the form
8309   //
8310   //       T*         operator+(T*);
8311   void addUnaryPlusPointerOverloads() {
8312     for (BuiltinCandidateTypeSet::iterator
8313               Ptr = CandidateTypes[0].pointer_begin(),
8314            PtrEnd = CandidateTypes[0].pointer_end();
8315          Ptr != PtrEnd; ++Ptr) {
8316       QualType ParamTy = *Ptr;
8317       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8318     }
8319   }
8320 
8321   // C++ [over.built]p10:
8322   //   For every promoted integral type T, there exist candidate
8323   //   operator functions of the form
8324   //
8325   //        T         operator~(T);
8326   void addUnaryTildePromotedIntegralOverloads() {
8327     if (!HasArithmeticOrEnumeralCandidateType)
8328       return;
8329 
8330     for (unsigned Int = FirstPromotedIntegralType;
8331          Int < LastPromotedIntegralType; ++Int) {
8332       QualType IntTy = ArithmeticTypes[Int];
8333       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8334     }
8335 
8336     // Extension: We also add this operator for vector types.
8337     for (QualType VecTy : CandidateTypes[0].vector_types())
8338       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8339   }
8340 
8341   // C++ [over.match.oper]p16:
8342   //   For every pointer to member type T or type std::nullptr_t, there
8343   //   exist candidate operator functions of the form
8344   //
8345   //        bool operator==(T,T);
8346   //        bool operator!=(T,T);
8347   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8348     /// Set of (canonical) types that we've already handled.
8349     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8350 
8351     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8352       for (BuiltinCandidateTypeSet::iterator
8353                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8354              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8355            MemPtr != MemPtrEnd;
8356            ++MemPtr) {
8357         // Don't add the same builtin candidate twice.
8358         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8359           continue;
8360 
8361         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8362         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8363       }
8364 
8365       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8366         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8367         if (AddedTypes.insert(NullPtrTy).second) {
8368           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8369           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8370         }
8371       }
8372     }
8373   }
8374 
8375   // C++ [over.built]p15:
8376   //
8377   //   For every T, where T is an enumeration type or a pointer type,
8378   //   there exist candidate operator functions of the form
8379   //
8380   //        bool       operator<(T, T);
8381   //        bool       operator>(T, T);
8382   //        bool       operator<=(T, T);
8383   //        bool       operator>=(T, T);
8384   //        bool       operator==(T, T);
8385   //        bool       operator!=(T, T);
8386   //           R       operator<=>(T, T)
8387   void addGenericBinaryPointerOrEnumeralOverloads() {
8388     // C++ [over.match.oper]p3:
8389     //   [...]the built-in candidates include all of the candidate operator
8390     //   functions defined in 13.6 that, compared to the given operator, [...]
8391     //   do not have the same parameter-type-list as any non-template non-member
8392     //   candidate.
8393     //
8394     // Note that in practice, this only affects enumeration types because there
8395     // aren't any built-in candidates of record type, and a user-defined operator
8396     // must have an operand of record or enumeration type. Also, the only other
8397     // overloaded operator with enumeration arguments, operator=,
8398     // cannot be overloaded for enumeration types, so this is the only place
8399     // where we must suppress candidates like this.
8400     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8401       UserDefinedBinaryOperators;
8402 
8403     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8404       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8405           CandidateTypes[ArgIdx].enumeration_end()) {
8406         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8407                                          CEnd = CandidateSet.end();
8408              C != CEnd; ++C) {
8409           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8410             continue;
8411 
8412           if (C->Function->isFunctionTemplateSpecialization())
8413             continue;
8414 
8415           // We interpret "same parameter-type-list" as applying to the
8416           // "synthesized candidate, with the order of the two parameters
8417           // reversed", not to the original function.
8418           bool Reversed = C->isReversed();
8419           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8420                                         ->getType()
8421                                         .getUnqualifiedType();
8422           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8423                                          ->getType()
8424                                          .getUnqualifiedType();
8425 
8426           // Skip if either parameter isn't of enumeral type.
8427           if (!FirstParamType->isEnumeralType() ||
8428               !SecondParamType->isEnumeralType())
8429             continue;
8430 
8431           // Add this operator to the set of known user-defined operators.
8432           UserDefinedBinaryOperators.insert(
8433             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8434                            S.Context.getCanonicalType(SecondParamType)));
8435         }
8436       }
8437     }
8438 
8439     /// Set of (canonical) types that we've already handled.
8440     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8441 
8442     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8443       for (BuiltinCandidateTypeSet::iterator
8444                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8445              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8446            Ptr != PtrEnd; ++Ptr) {
8447         // Don't add the same builtin candidate twice.
8448         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8449           continue;
8450 
8451         QualType ParamTypes[2] = { *Ptr, *Ptr };
8452         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8453       }
8454       for (BuiltinCandidateTypeSet::iterator
8455                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8456              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8457            Enum != EnumEnd; ++Enum) {
8458         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8459 
8460         // Don't add the same builtin candidate twice, or if a user defined
8461         // candidate exists.
8462         if (!AddedTypes.insert(CanonType).second ||
8463             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8464                                                             CanonType)))
8465           continue;
8466         QualType ParamTypes[2] = { *Enum, *Enum };
8467         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8468       }
8469     }
8470   }
8471 
8472   // C++ [over.built]p13:
8473   //
8474   //   For every cv-qualified or cv-unqualified object type T
8475   //   there exist candidate operator functions of the form
8476   //
8477   //      T*         operator+(T*, ptrdiff_t);
8478   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8479   //      T*         operator-(T*, ptrdiff_t);
8480   //      T*         operator+(ptrdiff_t, T*);
8481   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8482   //
8483   // C++ [over.built]p14:
8484   //
8485   //   For every T, where T is a pointer to object type, there
8486   //   exist candidate operator functions of the form
8487   //
8488   //      ptrdiff_t  operator-(T, T);
8489   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8490     /// Set of (canonical) types that we've already handled.
8491     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8492 
8493     for (int Arg = 0; Arg < 2; ++Arg) {
8494       QualType AsymmetricParamTypes[2] = {
8495         S.Context.getPointerDiffType(),
8496         S.Context.getPointerDiffType(),
8497       };
8498       for (BuiltinCandidateTypeSet::iterator
8499                 Ptr = CandidateTypes[Arg].pointer_begin(),
8500              PtrEnd = CandidateTypes[Arg].pointer_end();
8501            Ptr != PtrEnd; ++Ptr) {
8502         QualType PointeeTy = (*Ptr)->getPointeeType();
8503         if (!PointeeTy->isObjectType())
8504           continue;
8505 
8506         AsymmetricParamTypes[Arg] = *Ptr;
8507         if (Arg == 0 || Op == OO_Plus) {
8508           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8509           // T* operator+(ptrdiff_t, T*);
8510           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8511         }
8512         if (Op == OO_Minus) {
8513           // ptrdiff_t operator-(T, T);
8514           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8515             continue;
8516 
8517           QualType ParamTypes[2] = { *Ptr, *Ptr };
8518           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8519         }
8520       }
8521     }
8522   }
8523 
8524   // C++ [over.built]p12:
8525   //
8526   //   For every pair of promoted arithmetic types L and R, there
8527   //   exist candidate operator functions of the form
8528   //
8529   //        LR         operator*(L, R);
8530   //        LR         operator/(L, R);
8531   //        LR         operator+(L, R);
8532   //        LR         operator-(L, R);
8533   //        bool       operator<(L, R);
8534   //        bool       operator>(L, R);
8535   //        bool       operator<=(L, R);
8536   //        bool       operator>=(L, R);
8537   //        bool       operator==(L, R);
8538   //        bool       operator!=(L, R);
8539   //
8540   //   where LR is the result of the usual arithmetic conversions
8541   //   between types L and R.
8542   //
8543   // C++ [over.built]p24:
8544   //
8545   //   For every pair of promoted arithmetic types L and R, there exist
8546   //   candidate operator functions of the form
8547   //
8548   //        LR       operator?(bool, L, R);
8549   //
8550   //   where LR is the result of the usual arithmetic conversions
8551   //   between types L and R.
8552   // Our candidates ignore the first parameter.
8553   void addGenericBinaryArithmeticOverloads() {
8554     if (!HasArithmeticOrEnumeralCandidateType)
8555       return;
8556 
8557     for (unsigned Left = FirstPromotedArithmeticType;
8558          Left < LastPromotedArithmeticType; ++Left) {
8559       for (unsigned Right = FirstPromotedArithmeticType;
8560            Right < LastPromotedArithmeticType; ++Right) {
8561         QualType LandR[2] = { ArithmeticTypes[Left],
8562                               ArithmeticTypes[Right] };
8563         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8564       }
8565     }
8566 
8567     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8568     // conditional operator for vector types.
8569     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8570       for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
8571         QualType LandR[2] = {Vec1Ty, Vec2Ty};
8572         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8573       }
8574   }
8575 
8576   /// Add binary operator overloads for each candidate matrix type M1, M2:
8577   ///  * (M1, M1) -> M1
8578   ///  * (M1, M1.getElementType()) -> M1
8579   ///  * (M2.getElementType(), M2) -> M2
8580   ///  * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
8581   void addMatrixBinaryArithmeticOverloads() {
8582     if (!HasArithmeticOrEnumeralCandidateType)
8583       return;
8584 
8585     for (QualType M1 : CandidateTypes[0].matrix_types()) {
8586       AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
8587       AddCandidate(M1, M1);
8588     }
8589 
8590     for (QualType M2 : CandidateTypes[1].matrix_types()) {
8591       AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
8592       if (!CandidateTypes[0].containsMatrixType(M2))
8593         AddCandidate(M2, M2);
8594     }
8595   }
8596 
8597   // C++2a [over.built]p14:
8598   //
8599   //   For every integral type T there exists a candidate operator function
8600   //   of the form
8601   //
8602   //        std::strong_ordering operator<=>(T, T)
8603   //
8604   // C++2a [over.built]p15:
8605   //
8606   //   For every pair of floating-point types L and R, there exists a candidate
8607   //   operator function of the form
8608   //
8609   //       std::partial_ordering operator<=>(L, R);
8610   //
8611   // FIXME: The current specification for integral types doesn't play nice with
8612   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8613   // comparisons. Under the current spec this can lead to ambiguity during
8614   // overload resolution. For example:
8615   //
8616   //   enum A : int {a};
8617   //   auto x = (a <=> (long)42);
8618   //
8619   //   error: call is ambiguous for arguments 'A' and 'long'.
8620   //   note: candidate operator<=>(int, int)
8621   //   note: candidate operator<=>(long, long)
8622   //
8623   // To avoid this error, this function deviates from the specification and adds
8624   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8625   // arithmetic types (the same as the generic relational overloads).
8626   //
8627   // For now this function acts as a placeholder.
8628   void addThreeWayArithmeticOverloads() {
8629     addGenericBinaryArithmeticOverloads();
8630   }
8631 
8632   // C++ [over.built]p17:
8633   //
8634   //   For every pair of promoted integral types L and R, there
8635   //   exist candidate operator functions of the form
8636   //
8637   //      LR         operator%(L, R);
8638   //      LR         operator&(L, R);
8639   //      LR         operator^(L, R);
8640   //      LR         operator|(L, R);
8641   //      L          operator<<(L, R);
8642   //      L          operator>>(L, R);
8643   //
8644   //   where LR is the result of the usual arithmetic conversions
8645   //   between types L and R.
8646   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8647     if (!HasArithmeticOrEnumeralCandidateType)
8648       return;
8649 
8650     for (unsigned Left = FirstPromotedIntegralType;
8651          Left < LastPromotedIntegralType; ++Left) {
8652       for (unsigned Right = FirstPromotedIntegralType;
8653            Right < LastPromotedIntegralType; ++Right) {
8654         QualType LandR[2] = { ArithmeticTypes[Left],
8655                               ArithmeticTypes[Right] };
8656         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8657       }
8658     }
8659   }
8660 
8661   // C++ [over.built]p20:
8662   //
8663   //   For every pair (T, VQ), where T is an enumeration or
8664   //   pointer to member type and VQ is either volatile or
8665   //   empty, there exist candidate operator functions of the form
8666   //
8667   //        VQ T&      operator=(VQ T&, T);
8668   void addAssignmentMemberPointerOrEnumeralOverloads() {
8669     /// Set of (canonical) types that we've already handled.
8670     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8671 
8672     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8673       for (BuiltinCandidateTypeSet::iterator
8674                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8675              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8676            Enum != EnumEnd; ++Enum) {
8677         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8678           continue;
8679 
8680         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8681       }
8682 
8683       for (BuiltinCandidateTypeSet::iterator
8684                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8685              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8686            MemPtr != MemPtrEnd; ++MemPtr) {
8687         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8688           continue;
8689 
8690         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8691       }
8692     }
8693   }
8694 
8695   // C++ [over.built]p19:
8696   //
8697   //   For every pair (T, VQ), where T is any type and VQ is either
8698   //   volatile or empty, there exist candidate operator functions
8699   //   of the form
8700   //
8701   //        T*VQ&      operator=(T*VQ&, T*);
8702   //
8703   // C++ [over.built]p21:
8704   //
8705   //   For every pair (T, VQ), where T is a cv-qualified or
8706   //   cv-unqualified object type and VQ is either volatile or
8707   //   empty, there exist candidate operator functions of the form
8708   //
8709   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8710   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8711   void addAssignmentPointerOverloads(bool isEqualOp) {
8712     /// Set of (canonical) types that we've already handled.
8713     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8714 
8715     for (BuiltinCandidateTypeSet::iterator
8716               Ptr = CandidateTypes[0].pointer_begin(),
8717            PtrEnd = CandidateTypes[0].pointer_end();
8718          Ptr != PtrEnd; ++Ptr) {
8719       // If this is operator=, keep track of the builtin candidates we added.
8720       if (isEqualOp)
8721         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8722       else if (!(*Ptr)->getPointeeType()->isObjectType())
8723         continue;
8724 
8725       // non-volatile version
8726       QualType ParamTypes[2] = {
8727         S.Context.getLValueReferenceType(*Ptr),
8728         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8729       };
8730       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8731                             /*IsAssignmentOperator=*/ isEqualOp);
8732 
8733       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8734                           VisibleTypeConversionsQuals.hasVolatile();
8735       if (NeedVolatile) {
8736         // volatile version
8737         ParamTypes[0] =
8738           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8739         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8740                               /*IsAssignmentOperator=*/isEqualOp);
8741       }
8742 
8743       if (!(*Ptr).isRestrictQualified() &&
8744           VisibleTypeConversionsQuals.hasRestrict()) {
8745         // restrict version
8746         ParamTypes[0]
8747           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8748         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8749                               /*IsAssignmentOperator=*/isEqualOp);
8750 
8751         if (NeedVolatile) {
8752           // volatile restrict version
8753           ParamTypes[0]
8754             = S.Context.getLValueReferenceType(
8755                 S.Context.getCVRQualifiedType(*Ptr,
8756                                               (Qualifiers::Volatile |
8757                                                Qualifiers::Restrict)));
8758           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8759                                 /*IsAssignmentOperator=*/isEqualOp);
8760         }
8761       }
8762     }
8763 
8764     if (isEqualOp) {
8765       for (BuiltinCandidateTypeSet::iterator
8766                 Ptr = CandidateTypes[1].pointer_begin(),
8767              PtrEnd = CandidateTypes[1].pointer_end();
8768            Ptr != PtrEnd; ++Ptr) {
8769         // Make sure we don't add the same candidate twice.
8770         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8771           continue;
8772 
8773         QualType ParamTypes[2] = {
8774           S.Context.getLValueReferenceType(*Ptr),
8775           *Ptr,
8776         };
8777 
8778         // non-volatile version
8779         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8780                               /*IsAssignmentOperator=*/true);
8781 
8782         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8783                            VisibleTypeConversionsQuals.hasVolatile();
8784         if (NeedVolatile) {
8785           // volatile version
8786           ParamTypes[0] =
8787             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8788           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8789                                 /*IsAssignmentOperator=*/true);
8790         }
8791 
8792         if (!(*Ptr).isRestrictQualified() &&
8793             VisibleTypeConversionsQuals.hasRestrict()) {
8794           // restrict version
8795           ParamTypes[0]
8796             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8797           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8798                                 /*IsAssignmentOperator=*/true);
8799 
8800           if (NeedVolatile) {
8801             // volatile restrict version
8802             ParamTypes[0]
8803               = S.Context.getLValueReferenceType(
8804                   S.Context.getCVRQualifiedType(*Ptr,
8805                                                 (Qualifiers::Volatile |
8806                                                  Qualifiers::Restrict)));
8807             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8808                                   /*IsAssignmentOperator=*/true);
8809           }
8810         }
8811       }
8812     }
8813   }
8814 
8815   // C++ [over.built]p18:
8816   //
8817   //   For every triple (L, VQ, R), where L is an arithmetic type,
8818   //   VQ is either volatile or empty, and R is a promoted
8819   //   arithmetic type, there exist candidate operator functions of
8820   //   the form
8821   //
8822   //        VQ L&      operator=(VQ L&, R);
8823   //        VQ L&      operator*=(VQ L&, R);
8824   //        VQ L&      operator/=(VQ L&, R);
8825   //        VQ L&      operator+=(VQ L&, R);
8826   //        VQ L&      operator-=(VQ L&, R);
8827   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8828     if (!HasArithmeticOrEnumeralCandidateType)
8829       return;
8830 
8831     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8832       for (unsigned Right = FirstPromotedArithmeticType;
8833            Right < LastPromotedArithmeticType; ++Right) {
8834         QualType ParamTypes[2];
8835         ParamTypes[1] = ArithmeticTypes[Right];
8836         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8837             S, ArithmeticTypes[Left], Args[0]);
8838         // Add this built-in operator as a candidate (VQ is empty).
8839         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8840         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8841                               /*IsAssignmentOperator=*/isEqualOp);
8842 
8843         // Add this built-in operator as a candidate (VQ is 'volatile').
8844         if (VisibleTypeConversionsQuals.hasVolatile()) {
8845           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8846           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8847           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8848                                 /*IsAssignmentOperator=*/isEqualOp);
8849         }
8850       }
8851     }
8852 
8853     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8854     for (QualType Vec1Ty : CandidateTypes[0].vector_types())
8855       for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
8856         QualType ParamTypes[2];
8857         ParamTypes[1] = Vec2Ty;
8858         // Add this built-in operator as a candidate (VQ is empty).
8859         ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
8860         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8861                               /*IsAssignmentOperator=*/isEqualOp);
8862 
8863         // Add this built-in operator as a candidate (VQ is 'volatile').
8864         if (VisibleTypeConversionsQuals.hasVolatile()) {
8865           ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
8866           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8867           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8868                                 /*IsAssignmentOperator=*/isEqualOp);
8869         }
8870       }
8871   }
8872 
8873   // C++ [over.built]p22:
8874   //
8875   //   For every triple (L, VQ, R), where L is an integral type, VQ
8876   //   is either volatile or empty, and R is a promoted integral
8877   //   type, there exist candidate operator functions of the form
8878   //
8879   //        VQ L&       operator%=(VQ L&, R);
8880   //        VQ L&       operator<<=(VQ L&, R);
8881   //        VQ L&       operator>>=(VQ L&, R);
8882   //        VQ L&       operator&=(VQ L&, R);
8883   //        VQ L&       operator^=(VQ L&, R);
8884   //        VQ L&       operator|=(VQ L&, R);
8885   void addAssignmentIntegralOverloads() {
8886     if (!HasArithmeticOrEnumeralCandidateType)
8887       return;
8888 
8889     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8890       for (unsigned Right = FirstPromotedIntegralType;
8891            Right < LastPromotedIntegralType; ++Right) {
8892         QualType ParamTypes[2];
8893         ParamTypes[1] = ArithmeticTypes[Right];
8894         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8895             S, ArithmeticTypes[Left], Args[0]);
8896         // Add this built-in operator as a candidate (VQ is empty).
8897         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8898         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8899         if (VisibleTypeConversionsQuals.hasVolatile()) {
8900           // Add this built-in operator as a candidate (VQ is 'volatile').
8901           ParamTypes[0] = LeftBaseTy;
8902           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8903           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8904           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8905         }
8906       }
8907     }
8908   }
8909 
8910   // C++ [over.operator]p23:
8911   //
8912   //   There also exist candidate operator functions of the form
8913   //
8914   //        bool        operator!(bool);
8915   //        bool        operator&&(bool, bool);
8916   //        bool        operator||(bool, bool);
8917   void addExclaimOverload() {
8918     QualType ParamTy = S.Context.BoolTy;
8919     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8920                           /*IsAssignmentOperator=*/false,
8921                           /*NumContextualBoolArguments=*/1);
8922   }
8923   void addAmpAmpOrPipePipeOverload() {
8924     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8925     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8926                           /*IsAssignmentOperator=*/false,
8927                           /*NumContextualBoolArguments=*/2);
8928   }
8929 
8930   // C++ [over.built]p13:
8931   //
8932   //   For every cv-qualified or cv-unqualified object type T there
8933   //   exist candidate operator functions of the form
8934   //
8935   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8936   //        T&         operator[](T*, ptrdiff_t);
8937   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8938   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8939   //        T&         operator[](ptrdiff_t, T*);
8940   void addSubscriptOverloads() {
8941     for (BuiltinCandidateTypeSet::iterator
8942               Ptr = CandidateTypes[0].pointer_begin(),
8943            PtrEnd = CandidateTypes[0].pointer_end();
8944          Ptr != PtrEnd; ++Ptr) {
8945       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8946       QualType PointeeType = (*Ptr)->getPointeeType();
8947       if (!PointeeType->isObjectType())
8948         continue;
8949 
8950       // T& operator[](T*, ptrdiff_t)
8951       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8952     }
8953 
8954     for (BuiltinCandidateTypeSet::iterator
8955               Ptr = CandidateTypes[1].pointer_begin(),
8956            PtrEnd = CandidateTypes[1].pointer_end();
8957          Ptr != PtrEnd; ++Ptr) {
8958       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8959       QualType PointeeType = (*Ptr)->getPointeeType();
8960       if (!PointeeType->isObjectType())
8961         continue;
8962 
8963       // T& operator[](ptrdiff_t, T*)
8964       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8965     }
8966   }
8967 
8968   // C++ [over.built]p11:
8969   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8970   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8971   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8972   //    there exist candidate operator functions of the form
8973   //
8974   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8975   //
8976   //    where CV12 is the union of CV1 and CV2.
8977   void addArrowStarOverloads() {
8978     for (BuiltinCandidateTypeSet::iterator
8979              Ptr = CandidateTypes[0].pointer_begin(),
8980            PtrEnd = CandidateTypes[0].pointer_end();
8981          Ptr != PtrEnd; ++Ptr) {
8982       QualType C1Ty = (*Ptr);
8983       QualType C1;
8984       QualifierCollector Q1;
8985       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8986       if (!isa<RecordType>(C1))
8987         continue;
8988       // heuristic to reduce number of builtin candidates in the set.
8989       // Add volatile/restrict version only if there are conversions to a
8990       // volatile/restrict type.
8991       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8992         continue;
8993       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8994         continue;
8995       for (BuiltinCandidateTypeSet::iterator
8996                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8997              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8998            MemPtr != MemPtrEnd; ++MemPtr) {
8999         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
9000         QualType C2 = QualType(mptr->getClass(), 0);
9001         C2 = C2.getUnqualifiedType();
9002         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9003           break;
9004         QualType ParamTypes[2] = { *Ptr, *MemPtr };
9005         // build CV12 T&
9006         QualType T = mptr->getPointeeType();
9007         if (!VisibleTypeConversionsQuals.hasVolatile() &&
9008             T.isVolatileQualified())
9009           continue;
9010         if (!VisibleTypeConversionsQuals.hasRestrict() &&
9011             T.isRestrictQualified())
9012           continue;
9013         T = Q1.apply(S.Context, T);
9014         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9015       }
9016     }
9017   }
9018 
9019   // Note that we don't consider the first argument, since it has been
9020   // contextually converted to bool long ago. The candidates below are
9021   // therefore added as binary.
9022   //
9023   // C++ [over.built]p25:
9024   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9025   //   enumeration type, there exist candidate operator functions of the form
9026   //
9027   //        T        operator?(bool, T, T);
9028   //
9029   void addConditionalOperatorOverloads() {
9030     /// Set of (canonical) types that we've already handled.
9031     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9032 
9033     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9034       for (BuiltinCandidateTypeSet::iterator
9035                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9036              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9037            Ptr != PtrEnd; ++Ptr) {
9038         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9039           continue;
9040 
9041         QualType ParamTypes[2] = { *Ptr, *Ptr };
9042         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9043       }
9044 
9045       for (BuiltinCandidateTypeSet::iterator
9046                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9047              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9048            MemPtr != MemPtrEnd; ++MemPtr) {
9049         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9050           continue;
9051 
9052         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9053         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9054       }
9055 
9056       if (S.getLangOpts().CPlusPlus11) {
9057         for (BuiltinCandidateTypeSet::iterator
9058                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9059                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9060              Enum != EnumEnd; ++Enum) {
9061           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9062             continue;
9063 
9064           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9065             continue;
9066 
9067           QualType ParamTypes[2] = { *Enum, *Enum };
9068           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9069         }
9070       }
9071     }
9072   }
9073 };
9074 
9075 } // end anonymous namespace
9076 
9077 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9078 /// operator overloads to the candidate set (C++ [over.built]), based
9079 /// on the operator @p Op and the arguments given. For example, if the
9080 /// operator is a binary '+', this routine might add "int
9081 /// operator+(int, int)" to cover integer addition.
9082 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9083                                         SourceLocation OpLoc,
9084                                         ArrayRef<Expr *> Args,
9085                                         OverloadCandidateSet &CandidateSet) {
9086   // Find all of the types that the arguments can convert to, but only
9087   // if the operator we're looking at has built-in operator candidates
9088   // that make use of these types. Also record whether we encounter non-record
9089   // candidate types or either arithmetic or enumeral candidate types.
9090   Qualifiers VisibleTypeConversionsQuals;
9091   VisibleTypeConversionsQuals.addConst();
9092   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9093     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9094 
9095   bool HasNonRecordCandidateType = false;
9096   bool HasArithmeticOrEnumeralCandidateType = false;
9097   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9098   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9099     CandidateTypes.emplace_back(*this);
9100     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9101                                                  OpLoc,
9102                                                  true,
9103                                                  (Op == OO_Exclaim ||
9104                                                   Op == OO_AmpAmp ||
9105                                                   Op == OO_PipePipe),
9106                                                  VisibleTypeConversionsQuals);
9107     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9108         CandidateTypes[ArgIdx].hasNonRecordTypes();
9109     HasArithmeticOrEnumeralCandidateType =
9110         HasArithmeticOrEnumeralCandidateType ||
9111         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9112   }
9113 
9114   // Exit early when no non-record types have been added to the candidate set
9115   // for any of the arguments to the operator.
9116   //
9117   // We can't exit early for !, ||, or &&, since there we have always have
9118   // 'bool' overloads.
9119   if (!HasNonRecordCandidateType &&
9120       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9121     return;
9122 
9123   // Setup an object to manage the common state for building overloads.
9124   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9125                                            VisibleTypeConversionsQuals,
9126                                            HasArithmeticOrEnumeralCandidateType,
9127                                            CandidateTypes, CandidateSet);
9128 
9129   // Dispatch over the operation to add in only those overloads which apply.
9130   switch (Op) {
9131   case OO_None:
9132   case NUM_OVERLOADED_OPERATORS:
9133     llvm_unreachable("Expected an overloaded operator");
9134 
9135   case OO_New:
9136   case OO_Delete:
9137   case OO_Array_New:
9138   case OO_Array_Delete:
9139   case OO_Call:
9140     llvm_unreachable(
9141                     "Special operators don't use AddBuiltinOperatorCandidates");
9142 
9143   case OO_Comma:
9144   case OO_Arrow:
9145   case OO_Coawait:
9146     // C++ [over.match.oper]p3:
9147     //   -- For the operator ',', the unary operator '&', the
9148     //      operator '->', or the operator 'co_await', the
9149     //      built-in candidates set is empty.
9150     break;
9151 
9152   case OO_Plus: // '+' is either unary or binary
9153     if (Args.size() == 1)
9154       OpBuilder.addUnaryPlusPointerOverloads();
9155     LLVM_FALLTHROUGH;
9156 
9157   case OO_Minus: // '-' is either unary or binary
9158     if (Args.size() == 1) {
9159       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9160     } else {
9161       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9162       OpBuilder.addGenericBinaryArithmeticOverloads();
9163       OpBuilder.addMatrixBinaryArithmeticOverloads();
9164     }
9165     break;
9166 
9167   case OO_Star: // '*' is either unary or binary
9168     if (Args.size() == 1)
9169       OpBuilder.addUnaryStarPointerOverloads();
9170     else {
9171       OpBuilder.addGenericBinaryArithmeticOverloads();
9172       OpBuilder.addMatrixBinaryArithmeticOverloads();
9173     }
9174     break;
9175 
9176   case OO_Slash:
9177     OpBuilder.addGenericBinaryArithmeticOverloads();
9178     break;
9179 
9180   case OO_PlusPlus:
9181   case OO_MinusMinus:
9182     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9183     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9184     break;
9185 
9186   case OO_EqualEqual:
9187   case OO_ExclaimEqual:
9188     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9189     LLVM_FALLTHROUGH;
9190 
9191   case OO_Less:
9192   case OO_Greater:
9193   case OO_LessEqual:
9194   case OO_GreaterEqual:
9195     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9196     OpBuilder.addGenericBinaryArithmeticOverloads();
9197     break;
9198 
9199   case OO_Spaceship:
9200     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9201     OpBuilder.addThreeWayArithmeticOverloads();
9202     break;
9203 
9204   case OO_Percent:
9205   case OO_Caret:
9206   case OO_Pipe:
9207   case OO_LessLess:
9208   case OO_GreaterGreater:
9209     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9210     break;
9211 
9212   case OO_Amp: // '&' is either unary or binary
9213     if (Args.size() == 1)
9214       // C++ [over.match.oper]p3:
9215       //   -- For the operator ',', the unary operator '&', or the
9216       //      operator '->', the built-in candidates set is empty.
9217       break;
9218 
9219     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9220     break;
9221 
9222   case OO_Tilde:
9223     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9224     break;
9225 
9226   case OO_Equal:
9227     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9228     LLVM_FALLTHROUGH;
9229 
9230   case OO_PlusEqual:
9231   case OO_MinusEqual:
9232     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9233     LLVM_FALLTHROUGH;
9234 
9235   case OO_StarEqual:
9236   case OO_SlashEqual:
9237     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9238     break;
9239 
9240   case OO_PercentEqual:
9241   case OO_LessLessEqual:
9242   case OO_GreaterGreaterEqual:
9243   case OO_AmpEqual:
9244   case OO_CaretEqual:
9245   case OO_PipeEqual:
9246     OpBuilder.addAssignmentIntegralOverloads();
9247     break;
9248 
9249   case OO_Exclaim:
9250     OpBuilder.addExclaimOverload();
9251     break;
9252 
9253   case OO_AmpAmp:
9254   case OO_PipePipe:
9255     OpBuilder.addAmpAmpOrPipePipeOverload();
9256     break;
9257 
9258   case OO_Subscript:
9259     OpBuilder.addSubscriptOverloads();
9260     break;
9261 
9262   case OO_ArrowStar:
9263     OpBuilder.addArrowStarOverloads();
9264     break;
9265 
9266   case OO_Conditional:
9267     OpBuilder.addConditionalOperatorOverloads();
9268     OpBuilder.addGenericBinaryArithmeticOverloads();
9269     break;
9270   }
9271 }
9272 
9273 /// Add function candidates found via argument-dependent lookup
9274 /// to the set of overloading candidates.
9275 ///
9276 /// This routine performs argument-dependent name lookup based on the
9277 /// given function name (which may also be an operator name) and adds
9278 /// all of the overload candidates found by ADL to the overload
9279 /// candidate set (C++ [basic.lookup.argdep]).
9280 void
9281 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9282                                            SourceLocation Loc,
9283                                            ArrayRef<Expr *> Args,
9284                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9285                                            OverloadCandidateSet& CandidateSet,
9286                                            bool PartialOverloading) {
9287   ADLResult Fns;
9288 
9289   // FIXME: This approach for uniquing ADL results (and removing
9290   // redundant candidates from the set) relies on pointer-equality,
9291   // which means we need to key off the canonical decl.  However,
9292   // always going back to the canonical decl might not get us the
9293   // right set of default arguments.  What default arguments are
9294   // we supposed to consider on ADL candidates, anyway?
9295 
9296   // FIXME: Pass in the explicit template arguments?
9297   ArgumentDependentLookup(Name, Loc, Args, Fns);
9298 
9299   // Erase all of the candidates we already knew about.
9300   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9301                                    CandEnd = CandidateSet.end();
9302        Cand != CandEnd; ++Cand)
9303     if (Cand->Function) {
9304       Fns.erase(Cand->Function);
9305       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9306         Fns.erase(FunTmpl);
9307     }
9308 
9309   // For each of the ADL candidates we found, add it to the overload
9310   // set.
9311   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9312     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9313 
9314     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9315       if (ExplicitTemplateArgs)
9316         continue;
9317 
9318       AddOverloadCandidate(
9319           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9320           PartialOverloading, /*AllowExplicit=*/true,
9321           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9322       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9323         AddOverloadCandidate(
9324             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9325             /*SuppressUserConversions=*/false, PartialOverloading,
9326             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9327             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9328       }
9329     } else {
9330       auto *FTD = cast<FunctionTemplateDecl>(*I);
9331       AddTemplateOverloadCandidate(
9332           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9333           /*SuppressUserConversions=*/false, PartialOverloading,
9334           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9335       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9336               Context, FTD->getTemplatedDecl())) {
9337         AddTemplateOverloadCandidate(
9338             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9339             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9340             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9341             OverloadCandidateParamOrder::Reversed);
9342       }
9343     }
9344   }
9345 }
9346 
9347 namespace {
9348 enum class Comparison { Equal, Better, Worse };
9349 }
9350 
9351 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9352 /// overload resolution.
9353 ///
9354 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9355 /// Cand1's first N enable_if attributes have precisely the same conditions as
9356 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9357 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9358 ///
9359 /// Note that you can have a pair of candidates such that Cand1's enable_if
9360 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9361 /// worse than Cand1's.
9362 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9363                                        const FunctionDecl *Cand2) {
9364   // Common case: One (or both) decls don't have enable_if attrs.
9365   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9366   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9367   if (!Cand1Attr || !Cand2Attr) {
9368     if (Cand1Attr == Cand2Attr)
9369       return Comparison::Equal;
9370     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9371   }
9372 
9373   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9374   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9375 
9376   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9377   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9378     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9379     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9380 
9381     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9382     // has fewer enable_if attributes than Cand2, and vice versa.
9383     if (!Cand1A)
9384       return Comparison::Worse;
9385     if (!Cand2A)
9386       return Comparison::Better;
9387 
9388     Cand1ID.clear();
9389     Cand2ID.clear();
9390 
9391     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9392     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9393     if (Cand1ID != Cand2ID)
9394       return Comparison::Worse;
9395   }
9396 
9397   return Comparison::Equal;
9398 }
9399 
9400 static Comparison
9401 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9402                               const OverloadCandidate &Cand2) {
9403   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9404       !Cand2.Function->isMultiVersion())
9405     return Comparison::Equal;
9406 
9407   // If both are invalid, they are equal. If one of them is invalid, the other
9408   // is better.
9409   if (Cand1.Function->isInvalidDecl()) {
9410     if (Cand2.Function->isInvalidDecl())
9411       return Comparison::Equal;
9412     return Comparison::Worse;
9413   }
9414   if (Cand2.Function->isInvalidDecl())
9415     return Comparison::Better;
9416 
9417   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9418   // cpu_dispatch, else arbitrarily based on the identifiers.
9419   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9420   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9421   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9422   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9423 
9424   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9425     return Comparison::Equal;
9426 
9427   if (Cand1CPUDisp && !Cand2CPUDisp)
9428     return Comparison::Better;
9429   if (Cand2CPUDisp && !Cand1CPUDisp)
9430     return Comparison::Worse;
9431 
9432   if (Cand1CPUSpec && Cand2CPUSpec) {
9433     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9434       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
9435                  ? Comparison::Better
9436                  : Comparison::Worse;
9437 
9438     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9439         FirstDiff = std::mismatch(
9440             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9441             Cand2CPUSpec->cpus_begin(),
9442             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9443               return LHS->getName() == RHS->getName();
9444             });
9445 
9446     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9447            "Two different cpu-specific versions should not have the same "
9448            "identifier list, otherwise they'd be the same decl!");
9449     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
9450                ? Comparison::Better
9451                : Comparison::Worse;
9452   }
9453   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9454 }
9455 
9456 /// Compute the type of the implicit object parameter for the given function,
9457 /// if any. Returns None if there is no implicit object parameter, and a null
9458 /// QualType if there is a 'matches anything' implicit object parameter.
9459 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9460                                                      const FunctionDecl *F) {
9461   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9462     return llvm::None;
9463 
9464   auto *M = cast<CXXMethodDecl>(F);
9465   // Static member functions' object parameters match all types.
9466   if (M->isStatic())
9467     return QualType();
9468 
9469   QualType T = M->getThisObjectType();
9470   if (M->getRefQualifier() == RQ_RValue)
9471     return Context.getRValueReferenceType(T);
9472   return Context.getLValueReferenceType(T);
9473 }
9474 
9475 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9476                                    const FunctionDecl *F2, unsigned NumParams) {
9477   if (declaresSameEntity(F1, F2))
9478     return true;
9479 
9480   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9481     if (First) {
9482       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9483         return *T;
9484     }
9485     assert(I < F->getNumParams());
9486     return F->getParamDecl(I++)->getType();
9487   };
9488 
9489   unsigned I1 = 0, I2 = 0;
9490   for (unsigned I = 0; I != NumParams; ++I) {
9491     QualType T1 = NextParam(F1, I1, I == 0);
9492     QualType T2 = NextParam(F2, I2, I == 0);
9493     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9494       return false;
9495   }
9496   return true;
9497 }
9498 
9499 /// isBetterOverloadCandidate - Determines whether the first overload
9500 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9501 bool clang::isBetterOverloadCandidate(
9502     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9503     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9504   // Define viable functions to be better candidates than non-viable
9505   // functions.
9506   if (!Cand2.Viable)
9507     return Cand1.Viable;
9508   else if (!Cand1.Viable)
9509     return false;
9510 
9511   // C++ [over.match.best]p1:
9512   //
9513   //   -- if F is a static member function, ICS1(F) is defined such
9514   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9515   //      any function G, and, symmetrically, ICS1(G) is neither
9516   //      better nor worse than ICS1(F).
9517   unsigned StartArg = 0;
9518   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9519     StartArg = 1;
9520 
9521   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9522     // We don't allow incompatible pointer conversions in C++.
9523     if (!S.getLangOpts().CPlusPlus)
9524       return ICS.isStandard() &&
9525              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9526 
9527     // The only ill-formed conversion we allow in C++ is the string literal to
9528     // char* conversion, which is only considered ill-formed after C++11.
9529     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9530            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9531   };
9532 
9533   // Define functions that don't require ill-formed conversions for a given
9534   // argument to be better candidates than functions that do.
9535   unsigned NumArgs = Cand1.Conversions.size();
9536   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9537   bool HasBetterConversion = false;
9538   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9539     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9540     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9541     if (Cand1Bad != Cand2Bad) {
9542       if (Cand1Bad)
9543         return false;
9544       HasBetterConversion = true;
9545     }
9546   }
9547 
9548   if (HasBetterConversion)
9549     return true;
9550 
9551   // C++ [over.match.best]p1:
9552   //   A viable function F1 is defined to be a better function than another
9553   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9554   //   conversion sequence than ICSi(F2), and then...
9555   bool HasWorseConversion = false;
9556   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9557     switch (CompareImplicitConversionSequences(S, Loc,
9558                                                Cand1.Conversions[ArgIdx],
9559                                                Cand2.Conversions[ArgIdx])) {
9560     case ImplicitConversionSequence::Better:
9561       // Cand1 has a better conversion sequence.
9562       HasBetterConversion = true;
9563       break;
9564 
9565     case ImplicitConversionSequence::Worse:
9566       if (Cand1.Function && Cand2.Function &&
9567           Cand1.isReversed() != Cand2.isReversed() &&
9568           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9569                                  NumArgs)) {
9570         // Work around large-scale breakage caused by considering reversed
9571         // forms of operator== in C++20:
9572         //
9573         // When comparing a function against a reversed function with the same
9574         // parameter types, if we have a better conversion for one argument and
9575         // a worse conversion for the other, the implicit conversion sequences
9576         // are treated as being equally good.
9577         //
9578         // This prevents a comparison function from being considered ambiguous
9579         // with a reversed form that is written in the same way.
9580         //
9581         // We diagnose this as an extension from CreateOverloadedBinOp.
9582         HasWorseConversion = true;
9583         break;
9584       }
9585 
9586       // Cand1 can't be better than Cand2.
9587       return false;
9588 
9589     case ImplicitConversionSequence::Indistinguishable:
9590       // Do nothing.
9591       break;
9592     }
9593   }
9594 
9595   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9596   //       ICSj(F2), or, if not that,
9597   if (HasBetterConversion && !HasWorseConversion)
9598     return true;
9599 
9600   //   -- the context is an initialization by user-defined conversion
9601   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9602   //      from the return type of F1 to the destination type (i.e.,
9603   //      the type of the entity being initialized) is a better
9604   //      conversion sequence than the standard conversion sequence
9605   //      from the return type of F2 to the destination type.
9606   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9607       Cand1.Function && Cand2.Function &&
9608       isa<CXXConversionDecl>(Cand1.Function) &&
9609       isa<CXXConversionDecl>(Cand2.Function)) {
9610     // First check whether we prefer one of the conversion functions over the
9611     // other. This only distinguishes the results in non-standard, extension
9612     // cases such as the conversion from a lambda closure type to a function
9613     // pointer or block.
9614     ImplicitConversionSequence::CompareKind Result =
9615         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9616     if (Result == ImplicitConversionSequence::Indistinguishable)
9617       Result = CompareStandardConversionSequences(S, Loc,
9618                                                   Cand1.FinalConversion,
9619                                                   Cand2.FinalConversion);
9620 
9621     if (Result != ImplicitConversionSequence::Indistinguishable)
9622       return Result == ImplicitConversionSequence::Better;
9623 
9624     // FIXME: Compare kind of reference binding if conversion functions
9625     // convert to a reference type used in direct reference binding, per
9626     // C++14 [over.match.best]p1 section 2 bullet 3.
9627   }
9628 
9629   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9630   // as combined with the resolution to CWG issue 243.
9631   //
9632   // When the context is initialization by constructor ([over.match.ctor] or
9633   // either phase of [over.match.list]), a constructor is preferred over
9634   // a conversion function.
9635   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9636       Cand1.Function && Cand2.Function &&
9637       isa<CXXConstructorDecl>(Cand1.Function) !=
9638           isa<CXXConstructorDecl>(Cand2.Function))
9639     return isa<CXXConstructorDecl>(Cand1.Function);
9640 
9641   //    -- F1 is a non-template function and F2 is a function template
9642   //       specialization, or, if not that,
9643   bool Cand1IsSpecialization = Cand1.Function &&
9644                                Cand1.Function->getPrimaryTemplate();
9645   bool Cand2IsSpecialization = Cand2.Function &&
9646                                Cand2.Function->getPrimaryTemplate();
9647   if (Cand1IsSpecialization != Cand2IsSpecialization)
9648     return Cand2IsSpecialization;
9649 
9650   //   -- F1 and F2 are function template specializations, and the function
9651   //      template for F1 is more specialized than the template for F2
9652   //      according to the partial ordering rules described in 14.5.5.2, or,
9653   //      if not that,
9654   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9655     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9656             Cand1.Function->getPrimaryTemplate(),
9657             Cand2.Function->getPrimaryTemplate(), Loc,
9658             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9659                                                    : TPOC_Call,
9660             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9661             Cand1.isReversed() ^ Cand2.isReversed()))
9662       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9663   }
9664 
9665   //   -— F1 and F2 are non-template functions with the same
9666   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9667   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9668       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9669       Cand2.Function->hasPrototype()) {
9670     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9671     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9672     if (PT1->getNumParams() == PT2->getNumParams() &&
9673         PT1->isVariadic() == PT2->isVariadic() &&
9674         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9675       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9676       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9677       if (RC1 && RC2) {
9678         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9679         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9680                                      {RC2}, AtLeastAsConstrained1) ||
9681             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9682                                      {RC1}, AtLeastAsConstrained2))
9683           return false;
9684         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9685           return AtLeastAsConstrained1;
9686       } else if (RC1 || RC2) {
9687         return RC1 != nullptr;
9688       }
9689     }
9690   }
9691 
9692   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9693   //      class B of D, and for all arguments the corresponding parameters of
9694   //      F1 and F2 have the same type.
9695   // FIXME: Implement the "all parameters have the same type" check.
9696   bool Cand1IsInherited =
9697       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9698   bool Cand2IsInherited =
9699       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9700   if (Cand1IsInherited != Cand2IsInherited)
9701     return Cand2IsInherited;
9702   else if (Cand1IsInherited) {
9703     assert(Cand2IsInherited);
9704     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9705     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9706     if (Cand1Class->isDerivedFrom(Cand2Class))
9707       return true;
9708     if (Cand2Class->isDerivedFrom(Cand1Class))
9709       return false;
9710     // Inherited from sibling base classes: still ambiguous.
9711   }
9712 
9713   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9714   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9715   //      with reversed order of parameters and F1 is not
9716   //
9717   // We rank reversed + different operator as worse than just reversed, but
9718   // that comparison can never happen, because we only consider reversing for
9719   // the maximally-rewritten operator (== or <=>).
9720   if (Cand1.RewriteKind != Cand2.RewriteKind)
9721     return Cand1.RewriteKind < Cand2.RewriteKind;
9722 
9723   // Check C++17 tie-breakers for deduction guides.
9724   {
9725     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9726     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9727     if (Guide1 && Guide2) {
9728       //  -- F1 is generated from a deduction-guide and F2 is not
9729       if (Guide1->isImplicit() != Guide2->isImplicit())
9730         return Guide2->isImplicit();
9731 
9732       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9733       if (Guide1->isCopyDeductionCandidate())
9734         return true;
9735     }
9736   }
9737 
9738   // Check for enable_if value-based overload resolution.
9739   if (Cand1.Function && Cand2.Function) {
9740     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9741     if (Cmp != Comparison::Equal)
9742       return Cmp == Comparison::Better;
9743   }
9744 
9745   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9746     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9747     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9748            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9749   }
9750 
9751   bool HasPS1 = Cand1.Function != nullptr &&
9752                 functionHasPassObjectSizeParams(Cand1.Function);
9753   bool HasPS2 = Cand2.Function != nullptr &&
9754                 functionHasPassObjectSizeParams(Cand2.Function);
9755   if (HasPS1 != HasPS2 && HasPS1)
9756     return true;
9757 
9758   Comparison MV = isBetterMultiversionCandidate(Cand1, Cand2);
9759   return MV == Comparison::Better;
9760 }
9761 
9762 /// Determine whether two declarations are "equivalent" for the purposes of
9763 /// name lookup and overload resolution. This applies when the same internal/no
9764 /// linkage entity is defined by two modules (probably by textually including
9765 /// the same header). In such a case, we don't consider the declarations to
9766 /// declare the same entity, but we also don't want lookups with both
9767 /// declarations visible to be ambiguous in some cases (this happens when using
9768 /// a modularized libstdc++).
9769 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9770                                                   const NamedDecl *B) {
9771   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9772   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9773   if (!VA || !VB)
9774     return false;
9775 
9776   // The declarations must be declaring the same name as an internal linkage
9777   // entity in different modules.
9778   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9779           VB->getDeclContext()->getRedeclContext()) ||
9780       getOwningModule(VA) == getOwningModule(VB) ||
9781       VA->isExternallyVisible() || VB->isExternallyVisible())
9782     return false;
9783 
9784   // Check that the declarations appear to be equivalent.
9785   //
9786   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9787   // For constants and functions, we should check the initializer or body is
9788   // the same. For non-constant variables, we shouldn't allow it at all.
9789   if (Context.hasSameType(VA->getType(), VB->getType()))
9790     return true;
9791 
9792   // Enum constants within unnamed enumerations will have different types, but
9793   // may still be similar enough to be interchangeable for our purposes.
9794   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9795     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9796       // Only handle anonymous enums. If the enumerations were named and
9797       // equivalent, they would have been merged to the same type.
9798       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9799       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9800       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9801           !Context.hasSameType(EnumA->getIntegerType(),
9802                                EnumB->getIntegerType()))
9803         return false;
9804       // Allow this only if the value is the same for both enumerators.
9805       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9806     }
9807   }
9808 
9809   // Nothing else is sufficiently similar.
9810   return false;
9811 }
9812 
9813 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9814     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9815   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9816 
9817   Module *M = getOwningModule(D);
9818   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9819       << !M << (M ? M->getFullModuleName() : "");
9820 
9821   for (auto *E : Equiv) {
9822     Module *M = getOwningModule(E);
9823     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9824         << !M << (M ? M->getFullModuleName() : "");
9825   }
9826 }
9827 
9828 /// Computes the best viable function (C++ 13.3.3)
9829 /// within an overload candidate set.
9830 ///
9831 /// \param Loc The location of the function name (or operator symbol) for
9832 /// which overload resolution occurs.
9833 ///
9834 /// \param Best If overload resolution was successful or found a deleted
9835 /// function, \p Best points to the candidate function found.
9836 ///
9837 /// \returns The result of overload resolution.
9838 OverloadingResult
9839 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9840                                          iterator &Best) {
9841   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9842   std::transform(begin(), end(), std::back_inserter(Candidates),
9843                  [](OverloadCandidate &Cand) { return &Cand; });
9844 
9845   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9846   // are accepted by both clang and NVCC. However, during a particular
9847   // compilation mode only one call variant is viable. We need to
9848   // exclude non-viable overload candidates from consideration based
9849   // only on their host/device attributes. Specifically, if one
9850   // candidate call is WrongSide and the other is SameSide, we ignore
9851   // the WrongSide candidate.
9852   if (S.getLangOpts().CUDA) {
9853     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9854     bool ContainsSameSideCandidate =
9855         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9856           // Check viable function only.
9857           return Cand->Viable && Cand->Function &&
9858                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9859                      Sema::CFP_SameSide;
9860         });
9861     if (ContainsSameSideCandidate) {
9862       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9863         // Check viable function only to avoid unnecessary data copying/moving.
9864         return Cand->Viable && Cand->Function &&
9865                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9866                    Sema::CFP_WrongSide;
9867       };
9868       llvm::erase_if(Candidates, IsWrongSideCandidate);
9869     }
9870   }
9871 
9872   // Find the best viable function.
9873   Best = end();
9874   for (auto *Cand : Candidates) {
9875     Cand->Best = false;
9876     if (Cand->Viable)
9877       if (Best == end() ||
9878           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9879         Best = Cand;
9880   }
9881 
9882   // If we didn't find any viable functions, abort.
9883   if (Best == end())
9884     return OR_No_Viable_Function;
9885 
9886   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9887 
9888   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9889   PendingBest.push_back(&*Best);
9890   Best->Best = true;
9891 
9892   // Make sure that this function is better than every other viable
9893   // function. If not, we have an ambiguity.
9894   while (!PendingBest.empty()) {
9895     auto *Curr = PendingBest.pop_back_val();
9896     for (auto *Cand : Candidates) {
9897       if (Cand->Viable && !Cand->Best &&
9898           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9899         PendingBest.push_back(Cand);
9900         Cand->Best = true;
9901 
9902         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9903                                                      Curr->Function))
9904           EquivalentCands.push_back(Cand->Function);
9905         else
9906           Best = end();
9907       }
9908     }
9909   }
9910 
9911   // If we found more than one best candidate, this is ambiguous.
9912   if (Best == end())
9913     return OR_Ambiguous;
9914 
9915   // Best is the best viable function.
9916   if (Best->Function && Best->Function->isDeleted())
9917     return OR_Deleted;
9918 
9919   if (!EquivalentCands.empty())
9920     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9921                                                     EquivalentCands);
9922 
9923   return OR_Success;
9924 }
9925 
9926 namespace {
9927 
9928 enum OverloadCandidateKind {
9929   oc_function,
9930   oc_method,
9931   oc_reversed_binary_operator,
9932   oc_constructor,
9933   oc_implicit_default_constructor,
9934   oc_implicit_copy_constructor,
9935   oc_implicit_move_constructor,
9936   oc_implicit_copy_assignment,
9937   oc_implicit_move_assignment,
9938   oc_implicit_equality_comparison,
9939   oc_inherited_constructor
9940 };
9941 
9942 enum OverloadCandidateSelect {
9943   ocs_non_template,
9944   ocs_template,
9945   ocs_described_template,
9946 };
9947 
9948 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9949 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9950                           OverloadCandidateRewriteKind CRK,
9951                           std::string &Description) {
9952 
9953   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9954   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9955     isTemplate = true;
9956     Description = S.getTemplateArgumentBindingsText(
9957         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9958   }
9959 
9960   OverloadCandidateSelect Select = [&]() {
9961     if (!Description.empty())
9962       return ocs_described_template;
9963     return isTemplate ? ocs_template : ocs_non_template;
9964   }();
9965 
9966   OverloadCandidateKind Kind = [&]() {
9967     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9968       return oc_implicit_equality_comparison;
9969 
9970     if (CRK & CRK_Reversed)
9971       return oc_reversed_binary_operator;
9972 
9973     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9974       if (!Ctor->isImplicit()) {
9975         if (isa<ConstructorUsingShadowDecl>(Found))
9976           return oc_inherited_constructor;
9977         else
9978           return oc_constructor;
9979       }
9980 
9981       if (Ctor->isDefaultConstructor())
9982         return oc_implicit_default_constructor;
9983 
9984       if (Ctor->isMoveConstructor())
9985         return oc_implicit_move_constructor;
9986 
9987       assert(Ctor->isCopyConstructor() &&
9988              "unexpected sort of implicit constructor");
9989       return oc_implicit_copy_constructor;
9990     }
9991 
9992     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9993       // This actually gets spelled 'candidate function' for now, but
9994       // it doesn't hurt to split it out.
9995       if (!Meth->isImplicit())
9996         return oc_method;
9997 
9998       if (Meth->isMoveAssignmentOperator())
9999         return oc_implicit_move_assignment;
10000 
10001       if (Meth->isCopyAssignmentOperator())
10002         return oc_implicit_copy_assignment;
10003 
10004       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10005       return oc_method;
10006     }
10007 
10008     return oc_function;
10009   }();
10010 
10011   return std::make_pair(Kind, Select);
10012 }
10013 
10014 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
10015   // FIXME: It'd be nice to only emit a note once per using-decl per overload
10016   // set.
10017   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10018     S.Diag(FoundDecl->getLocation(),
10019            diag::note_ovl_candidate_inherited_constructor)
10020       << Shadow->getNominatedBaseClass();
10021 }
10022 
10023 } // end anonymous namespace
10024 
10025 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10026                                     const FunctionDecl *FD) {
10027   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10028     bool AlwaysTrue;
10029     if (EnableIf->getCond()->isValueDependent() ||
10030         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10031       return false;
10032     if (!AlwaysTrue)
10033       return false;
10034   }
10035   return true;
10036 }
10037 
10038 /// Returns true if we can take the address of the function.
10039 ///
10040 /// \param Complain - If true, we'll emit a diagnostic
10041 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10042 ///   we in overload resolution?
10043 /// \param Loc - The location of the statement we're complaining about. Ignored
10044 ///   if we're not complaining, or if we're in overload resolution.
10045 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10046                                               bool Complain,
10047                                               bool InOverloadResolution,
10048                                               SourceLocation Loc) {
10049   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10050     if (Complain) {
10051       if (InOverloadResolution)
10052         S.Diag(FD->getBeginLoc(),
10053                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10054       else
10055         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10056     }
10057     return false;
10058   }
10059 
10060   if (FD->getTrailingRequiresClause()) {
10061     ConstraintSatisfaction Satisfaction;
10062     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10063       return false;
10064     if (!Satisfaction.IsSatisfied) {
10065       if (Complain) {
10066         if (InOverloadResolution)
10067           S.Diag(FD->getBeginLoc(),
10068                  diag::note_ovl_candidate_unsatisfied_constraints);
10069         else
10070           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10071               << FD;
10072         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10073       }
10074       return false;
10075     }
10076   }
10077 
10078   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10079     return P->hasAttr<PassObjectSizeAttr>();
10080   });
10081   if (I == FD->param_end())
10082     return true;
10083 
10084   if (Complain) {
10085     // Add one to ParamNo because it's user-facing
10086     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10087     if (InOverloadResolution)
10088       S.Diag(FD->getLocation(),
10089              diag::note_ovl_candidate_has_pass_object_size_params)
10090           << ParamNo;
10091     else
10092       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10093           << FD << ParamNo;
10094   }
10095   return false;
10096 }
10097 
10098 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10099                                                const FunctionDecl *FD) {
10100   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10101                                            /*InOverloadResolution=*/true,
10102                                            /*Loc=*/SourceLocation());
10103 }
10104 
10105 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10106                                              bool Complain,
10107                                              SourceLocation Loc) {
10108   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10109                                              /*InOverloadResolution=*/false,
10110                                              Loc);
10111 }
10112 
10113 // Notes the location of an overload candidate.
10114 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10115                                  OverloadCandidateRewriteKind RewriteKind,
10116                                  QualType DestType, bool TakingAddress) {
10117   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10118     return;
10119   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10120       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10121     return;
10122 
10123   std::string FnDesc;
10124   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10125       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10126   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10127                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10128                          << Fn << FnDesc;
10129 
10130   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10131   Diag(Fn->getLocation(), PD);
10132   MaybeEmitInheritedConstructorNote(*this, Found);
10133 }
10134 
10135 static void
10136 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10137   // Perhaps the ambiguity was caused by two atomic constraints that are
10138   // 'identical' but not equivalent:
10139   //
10140   // void foo() requires (sizeof(T) > 4) { } // #1
10141   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10142   //
10143   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10144   // #2 to subsume #1, but these constraint are not considered equivalent
10145   // according to the subsumption rules because they are not the same
10146   // source-level construct. This behavior is quite confusing and we should try
10147   // to help the user figure out what happened.
10148 
10149   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10150   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10151   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10152     if (!I->Function)
10153       continue;
10154     SmallVector<const Expr *, 3> AC;
10155     if (auto *Template = I->Function->getPrimaryTemplate())
10156       Template->getAssociatedConstraints(AC);
10157     else
10158       I->Function->getAssociatedConstraints(AC);
10159     if (AC.empty())
10160       continue;
10161     if (FirstCand == nullptr) {
10162       FirstCand = I->Function;
10163       FirstAC = AC;
10164     } else if (SecondCand == nullptr) {
10165       SecondCand = I->Function;
10166       SecondAC = AC;
10167     } else {
10168       // We have more than one pair of constrained functions - this check is
10169       // expensive and we'd rather not try to diagnose it.
10170       return;
10171     }
10172   }
10173   if (!SecondCand)
10174     return;
10175   // The diagnostic can only happen if there are associated constraints on
10176   // both sides (there needs to be some identical atomic constraint).
10177   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10178                                                       SecondCand, SecondAC))
10179     // Just show the user one diagnostic, they'll probably figure it out
10180     // from here.
10181     return;
10182 }
10183 
10184 // Notes the location of all overload candidates designated through
10185 // OverloadedExpr
10186 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10187                                      bool TakingAddress) {
10188   assert(OverloadedExpr->getType() == Context.OverloadTy);
10189 
10190   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10191   OverloadExpr *OvlExpr = Ovl.Expression;
10192 
10193   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10194                             IEnd = OvlExpr->decls_end();
10195        I != IEnd; ++I) {
10196     if (FunctionTemplateDecl *FunTmpl =
10197                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10198       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10199                             TakingAddress);
10200     } else if (FunctionDecl *Fun
10201                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10202       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10203     }
10204   }
10205 }
10206 
10207 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10208 /// "lead" diagnostic; it will be given two arguments, the source and
10209 /// target types of the conversion.
10210 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10211                                  Sema &S,
10212                                  SourceLocation CaretLoc,
10213                                  const PartialDiagnostic &PDiag) const {
10214   S.Diag(CaretLoc, PDiag)
10215     << Ambiguous.getFromType() << Ambiguous.getToType();
10216   // FIXME: The note limiting machinery is borrowed from
10217   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10218   // refactoring here.
10219   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10220   unsigned CandsShown = 0;
10221   AmbiguousConversionSequence::const_iterator I, E;
10222   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10223     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10224       break;
10225     ++CandsShown;
10226     S.NoteOverloadCandidate(I->first, I->second);
10227   }
10228   if (I != E)
10229     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10230 }
10231 
10232 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10233                                   unsigned I, bool TakingCandidateAddress) {
10234   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10235   assert(Conv.isBad());
10236   assert(Cand->Function && "for now, candidate must be a function");
10237   FunctionDecl *Fn = Cand->Function;
10238 
10239   // There's a conversion slot for the object argument if this is a
10240   // non-constructor method.  Note that 'I' corresponds the
10241   // conversion-slot index.
10242   bool isObjectArgument = false;
10243   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10244     if (I == 0)
10245       isObjectArgument = true;
10246     else
10247       I--;
10248   }
10249 
10250   std::string FnDesc;
10251   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10252       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10253                                 FnDesc);
10254 
10255   Expr *FromExpr = Conv.Bad.FromExpr;
10256   QualType FromTy = Conv.Bad.getFromType();
10257   QualType ToTy = Conv.Bad.getToType();
10258 
10259   if (FromTy == S.Context.OverloadTy) {
10260     assert(FromExpr && "overload set argument came from implicit argument?");
10261     Expr *E = FromExpr->IgnoreParens();
10262     if (isa<UnaryOperator>(E))
10263       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10264     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10265 
10266     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10267         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10268         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10269         << Name << I + 1;
10270     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10271     return;
10272   }
10273 
10274   // Do some hand-waving analysis to see if the non-viability is due
10275   // to a qualifier mismatch.
10276   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10277   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10278   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10279     CToTy = RT->getPointeeType();
10280   else {
10281     // TODO: detect and diagnose the full richness of const mismatches.
10282     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10283       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10284         CFromTy = FromPT->getPointeeType();
10285         CToTy = ToPT->getPointeeType();
10286       }
10287   }
10288 
10289   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10290       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10291     Qualifiers FromQs = CFromTy.getQualifiers();
10292     Qualifiers ToQs = CToTy.getQualifiers();
10293 
10294     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10295       if (isObjectArgument)
10296         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10297             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10298             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10299             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10300       else
10301         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10302             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10303             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10304             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10305             << ToTy->isReferenceType() << I + 1;
10306       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10307       return;
10308     }
10309 
10310     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10311       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10312           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10313           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10314           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10315           << (unsigned)isObjectArgument << I + 1;
10316       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10317       return;
10318     }
10319 
10320     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10321       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10322           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10323           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10324           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10325           << (unsigned)isObjectArgument << I + 1;
10326       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10327       return;
10328     }
10329 
10330     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10331       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10332           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10333           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10334           << FromQs.hasUnaligned() << I + 1;
10335       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10336       return;
10337     }
10338 
10339     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10340     assert(CVR && "unexpected qualifiers mismatch");
10341 
10342     if (isObjectArgument) {
10343       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10344           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10345           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10346           << (CVR - 1);
10347     } else {
10348       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10349           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10350           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10351           << (CVR - 1) << I + 1;
10352     }
10353     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10354     return;
10355   }
10356 
10357   // Special diagnostic for failure to convert an initializer list, since
10358   // telling the user that it has type void is not useful.
10359   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10360     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10361         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10362         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10363         << ToTy << (unsigned)isObjectArgument << I + 1;
10364     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10365     return;
10366   }
10367 
10368   // Diagnose references or pointers to incomplete types differently,
10369   // since it's far from impossible that the incompleteness triggered
10370   // the failure.
10371   QualType TempFromTy = FromTy.getNonReferenceType();
10372   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10373     TempFromTy = PTy->getPointeeType();
10374   if (TempFromTy->isIncompleteType()) {
10375     // Emit the generic diagnostic and, optionally, add the hints to it.
10376     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10377         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10378         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10379         << ToTy << (unsigned)isObjectArgument << I + 1
10380         << (unsigned)(Cand->Fix.Kind);
10381 
10382     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10383     return;
10384   }
10385 
10386   // Diagnose base -> derived pointer conversions.
10387   unsigned BaseToDerivedConversion = 0;
10388   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10389     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10390       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10391                                                FromPtrTy->getPointeeType()) &&
10392           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10393           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10394           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10395                           FromPtrTy->getPointeeType()))
10396         BaseToDerivedConversion = 1;
10397     }
10398   } else if (const ObjCObjectPointerType *FromPtrTy
10399                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10400     if (const ObjCObjectPointerType *ToPtrTy
10401                                         = ToTy->getAs<ObjCObjectPointerType>())
10402       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10403         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10404           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10405                                                 FromPtrTy->getPointeeType()) &&
10406               FromIface->isSuperClassOf(ToIface))
10407             BaseToDerivedConversion = 2;
10408   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10409     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10410         !FromTy->isIncompleteType() &&
10411         !ToRefTy->getPointeeType()->isIncompleteType() &&
10412         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10413       BaseToDerivedConversion = 3;
10414     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10415                ToTy.getNonReferenceType().getCanonicalType() ==
10416                FromTy.getNonReferenceType().getCanonicalType()) {
10417       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10418           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10419           << (unsigned)isObjectArgument << I + 1
10420           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10421       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10422       return;
10423     }
10424   }
10425 
10426   if (BaseToDerivedConversion) {
10427     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10428         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10429         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10430         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10431     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10432     return;
10433   }
10434 
10435   if (isa<ObjCObjectPointerType>(CFromTy) &&
10436       isa<PointerType>(CToTy)) {
10437       Qualifiers FromQs = CFromTy.getQualifiers();
10438       Qualifiers ToQs = CToTy.getQualifiers();
10439       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10440         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10441             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10442             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10443             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10444         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10445         return;
10446       }
10447   }
10448 
10449   if (TakingCandidateAddress &&
10450       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10451     return;
10452 
10453   // Emit the generic diagnostic and, optionally, add the hints to it.
10454   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10455   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10456         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10457         << ToTy << (unsigned)isObjectArgument << I + 1
10458         << (unsigned)(Cand->Fix.Kind);
10459 
10460   // If we can fix the conversion, suggest the FixIts.
10461   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10462        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10463     FDiag << *HI;
10464   S.Diag(Fn->getLocation(), FDiag);
10465 
10466   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10467 }
10468 
10469 /// Additional arity mismatch diagnosis specific to a function overload
10470 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10471 /// over a candidate in any candidate set.
10472 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10473                                unsigned NumArgs) {
10474   FunctionDecl *Fn = Cand->Function;
10475   unsigned MinParams = Fn->getMinRequiredArguments();
10476 
10477   // With invalid overloaded operators, it's possible that we think we
10478   // have an arity mismatch when in fact it looks like we have the
10479   // right number of arguments, because only overloaded operators have
10480   // the weird behavior of overloading member and non-member functions.
10481   // Just don't report anything.
10482   if (Fn->isInvalidDecl() &&
10483       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10484     return true;
10485 
10486   if (NumArgs < MinParams) {
10487     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10488            (Cand->FailureKind == ovl_fail_bad_deduction &&
10489             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10490   } else {
10491     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10492            (Cand->FailureKind == ovl_fail_bad_deduction &&
10493             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10494   }
10495 
10496   return false;
10497 }
10498 
10499 /// General arity mismatch diagnosis over a candidate in a candidate set.
10500 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10501                                   unsigned NumFormalArgs) {
10502   assert(isa<FunctionDecl>(D) &&
10503       "The templated declaration should at least be a function"
10504       " when diagnosing bad template argument deduction due to too many"
10505       " or too few arguments");
10506 
10507   FunctionDecl *Fn = cast<FunctionDecl>(D);
10508 
10509   // TODO: treat calls to a missing default constructor as a special case
10510   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10511   unsigned MinParams = Fn->getMinRequiredArguments();
10512 
10513   // at least / at most / exactly
10514   unsigned mode, modeCount;
10515   if (NumFormalArgs < MinParams) {
10516     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10517         FnTy->isTemplateVariadic())
10518       mode = 0; // "at least"
10519     else
10520       mode = 2; // "exactly"
10521     modeCount = MinParams;
10522   } else {
10523     if (MinParams != FnTy->getNumParams())
10524       mode = 1; // "at most"
10525     else
10526       mode = 2; // "exactly"
10527     modeCount = FnTy->getNumParams();
10528   }
10529 
10530   std::string Description;
10531   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10532       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10533 
10534   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10535     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10536         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10537         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10538   else
10539     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10540         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10541         << Description << mode << modeCount << NumFormalArgs;
10542 
10543   MaybeEmitInheritedConstructorNote(S, Found);
10544 }
10545 
10546 /// Arity mismatch diagnosis specific to a function overload candidate.
10547 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10548                                   unsigned NumFormalArgs) {
10549   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10550     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10551 }
10552 
10553 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10554   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10555     return TD;
10556   llvm_unreachable("Unsupported: Getting the described template declaration"
10557                    " for bad deduction diagnosis");
10558 }
10559 
10560 /// Diagnose a failed template-argument deduction.
10561 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10562                                  DeductionFailureInfo &DeductionFailure,
10563                                  unsigned NumArgs,
10564                                  bool TakingCandidateAddress) {
10565   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10566   NamedDecl *ParamD;
10567   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10568   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10569   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10570   switch (DeductionFailure.Result) {
10571   case Sema::TDK_Success:
10572     llvm_unreachable("TDK_success while diagnosing bad deduction");
10573 
10574   case Sema::TDK_Incomplete: {
10575     assert(ParamD && "no parameter found for incomplete deduction result");
10576     S.Diag(Templated->getLocation(),
10577            diag::note_ovl_candidate_incomplete_deduction)
10578         << ParamD->getDeclName();
10579     MaybeEmitInheritedConstructorNote(S, Found);
10580     return;
10581   }
10582 
10583   case Sema::TDK_IncompletePack: {
10584     assert(ParamD && "no parameter found for incomplete deduction result");
10585     S.Diag(Templated->getLocation(),
10586            diag::note_ovl_candidate_incomplete_deduction_pack)
10587         << ParamD->getDeclName()
10588         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10589         << *DeductionFailure.getFirstArg();
10590     MaybeEmitInheritedConstructorNote(S, Found);
10591     return;
10592   }
10593 
10594   case Sema::TDK_Underqualified: {
10595     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10596     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10597 
10598     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10599 
10600     // Param will have been canonicalized, but it should just be a
10601     // qualified version of ParamD, so move the qualifiers to that.
10602     QualifierCollector Qs;
10603     Qs.strip(Param);
10604     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10605     assert(S.Context.hasSameType(Param, NonCanonParam));
10606 
10607     // Arg has also been canonicalized, but there's nothing we can do
10608     // about that.  It also doesn't matter as much, because it won't
10609     // have any template parameters in it (because deduction isn't
10610     // done on dependent types).
10611     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10612 
10613     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10614         << ParamD->getDeclName() << Arg << NonCanonParam;
10615     MaybeEmitInheritedConstructorNote(S, Found);
10616     return;
10617   }
10618 
10619   case Sema::TDK_Inconsistent: {
10620     assert(ParamD && "no parameter found for inconsistent deduction result");
10621     int which = 0;
10622     if (isa<TemplateTypeParmDecl>(ParamD))
10623       which = 0;
10624     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10625       // Deduction might have failed because we deduced arguments of two
10626       // different types for a non-type template parameter.
10627       // FIXME: Use a different TDK value for this.
10628       QualType T1 =
10629           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10630       QualType T2 =
10631           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10632       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10633         S.Diag(Templated->getLocation(),
10634                diag::note_ovl_candidate_inconsistent_deduction_types)
10635           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10636           << *DeductionFailure.getSecondArg() << T2;
10637         MaybeEmitInheritedConstructorNote(S, Found);
10638         return;
10639       }
10640 
10641       which = 1;
10642     } else {
10643       which = 2;
10644     }
10645 
10646     // Tweak the diagnostic if the problem is that we deduced packs of
10647     // different arities. We'll print the actual packs anyway in case that
10648     // includes additional useful information.
10649     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10650         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10651         DeductionFailure.getFirstArg()->pack_size() !=
10652             DeductionFailure.getSecondArg()->pack_size()) {
10653       which = 3;
10654     }
10655 
10656     S.Diag(Templated->getLocation(),
10657            diag::note_ovl_candidate_inconsistent_deduction)
10658         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10659         << *DeductionFailure.getSecondArg();
10660     MaybeEmitInheritedConstructorNote(S, Found);
10661     return;
10662   }
10663 
10664   case Sema::TDK_InvalidExplicitArguments:
10665     assert(ParamD && "no parameter found for invalid explicit arguments");
10666     if (ParamD->getDeclName())
10667       S.Diag(Templated->getLocation(),
10668              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10669           << ParamD->getDeclName();
10670     else {
10671       int index = 0;
10672       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10673         index = TTP->getIndex();
10674       else if (NonTypeTemplateParmDecl *NTTP
10675                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10676         index = NTTP->getIndex();
10677       else
10678         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10679       S.Diag(Templated->getLocation(),
10680              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10681           << (index + 1);
10682     }
10683     MaybeEmitInheritedConstructorNote(S, Found);
10684     return;
10685 
10686   case Sema::TDK_ConstraintsNotSatisfied: {
10687     // Format the template argument list into the argument string.
10688     SmallString<128> TemplateArgString;
10689     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10690     TemplateArgString = " ";
10691     TemplateArgString += S.getTemplateArgumentBindingsText(
10692         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10693     if (TemplateArgString.size() == 1)
10694       TemplateArgString.clear();
10695     S.Diag(Templated->getLocation(),
10696            diag::note_ovl_candidate_unsatisfied_constraints)
10697         << TemplateArgString;
10698 
10699     S.DiagnoseUnsatisfiedConstraint(
10700         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10701     return;
10702   }
10703   case Sema::TDK_TooManyArguments:
10704   case Sema::TDK_TooFewArguments:
10705     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10706     return;
10707 
10708   case Sema::TDK_InstantiationDepth:
10709     S.Diag(Templated->getLocation(),
10710            diag::note_ovl_candidate_instantiation_depth);
10711     MaybeEmitInheritedConstructorNote(S, Found);
10712     return;
10713 
10714   case Sema::TDK_SubstitutionFailure: {
10715     // Format the template argument list into the argument string.
10716     SmallString<128> TemplateArgString;
10717     if (TemplateArgumentList *Args =
10718             DeductionFailure.getTemplateArgumentList()) {
10719       TemplateArgString = " ";
10720       TemplateArgString += S.getTemplateArgumentBindingsText(
10721           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10722       if (TemplateArgString.size() == 1)
10723         TemplateArgString.clear();
10724     }
10725 
10726     // If this candidate was disabled by enable_if, say so.
10727     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10728     if (PDiag && PDiag->second.getDiagID() ==
10729           diag::err_typename_nested_not_found_enable_if) {
10730       // FIXME: Use the source range of the condition, and the fully-qualified
10731       //        name of the enable_if template. These are both present in PDiag.
10732       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10733         << "'enable_if'" << TemplateArgString;
10734       return;
10735     }
10736 
10737     // We found a specific requirement that disabled the enable_if.
10738     if (PDiag && PDiag->second.getDiagID() ==
10739         diag::err_typename_nested_not_found_requirement) {
10740       S.Diag(Templated->getLocation(),
10741              diag::note_ovl_candidate_disabled_by_requirement)
10742         << PDiag->second.getStringArg(0) << TemplateArgString;
10743       return;
10744     }
10745 
10746     // Format the SFINAE diagnostic into the argument string.
10747     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10748     //        formatted message in another diagnostic.
10749     SmallString<128> SFINAEArgString;
10750     SourceRange R;
10751     if (PDiag) {
10752       SFINAEArgString = ": ";
10753       R = SourceRange(PDiag->first, PDiag->first);
10754       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10755     }
10756 
10757     S.Diag(Templated->getLocation(),
10758            diag::note_ovl_candidate_substitution_failure)
10759         << TemplateArgString << SFINAEArgString << R;
10760     MaybeEmitInheritedConstructorNote(S, Found);
10761     return;
10762   }
10763 
10764   case Sema::TDK_DeducedMismatch:
10765   case Sema::TDK_DeducedMismatchNested: {
10766     // Format the template argument list into the argument string.
10767     SmallString<128> TemplateArgString;
10768     if (TemplateArgumentList *Args =
10769             DeductionFailure.getTemplateArgumentList()) {
10770       TemplateArgString = " ";
10771       TemplateArgString += S.getTemplateArgumentBindingsText(
10772           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10773       if (TemplateArgString.size() == 1)
10774         TemplateArgString.clear();
10775     }
10776 
10777     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10778         << (*DeductionFailure.getCallArgIndex() + 1)
10779         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10780         << TemplateArgString
10781         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10782     break;
10783   }
10784 
10785   case Sema::TDK_NonDeducedMismatch: {
10786     // FIXME: Provide a source location to indicate what we couldn't match.
10787     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10788     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10789     if (FirstTA.getKind() == TemplateArgument::Template &&
10790         SecondTA.getKind() == TemplateArgument::Template) {
10791       TemplateName FirstTN = FirstTA.getAsTemplate();
10792       TemplateName SecondTN = SecondTA.getAsTemplate();
10793       if (FirstTN.getKind() == TemplateName::Template &&
10794           SecondTN.getKind() == TemplateName::Template) {
10795         if (FirstTN.getAsTemplateDecl()->getName() ==
10796             SecondTN.getAsTemplateDecl()->getName()) {
10797           // FIXME: This fixes a bad diagnostic where both templates are named
10798           // the same.  This particular case is a bit difficult since:
10799           // 1) It is passed as a string to the diagnostic printer.
10800           // 2) The diagnostic printer only attempts to find a better
10801           //    name for types, not decls.
10802           // Ideally, this should folded into the diagnostic printer.
10803           S.Diag(Templated->getLocation(),
10804                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10805               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10806           return;
10807         }
10808       }
10809     }
10810 
10811     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10812         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10813       return;
10814 
10815     // FIXME: For generic lambda parameters, check if the function is a lambda
10816     // call operator, and if so, emit a prettier and more informative
10817     // diagnostic that mentions 'auto' and lambda in addition to
10818     // (or instead of?) the canonical template type parameters.
10819     S.Diag(Templated->getLocation(),
10820            diag::note_ovl_candidate_non_deduced_mismatch)
10821         << FirstTA << SecondTA;
10822     return;
10823   }
10824   // TODO: diagnose these individually, then kill off
10825   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10826   case Sema::TDK_MiscellaneousDeductionFailure:
10827     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10828     MaybeEmitInheritedConstructorNote(S, Found);
10829     return;
10830   case Sema::TDK_CUDATargetMismatch:
10831     S.Diag(Templated->getLocation(),
10832            diag::note_cuda_ovl_candidate_target_mismatch);
10833     return;
10834   }
10835 }
10836 
10837 /// Diagnose a failed template-argument deduction, for function calls.
10838 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10839                                  unsigned NumArgs,
10840                                  bool TakingCandidateAddress) {
10841   unsigned TDK = Cand->DeductionFailure.Result;
10842   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10843     if (CheckArityMismatch(S, Cand, NumArgs))
10844       return;
10845   }
10846   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10847                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10848 }
10849 
10850 /// CUDA: diagnose an invalid call across targets.
10851 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10852   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10853   FunctionDecl *Callee = Cand->Function;
10854 
10855   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10856                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10857 
10858   std::string FnDesc;
10859   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10860       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10861                                 Cand->getRewriteKind(), FnDesc);
10862 
10863   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10864       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10865       << FnDesc /* Ignored */
10866       << CalleeTarget << CallerTarget;
10867 
10868   // This could be an implicit constructor for which we could not infer the
10869   // target due to a collsion. Diagnose that case.
10870   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10871   if (Meth != nullptr && Meth->isImplicit()) {
10872     CXXRecordDecl *ParentClass = Meth->getParent();
10873     Sema::CXXSpecialMember CSM;
10874 
10875     switch (FnKindPair.first) {
10876     default:
10877       return;
10878     case oc_implicit_default_constructor:
10879       CSM = Sema::CXXDefaultConstructor;
10880       break;
10881     case oc_implicit_copy_constructor:
10882       CSM = Sema::CXXCopyConstructor;
10883       break;
10884     case oc_implicit_move_constructor:
10885       CSM = Sema::CXXMoveConstructor;
10886       break;
10887     case oc_implicit_copy_assignment:
10888       CSM = Sema::CXXCopyAssignment;
10889       break;
10890     case oc_implicit_move_assignment:
10891       CSM = Sema::CXXMoveAssignment;
10892       break;
10893     };
10894 
10895     bool ConstRHS = false;
10896     if (Meth->getNumParams()) {
10897       if (const ReferenceType *RT =
10898               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10899         ConstRHS = RT->getPointeeType().isConstQualified();
10900       }
10901     }
10902 
10903     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10904                                               /* ConstRHS */ ConstRHS,
10905                                               /* Diagnose */ true);
10906   }
10907 }
10908 
10909 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10910   FunctionDecl *Callee = Cand->Function;
10911   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10912 
10913   S.Diag(Callee->getLocation(),
10914          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10915       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10916 }
10917 
10918 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10919   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10920   assert(ES.isExplicit() && "not an explicit candidate");
10921 
10922   unsigned Kind;
10923   switch (Cand->Function->getDeclKind()) {
10924   case Decl::Kind::CXXConstructor:
10925     Kind = 0;
10926     break;
10927   case Decl::Kind::CXXConversion:
10928     Kind = 1;
10929     break;
10930   case Decl::Kind::CXXDeductionGuide:
10931     Kind = Cand->Function->isImplicit() ? 0 : 2;
10932     break;
10933   default:
10934     llvm_unreachable("invalid Decl");
10935   }
10936 
10937   // Note the location of the first (in-class) declaration; a redeclaration
10938   // (particularly an out-of-class definition) will typically lack the
10939   // 'explicit' specifier.
10940   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10941   FunctionDecl *First = Cand->Function->getFirstDecl();
10942   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10943     First = Pattern->getFirstDecl();
10944 
10945   S.Diag(First->getLocation(),
10946          diag::note_ovl_candidate_explicit)
10947       << Kind << (ES.getExpr() ? 1 : 0)
10948       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10949 }
10950 
10951 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10952   FunctionDecl *Callee = Cand->Function;
10953 
10954   S.Diag(Callee->getLocation(),
10955          diag::note_ovl_candidate_disabled_by_extension)
10956     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10957 }
10958 
10959 /// Generates a 'note' diagnostic for an overload candidate.  We've
10960 /// already generated a primary error at the call site.
10961 ///
10962 /// It really does need to be a single diagnostic with its caret
10963 /// pointed at the candidate declaration.  Yes, this creates some
10964 /// major challenges of technical writing.  Yes, this makes pointing
10965 /// out problems with specific arguments quite awkward.  It's still
10966 /// better than generating twenty screens of text for every failed
10967 /// overload.
10968 ///
10969 /// It would be great to be able to express per-candidate problems
10970 /// more richly for those diagnostic clients that cared, but we'd
10971 /// still have to be just as careful with the default diagnostics.
10972 /// \param CtorDestAS Addr space of object being constructed (for ctor
10973 /// candidates only).
10974 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10975                                   unsigned NumArgs,
10976                                   bool TakingCandidateAddress,
10977                                   LangAS CtorDestAS = LangAS::Default) {
10978   FunctionDecl *Fn = Cand->Function;
10979 
10980   // Note deleted candidates, but only if they're viable.
10981   if (Cand->Viable) {
10982     if (Fn->isDeleted()) {
10983       std::string FnDesc;
10984       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10985           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10986                                     Cand->getRewriteKind(), FnDesc);
10987 
10988       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10989           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10990           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10991       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10992       return;
10993     }
10994 
10995     // We don't really have anything else to say about viable candidates.
10996     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10997     return;
10998   }
10999 
11000   switch (Cand->FailureKind) {
11001   case ovl_fail_too_many_arguments:
11002   case ovl_fail_too_few_arguments:
11003     return DiagnoseArityMismatch(S, Cand, NumArgs);
11004 
11005   case ovl_fail_bad_deduction:
11006     return DiagnoseBadDeduction(S, Cand, NumArgs,
11007                                 TakingCandidateAddress);
11008 
11009   case ovl_fail_illegal_constructor: {
11010     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
11011       << (Fn->getPrimaryTemplate() ? 1 : 0);
11012     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11013     return;
11014   }
11015 
11016   case ovl_fail_object_addrspace_mismatch: {
11017     Qualifiers QualsForPrinting;
11018     QualsForPrinting.setAddressSpace(CtorDestAS);
11019     S.Diag(Fn->getLocation(),
11020            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
11021         << QualsForPrinting;
11022     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11023     return;
11024   }
11025 
11026   case ovl_fail_trivial_conversion:
11027   case ovl_fail_bad_final_conversion:
11028   case ovl_fail_final_conversion_not_exact:
11029     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11030 
11031   case ovl_fail_bad_conversion: {
11032     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
11033     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11034       if (Cand->Conversions[I].isBad())
11035         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11036 
11037     // FIXME: this currently happens when we're called from SemaInit
11038     // when user-conversion overload fails.  Figure out how to handle
11039     // those conditions and diagnose them well.
11040     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11041   }
11042 
11043   case ovl_fail_bad_target:
11044     return DiagnoseBadTarget(S, Cand);
11045 
11046   case ovl_fail_enable_if:
11047     return DiagnoseFailedEnableIfAttr(S, Cand);
11048 
11049   case ovl_fail_explicit:
11050     return DiagnoseFailedExplicitSpec(S, Cand);
11051 
11052   case ovl_fail_ext_disabled:
11053     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11054 
11055   case ovl_fail_inhctor_slice:
11056     // It's generally not interesting to note copy/move constructors here.
11057     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11058       return;
11059     S.Diag(Fn->getLocation(),
11060            diag::note_ovl_candidate_inherited_constructor_slice)
11061       << (Fn->getPrimaryTemplate() ? 1 : 0)
11062       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11063     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11064     return;
11065 
11066   case ovl_fail_addr_not_available: {
11067     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11068     (void)Available;
11069     assert(!Available);
11070     break;
11071   }
11072   case ovl_non_default_multiversion_function:
11073     // Do nothing, these should simply be ignored.
11074     break;
11075 
11076   case ovl_fail_constraints_not_satisfied: {
11077     std::string FnDesc;
11078     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11079         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11080                                   Cand->getRewriteKind(), FnDesc);
11081 
11082     S.Diag(Fn->getLocation(),
11083            diag::note_ovl_candidate_constraints_not_satisfied)
11084         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11085         << FnDesc /* Ignored */;
11086     ConstraintSatisfaction Satisfaction;
11087     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11088       break;
11089     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11090   }
11091   }
11092 }
11093 
11094 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11095   // Desugar the type of the surrogate down to a function type,
11096   // retaining as many typedefs as possible while still showing
11097   // the function type (and, therefore, its parameter types).
11098   QualType FnType = Cand->Surrogate->getConversionType();
11099   bool isLValueReference = false;
11100   bool isRValueReference = false;
11101   bool isPointer = false;
11102   if (const LValueReferenceType *FnTypeRef =
11103         FnType->getAs<LValueReferenceType>()) {
11104     FnType = FnTypeRef->getPointeeType();
11105     isLValueReference = true;
11106   } else if (const RValueReferenceType *FnTypeRef =
11107                FnType->getAs<RValueReferenceType>()) {
11108     FnType = FnTypeRef->getPointeeType();
11109     isRValueReference = true;
11110   }
11111   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11112     FnType = FnTypePtr->getPointeeType();
11113     isPointer = true;
11114   }
11115   // Desugar down to a function type.
11116   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11117   // Reconstruct the pointer/reference as appropriate.
11118   if (isPointer) FnType = S.Context.getPointerType(FnType);
11119   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11120   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11121 
11122   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11123     << FnType;
11124 }
11125 
11126 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11127                                          SourceLocation OpLoc,
11128                                          OverloadCandidate *Cand) {
11129   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11130   std::string TypeStr("operator");
11131   TypeStr += Opc;
11132   TypeStr += "(";
11133   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11134   if (Cand->Conversions.size() == 1) {
11135     TypeStr += ")";
11136     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11137   } else {
11138     TypeStr += ", ";
11139     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11140     TypeStr += ")";
11141     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11142   }
11143 }
11144 
11145 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11146                                          OverloadCandidate *Cand) {
11147   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11148     if (ICS.isBad()) break; // all meaningless after first invalid
11149     if (!ICS.isAmbiguous()) continue;
11150 
11151     ICS.DiagnoseAmbiguousConversion(
11152         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11153   }
11154 }
11155 
11156 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11157   if (Cand->Function)
11158     return Cand->Function->getLocation();
11159   if (Cand->IsSurrogate)
11160     return Cand->Surrogate->getLocation();
11161   return SourceLocation();
11162 }
11163 
11164 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11165   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11166   case Sema::TDK_Success:
11167   case Sema::TDK_NonDependentConversionFailure:
11168     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11169 
11170   case Sema::TDK_Invalid:
11171   case Sema::TDK_Incomplete:
11172   case Sema::TDK_IncompletePack:
11173     return 1;
11174 
11175   case Sema::TDK_Underqualified:
11176   case Sema::TDK_Inconsistent:
11177     return 2;
11178 
11179   case Sema::TDK_SubstitutionFailure:
11180   case Sema::TDK_DeducedMismatch:
11181   case Sema::TDK_ConstraintsNotSatisfied:
11182   case Sema::TDK_DeducedMismatchNested:
11183   case Sema::TDK_NonDeducedMismatch:
11184   case Sema::TDK_MiscellaneousDeductionFailure:
11185   case Sema::TDK_CUDATargetMismatch:
11186     return 3;
11187 
11188   case Sema::TDK_InstantiationDepth:
11189     return 4;
11190 
11191   case Sema::TDK_InvalidExplicitArguments:
11192     return 5;
11193 
11194   case Sema::TDK_TooManyArguments:
11195   case Sema::TDK_TooFewArguments:
11196     return 6;
11197   }
11198   llvm_unreachable("Unhandled deduction result");
11199 }
11200 
11201 namespace {
11202 struct CompareOverloadCandidatesForDisplay {
11203   Sema &S;
11204   SourceLocation Loc;
11205   size_t NumArgs;
11206   OverloadCandidateSet::CandidateSetKind CSK;
11207 
11208   CompareOverloadCandidatesForDisplay(
11209       Sema &S, SourceLocation Loc, size_t NArgs,
11210       OverloadCandidateSet::CandidateSetKind CSK)
11211       : S(S), NumArgs(NArgs), CSK(CSK) {}
11212 
11213   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11214     // If there are too many or too few arguments, that's the high-order bit we
11215     // want to sort by, even if the immediate failure kind was something else.
11216     if (C->FailureKind == ovl_fail_too_many_arguments ||
11217         C->FailureKind == ovl_fail_too_few_arguments)
11218       return static_cast<OverloadFailureKind>(C->FailureKind);
11219 
11220     if (C->Function) {
11221       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11222         return ovl_fail_too_many_arguments;
11223       if (NumArgs < C->Function->getMinRequiredArguments())
11224         return ovl_fail_too_few_arguments;
11225     }
11226 
11227     return static_cast<OverloadFailureKind>(C->FailureKind);
11228   }
11229 
11230   bool operator()(const OverloadCandidate *L,
11231                   const OverloadCandidate *R) {
11232     // Fast-path this check.
11233     if (L == R) return false;
11234 
11235     // Order first by viability.
11236     if (L->Viable) {
11237       if (!R->Viable) return true;
11238 
11239       // TODO: introduce a tri-valued comparison for overload
11240       // candidates.  Would be more worthwhile if we had a sort
11241       // that could exploit it.
11242       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11243         return true;
11244       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11245         return false;
11246     } else if (R->Viable)
11247       return false;
11248 
11249     assert(L->Viable == R->Viable);
11250 
11251     // Criteria by which we can sort non-viable candidates:
11252     if (!L->Viable) {
11253       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11254       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11255 
11256       // 1. Arity mismatches come after other candidates.
11257       if (LFailureKind == ovl_fail_too_many_arguments ||
11258           LFailureKind == ovl_fail_too_few_arguments) {
11259         if (RFailureKind == ovl_fail_too_many_arguments ||
11260             RFailureKind == ovl_fail_too_few_arguments) {
11261           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11262           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11263           if (LDist == RDist) {
11264             if (LFailureKind == RFailureKind)
11265               // Sort non-surrogates before surrogates.
11266               return !L->IsSurrogate && R->IsSurrogate;
11267             // Sort candidates requiring fewer parameters than there were
11268             // arguments given after candidates requiring more parameters
11269             // than there were arguments given.
11270             return LFailureKind == ovl_fail_too_many_arguments;
11271           }
11272           return LDist < RDist;
11273         }
11274         return false;
11275       }
11276       if (RFailureKind == ovl_fail_too_many_arguments ||
11277           RFailureKind == ovl_fail_too_few_arguments)
11278         return true;
11279 
11280       // 2. Bad conversions come first and are ordered by the number
11281       // of bad conversions and quality of good conversions.
11282       if (LFailureKind == ovl_fail_bad_conversion) {
11283         if (RFailureKind != ovl_fail_bad_conversion)
11284           return true;
11285 
11286         // The conversion that can be fixed with a smaller number of changes,
11287         // comes first.
11288         unsigned numLFixes = L->Fix.NumConversionsFixed;
11289         unsigned numRFixes = R->Fix.NumConversionsFixed;
11290         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11291         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11292         if (numLFixes != numRFixes) {
11293           return numLFixes < numRFixes;
11294         }
11295 
11296         // If there's any ordering between the defined conversions...
11297         // FIXME: this might not be transitive.
11298         assert(L->Conversions.size() == R->Conversions.size());
11299 
11300         int leftBetter = 0;
11301         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11302         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11303           switch (CompareImplicitConversionSequences(S, Loc,
11304                                                      L->Conversions[I],
11305                                                      R->Conversions[I])) {
11306           case ImplicitConversionSequence::Better:
11307             leftBetter++;
11308             break;
11309 
11310           case ImplicitConversionSequence::Worse:
11311             leftBetter--;
11312             break;
11313 
11314           case ImplicitConversionSequence::Indistinguishable:
11315             break;
11316           }
11317         }
11318         if (leftBetter > 0) return true;
11319         if (leftBetter < 0) return false;
11320 
11321       } else if (RFailureKind == ovl_fail_bad_conversion)
11322         return false;
11323 
11324       if (LFailureKind == ovl_fail_bad_deduction) {
11325         if (RFailureKind != ovl_fail_bad_deduction)
11326           return true;
11327 
11328         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11329           return RankDeductionFailure(L->DeductionFailure)
11330                < RankDeductionFailure(R->DeductionFailure);
11331       } else if (RFailureKind == ovl_fail_bad_deduction)
11332         return false;
11333 
11334       // TODO: others?
11335     }
11336 
11337     // Sort everything else by location.
11338     SourceLocation LLoc = GetLocationForCandidate(L);
11339     SourceLocation RLoc = GetLocationForCandidate(R);
11340 
11341     // Put candidates without locations (e.g. builtins) at the end.
11342     if (LLoc.isInvalid()) return false;
11343     if (RLoc.isInvalid()) return true;
11344 
11345     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11346   }
11347 };
11348 }
11349 
11350 /// CompleteNonViableCandidate - Normally, overload resolution only
11351 /// computes up to the first bad conversion. Produces the FixIt set if
11352 /// possible.
11353 static void
11354 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11355                            ArrayRef<Expr *> Args,
11356                            OverloadCandidateSet::CandidateSetKind CSK) {
11357   assert(!Cand->Viable);
11358 
11359   // Don't do anything on failures other than bad conversion.
11360   if (Cand->FailureKind != ovl_fail_bad_conversion)
11361     return;
11362 
11363   // We only want the FixIts if all the arguments can be corrected.
11364   bool Unfixable = false;
11365   // Use a implicit copy initialization to check conversion fixes.
11366   Cand->Fix.setConversionChecker(TryCopyInitialization);
11367 
11368   // Attempt to fix the bad conversion.
11369   unsigned ConvCount = Cand->Conversions.size();
11370   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11371        ++ConvIdx) {
11372     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11373     if (Cand->Conversions[ConvIdx].isInitialized() &&
11374         Cand->Conversions[ConvIdx].isBad()) {
11375       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11376       break;
11377     }
11378   }
11379 
11380   // FIXME: this should probably be preserved from the overload
11381   // operation somehow.
11382   bool SuppressUserConversions = false;
11383 
11384   unsigned ConvIdx = 0;
11385   unsigned ArgIdx = 0;
11386   ArrayRef<QualType> ParamTypes;
11387   bool Reversed = Cand->isReversed();
11388 
11389   if (Cand->IsSurrogate) {
11390     QualType ConvType
11391       = Cand->Surrogate->getConversionType().getNonReferenceType();
11392     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11393       ConvType = ConvPtrType->getPointeeType();
11394     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11395     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11396     ConvIdx = 1;
11397   } else if (Cand->Function) {
11398     ParamTypes =
11399         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11400     if (isa<CXXMethodDecl>(Cand->Function) &&
11401         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11402       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11403       ConvIdx = 1;
11404       if (CSK == OverloadCandidateSet::CSK_Operator &&
11405           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11406         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11407         ArgIdx = 1;
11408     }
11409   } else {
11410     // Builtin operator.
11411     assert(ConvCount <= 3);
11412     ParamTypes = Cand->BuiltinParamTypes;
11413   }
11414 
11415   // Fill in the rest of the conversions.
11416   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11417        ConvIdx != ConvCount;
11418        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11419     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11420     if (Cand->Conversions[ConvIdx].isInitialized()) {
11421       // We've already checked this conversion.
11422     } else if (ParamIdx < ParamTypes.size()) {
11423       if (ParamTypes[ParamIdx]->isDependentType())
11424         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11425             Args[ArgIdx]->getType());
11426       else {
11427         Cand->Conversions[ConvIdx] =
11428             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11429                                   SuppressUserConversions,
11430                                   /*InOverloadResolution=*/true,
11431                                   /*AllowObjCWritebackConversion=*/
11432                                   S.getLangOpts().ObjCAutoRefCount);
11433         // Store the FixIt in the candidate if it exists.
11434         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11435           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11436       }
11437     } else
11438       Cand->Conversions[ConvIdx].setEllipsis();
11439   }
11440 }
11441 
11442 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11443     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11444     SourceLocation OpLoc,
11445     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11446   // Sort the candidates by viability and position.  Sorting directly would
11447   // be prohibitive, so we make a set of pointers and sort those.
11448   SmallVector<OverloadCandidate*, 32> Cands;
11449   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11450   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11451     if (!Filter(*Cand))
11452       continue;
11453     switch (OCD) {
11454     case OCD_AllCandidates:
11455       if (!Cand->Viable) {
11456         if (!Cand->Function && !Cand->IsSurrogate) {
11457           // This a non-viable builtin candidate.  We do not, in general,
11458           // want to list every possible builtin candidate.
11459           continue;
11460         }
11461         CompleteNonViableCandidate(S, Cand, Args, Kind);
11462       }
11463       break;
11464 
11465     case OCD_ViableCandidates:
11466       if (!Cand->Viable)
11467         continue;
11468       break;
11469 
11470     case OCD_AmbiguousCandidates:
11471       if (!Cand->Best)
11472         continue;
11473       break;
11474     }
11475 
11476     Cands.push_back(Cand);
11477   }
11478 
11479   llvm::stable_sort(
11480       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11481 
11482   return Cands;
11483 }
11484 
11485 /// When overload resolution fails, prints diagnostic messages containing the
11486 /// candidates in the candidate set.
11487 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11488     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11489     StringRef Opc, SourceLocation OpLoc,
11490     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11491 
11492   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11493 
11494   S.Diag(PD.first, PD.second);
11495 
11496   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11497 
11498   if (OCD == OCD_AmbiguousCandidates)
11499     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11500 }
11501 
11502 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11503                                           ArrayRef<OverloadCandidate *> Cands,
11504                                           StringRef Opc, SourceLocation OpLoc) {
11505   bool ReportedAmbiguousConversions = false;
11506 
11507   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11508   unsigned CandsShown = 0;
11509   auto I = Cands.begin(), E = Cands.end();
11510   for (; I != E; ++I) {
11511     OverloadCandidate *Cand = *I;
11512 
11513     // Set an arbitrary limit on the number of candidate functions we'll spam
11514     // the user with.  FIXME: This limit should depend on details of the
11515     // candidate list.
11516     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11517       break;
11518     }
11519     ++CandsShown;
11520 
11521     if (Cand->Function)
11522       NoteFunctionCandidate(S, Cand, Args.size(),
11523                             /*TakingCandidateAddress=*/false, DestAS);
11524     else if (Cand->IsSurrogate)
11525       NoteSurrogateCandidate(S, Cand);
11526     else {
11527       assert(Cand->Viable &&
11528              "Non-viable built-in candidates are not added to Cands.");
11529       // Generally we only see ambiguities including viable builtin
11530       // operators if overload resolution got screwed up by an
11531       // ambiguous user-defined conversion.
11532       //
11533       // FIXME: It's quite possible for different conversions to see
11534       // different ambiguities, though.
11535       if (!ReportedAmbiguousConversions) {
11536         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11537         ReportedAmbiguousConversions = true;
11538       }
11539 
11540       // If this is a viable builtin, print it.
11541       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11542     }
11543   }
11544 
11545   if (I != E)
11546     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11547 }
11548 
11549 static SourceLocation
11550 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11551   return Cand->Specialization ? Cand->Specialization->getLocation()
11552                               : SourceLocation();
11553 }
11554 
11555 namespace {
11556 struct CompareTemplateSpecCandidatesForDisplay {
11557   Sema &S;
11558   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11559 
11560   bool operator()(const TemplateSpecCandidate *L,
11561                   const TemplateSpecCandidate *R) {
11562     // Fast-path this check.
11563     if (L == R)
11564       return false;
11565 
11566     // Assuming that both candidates are not matches...
11567 
11568     // Sort by the ranking of deduction failures.
11569     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11570       return RankDeductionFailure(L->DeductionFailure) <
11571              RankDeductionFailure(R->DeductionFailure);
11572 
11573     // Sort everything else by location.
11574     SourceLocation LLoc = GetLocationForCandidate(L);
11575     SourceLocation RLoc = GetLocationForCandidate(R);
11576 
11577     // Put candidates without locations (e.g. builtins) at the end.
11578     if (LLoc.isInvalid())
11579       return false;
11580     if (RLoc.isInvalid())
11581       return true;
11582 
11583     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11584   }
11585 };
11586 }
11587 
11588 /// Diagnose a template argument deduction failure.
11589 /// We are treating these failures as overload failures due to bad
11590 /// deductions.
11591 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11592                                                  bool ForTakingAddress) {
11593   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11594                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11595 }
11596 
11597 void TemplateSpecCandidateSet::destroyCandidates() {
11598   for (iterator i = begin(), e = end(); i != e; ++i) {
11599     i->DeductionFailure.Destroy();
11600   }
11601 }
11602 
11603 void TemplateSpecCandidateSet::clear() {
11604   destroyCandidates();
11605   Candidates.clear();
11606 }
11607 
11608 /// NoteCandidates - When no template specialization match is found, prints
11609 /// diagnostic messages containing the non-matching specializations that form
11610 /// the candidate set.
11611 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11612 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11613 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11614   // Sort the candidates by position (assuming no candidate is a match).
11615   // Sorting directly would be prohibitive, so we make a set of pointers
11616   // and sort those.
11617   SmallVector<TemplateSpecCandidate *, 32> Cands;
11618   Cands.reserve(size());
11619   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11620     if (Cand->Specialization)
11621       Cands.push_back(Cand);
11622     // Otherwise, this is a non-matching builtin candidate.  We do not,
11623     // in general, want to list every possible builtin candidate.
11624   }
11625 
11626   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11627 
11628   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11629   // for generalization purposes (?).
11630   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11631 
11632   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11633   unsigned CandsShown = 0;
11634   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11635     TemplateSpecCandidate *Cand = *I;
11636 
11637     // Set an arbitrary limit on the number of candidates we'll spam
11638     // the user with.  FIXME: This limit should depend on details of the
11639     // candidate list.
11640     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11641       break;
11642     ++CandsShown;
11643 
11644     assert(Cand->Specialization &&
11645            "Non-matching built-in candidates are not added to Cands.");
11646     Cand->NoteDeductionFailure(S, ForTakingAddress);
11647   }
11648 
11649   if (I != E)
11650     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11651 }
11652 
11653 // [PossiblyAFunctionType]  -->   [Return]
11654 // NonFunctionType --> NonFunctionType
11655 // R (A) --> R(A)
11656 // R (*)(A) --> R (A)
11657 // R (&)(A) --> R (A)
11658 // R (S::*)(A) --> R (A)
11659 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11660   QualType Ret = PossiblyAFunctionType;
11661   if (const PointerType *ToTypePtr =
11662     PossiblyAFunctionType->getAs<PointerType>())
11663     Ret = ToTypePtr->getPointeeType();
11664   else if (const ReferenceType *ToTypeRef =
11665     PossiblyAFunctionType->getAs<ReferenceType>())
11666     Ret = ToTypeRef->getPointeeType();
11667   else if (const MemberPointerType *MemTypePtr =
11668     PossiblyAFunctionType->getAs<MemberPointerType>())
11669     Ret = MemTypePtr->getPointeeType();
11670   Ret =
11671     Context.getCanonicalType(Ret).getUnqualifiedType();
11672   return Ret;
11673 }
11674 
11675 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11676                                  bool Complain = true) {
11677   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11678       S.DeduceReturnType(FD, Loc, Complain))
11679     return true;
11680 
11681   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11682   if (S.getLangOpts().CPlusPlus17 &&
11683       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11684       !S.ResolveExceptionSpec(Loc, FPT))
11685     return true;
11686 
11687   return false;
11688 }
11689 
11690 namespace {
11691 // A helper class to help with address of function resolution
11692 // - allows us to avoid passing around all those ugly parameters
11693 class AddressOfFunctionResolver {
11694   Sema& S;
11695   Expr* SourceExpr;
11696   const QualType& TargetType;
11697   QualType TargetFunctionType; // Extracted function type from target type
11698 
11699   bool Complain;
11700   //DeclAccessPair& ResultFunctionAccessPair;
11701   ASTContext& Context;
11702 
11703   bool TargetTypeIsNonStaticMemberFunction;
11704   bool FoundNonTemplateFunction;
11705   bool StaticMemberFunctionFromBoundPointer;
11706   bool HasComplained;
11707 
11708   OverloadExpr::FindResult OvlExprInfo;
11709   OverloadExpr *OvlExpr;
11710   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11711   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11712   TemplateSpecCandidateSet FailedCandidates;
11713 
11714 public:
11715   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11716                             const QualType &TargetType, bool Complain)
11717       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11718         Complain(Complain), Context(S.getASTContext()),
11719         TargetTypeIsNonStaticMemberFunction(
11720             !!TargetType->getAs<MemberPointerType>()),
11721         FoundNonTemplateFunction(false),
11722         StaticMemberFunctionFromBoundPointer(false),
11723         HasComplained(false),
11724         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11725         OvlExpr(OvlExprInfo.Expression),
11726         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11727     ExtractUnqualifiedFunctionTypeFromTargetType();
11728 
11729     if (TargetFunctionType->isFunctionType()) {
11730       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11731         if (!UME->isImplicitAccess() &&
11732             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11733           StaticMemberFunctionFromBoundPointer = true;
11734     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11735       DeclAccessPair dap;
11736       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11737               OvlExpr, false, &dap)) {
11738         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11739           if (!Method->isStatic()) {
11740             // If the target type is a non-function type and the function found
11741             // is a non-static member function, pretend as if that was the
11742             // target, it's the only possible type to end up with.
11743             TargetTypeIsNonStaticMemberFunction = true;
11744 
11745             // And skip adding the function if its not in the proper form.
11746             // We'll diagnose this due to an empty set of functions.
11747             if (!OvlExprInfo.HasFormOfMemberPointer)
11748               return;
11749           }
11750 
11751         Matches.push_back(std::make_pair(dap, Fn));
11752       }
11753       return;
11754     }
11755 
11756     if (OvlExpr->hasExplicitTemplateArgs())
11757       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11758 
11759     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11760       // C++ [over.over]p4:
11761       //   If more than one function is selected, [...]
11762       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11763         if (FoundNonTemplateFunction)
11764           EliminateAllTemplateMatches();
11765         else
11766           EliminateAllExceptMostSpecializedTemplate();
11767       }
11768     }
11769 
11770     if (S.getLangOpts().CUDA && Matches.size() > 1)
11771       EliminateSuboptimalCudaMatches();
11772   }
11773 
11774   bool hasComplained() const { return HasComplained; }
11775 
11776 private:
11777   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11778     QualType Discard;
11779     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11780            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11781   }
11782 
11783   /// \return true if A is considered a better overload candidate for the
11784   /// desired type than B.
11785   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11786     // If A doesn't have exactly the correct type, we don't want to classify it
11787     // as "better" than anything else. This way, the user is required to
11788     // disambiguate for us if there are multiple candidates and no exact match.
11789     return candidateHasExactlyCorrectType(A) &&
11790            (!candidateHasExactlyCorrectType(B) ||
11791             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11792   }
11793 
11794   /// \return true if we were able to eliminate all but one overload candidate,
11795   /// false otherwise.
11796   bool eliminiateSuboptimalOverloadCandidates() {
11797     // Same algorithm as overload resolution -- one pass to pick the "best",
11798     // another pass to be sure that nothing is better than the best.
11799     auto Best = Matches.begin();
11800     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11801       if (isBetterCandidate(I->second, Best->second))
11802         Best = I;
11803 
11804     const FunctionDecl *BestFn = Best->second;
11805     auto IsBestOrInferiorToBest = [this, BestFn](
11806         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11807       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11808     };
11809 
11810     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11811     // option, so we can potentially give the user a better error
11812     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11813       return false;
11814     Matches[0] = *Best;
11815     Matches.resize(1);
11816     return true;
11817   }
11818 
11819   bool isTargetTypeAFunction() const {
11820     return TargetFunctionType->isFunctionType();
11821   }
11822 
11823   // [ToType]     [Return]
11824 
11825   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11826   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11827   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11828   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11829     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11830   }
11831 
11832   // return true if any matching specializations were found
11833   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11834                                    const DeclAccessPair& CurAccessFunPair) {
11835     if (CXXMethodDecl *Method
11836               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11837       // Skip non-static function templates when converting to pointer, and
11838       // static when converting to member pointer.
11839       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11840         return false;
11841     }
11842     else if (TargetTypeIsNonStaticMemberFunction)
11843       return false;
11844 
11845     // C++ [over.over]p2:
11846     //   If the name is a function template, template argument deduction is
11847     //   done (14.8.2.2), and if the argument deduction succeeds, the
11848     //   resulting template argument list is used to generate a single
11849     //   function template specialization, which is added to the set of
11850     //   overloaded functions considered.
11851     FunctionDecl *Specialization = nullptr;
11852     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11853     if (Sema::TemplateDeductionResult Result
11854           = S.DeduceTemplateArguments(FunctionTemplate,
11855                                       &OvlExplicitTemplateArgs,
11856                                       TargetFunctionType, Specialization,
11857                                       Info, /*IsAddressOfFunction*/true)) {
11858       // Make a note of the failed deduction for diagnostics.
11859       FailedCandidates.addCandidate()
11860           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11861                MakeDeductionFailureInfo(Context, Result, Info));
11862       return false;
11863     }
11864 
11865     // Template argument deduction ensures that we have an exact match or
11866     // compatible pointer-to-function arguments that would be adjusted by ICS.
11867     // This function template specicalization works.
11868     assert(S.isSameOrCompatibleFunctionType(
11869               Context.getCanonicalType(Specialization->getType()),
11870               Context.getCanonicalType(TargetFunctionType)));
11871 
11872     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11873       return false;
11874 
11875     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11876     return true;
11877   }
11878 
11879   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11880                                       const DeclAccessPair& CurAccessFunPair) {
11881     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11882       // Skip non-static functions when converting to pointer, and static
11883       // when converting to member pointer.
11884       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11885         return false;
11886     }
11887     else if (TargetTypeIsNonStaticMemberFunction)
11888       return false;
11889 
11890     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11891       if (S.getLangOpts().CUDA)
11892         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11893           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11894             return false;
11895       if (FunDecl->isMultiVersion()) {
11896         const auto *TA = FunDecl->getAttr<TargetAttr>();
11897         if (TA && !TA->isDefaultVersion())
11898           return false;
11899       }
11900 
11901       // If any candidate has a placeholder return type, trigger its deduction
11902       // now.
11903       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11904                                Complain)) {
11905         HasComplained |= Complain;
11906         return false;
11907       }
11908 
11909       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11910         return false;
11911 
11912       // If we're in C, we need to support types that aren't exactly identical.
11913       if (!S.getLangOpts().CPlusPlus ||
11914           candidateHasExactlyCorrectType(FunDecl)) {
11915         Matches.push_back(std::make_pair(
11916             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11917         FoundNonTemplateFunction = true;
11918         return true;
11919       }
11920     }
11921 
11922     return false;
11923   }
11924 
11925   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11926     bool Ret = false;
11927 
11928     // If the overload expression doesn't have the form of a pointer to
11929     // member, don't try to convert it to a pointer-to-member type.
11930     if (IsInvalidFormOfPointerToMemberFunction())
11931       return false;
11932 
11933     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11934                                E = OvlExpr->decls_end();
11935          I != E; ++I) {
11936       // Look through any using declarations to find the underlying function.
11937       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11938 
11939       // C++ [over.over]p3:
11940       //   Non-member functions and static member functions match
11941       //   targets of type "pointer-to-function" or "reference-to-function."
11942       //   Nonstatic member functions match targets of
11943       //   type "pointer-to-member-function."
11944       // Note that according to DR 247, the containing class does not matter.
11945       if (FunctionTemplateDecl *FunctionTemplate
11946                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11947         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11948           Ret = true;
11949       }
11950       // If we have explicit template arguments supplied, skip non-templates.
11951       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11952                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11953         Ret = true;
11954     }
11955     assert(Ret || Matches.empty());
11956     return Ret;
11957   }
11958 
11959   void EliminateAllExceptMostSpecializedTemplate() {
11960     //   [...] and any given function template specialization F1 is
11961     //   eliminated if the set contains a second function template
11962     //   specialization whose function template is more specialized
11963     //   than the function template of F1 according to the partial
11964     //   ordering rules of 14.5.5.2.
11965 
11966     // The algorithm specified above is quadratic. We instead use a
11967     // two-pass algorithm (similar to the one used to identify the
11968     // best viable function in an overload set) that identifies the
11969     // best function template (if it exists).
11970 
11971     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11972     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11973       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11974 
11975     // TODO: It looks like FailedCandidates does not serve much purpose
11976     // here, since the no_viable diagnostic has index 0.
11977     UnresolvedSetIterator Result = S.getMostSpecialized(
11978         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11979         SourceExpr->getBeginLoc(), S.PDiag(),
11980         S.PDiag(diag::err_addr_ovl_ambiguous)
11981             << Matches[0].second->getDeclName(),
11982         S.PDiag(diag::note_ovl_candidate)
11983             << (unsigned)oc_function << (unsigned)ocs_described_template,
11984         Complain, TargetFunctionType);
11985 
11986     if (Result != MatchesCopy.end()) {
11987       // Make it the first and only element
11988       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11989       Matches[0].second = cast<FunctionDecl>(*Result);
11990       Matches.resize(1);
11991     } else
11992       HasComplained |= Complain;
11993   }
11994 
11995   void EliminateAllTemplateMatches() {
11996     //   [...] any function template specializations in the set are
11997     //   eliminated if the set also contains a non-template function, [...]
11998     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11999       if (Matches[I].second->getPrimaryTemplate() == nullptr)
12000         ++I;
12001       else {
12002         Matches[I] = Matches[--N];
12003         Matches.resize(N);
12004       }
12005     }
12006   }
12007 
12008   void EliminateSuboptimalCudaMatches() {
12009     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
12010   }
12011 
12012 public:
12013   void ComplainNoMatchesFound() const {
12014     assert(Matches.empty());
12015     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
12016         << OvlExpr->getName() << TargetFunctionType
12017         << OvlExpr->getSourceRange();
12018     if (FailedCandidates.empty())
12019       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12020                                   /*TakingAddress=*/true);
12021     else {
12022       // We have some deduction failure messages. Use them to diagnose
12023       // the function templates, and diagnose the non-template candidates
12024       // normally.
12025       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12026                                  IEnd = OvlExpr->decls_end();
12027            I != IEnd; ++I)
12028         if (FunctionDecl *Fun =
12029                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
12030           if (!functionHasPassObjectSizeParams(Fun))
12031             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
12032                                     /*TakingAddress=*/true);
12033       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12034     }
12035   }
12036 
12037   bool IsInvalidFormOfPointerToMemberFunction() const {
12038     return TargetTypeIsNonStaticMemberFunction &&
12039       !OvlExprInfo.HasFormOfMemberPointer;
12040   }
12041 
12042   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12043       // TODO: Should we condition this on whether any functions might
12044       // have matched, or is it more appropriate to do that in callers?
12045       // TODO: a fixit wouldn't hurt.
12046       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12047         << TargetType << OvlExpr->getSourceRange();
12048   }
12049 
12050   bool IsStaticMemberFunctionFromBoundPointer() const {
12051     return StaticMemberFunctionFromBoundPointer;
12052   }
12053 
12054   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12055     S.Diag(OvlExpr->getBeginLoc(),
12056            diag::err_invalid_form_pointer_member_function)
12057         << OvlExpr->getSourceRange();
12058   }
12059 
12060   void ComplainOfInvalidConversion() const {
12061     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12062         << OvlExpr->getName() << TargetType;
12063   }
12064 
12065   void ComplainMultipleMatchesFound() const {
12066     assert(Matches.size() > 1);
12067     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12068         << OvlExpr->getName() << OvlExpr->getSourceRange();
12069     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12070                                 /*TakingAddress=*/true);
12071   }
12072 
12073   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12074 
12075   int getNumMatches() const { return Matches.size(); }
12076 
12077   FunctionDecl* getMatchingFunctionDecl() const {
12078     if (Matches.size() != 1) return nullptr;
12079     return Matches[0].second;
12080   }
12081 
12082   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12083     if (Matches.size() != 1) return nullptr;
12084     return &Matches[0].first;
12085   }
12086 };
12087 }
12088 
12089 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12090 /// an overloaded function (C++ [over.over]), where @p From is an
12091 /// expression with overloaded function type and @p ToType is the type
12092 /// we're trying to resolve to. For example:
12093 ///
12094 /// @code
12095 /// int f(double);
12096 /// int f(int);
12097 ///
12098 /// int (*pfd)(double) = f; // selects f(double)
12099 /// @endcode
12100 ///
12101 /// This routine returns the resulting FunctionDecl if it could be
12102 /// resolved, and NULL otherwise. When @p Complain is true, this
12103 /// routine will emit diagnostics if there is an error.
12104 FunctionDecl *
12105 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12106                                          QualType TargetType,
12107                                          bool Complain,
12108                                          DeclAccessPair &FoundResult,
12109                                          bool *pHadMultipleCandidates) {
12110   assert(AddressOfExpr->getType() == Context.OverloadTy);
12111 
12112   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12113                                      Complain);
12114   int NumMatches = Resolver.getNumMatches();
12115   FunctionDecl *Fn = nullptr;
12116   bool ShouldComplain = Complain && !Resolver.hasComplained();
12117   if (NumMatches == 0 && ShouldComplain) {
12118     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12119       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12120     else
12121       Resolver.ComplainNoMatchesFound();
12122   }
12123   else if (NumMatches > 1 && ShouldComplain)
12124     Resolver.ComplainMultipleMatchesFound();
12125   else if (NumMatches == 1) {
12126     Fn = Resolver.getMatchingFunctionDecl();
12127     assert(Fn);
12128     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12129       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12130     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12131     if (Complain) {
12132       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12133         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12134       else
12135         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12136     }
12137   }
12138 
12139   if (pHadMultipleCandidates)
12140     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12141   return Fn;
12142 }
12143 
12144 /// Given an expression that refers to an overloaded function, try to
12145 /// resolve that function to a single function that can have its address taken.
12146 /// This will modify `Pair` iff it returns non-null.
12147 ///
12148 /// This routine can only succeed if from all of the candidates in the overload
12149 /// set for SrcExpr that can have their addresses taken, there is one candidate
12150 /// that is more constrained than the rest.
12151 FunctionDecl *
12152 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12153   OverloadExpr::FindResult R = OverloadExpr::find(E);
12154   OverloadExpr *Ovl = R.Expression;
12155   bool IsResultAmbiguous = false;
12156   FunctionDecl *Result = nullptr;
12157   DeclAccessPair DAP;
12158   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12159 
12160   auto CheckMoreConstrained =
12161       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12162         SmallVector<const Expr *, 1> AC1, AC2;
12163         FD1->getAssociatedConstraints(AC1);
12164         FD2->getAssociatedConstraints(AC2);
12165         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12166         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12167           return None;
12168         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12169           return None;
12170         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12171           return None;
12172         return AtLeastAsConstrained1;
12173       };
12174 
12175   // Don't use the AddressOfResolver because we're specifically looking for
12176   // cases where we have one overload candidate that lacks
12177   // enable_if/pass_object_size/...
12178   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12179     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12180     if (!FD)
12181       return nullptr;
12182 
12183     if (!checkAddressOfFunctionIsAvailable(FD))
12184       continue;
12185 
12186     // We have more than one result - see if it is more constrained than the
12187     // previous one.
12188     if (Result) {
12189       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12190                                                                         Result);
12191       if (!MoreConstrainedThanPrevious) {
12192         IsResultAmbiguous = true;
12193         AmbiguousDecls.push_back(FD);
12194         continue;
12195       }
12196       if (!*MoreConstrainedThanPrevious)
12197         continue;
12198       // FD is more constrained - replace Result with it.
12199     }
12200     IsResultAmbiguous = false;
12201     DAP = I.getPair();
12202     Result = FD;
12203   }
12204 
12205   if (IsResultAmbiguous)
12206     return nullptr;
12207 
12208   if (Result) {
12209     SmallVector<const Expr *, 1> ResultAC;
12210     // We skipped over some ambiguous declarations which might be ambiguous with
12211     // the selected result.
12212     for (FunctionDecl *Skipped : AmbiguousDecls)
12213       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12214         return nullptr;
12215     Pair = DAP;
12216   }
12217   return Result;
12218 }
12219 
12220 /// Given an overloaded function, tries to turn it into a non-overloaded
12221 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12222 /// will perform access checks, diagnose the use of the resultant decl, and, if
12223 /// requested, potentially perform a function-to-pointer decay.
12224 ///
12225 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12226 /// Otherwise, returns true. This may emit diagnostics and return true.
12227 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12228     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12229   Expr *E = SrcExpr.get();
12230   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12231 
12232   DeclAccessPair DAP;
12233   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12234   if (!Found || Found->isCPUDispatchMultiVersion() ||
12235       Found->isCPUSpecificMultiVersion())
12236     return false;
12237 
12238   // Emitting multiple diagnostics for a function that is both inaccessible and
12239   // unavailable is consistent with our behavior elsewhere. So, always check
12240   // for both.
12241   DiagnoseUseOfDecl(Found, E->getExprLoc());
12242   CheckAddressOfMemberAccess(E, DAP);
12243   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12244   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12245     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12246   else
12247     SrcExpr = Fixed;
12248   return true;
12249 }
12250 
12251 /// Given an expression that refers to an overloaded function, try to
12252 /// resolve that overloaded function expression down to a single function.
12253 ///
12254 /// This routine can only resolve template-ids that refer to a single function
12255 /// template, where that template-id refers to a single template whose template
12256 /// arguments are either provided by the template-id or have defaults,
12257 /// as described in C++0x [temp.arg.explicit]p3.
12258 ///
12259 /// If no template-ids are found, no diagnostics are emitted and NULL is
12260 /// returned.
12261 FunctionDecl *
12262 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12263                                                   bool Complain,
12264                                                   DeclAccessPair *FoundResult) {
12265   // C++ [over.over]p1:
12266   //   [...] [Note: any redundant set of parentheses surrounding the
12267   //   overloaded function name is ignored (5.1). ]
12268   // C++ [over.over]p1:
12269   //   [...] The overloaded function name can be preceded by the &
12270   //   operator.
12271 
12272   // If we didn't actually find any template-ids, we're done.
12273   if (!ovl->hasExplicitTemplateArgs())
12274     return nullptr;
12275 
12276   TemplateArgumentListInfo ExplicitTemplateArgs;
12277   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12278   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12279 
12280   // Look through all of the overloaded functions, searching for one
12281   // whose type matches exactly.
12282   FunctionDecl *Matched = nullptr;
12283   for (UnresolvedSetIterator I = ovl->decls_begin(),
12284          E = ovl->decls_end(); I != E; ++I) {
12285     // C++0x [temp.arg.explicit]p3:
12286     //   [...] In contexts where deduction is done and fails, or in contexts
12287     //   where deduction is not done, if a template argument list is
12288     //   specified and it, along with any default template arguments,
12289     //   identifies a single function template specialization, then the
12290     //   template-id is an lvalue for the function template specialization.
12291     FunctionTemplateDecl *FunctionTemplate
12292       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12293 
12294     // C++ [over.over]p2:
12295     //   If the name is a function template, template argument deduction is
12296     //   done (14.8.2.2), and if the argument deduction succeeds, the
12297     //   resulting template argument list is used to generate a single
12298     //   function template specialization, which is added to the set of
12299     //   overloaded functions considered.
12300     FunctionDecl *Specialization = nullptr;
12301     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12302     if (TemplateDeductionResult Result
12303           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12304                                     Specialization, Info,
12305                                     /*IsAddressOfFunction*/true)) {
12306       // Make a note of the failed deduction for diagnostics.
12307       // TODO: Actually use the failed-deduction info?
12308       FailedCandidates.addCandidate()
12309           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12310                MakeDeductionFailureInfo(Context, Result, Info));
12311       continue;
12312     }
12313 
12314     assert(Specialization && "no specialization and no error?");
12315 
12316     // Multiple matches; we can't resolve to a single declaration.
12317     if (Matched) {
12318       if (Complain) {
12319         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12320           << ovl->getName();
12321         NoteAllOverloadCandidates(ovl);
12322       }
12323       return nullptr;
12324     }
12325 
12326     Matched = Specialization;
12327     if (FoundResult) *FoundResult = I.getPair();
12328   }
12329 
12330   if (Matched &&
12331       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12332     return nullptr;
12333 
12334   return Matched;
12335 }
12336 
12337 // Resolve and fix an overloaded expression that can be resolved
12338 // because it identifies a single function template specialization.
12339 //
12340 // Last three arguments should only be supplied if Complain = true
12341 //
12342 // Return true if it was logically possible to so resolve the
12343 // expression, regardless of whether or not it succeeded.  Always
12344 // returns true if 'complain' is set.
12345 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12346                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12347                       bool complain, SourceRange OpRangeForComplaining,
12348                                            QualType DestTypeForComplaining,
12349                                             unsigned DiagIDForComplaining) {
12350   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12351 
12352   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12353 
12354   DeclAccessPair found;
12355   ExprResult SingleFunctionExpression;
12356   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12357                            ovl.Expression, /*complain*/ false, &found)) {
12358     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12359       SrcExpr = ExprError();
12360       return true;
12361     }
12362 
12363     // It is only correct to resolve to an instance method if we're
12364     // resolving a form that's permitted to be a pointer to member.
12365     // Otherwise we'll end up making a bound member expression, which
12366     // is illegal in all the contexts we resolve like this.
12367     if (!ovl.HasFormOfMemberPointer &&
12368         isa<CXXMethodDecl>(fn) &&
12369         cast<CXXMethodDecl>(fn)->isInstance()) {
12370       if (!complain) return false;
12371 
12372       Diag(ovl.Expression->getExprLoc(),
12373            diag::err_bound_member_function)
12374         << 0 << ovl.Expression->getSourceRange();
12375 
12376       // TODO: I believe we only end up here if there's a mix of
12377       // static and non-static candidates (otherwise the expression
12378       // would have 'bound member' type, not 'overload' type).
12379       // Ideally we would note which candidate was chosen and why
12380       // the static candidates were rejected.
12381       SrcExpr = ExprError();
12382       return true;
12383     }
12384 
12385     // Fix the expression to refer to 'fn'.
12386     SingleFunctionExpression =
12387         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12388 
12389     // If desired, do function-to-pointer decay.
12390     if (doFunctionPointerConverion) {
12391       SingleFunctionExpression =
12392         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12393       if (SingleFunctionExpression.isInvalid()) {
12394         SrcExpr = ExprError();
12395         return true;
12396       }
12397     }
12398   }
12399 
12400   if (!SingleFunctionExpression.isUsable()) {
12401     if (complain) {
12402       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12403         << ovl.Expression->getName()
12404         << DestTypeForComplaining
12405         << OpRangeForComplaining
12406         << ovl.Expression->getQualifierLoc().getSourceRange();
12407       NoteAllOverloadCandidates(SrcExpr.get());
12408 
12409       SrcExpr = ExprError();
12410       return true;
12411     }
12412 
12413     return false;
12414   }
12415 
12416   SrcExpr = SingleFunctionExpression;
12417   return true;
12418 }
12419 
12420 /// Add a single candidate to the overload set.
12421 static void AddOverloadedCallCandidate(Sema &S,
12422                                        DeclAccessPair FoundDecl,
12423                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12424                                        ArrayRef<Expr *> Args,
12425                                        OverloadCandidateSet &CandidateSet,
12426                                        bool PartialOverloading,
12427                                        bool KnownValid) {
12428   NamedDecl *Callee = FoundDecl.getDecl();
12429   if (isa<UsingShadowDecl>(Callee))
12430     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12431 
12432   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12433     if (ExplicitTemplateArgs) {
12434       assert(!KnownValid && "Explicit template arguments?");
12435       return;
12436     }
12437     // Prevent ill-formed function decls to be added as overload candidates.
12438     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12439       return;
12440 
12441     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12442                            /*SuppressUserConversions=*/false,
12443                            PartialOverloading);
12444     return;
12445   }
12446 
12447   if (FunctionTemplateDecl *FuncTemplate
12448       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12449     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12450                                    ExplicitTemplateArgs, Args, CandidateSet,
12451                                    /*SuppressUserConversions=*/false,
12452                                    PartialOverloading);
12453     return;
12454   }
12455 
12456   assert(!KnownValid && "unhandled case in overloaded call candidate");
12457 }
12458 
12459 /// Add the overload candidates named by callee and/or found by argument
12460 /// dependent lookup to the given overload set.
12461 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12462                                        ArrayRef<Expr *> Args,
12463                                        OverloadCandidateSet &CandidateSet,
12464                                        bool PartialOverloading) {
12465 
12466 #ifndef NDEBUG
12467   // Verify that ArgumentDependentLookup is consistent with the rules
12468   // in C++0x [basic.lookup.argdep]p3:
12469   //
12470   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12471   //   and let Y be the lookup set produced by argument dependent
12472   //   lookup (defined as follows). If X contains
12473   //
12474   //     -- a declaration of a class member, or
12475   //
12476   //     -- a block-scope function declaration that is not a
12477   //        using-declaration, or
12478   //
12479   //     -- a declaration that is neither a function or a function
12480   //        template
12481   //
12482   //   then Y is empty.
12483 
12484   if (ULE->requiresADL()) {
12485     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12486            E = ULE->decls_end(); I != E; ++I) {
12487       assert(!(*I)->getDeclContext()->isRecord());
12488       assert(isa<UsingShadowDecl>(*I) ||
12489              !(*I)->getDeclContext()->isFunctionOrMethod());
12490       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12491     }
12492   }
12493 #endif
12494 
12495   // It would be nice to avoid this copy.
12496   TemplateArgumentListInfo TABuffer;
12497   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12498   if (ULE->hasExplicitTemplateArgs()) {
12499     ULE->copyTemplateArgumentsInto(TABuffer);
12500     ExplicitTemplateArgs = &TABuffer;
12501   }
12502 
12503   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12504          E = ULE->decls_end(); I != E; ++I)
12505     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12506                                CandidateSet, PartialOverloading,
12507                                /*KnownValid*/ true);
12508 
12509   if (ULE->requiresADL())
12510     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12511                                          Args, ExplicitTemplateArgs,
12512                                          CandidateSet, PartialOverloading);
12513 }
12514 
12515 /// Determine whether a declaration with the specified name could be moved into
12516 /// a different namespace.
12517 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12518   switch (Name.getCXXOverloadedOperator()) {
12519   case OO_New: case OO_Array_New:
12520   case OO_Delete: case OO_Array_Delete:
12521     return false;
12522 
12523   default:
12524     return true;
12525   }
12526 }
12527 
12528 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12529 /// template, where the non-dependent name was declared after the template
12530 /// was defined. This is common in code written for a compilers which do not
12531 /// correctly implement two-stage name lookup.
12532 ///
12533 /// Returns true if a viable candidate was found and a diagnostic was issued.
12534 static bool
12535 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12536                        const CXXScopeSpec &SS, LookupResult &R,
12537                        OverloadCandidateSet::CandidateSetKind CSK,
12538                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12539                        ArrayRef<Expr *> Args,
12540                        bool *DoDiagnoseEmptyLookup = nullptr) {
12541   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12542     return false;
12543 
12544   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12545     if (DC->isTransparentContext())
12546       continue;
12547 
12548     SemaRef.LookupQualifiedName(R, DC);
12549 
12550     if (!R.empty()) {
12551       R.suppressDiagnostics();
12552 
12553       if (isa<CXXRecordDecl>(DC)) {
12554         // Don't diagnose names we find in classes; we get much better
12555         // diagnostics for these from DiagnoseEmptyLookup.
12556         R.clear();
12557         if (DoDiagnoseEmptyLookup)
12558           *DoDiagnoseEmptyLookup = true;
12559         return false;
12560       }
12561 
12562       OverloadCandidateSet Candidates(FnLoc, CSK);
12563       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12564         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12565                                    ExplicitTemplateArgs, Args,
12566                                    Candidates, false, /*KnownValid*/ false);
12567 
12568       OverloadCandidateSet::iterator Best;
12569       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12570         // No viable functions. Don't bother the user with notes for functions
12571         // which don't work and shouldn't be found anyway.
12572         R.clear();
12573         return false;
12574       }
12575 
12576       // Find the namespaces where ADL would have looked, and suggest
12577       // declaring the function there instead.
12578       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12579       Sema::AssociatedClassSet AssociatedClasses;
12580       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12581                                                  AssociatedNamespaces,
12582                                                  AssociatedClasses);
12583       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12584       if (canBeDeclaredInNamespace(R.getLookupName())) {
12585         DeclContext *Std = SemaRef.getStdNamespace();
12586         for (Sema::AssociatedNamespaceSet::iterator
12587                it = AssociatedNamespaces.begin(),
12588                end = AssociatedNamespaces.end(); it != end; ++it) {
12589           // Never suggest declaring a function within namespace 'std'.
12590           if (Std && Std->Encloses(*it))
12591             continue;
12592 
12593           // Never suggest declaring a function within a namespace with a
12594           // reserved name, like __gnu_cxx.
12595           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12596           if (NS &&
12597               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12598             continue;
12599 
12600           SuggestedNamespaces.insert(*it);
12601         }
12602       }
12603 
12604       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12605         << R.getLookupName();
12606       if (SuggestedNamespaces.empty()) {
12607         SemaRef.Diag(Best->Function->getLocation(),
12608                      diag::note_not_found_by_two_phase_lookup)
12609           << R.getLookupName() << 0;
12610       } else if (SuggestedNamespaces.size() == 1) {
12611         SemaRef.Diag(Best->Function->getLocation(),
12612                      diag::note_not_found_by_two_phase_lookup)
12613           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12614       } else {
12615         // FIXME: It would be useful to list the associated namespaces here,
12616         // but the diagnostics infrastructure doesn't provide a way to produce
12617         // a localized representation of a list of items.
12618         SemaRef.Diag(Best->Function->getLocation(),
12619                      diag::note_not_found_by_two_phase_lookup)
12620           << R.getLookupName() << 2;
12621       }
12622 
12623       // Try to recover by calling this function.
12624       return true;
12625     }
12626 
12627     R.clear();
12628   }
12629 
12630   return false;
12631 }
12632 
12633 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12634 /// template, where the non-dependent operator was declared after the template
12635 /// was defined.
12636 ///
12637 /// Returns true if a viable candidate was found and a diagnostic was issued.
12638 static bool
12639 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12640                                SourceLocation OpLoc,
12641                                ArrayRef<Expr *> Args) {
12642   DeclarationName OpName =
12643     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12644   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12645   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12646                                 OverloadCandidateSet::CSK_Operator,
12647                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12648 }
12649 
12650 namespace {
12651 class BuildRecoveryCallExprRAII {
12652   Sema &SemaRef;
12653 public:
12654   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12655     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12656     SemaRef.IsBuildingRecoveryCallExpr = true;
12657   }
12658 
12659   ~BuildRecoveryCallExprRAII() {
12660     SemaRef.IsBuildingRecoveryCallExpr = false;
12661   }
12662 };
12663 
12664 }
12665 
12666 /// Attempts to recover from a call where no functions were found.
12667 ///
12668 /// Returns true if new candidates were found.
12669 static ExprResult
12670 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12671                       UnresolvedLookupExpr *ULE,
12672                       SourceLocation LParenLoc,
12673                       MutableArrayRef<Expr *> Args,
12674                       SourceLocation RParenLoc,
12675                       bool EmptyLookup, bool AllowTypoCorrection) {
12676   // Do not try to recover if it is already building a recovery call.
12677   // This stops infinite loops for template instantiations like
12678   //
12679   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12680   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12681   //
12682   if (SemaRef.IsBuildingRecoveryCallExpr)
12683     return ExprError();
12684   BuildRecoveryCallExprRAII RCE(SemaRef);
12685 
12686   CXXScopeSpec SS;
12687   SS.Adopt(ULE->getQualifierLoc());
12688   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12689 
12690   TemplateArgumentListInfo TABuffer;
12691   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12692   if (ULE->hasExplicitTemplateArgs()) {
12693     ULE->copyTemplateArgumentsInto(TABuffer);
12694     ExplicitTemplateArgs = &TABuffer;
12695   }
12696 
12697   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12698                  Sema::LookupOrdinaryName);
12699   bool DoDiagnoseEmptyLookup = EmptyLookup;
12700   if (!DiagnoseTwoPhaseLookup(
12701           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12702           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12703     NoTypoCorrectionCCC NoTypoValidator{};
12704     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12705                                                 ExplicitTemplateArgs != nullptr,
12706                                                 dyn_cast<MemberExpr>(Fn));
12707     CorrectionCandidateCallback &Validator =
12708         AllowTypoCorrection
12709             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12710             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12711     if (!DoDiagnoseEmptyLookup ||
12712         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12713                                     Args))
12714       return ExprError();
12715   }
12716 
12717   assert(!R.empty() && "lookup results empty despite recovery");
12718 
12719   // If recovery created an ambiguity, just bail out.
12720   if (R.isAmbiguous()) {
12721     R.suppressDiagnostics();
12722     return ExprError();
12723   }
12724 
12725   // Build an implicit member call if appropriate.  Just drop the
12726   // casts and such from the call, we don't really care.
12727   ExprResult NewFn = ExprError();
12728   if ((*R.begin())->isCXXClassMember())
12729     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12730                                                     ExplicitTemplateArgs, S);
12731   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12732     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12733                                         ExplicitTemplateArgs);
12734   else
12735     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12736 
12737   if (NewFn.isInvalid())
12738     return ExprError();
12739 
12740   // This shouldn't cause an infinite loop because we're giving it
12741   // an expression with viable lookup results, which should never
12742   // end up here.
12743   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12744                                MultiExprArg(Args.data(), Args.size()),
12745                                RParenLoc);
12746 }
12747 
12748 /// Constructs and populates an OverloadedCandidateSet from
12749 /// the given function.
12750 /// \returns true when an the ExprResult output parameter has been set.
12751 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12752                                   UnresolvedLookupExpr *ULE,
12753                                   MultiExprArg Args,
12754                                   SourceLocation RParenLoc,
12755                                   OverloadCandidateSet *CandidateSet,
12756                                   ExprResult *Result) {
12757 #ifndef NDEBUG
12758   if (ULE->requiresADL()) {
12759     // To do ADL, we must have found an unqualified name.
12760     assert(!ULE->getQualifier() && "qualified name with ADL");
12761 
12762     // We don't perform ADL for implicit declarations of builtins.
12763     // Verify that this was correctly set up.
12764     FunctionDecl *F;
12765     if (ULE->decls_begin() != ULE->decls_end() &&
12766         ULE->decls_begin() + 1 == ULE->decls_end() &&
12767         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12768         F->getBuiltinID() && F->isImplicit())
12769       llvm_unreachable("performing ADL for builtin");
12770 
12771     // We don't perform ADL in C.
12772     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12773   }
12774 #endif
12775 
12776   UnbridgedCastsSet UnbridgedCasts;
12777   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12778     *Result = ExprError();
12779     return true;
12780   }
12781 
12782   // Add the functions denoted by the callee to the set of candidate
12783   // functions, including those from argument-dependent lookup.
12784   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12785 
12786   if (getLangOpts().MSVCCompat &&
12787       CurContext->isDependentContext() && !isSFINAEContext() &&
12788       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12789 
12790     OverloadCandidateSet::iterator Best;
12791     if (CandidateSet->empty() ||
12792         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12793             OR_No_Viable_Function) {
12794       // In Microsoft mode, if we are inside a template class member function
12795       // then create a type dependent CallExpr. The goal is to postpone name
12796       // lookup to instantiation time to be able to search into type dependent
12797       // base classes.
12798       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12799                                       VK_RValue, RParenLoc);
12800       CE->markDependentForPostponedNameLookup();
12801       *Result = CE;
12802       return true;
12803     }
12804   }
12805 
12806   if (CandidateSet->empty())
12807     return false;
12808 
12809   UnbridgedCasts.restore();
12810   return false;
12811 }
12812 
12813 // Guess at what the return type for an unresolvable overload should be.
12814 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12815                                    OverloadCandidateSet::iterator *Best) {
12816   llvm::Optional<QualType> Result;
12817   // Adjust Type after seeing a candidate.
12818   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12819     if (!Candidate.Function)
12820       return;
12821     QualType T = Candidate.Function->getReturnType();
12822     if (T.isNull())
12823       return;
12824     if (!Result)
12825       Result = T;
12826     else if (Result != T)
12827       Result = QualType();
12828   };
12829 
12830   // Look for an unambiguous type from a progressively larger subset.
12831   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12832   //
12833   // First, consider only the best candidate.
12834   if (Best && *Best != CS.end())
12835     ConsiderCandidate(**Best);
12836   // Next, consider only viable candidates.
12837   if (!Result)
12838     for (const auto &C : CS)
12839       if (C.Viable)
12840         ConsiderCandidate(C);
12841   // Finally, consider all candidates.
12842   if (!Result)
12843     for (const auto &C : CS)
12844       ConsiderCandidate(C);
12845 
12846   return Result.getValueOr(QualType());
12847 }
12848 
12849 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12850 /// the completed call expression. If overload resolution fails, emits
12851 /// diagnostics and returns ExprError()
12852 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12853                                            UnresolvedLookupExpr *ULE,
12854                                            SourceLocation LParenLoc,
12855                                            MultiExprArg Args,
12856                                            SourceLocation RParenLoc,
12857                                            Expr *ExecConfig,
12858                                            OverloadCandidateSet *CandidateSet,
12859                                            OverloadCandidateSet::iterator *Best,
12860                                            OverloadingResult OverloadResult,
12861                                            bool AllowTypoCorrection) {
12862   if (CandidateSet->empty())
12863     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12864                                  RParenLoc, /*EmptyLookup=*/true,
12865                                  AllowTypoCorrection);
12866 
12867   switch (OverloadResult) {
12868   case OR_Success: {
12869     FunctionDecl *FDecl = (*Best)->Function;
12870     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12871     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12872       return ExprError();
12873     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12874     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12875                                          ExecConfig, /*IsExecConfig=*/false,
12876                                          (*Best)->IsADLCandidate);
12877   }
12878 
12879   case OR_No_Viable_Function: {
12880     // Try to recover by looking for viable functions which the user might
12881     // have meant to call.
12882     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12883                                                 Args, RParenLoc,
12884                                                 /*EmptyLookup=*/false,
12885                                                 AllowTypoCorrection);
12886     if (!Recovery.isInvalid())
12887       return Recovery;
12888 
12889     // If the user passes in a function that we can't take the address of, we
12890     // generally end up emitting really bad error messages. Here, we attempt to
12891     // emit better ones.
12892     for (const Expr *Arg : Args) {
12893       if (!Arg->getType()->isFunctionType())
12894         continue;
12895       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12896         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12897         if (FD &&
12898             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12899                                                        Arg->getExprLoc()))
12900           return ExprError();
12901       }
12902     }
12903 
12904     CandidateSet->NoteCandidates(
12905         PartialDiagnosticAt(
12906             Fn->getBeginLoc(),
12907             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12908                 << ULE->getName() << Fn->getSourceRange()),
12909         SemaRef, OCD_AllCandidates, Args);
12910     break;
12911   }
12912 
12913   case OR_Ambiguous:
12914     CandidateSet->NoteCandidates(
12915         PartialDiagnosticAt(Fn->getBeginLoc(),
12916                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12917                                 << ULE->getName() << Fn->getSourceRange()),
12918         SemaRef, OCD_AmbiguousCandidates, Args);
12919     break;
12920 
12921   case OR_Deleted: {
12922     CandidateSet->NoteCandidates(
12923         PartialDiagnosticAt(Fn->getBeginLoc(),
12924                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12925                                 << ULE->getName() << Fn->getSourceRange()),
12926         SemaRef, OCD_AllCandidates, Args);
12927 
12928     // We emitted an error for the unavailable/deleted function call but keep
12929     // the call in the AST.
12930     FunctionDecl *FDecl = (*Best)->Function;
12931     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12932     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12933                                          ExecConfig, /*IsExecConfig=*/false,
12934                                          (*Best)->IsADLCandidate);
12935   }
12936   }
12937 
12938   // Overload resolution failed, try to recover.
12939   SmallVector<Expr *, 8> SubExprs = {Fn};
12940   SubExprs.append(Args.begin(), Args.end());
12941   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12942                                     chooseRecoveryType(*CandidateSet, Best));
12943 }
12944 
12945 static void markUnaddressableCandidatesUnviable(Sema &S,
12946                                                 OverloadCandidateSet &CS) {
12947   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12948     if (I->Viable &&
12949         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12950       I->Viable = false;
12951       I->FailureKind = ovl_fail_addr_not_available;
12952     }
12953   }
12954 }
12955 
12956 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12957 /// (which eventually refers to the declaration Func) and the call
12958 /// arguments Args/NumArgs, attempt to resolve the function call down
12959 /// to a specific function. If overload resolution succeeds, returns
12960 /// the call expression produced by overload resolution.
12961 /// Otherwise, emits diagnostics and returns ExprError.
12962 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12963                                          UnresolvedLookupExpr *ULE,
12964                                          SourceLocation LParenLoc,
12965                                          MultiExprArg Args,
12966                                          SourceLocation RParenLoc,
12967                                          Expr *ExecConfig,
12968                                          bool AllowTypoCorrection,
12969                                          bool CalleesAddressIsTaken) {
12970   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12971                                     OverloadCandidateSet::CSK_Normal);
12972   ExprResult result;
12973 
12974   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12975                              &result))
12976     return result;
12977 
12978   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12979   // functions that aren't addressible are considered unviable.
12980   if (CalleesAddressIsTaken)
12981     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12982 
12983   OverloadCandidateSet::iterator Best;
12984   OverloadingResult OverloadResult =
12985       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12986 
12987   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12988                                   ExecConfig, &CandidateSet, &Best,
12989                                   OverloadResult, AllowTypoCorrection);
12990 }
12991 
12992 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12993   return Functions.size() > 1 ||
12994     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12995 }
12996 
12997 /// Create a unary operation that may resolve to an overloaded
12998 /// operator.
12999 ///
13000 /// \param OpLoc The location of the operator itself (e.g., '*').
13001 ///
13002 /// \param Opc The UnaryOperatorKind that describes this operator.
13003 ///
13004 /// \param Fns The set of non-member functions that will be
13005 /// considered by overload resolution. The caller needs to build this
13006 /// set based on the context using, e.g.,
13007 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13008 /// set should not contain any member functions; those will be added
13009 /// by CreateOverloadedUnaryOp().
13010 ///
13011 /// \param Input The input argument.
13012 ExprResult
13013 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
13014                               const UnresolvedSetImpl &Fns,
13015                               Expr *Input, bool PerformADL) {
13016   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
13017   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
13018   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13019   // TODO: provide better source location info.
13020   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13021 
13022   if (checkPlaceholderForOverload(*this, Input))
13023     return ExprError();
13024 
13025   Expr *Args[2] = { Input, nullptr };
13026   unsigned NumArgs = 1;
13027 
13028   // For post-increment and post-decrement, add the implicit '0' as
13029   // the second argument, so that we know this is a post-increment or
13030   // post-decrement.
13031   if (Opc == UO_PostInc || Opc == UO_PostDec) {
13032     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13033     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13034                                      SourceLocation());
13035     NumArgs = 2;
13036   }
13037 
13038   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13039 
13040   if (Input->isTypeDependent()) {
13041     if (Fns.empty())
13042       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13043                                    VK_RValue, OK_Ordinary, OpLoc, false,
13044                                    CurFPFeatureOverrides());
13045 
13046     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13047     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13048         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13049         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
13050     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
13051                                        Context.DependentTy, VK_RValue, OpLoc,
13052                                        CurFPFeatureOverrides());
13053   }
13054 
13055   // Build an empty overload set.
13056   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13057 
13058   // Add the candidates from the given function set.
13059   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13060 
13061   // Add operator candidates that are member functions.
13062   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13063 
13064   // Add candidates from ADL.
13065   if (PerformADL) {
13066     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13067                                          /*ExplicitTemplateArgs*/nullptr,
13068                                          CandidateSet);
13069   }
13070 
13071   // Add builtin operator candidates.
13072   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13073 
13074   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13075 
13076   // Perform overload resolution.
13077   OverloadCandidateSet::iterator Best;
13078   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13079   case OR_Success: {
13080     // We found a built-in operator or an overloaded operator.
13081     FunctionDecl *FnDecl = Best->Function;
13082 
13083     if (FnDecl) {
13084       Expr *Base = nullptr;
13085       // We matched an overloaded operator. Build a call to that
13086       // operator.
13087 
13088       // Convert the arguments.
13089       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13090         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13091 
13092         ExprResult InputRes =
13093           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13094                                               Best->FoundDecl, Method);
13095         if (InputRes.isInvalid())
13096           return ExprError();
13097         Base = Input = InputRes.get();
13098       } else {
13099         // Convert the arguments.
13100         ExprResult InputInit
13101           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13102                                                       Context,
13103                                                       FnDecl->getParamDecl(0)),
13104                                       SourceLocation(),
13105                                       Input);
13106         if (InputInit.isInvalid())
13107           return ExprError();
13108         Input = InputInit.get();
13109       }
13110 
13111       // Build the actual expression node.
13112       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13113                                                 Base, HadMultipleCandidates,
13114                                                 OpLoc);
13115       if (FnExpr.isInvalid())
13116         return ExprError();
13117 
13118       // Determine the result type.
13119       QualType ResultTy = FnDecl->getReturnType();
13120       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13121       ResultTy = ResultTy.getNonLValueExprType(Context);
13122 
13123       Args[0] = Input;
13124       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13125           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13126           CurFPFeatureOverrides(), Best->IsADLCandidate);
13127 
13128       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13129         return ExprError();
13130 
13131       if (CheckFunctionCall(FnDecl, TheCall,
13132                             FnDecl->getType()->castAs<FunctionProtoType>()))
13133         return ExprError();
13134       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13135     } else {
13136       // We matched a built-in operator. Convert the arguments, then
13137       // break out so that we will build the appropriate built-in
13138       // operator node.
13139       ExprResult InputRes = PerformImplicitConversion(
13140           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13141           CCK_ForBuiltinOverloadedOp);
13142       if (InputRes.isInvalid())
13143         return ExprError();
13144       Input = InputRes.get();
13145       break;
13146     }
13147   }
13148 
13149   case OR_No_Viable_Function:
13150     // This is an erroneous use of an operator which can be overloaded by
13151     // a non-member function. Check for non-member operators which were
13152     // defined too late to be candidates.
13153     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13154       // FIXME: Recover by calling the found function.
13155       return ExprError();
13156 
13157     // No viable function; fall through to handling this as a
13158     // built-in operator, which will produce an error message for us.
13159     break;
13160 
13161   case OR_Ambiguous:
13162     CandidateSet.NoteCandidates(
13163         PartialDiagnosticAt(OpLoc,
13164                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13165                                 << UnaryOperator::getOpcodeStr(Opc)
13166                                 << Input->getType() << Input->getSourceRange()),
13167         *this, OCD_AmbiguousCandidates, ArgsArray,
13168         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13169     return ExprError();
13170 
13171   case OR_Deleted:
13172     CandidateSet.NoteCandidates(
13173         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13174                                        << UnaryOperator::getOpcodeStr(Opc)
13175                                        << Input->getSourceRange()),
13176         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13177         OpLoc);
13178     return ExprError();
13179   }
13180 
13181   // Either we found no viable overloaded operator or we matched a
13182   // built-in operator. In either case, fall through to trying to
13183   // build a built-in operation.
13184   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13185 }
13186 
13187 /// Perform lookup for an overloaded binary operator.
13188 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13189                                  OverloadedOperatorKind Op,
13190                                  const UnresolvedSetImpl &Fns,
13191                                  ArrayRef<Expr *> Args, bool PerformADL) {
13192   SourceLocation OpLoc = CandidateSet.getLocation();
13193 
13194   OverloadedOperatorKind ExtraOp =
13195       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13196           ? getRewrittenOverloadedOperator(Op)
13197           : OO_None;
13198 
13199   // Add the candidates from the given function set. This also adds the
13200   // rewritten candidates using these functions if necessary.
13201   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13202 
13203   // Add operator candidates that are member functions.
13204   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13205   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13206     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13207                                 OverloadCandidateParamOrder::Reversed);
13208 
13209   // In C++20, also add any rewritten member candidates.
13210   if (ExtraOp) {
13211     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13212     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13213       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13214                                   CandidateSet,
13215                                   OverloadCandidateParamOrder::Reversed);
13216   }
13217 
13218   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13219   // performed for an assignment operator (nor for operator[] nor operator->,
13220   // which don't get here).
13221   if (Op != OO_Equal && PerformADL) {
13222     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13223     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13224                                          /*ExplicitTemplateArgs*/ nullptr,
13225                                          CandidateSet);
13226     if (ExtraOp) {
13227       DeclarationName ExtraOpName =
13228           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13229       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13230                                            /*ExplicitTemplateArgs*/ nullptr,
13231                                            CandidateSet);
13232     }
13233   }
13234 
13235   // Add builtin operator candidates.
13236   //
13237   // FIXME: We don't add any rewritten candidates here. This is strictly
13238   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13239   // resulting in our selecting a rewritten builtin candidate. For example:
13240   //
13241   //   enum class E { e };
13242   //   bool operator!=(E, E) requires false;
13243   //   bool k = E::e != E::e;
13244   //
13245   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13246   // it seems unreasonable to consider rewritten builtin candidates. A core
13247   // issue has been filed proposing to removed this requirement.
13248   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13249 }
13250 
13251 /// Create a binary operation that may resolve to an overloaded
13252 /// operator.
13253 ///
13254 /// \param OpLoc The location of the operator itself (e.g., '+').
13255 ///
13256 /// \param Opc The BinaryOperatorKind that describes this operator.
13257 ///
13258 /// \param Fns The set of non-member functions that will be
13259 /// considered by overload resolution. The caller needs to build this
13260 /// set based on the context using, e.g.,
13261 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13262 /// set should not contain any member functions; those will be added
13263 /// by CreateOverloadedBinOp().
13264 ///
13265 /// \param LHS Left-hand argument.
13266 /// \param RHS Right-hand argument.
13267 /// \param PerformADL Whether to consider operator candidates found by ADL.
13268 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13269 ///        C++20 operator rewrites.
13270 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13271 ///        the function in question. Such a function is never a candidate in
13272 ///        our overload resolution. This also enables synthesizing a three-way
13273 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13274 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13275                                        BinaryOperatorKind Opc,
13276                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13277                                        Expr *RHS, bool PerformADL,
13278                                        bool AllowRewrittenCandidates,
13279                                        FunctionDecl *DefaultedFn) {
13280   Expr *Args[2] = { LHS, RHS };
13281   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13282 
13283   if (!getLangOpts().CPlusPlus20)
13284     AllowRewrittenCandidates = false;
13285 
13286   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13287 
13288   // If either side is type-dependent, create an appropriate dependent
13289   // expression.
13290   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13291     if (Fns.empty()) {
13292       // If there are no functions to store, just build a dependent
13293       // BinaryOperator or CompoundAssignment.
13294       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13295         return BinaryOperator::Create(
13296             Context, Args[0], Args[1], Opc, Context.DependentTy, VK_RValue,
13297             OK_Ordinary, OpLoc, CurFPFeatureOverrides());
13298       return CompoundAssignOperator::Create(
13299           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13300           OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
13301           Context.DependentTy);
13302     }
13303 
13304     // FIXME: save results of ADL from here?
13305     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13306     // TODO: provide better source location info in DNLoc component.
13307     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13308     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13309     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13310         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13311         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13312     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13313                                        Context.DependentTy, VK_RValue, OpLoc,
13314                                        CurFPFeatureOverrides());
13315   }
13316 
13317   // Always do placeholder-like conversions on the RHS.
13318   if (checkPlaceholderForOverload(*this, Args[1]))
13319     return ExprError();
13320 
13321   // Do placeholder-like conversion on the LHS; note that we should
13322   // not get here with a PseudoObject LHS.
13323   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13324   if (checkPlaceholderForOverload(*this, Args[0]))
13325     return ExprError();
13326 
13327   // If this is the assignment operator, we only perform overload resolution
13328   // if the left-hand side is a class or enumeration type. This is actually
13329   // a hack. The standard requires that we do overload resolution between the
13330   // various built-in candidates, but as DR507 points out, this can lead to
13331   // problems. So we do it this way, which pretty much follows what GCC does.
13332   // Note that we go the traditional code path for compound assignment forms.
13333   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13334     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13335 
13336   // If this is the .* operator, which is not overloadable, just
13337   // create a built-in binary operator.
13338   if (Opc == BO_PtrMemD)
13339     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13340 
13341   // Build the overload set.
13342   OverloadCandidateSet CandidateSet(
13343       OpLoc, OverloadCandidateSet::CSK_Operator,
13344       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13345   if (DefaultedFn)
13346     CandidateSet.exclude(DefaultedFn);
13347   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13348 
13349   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13350 
13351   // Perform overload resolution.
13352   OverloadCandidateSet::iterator Best;
13353   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13354     case OR_Success: {
13355       // We found a built-in operator or an overloaded operator.
13356       FunctionDecl *FnDecl = Best->Function;
13357 
13358       bool IsReversed = Best->isReversed();
13359       if (IsReversed)
13360         std::swap(Args[0], Args[1]);
13361 
13362       if (FnDecl) {
13363         Expr *Base = nullptr;
13364         // We matched an overloaded operator. Build a call to that
13365         // operator.
13366 
13367         OverloadedOperatorKind ChosenOp =
13368             FnDecl->getDeclName().getCXXOverloadedOperator();
13369 
13370         // C++2a [over.match.oper]p9:
13371         //   If a rewritten operator== candidate is selected by overload
13372         //   resolution for an operator@, its return type shall be cv bool
13373         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13374             !FnDecl->getReturnType()->isBooleanType()) {
13375           bool IsExtension =
13376               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13377           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13378                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13379               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13380               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13381           Diag(FnDecl->getLocation(), diag::note_declared_at);
13382           if (!IsExtension)
13383             return ExprError();
13384         }
13385 
13386         if (AllowRewrittenCandidates && !IsReversed &&
13387             CandidateSet.getRewriteInfo().isReversible()) {
13388           // We could have reversed this operator, but didn't. Check if some
13389           // reversed form was a viable candidate, and if so, if it had a
13390           // better conversion for either parameter. If so, this call is
13391           // formally ambiguous, and allowing it is an extension.
13392           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13393           for (OverloadCandidate &Cand : CandidateSet) {
13394             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13395                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13396               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13397                 if (CompareImplicitConversionSequences(
13398                         *this, OpLoc, Cand.Conversions[ArgIdx],
13399                         Best->Conversions[ArgIdx]) ==
13400                     ImplicitConversionSequence::Better) {
13401                   AmbiguousWith.push_back(Cand.Function);
13402                   break;
13403                 }
13404               }
13405             }
13406           }
13407 
13408           if (!AmbiguousWith.empty()) {
13409             bool AmbiguousWithSelf =
13410                 AmbiguousWith.size() == 1 &&
13411                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13412             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13413                 << BinaryOperator::getOpcodeStr(Opc)
13414                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13415                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13416             if (AmbiguousWithSelf) {
13417               Diag(FnDecl->getLocation(),
13418                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13419             } else {
13420               Diag(FnDecl->getLocation(),
13421                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13422               for (auto *F : AmbiguousWith)
13423                 Diag(F->getLocation(),
13424                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13425             }
13426           }
13427         }
13428 
13429         // Convert the arguments.
13430         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13431           // Best->Access is only meaningful for class members.
13432           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13433 
13434           ExprResult Arg1 =
13435             PerformCopyInitialization(
13436               InitializedEntity::InitializeParameter(Context,
13437                                                      FnDecl->getParamDecl(0)),
13438               SourceLocation(), Args[1]);
13439           if (Arg1.isInvalid())
13440             return ExprError();
13441 
13442           ExprResult Arg0 =
13443             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13444                                                 Best->FoundDecl, Method);
13445           if (Arg0.isInvalid())
13446             return ExprError();
13447           Base = Args[0] = Arg0.getAs<Expr>();
13448           Args[1] = RHS = Arg1.getAs<Expr>();
13449         } else {
13450           // Convert the arguments.
13451           ExprResult Arg0 = PerformCopyInitialization(
13452             InitializedEntity::InitializeParameter(Context,
13453                                                    FnDecl->getParamDecl(0)),
13454             SourceLocation(), Args[0]);
13455           if (Arg0.isInvalid())
13456             return ExprError();
13457 
13458           ExprResult Arg1 =
13459             PerformCopyInitialization(
13460               InitializedEntity::InitializeParameter(Context,
13461                                                      FnDecl->getParamDecl(1)),
13462               SourceLocation(), Args[1]);
13463           if (Arg1.isInvalid())
13464             return ExprError();
13465           Args[0] = LHS = Arg0.getAs<Expr>();
13466           Args[1] = RHS = Arg1.getAs<Expr>();
13467         }
13468 
13469         // Build the actual expression node.
13470         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13471                                                   Best->FoundDecl, Base,
13472                                                   HadMultipleCandidates, OpLoc);
13473         if (FnExpr.isInvalid())
13474           return ExprError();
13475 
13476         // Determine the result type.
13477         QualType ResultTy = FnDecl->getReturnType();
13478         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13479         ResultTy = ResultTy.getNonLValueExprType(Context);
13480 
13481         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13482             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13483             CurFPFeatureOverrides(), Best->IsADLCandidate);
13484 
13485         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13486                                 FnDecl))
13487           return ExprError();
13488 
13489         ArrayRef<const Expr *> ArgsArray(Args, 2);
13490         const Expr *ImplicitThis = nullptr;
13491         // Cut off the implicit 'this'.
13492         if (isa<CXXMethodDecl>(FnDecl)) {
13493           ImplicitThis = ArgsArray[0];
13494           ArgsArray = ArgsArray.slice(1);
13495         }
13496 
13497         // Check for a self move.
13498         if (Op == OO_Equal)
13499           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13500 
13501         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13502                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13503                   VariadicDoesNotApply);
13504 
13505         ExprResult R = MaybeBindToTemporary(TheCall);
13506         if (R.isInvalid())
13507           return ExprError();
13508 
13509         R = CheckForImmediateInvocation(R, FnDecl);
13510         if (R.isInvalid())
13511           return ExprError();
13512 
13513         // For a rewritten candidate, we've already reversed the arguments
13514         // if needed. Perform the rest of the rewrite now.
13515         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13516             (Op == OO_Spaceship && IsReversed)) {
13517           if (Op == OO_ExclaimEqual) {
13518             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13519             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13520           } else {
13521             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13522             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13523             Expr *ZeroLiteral =
13524                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13525 
13526             Sema::CodeSynthesisContext Ctx;
13527             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13528             Ctx.Entity = FnDecl;
13529             pushCodeSynthesisContext(Ctx);
13530 
13531             R = CreateOverloadedBinOp(
13532                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13533                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13534                 /*AllowRewrittenCandidates=*/false);
13535 
13536             popCodeSynthesisContext();
13537           }
13538           if (R.isInvalid())
13539             return ExprError();
13540         } else {
13541           assert(ChosenOp == Op && "unexpected operator name");
13542         }
13543 
13544         // Make a note in the AST if we did any rewriting.
13545         if (Best->RewriteKind != CRK_None)
13546           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13547 
13548         return R;
13549       } else {
13550         // We matched a built-in operator. Convert the arguments, then
13551         // break out so that we will build the appropriate built-in
13552         // operator node.
13553         ExprResult ArgsRes0 = PerformImplicitConversion(
13554             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13555             AA_Passing, CCK_ForBuiltinOverloadedOp);
13556         if (ArgsRes0.isInvalid())
13557           return ExprError();
13558         Args[0] = ArgsRes0.get();
13559 
13560         ExprResult ArgsRes1 = PerformImplicitConversion(
13561             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13562             AA_Passing, CCK_ForBuiltinOverloadedOp);
13563         if (ArgsRes1.isInvalid())
13564           return ExprError();
13565         Args[1] = ArgsRes1.get();
13566         break;
13567       }
13568     }
13569 
13570     case OR_No_Viable_Function: {
13571       // C++ [over.match.oper]p9:
13572       //   If the operator is the operator , [...] and there are no
13573       //   viable functions, then the operator is assumed to be the
13574       //   built-in operator and interpreted according to clause 5.
13575       if (Opc == BO_Comma)
13576         break;
13577 
13578       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13579       // compare result using '==' and '<'.
13580       if (DefaultedFn && Opc == BO_Cmp) {
13581         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13582                                                           Args[1], DefaultedFn);
13583         if (E.isInvalid() || E.isUsable())
13584           return E;
13585       }
13586 
13587       // For class as left operand for assignment or compound assignment
13588       // operator do not fall through to handling in built-in, but report that
13589       // no overloaded assignment operator found
13590       ExprResult Result = ExprError();
13591       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13592       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13593                                                    Args, OpLoc);
13594       if (Args[0]->getType()->isRecordType() &&
13595           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13596         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13597              << BinaryOperator::getOpcodeStr(Opc)
13598              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13599         if (Args[0]->getType()->isIncompleteType()) {
13600           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13601             << Args[0]->getType()
13602             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13603         }
13604       } else {
13605         // This is an erroneous use of an operator which can be overloaded by
13606         // a non-member function. Check for non-member operators which were
13607         // defined too late to be candidates.
13608         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13609           // FIXME: Recover by calling the found function.
13610           return ExprError();
13611 
13612         // No viable function; try to create a built-in operation, which will
13613         // produce an error. Then, show the non-viable candidates.
13614         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13615       }
13616       assert(Result.isInvalid() &&
13617              "C++ binary operator overloading is missing candidates!");
13618       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13619       return Result;
13620     }
13621 
13622     case OR_Ambiguous:
13623       CandidateSet.NoteCandidates(
13624           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13625                                          << BinaryOperator::getOpcodeStr(Opc)
13626                                          << Args[0]->getType()
13627                                          << Args[1]->getType()
13628                                          << Args[0]->getSourceRange()
13629                                          << Args[1]->getSourceRange()),
13630           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13631           OpLoc);
13632       return ExprError();
13633 
13634     case OR_Deleted:
13635       if (isImplicitlyDeleted(Best->Function)) {
13636         FunctionDecl *DeletedFD = Best->Function;
13637         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13638         if (DFK.isSpecialMember()) {
13639           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13640             << Args[0]->getType() << DFK.asSpecialMember();
13641         } else {
13642           assert(DFK.isComparison());
13643           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13644             << Args[0]->getType() << DeletedFD;
13645         }
13646 
13647         // The user probably meant to call this special member. Just
13648         // explain why it's deleted.
13649         NoteDeletedFunction(DeletedFD);
13650         return ExprError();
13651       }
13652       CandidateSet.NoteCandidates(
13653           PartialDiagnosticAt(
13654               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13655                          << getOperatorSpelling(Best->Function->getDeclName()
13656                                                     .getCXXOverloadedOperator())
13657                          << Args[0]->getSourceRange()
13658                          << Args[1]->getSourceRange()),
13659           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13660           OpLoc);
13661       return ExprError();
13662   }
13663 
13664   // We matched a built-in operator; build it.
13665   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13666 }
13667 
13668 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13669     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13670     FunctionDecl *DefaultedFn) {
13671   const ComparisonCategoryInfo *Info =
13672       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13673   // If we're not producing a known comparison category type, we can't
13674   // synthesize a three-way comparison. Let the caller diagnose this.
13675   if (!Info)
13676     return ExprResult((Expr*)nullptr);
13677 
13678   // If we ever want to perform this synthesis more generally, we will need to
13679   // apply the temporary materialization conversion to the operands.
13680   assert(LHS->isGLValue() && RHS->isGLValue() &&
13681          "cannot use prvalue expressions more than once");
13682   Expr *OrigLHS = LHS;
13683   Expr *OrigRHS = RHS;
13684 
13685   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13686   // each of them multiple times below.
13687   LHS = new (Context)
13688       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13689                       LHS->getObjectKind(), LHS);
13690   RHS = new (Context)
13691       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13692                       RHS->getObjectKind(), RHS);
13693 
13694   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13695                                         DefaultedFn);
13696   if (Eq.isInvalid())
13697     return ExprError();
13698 
13699   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13700                                           true, DefaultedFn);
13701   if (Less.isInvalid())
13702     return ExprError();
13703 
13704   ExprResult Greater;
13705   if (Info->isPartial()) {
13706     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13707                                     DefaultedFn);
13708     if (Greater.isInvalid())
13709       return ExprError();
13710   }
13711 
13712   // Form the list of comparisons we're going to perform.
13713   struct Comparison {
13714     ExprResult Cmp;
13715     ComparisonCategoryResult Result;
13716   } Comparisons[4] =
13717   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13718                           : ComparisonCategoryResult::Equivalent},
13719     {Less, ComparisonCategoryResult::Less},
13720     {Greater, ComparisonCategoryResult::Greater},
13721     {ExprResult(), ComparisonCategoryResult::Unordered},
13722   };
13723 
13724   int I = Info->isPartial() ? 3 : 2;
13725 
13726   // Combine the comparisons with suitable conditional expressions.
13727   ExprResult Result;
13728   for (; I >= 0; --I) {
13729     // Build a reference to the comparison category constant.
13730     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13731     // FIXME: Missing a constant for a comparison category. Diagnose this?
13732     if (!VI)
13733       return ExprResult((Expr*)nullptr);
13734     ExprResult ThisResult =
13735         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13736     if (ThisResult.isInvalid())
13737       return ExprError();
13738 
13739     // Build a conditional unless this is the final case.
13740     if (Result.get()) {
13741       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13742                                   ThisResult.get(), Result.get());
13743       if (Result.isInvalid())
13744         return ExprError();
13745     } else {
13746       Result = ThisResult;
13747     }
13748   }
13749 
13750   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13751   // bind the OpaqueValueExprs before they're (repeatedly) used.
13752   Expr *SyntacticForm = BinaryOperator::Create(
13753       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13754       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13755       CurFPFeatureOverrides());
13756   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13757   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13758 }
13759 
13760 ExprResult
13761 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13762                                          SourceLocation RLoc,
13763                                          Expr *Base, Expr *Idx) {
13764   Expr *Args[2] = { Base, Idx };
13765   DeclarationName OpName =
13766       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13767 
13768   // If either side is type-dependent, create an appropriate dependent
13769   // expression.
13770   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13771 
13772     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13773     // CHECKME: no 'operator' keyword?
13774     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13775     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13776     UnresolvedLookupExpr *Fn
13777       = UnresolvedLookupExpr::Create(Context, NamingClass,
13778                                      NestedNameSpecifierLoc(), OpNameInfo,
13779                                      /*ADL*/ true, /*Overloaded*/ false,
13780                                      UnresolvedSetIterator(),
13781                                      UnresolvedSetIterator());
13782     // Can't add any actual overloads yet
13783 
13784     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13785                                        Context.DependentTy, VK_RValue, RLoc,
13786                                        CurFPFeatureOverrides());
13787   }
13788 
13789   // Handle placeholders on both operands.
13790   if (checkPlaceholderForOverload(*this, Args[0]))
13791     return ExprError();
13792   if (checkPlaceholderForOverload(*this, Args[1]))
13793     return ExprError();
13794 
13795   // Build an empty overload set.
13796   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13797 
13798   // Subscript can only be overloaded as a member function.
13799 
13800   // Add operator candidates that are member functions.
13801   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13802 
13803   // Add builtin operator candidates.
13804   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13805 
13806   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13807 
13808   // Perform overload resolution.
13809   OverloadCandidateSet::iterator Best;
13810   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13811     case OR_Success: {
13812       // We found a built-in operator or an overloaded operator.
13813       FunctionDecl *FnDecl = Best->Function;
13814 
13815       if (FnDecl) {
13816         // We matched an overloaded operator. Build a call to that
13817         // operator.
13818 
13819         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13820 
13821         // Convert the arguments.
13822         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13823         ExprResult Arg0 =
13824           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13825                                               Best->FoundDecl, Method);
13826         if (Arg0.isInvalid())
13827           return ExprError();
13828         Args[0] = Arg0.get();
13829 
13830         // Convert the arguments.
13831         ExprResult InputInit
13832           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13833                                                       Context,
13834                                                       FnDecl->getParamDecl(0)),
13835                                       SourceLocation(),
13836                                       Args[1]);
13837         if (InputInit.isInvalid())
13838           return ExprError();
13839 
13840         Args[1] = InputInit.getAs<Expr>();
13841 
13842         // Build the actual expression node.
13843         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13844         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13845         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13846                                                   Best->FoundDecl,
13847                                                   Base,
13848                                                   HadMultipleCandidates,
13849                                                   OpLocInfo.getLoc(),
13850                                                   OpLocInfo.getInfo());
13851         if (FnExpr.isInvalid())
13852           return ExprError();
13853 
13854         // Determine the result type
13855         QualType ResultTy = FnDecl->getReturnType();
13856         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13857         ResultTy = ResultTy.getNonLValueExprType(Context);
13858 
13859         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13860             Context, OO_Subscript, FnExpr.get(), Args, ResultTy, VK, RLoc,
13861             CurFPFeatureOverrides());
13862         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13863           return ExprError();
13864 
13865         if (CheckFunctionCall(Method, TheCall,
13866                               Method->getType()->castAs<FunctionProtoType>()))
13867           return ExprError();
13868 
13869         return MaybeBindToTemporary(TheCall);
13870       } else {
13871         // We matched a built-in operator. Convert the arguments, then
13872         // break out so that we will build the appropriate built-in
13873         // operator node.
13874         ExprResult ArgsRes0 = PerformImplicitConversion(
13875             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13876             AA_Passing, CCK_ForBuiltinOverloadedOp);
13877         if (ArgsRes0.isInvalid())
13878           return ExprError();
13879         Args[0] = ArgsRes0.get();
13880 
13881         ExprResult ArgsRes1 = PerformImplicitConversion(
13882             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13883             AA_Passing, CCK_ForBuiltinOverloadedOp);
13884         if (ArgsRes1.isInvalid())
13885           return ExprError();
13886         Args[1] = ArgsRes1.get();
13887 
13888         break;
13889       }
13890     }
13891 
13892     case OR_No_Viable_Function: {
13893       PartialDiagnostic PD = CandidateSet.empty()
13894           ? (PDiag(diag::err_ovl_no_oper)
13895              << Args[0]->getType() << /*subscript*/ 0
13896              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13897           : (PDiag(diag::err_ovl_no_viable_subscript)
13898              << Args[0]->getType() << Args[0]->getSourceRange()
13899              << Args[1]->getSourceRange());
13900       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13901                                   OCD_AllCandidates, Args, "[]", LLoc);
13902       return ExprError();
13903     }
13904 
13905     case OR_Ambiguous:
13906       CandidateSet.NoteCandidates(
13907           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13908                                         << "[]" << Args[0]->getType()
13909                                         << Args[1]->getType()
13910                                         << Args[0]->getSourceRange()
13911                                         << Args[1]->getSourceRange()),
13912           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13913       return ExprError();
13914 
13915     case OR_Deleted:
13916       CandidateSet.NoteCandidates(
13917           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13918                                         << "[]" << Args[0]->getSourceRange()
13919                                         << Args[1]->getSourceRange()),
13920           *this, OCD_AllCandidates, Args, "[]", LLoc);
13921       return ExprError();
13922     }
13923 
13924   // We matched a built-in operator; build it.
13925   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13926 }
13927 
13928 /// BuildCallToMemberFunction - Build a call to a member
13929 /// function. MemExpr is the expression that refers to the member
13930 /// function (and includes the object parameter), Args/NumArgs are the
13931 /// arguments to the function call (not including the object
13932 /// parameter). The caller needs to validate that the member
13933 /// expression refers to a non-static member function or an overloaded
13934 /// member function.
13935 ExprResult
13936 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13937                                 SourceLocation LParenLoc,
13938                                 MultiExprArg Args,
13939                                 SourceLocation RParenLoc) {
13940   assert(MemExprE->getType() == Context.BoundMemberTy ||
13941          MemExprE->getType() == Context.OverloadTy);
13942 
13943   // Dig out the member expression. This holds both the object
13944   // argument and the member function we're referring to.
13945   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13946 
13947   // Determine whether this is a call to a pointer-to-member function.
13948   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13949     assert(op->getType() == Context.BoundMemberTy);
13950     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13951 
13952     QualType fnType =
13953       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13954 
13955     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13956     QualType resultType = proto->getCallResultType(Context);
13957     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13958 
13959     // Check that the object type isn't more qualified than the
13960     // member function we're calling.
13961     Qualifiers funcQuals = proto->getMethodQuals();
13962 
13963     QualType objectType = op->getLHS()->getType();
13964     if (op->getOpcode() == BO_PtrMemI)
13965       objectType = objectType->castAs<PointerType>()->getPointeeType();
13966     Qualifiers objectQuals = objectType.getQualifiers();
13967 
13968     Qualifiers difference = objectQuals - funcQuals;
13969     difference.removeObjCGCAttr();
13970     difference.removeAddressSpace();
13971     if (difference) {
13972       std::string qualsString = difference.getAsString();
13973       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13974         << fnType.getUnqualifiedType()
13975         << qualsString
13976         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13977     }
13978 
13979     CXXMemberCallExpr *call =
13980         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13981                                   valueKind, RParenLoc, proto->getNumParams());
13982 
13983     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13984                             call, nullptr))
13985       return ExprError();
13986 
13987     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13988       return ExprError();
13989 
13990     if (CheckOtherCall(call, proto))
13991       return ExprError();
13992 
13993     return MaybeBindToTemporary(call);
13994   }
13995 
13996   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13997     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13998                             RParenLoc);
13999 
14000   UnbridgedCastsSet UnbridgedCasts;
14001   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14002     return ExprError();
14003 
14004   MemberExpr *MemExpr;
14005   CXXMethodDecl *Method = nullptr;
14006   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
14007   NestedNameSpecifier *Qualifier = nullptr;
14008   if (isa<MemberExpr>(NakedMemExpr)) {
14009     MemExpr = cast<MemberExpr>(NakedMemExpr);
14010     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
14011     FoundDecl = MemExpr->getFoundDecl();
14012     Qualifier = MemExpr->getQualifier();
14013     UnbridgedCasts.restore();
14014   } else {
14015     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
14016     Qualifier = UnresExpr->getQualifier();
14017 
14018     QualType ObjectType = UnresExpr->getBaseType();
14019     Expr::Classification ObjectClassification
14020       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
14021                             : UnresExpr->getBase()->Classify(Context);
14022 
14023     // Add overload candidates
14024     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
14025                                       OverloadCandidateSet::CSK_Normal);
14026 
14027     // FIXME: avoid copy.
14028     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14029     if (UnresExpr->hasExplicitTemplateArgs()) {
14030       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14031       TemplateArgs = &TemplateArgsBuffer;
14032     }
14033 
14034     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
14035            E = UnresExpr->decls_end(); I != E; ++I) {
14036 
14037       NamedDecl *Func = *I;
14038       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14039       if (isa<UsingShadowDecl>(Func))
14040         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14041 
14042 
14043       // Microsoft supports direct constructor calls.
14044       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14045         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14046                              CandidateSet,
14047                              /*SuppressUserConversions*/ false);
14048       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14049         // If explicit template arguments were provided, we can't call a
14050         // non-template member function.
14051         if (TemplateArgs)
14052           continue;
14053 
14054         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14055                            ObjectClassification, Args, CandidateSet,
14056                            /*SuppressUserConversions=*/false);
14057       } else {
14058         AddMethodTemplateCandidate(
14059             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14060             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14061             /*SuppressUserConversions=*/false);
14062       }
14063     }
14064 
14065     DeclarationName DeclName = UnresExpr->getMemberName();
14066 
14067     UnbridgedCasts.restore();
14068 
14069     OverloadCandidateSet::iterator Best;
14070     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14071                                             Best)) {
14072     case OR_Success:
14073       Method = cast<CXXMethodDecl>(Best->Function);
14074       FoundDecl = Best->FoundDecl;
14075       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14076       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14077         return ExprError();
14078       // If FoundDecl is different from Method (such as if one is a template
14079       // and the other a specialization), make sure DiagnoseUseOfDecl is
14080       // called on both.
14081       // FIXME: This would be more comprehensively addressed by modifying
14082       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14083       // being used.
14084       if (Method != FoundDecl.getDecl() &&
14085                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14086         return ExprError();
14087       break;
14088 
14089     case OR_No_Viable_Function:
14090       CandidateSet.NoteCandidates(
14091           PartialDiagnosticAt(
14092               UnresExpr->getMemberLoc(),
14093               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14094                   << DeclName << MemExprE->getSourceRange()),
14095           *this, OCD_AllCandidates, Args);
14096       // FIXME: Leaking incoming expressions!
14097       return ExprError();
14098 
14099     case OR_Ambiguous:
14100       CandidateSet.NoteCandidates(
14101           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14102                               PDiag(diag::err_ovl_ambiguous_member_call)
14103                                   << DeclName << MemExprE->getSourceRange()),
14104           *this, OCD_AmbiguousCandidates, Args);
14105       // FIXME: Leaking incoming expressions!
14106       return ExprError();
14107 
14108     case OR_Deleted:
14109       CandidateSet.NoteCandidates(
14110           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14111                               PDiag(diag::err_ovl_deleted_member_call)
14112                                   << DeclName << MemExprE->getSourceRange()),
14113           *this, OCD_AllCandidates, Args);
14114       // FIXME: Leaking incoming expressions!
14115       return ExprError();
14116     }
14117 
14118     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14119 
14120     // If overload resolution picked a static member, build a
14121     // non-member call based on that function.
14122     if (Method->isStatic()) {
14123       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14124                                    RParenLoc);
14125     }
14126 
14127     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14128   }
14129 
14130   QualType ResultType = Method->getReturnType();
14131   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14132   ResultType = ResultType.getNonLValueExprType(Context);
14133 
14134   assert(Method && "Member call to something that isn't a method?");
14135   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14136   CXXMemberCallExpr *TheCall =
14137       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
14138                                 RParenLoc, Proto->getNumParams());
14139 
14140   // Check for a valid return type.
14141   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14142                           TheCall, Method))
14143     return ExprError();
14144 
14145   // Convert the object argument (for a non-static member function call).
14146   // We only need to do this if there was actually an overload; otherwise
14147   // it was done at lookup.
14148   if (!Method->isStatic()) {
14149     ExprResult ObjectArg =
14150       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14151                                           FoundDecl, Method);
14152     if (ObjectArg.isInvalid())
14153       return ExprError();
14154     MemExpr->setBase(ObjectArg.get());
14155   }
14156 
14157   // Convert the rest of the arguments
14158   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14159                               RParenLoc))
14160     return ExprError();
14161 
14162   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14163 
14164   if (CheckFunctionCall(Method, TheCall, Proto))
14165     return ExprError();
14166 
14167   // In the case the method to call was not selected by the overloading
14168   // resolution process, we still need to handle the enable_if attribute. Do
14169   // that here, so it will not hide previous -- and more relevant -- errors.
14170   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14171     if (const EnableIfAttr *Attr =
14172             CheckEnableIf(Method, LParenLoc, Args, true)) {
14173       Diag(MemE->getMemberLoc(),
14174            diag::err_ovl_no_viable_member_function_in_call)
14175           << Method << Method->getSourceRange();
14176       Diag(Method->getLocation(),
14177            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14178           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14179       return ExprError();
14180     }
14181   }
14182 
14183   if ((isa<CXXConstructorDecl>(CurContext) ||
14184        isa<CXXDestructorDecl>(CurContext)) &&
14185       TheCall->getMethodDecl()->isPure()) {
14186     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14187 
14188     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14189         MemExpr->performsVirtualDispatch(getLangOpts())) {
14190       Diag(MemExpr->getBeginLoc(),
14191            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14192           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14193           << MD->getParent()->getDeclName();
14194 
14195       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14196       if (getLangOpts().AppleKext)
14197         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14198             << MD->getParent()->getDeclName() << MD->getDeclName();
14199     }
14200   }
14201 
14202   if (CXXDestructorDecl *DD =
14203           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14204     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14205     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14206     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14207                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14208                          MemExpr->getMemberLoc());
14209   }
14210 
14211   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14212                                      TheCall->getMethodDecl());
14213 }
14214 
14215 /// BuildCallToObjectOfClassType - Build a call to an object of class
14216 /// type (C++ [over.call.object]), which can end up invoking an
14217 /// overloaded function call operator (@c operator()) or performing a
14218 /// user-defined conversion on the object argument.
14219 ExprResult
14220 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14221                                    SourceLocation LParenLoc,
14222                                    MultiExprArg Args,
14223                                    SourceLocation RParenLoc) {
14224   if (checkPlaceholderForOverload(*this, Obj))
14225     return ExprError();
14226   ExprResult Object = Obj;
14227 
14228   UnbridgedCastsSet UnbridgedCasts;
14229   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14230     return ExprError();
14231 
14232   assert(Object.get()->getType()->isRecordType() &&
14233          "Requires object type argument");
14234 
14235   // C++ [over.call.object]p1:
14236   //  If the primary-expression E in the function call syntax
14237   //  evaluates to a class object of type "cv T", then the set of
14238   //  candidate functions includes at least the function call
14239   //  operators of T. The function call operators of T are obtained by
14240   //  ordinary lookup of the name operator() in the context of
14241   //  (E).operator().
14242   OverloadCandidateSet CandidateSet(LParenLoc,
14243                                     OverloadCandidateSet::CSK_Operator);
14244   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14245 
14246   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14247                           diag::err_incomplete_object_call, Object.get()))
14248     return true;
14249 
14250   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14251   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14252   LookupQualifiedName(R, Record->getDecl());
14253   R.suppressDiagnostics();
14254 
14255   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14256        Oper != OperEnd; ++Oper) {
14257     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14258                        Object.get()->Classify(Context), Args, CandidateSet,
14259                        /*SuppressUserConversion=*/false);
14260   }
14261 
14262   // C++ [over.call.object]p2:
14263   //   In addition, for each (non-explicit in C++0x) conversion function
14264   //   declared in T of the form
14265   //
14266   //        operator conversion-type-id () cv-qualifier;
14267   //
14268   //   where cv-qualifier is the same cv-qualification as, or a
14269   //   greater cv-qualification than, cv, and where conversion-type-id
14270   //   denotes the type "pointer to function of (P1,...,Pn) returning
14271   //   R", or the type "reference to pointer to function of
14272   //   (P1,...,Pn) returning R", or the type "reference to function
14273   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14274   //   is also considered as a candidate function. Similarly,
14275   //   surrogate call functions are added to the set of candidate
14276   //   functions for each conversion function declared in an
14277   //   accessible base class provided the function is not hidden
14278   //   within T by another intervening declaration.
14279   const auto &Conversions =
14280       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14281   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14282     NamedDecl *D = *I;
14283     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14284     if (isa<UsingShadowDecl>(D))
14285       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14286 
14287     // Skip over templated conversion functions; they aren't
14288     // surrogates.
14289     if (isa<FunctionTemplateDecl>(D))
14290       continue;
14291 
14292     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14293     if (!Conv->isExplicit()) {
14294       // Strip the reference type (if any) and then the pointer type (if
14295       // any) to get down to what might be a function type.
14296       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14297       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14298         ConvType = ConvPtrType->getPointeeType();
14299 
14300       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14301       {
14302         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14303                               Object.get(), Args, CandidateSet);
14304       }
14305     }
14306   }
14307 
14308   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14309 
14310   // Perform overload resolution.
14311   OverloadCandidateSet::iterator Best;
14312   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14313                                           Best)) {
14314   case OR_Success:
14315     // Overload resolution succeeded; we'll build the appropriate call
14316     // below.
14317     break;
14318 
14319   case OR_No_Viable_Function: {
14320     PartialDiagnostic PD =
14321         CandidateSet.empty()
14322             ? (PDiag(diag::err_ovl_no_oper)
14323                << Object.get()->getType() << /*call*/ 1
14324                << Object.get()->getSourceRange())
14325             : (PDiag(diag::err_ovl_no_viable_object_call)
14326                << Object.get()->getType() << Object.get()->getSourceRange());
14327     CandidateSet.NoteCandidates(
14328         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14329         OCD_AllCandidates, Args);
14330     break;
14331   }
14332   case OR_Ambiguous:
14333     CandidateSet.NoteCandidates(
14334         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14335                             PDiag(diag::err_ovl_ambiguous_object_call)
14336                                 << Object.get()->getType()
14337                                 << Object.get()->getSourceRange()),
14338         *this, OCD_AmbiguousCandidates, Args);
14339     break;
14340 
14341   case OR_Deleted:
14342     CandidateSet.NoteCandidates(
14343         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14344                             PDiag(diag::err_ovl_deleted_object_call)
14345                                 << Object.get()->getType()
14346                                 << Object.get()->getSourceRange()),
14347         *this, OCD_AllCandidates, Args);
14348     break;
14349   }
14350 
14351   if (Best == CandidateSet.end())
14352     return true;
14353 
14354   UnbridgedCasts.restore();
14355 
14356   if (Best->Function == nullptr) {
14357     // Since there is no function declaration, this is one of the
14358     // surrogate candidates. Dig out the conversion function.
14359     CXXConversionDecl *Conv
14360       = cast<CXXConversionDecl>(
14361                          Best->Conversions[0].UserDefined.ConversionFunction);
14362 
14363     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14364                               Best->FoundDecl);
14365     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14366       return ExprError();
14367     assert(Conv == Best->FoundDecl.getDecl() &&
14368              "Found Decl & conversion-to-functionptr should be same, right?!");
14369     // We selected one of the surrogate functions that converts the
14370     // object parameter to a function pointer. Perform the conversion
14371     // on the object argument, then let BuildCallExpr finish the job.
14372 
14373     // Create an implicit member expr to refer to the conversion operator.
14374     // and then call it.
14375     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14376                                              Conv, HadMultipleCandidates);
14377     if (Call.isInvalid())
14378       return ExprError();
14379     // Record usage of conversion in an implicit cast.
14380     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14381                                     CK_UserDefinedConversion, Call.get(),
14382                                     nullptr, VK_RValue);
14383 
14384     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14385   }
14386 
14387   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14388 
14389   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14390   // that calls this method, using Object for the implicit object
14391   // parameter and passing along the remaining arguments.
14392   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14393 
14394   // An error diagnostic has already been printed when parsing the declaration.
14395   if (Method->isInvalidDecl())
14396     return ExprError();
14397 
14398   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14399   unsigned NumParams = Proto->getNumParams();
14400 
14401   DeclarationNameInfo OpLocInfo(
14402                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14403   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14404   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14405                                            Obj, HadMultipleCandidates,
14406                                            OpLocInfo.getLoc(),
14407                                            OpLocInfo.getInfo());
14408   if (NewFn.isInvalid())
14409     return true;
14410 
14411   // The number of argument slots to allocate in the call. If we have default
14412   // arguments we need to allocate space for them as well. We additionally
14413   // need one more slot for the object parameter.
14414   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14415 
14416   // Build the full argument list for the method call (the implicit object
14417   // parameter is placed at the beginning of the list).
14418   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14419 
14420   bool IsError = false;
14421 
14422   // Initialize the implicit object parameter.
14423   ExprResult ObjRes =
14424     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14425                                         Best->FoundDecl, Method);
14426   if (ObjRes.isInvalid())
14427     IsError = true;
14428   else
14429     Object = ObjRes;
14430   MethodArgs[0] = Object.get();
14431 
14432   // Check the argument types.
14433   for (unsigned i = 0; i != NumParams; i++) {
14434     Expr *Arg;
14435     if (i < Args.size()) {
14436       Arg = Args[i];
14437 
14438       // Pass the argument.
14439 
14440       ExprResult InputInit
14441         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14442                                                     Context,
14443                                                     Method->getParamDecl(i)),
14444                                     SourceLocation(), Arg);
14445 
14446       IsError |= InputInit.isInvalid();
14447       Arg = InputInit.getAs<Expr>();
14448     } else {
14449       ExprResult DefArg
14450         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14451       if (DefArg.isInvalid()) {
14452         IsError = true;
14453         break;
14454       }
14455 
14456       Arg = DefArg.getAs<Expr>();
14457     }
14458 
14459     MethodArgs[i + 1] = Arg;
14460   }
14461 
14462   // If this is a variadic call, handle args passed through "...".
14463   if (Proto->isVariadic()) {
14464     // Promote the arguments (C99 6.5.2.2p7).
14465     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14466       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14467                                                         nullptr);
14468       IsError |= Arg.isInvalid();
14469       MethodArgs[i + 1] = Arg.get();
14470     }
14471   }
14472 
14473   if (IsError)
14474     return true;
14475 
14476   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14477 
14478   // Once we've built TheCall, all of the expressions are properly owned.
14479   QualType ResultTy = Method->getReturnType();
14480   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14481   ResultTy = ResultTy.getNonLValueExprType(Context);
14482 
14483   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14484       Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
14485       CurFPFeatureOverrides());
14486 
14487   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14488     return true;
14489 
14490   if (CheckFunctionCall(Method, TheCall, Proto))
14491     return true;
14492 
14493   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14494 }
14495 
14496 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14497 ///  (if one exists), where @c Base is an expression of class type and
14498 /// @c Member is the name of the member we're trying to find.
14499 ExprResult
14500 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14501                                bool *NoArrowOperatorFound) {
14502   assert(Base->getType()->isRecordType() &&
14503          "left-hand side must have class type");
14504 
14505   if (checkPlaceholderForOverload(*this, Base))
14506     return ExprError();
14507 
14508   SourceLocation Loc = Base->getExprLoc();
14509 
14510   // C++ [over.ref]p1:
14511   //
14512   //   [...] An expression x->m is interpreted as (x.operator->())->m
14513   //   for a class object x of type T if T::operator->() exists and if
14514   //   the operator is selected as the best match function by the
14515   //   overload resolution mechanism (13.3).
14516   DeclarationName OpName =
14517     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14518   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14519 
14520   if (RequireCompleteType(Loc, Base->getType(),
14521                           diag::err_typecheck_incomplete_tag, Base))
14522     return ExprError();
14523 
14524   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14525   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14526   R.suppressDiagnostics();
14527 
14528   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14529        Oper != OperEnd; ++Oper) {
14530     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14531                        None, CandidateSet, /*SuppressUserConversion=*/false);
14532   }
14533 
14534   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14535 
14536   // Perform overload resolution.
14537   OverloadCandidateSet::iterator Best;
14538   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14539   case OR_Success:
14540     // Overload resolution succeeded; we'll build the call below.
14541     break;
14542 
14543   case OR_No_Viable_Function: {
14544     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14545     if (CandidateSet.empty()) {
14546       QualType BaseType = Base->getType();
14547       if (NoArrowOperatorFound) {
14548         // Report this specific error to the caller instead of emitting a
14549         // diagnostic, as requested.
14550         *NoArrowOperatorFound = true;
14551         return ExprError();
14552       }
14553       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14554         << BaseType << Base->getSourceRange();
14555       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14556         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14557           << FixItHint::CreateReplacement(OpLoc, ".");
14558       }
14559     } else
14560       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14561         << "operator->" << Base->getSourceRange();
14562     CandidateSet.NoteCandidates(*this, Base, Cands);
14563     return ExprError();
14564   }
14565   case OR_Ambiguous:
14566     CandidateSet.NoteCandidates(
14567         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14568                                        << "->" << Base->getType()
14569                                        << Base->getSourceRange()),
14570         *this, OCD_AmbiguousCandidates, Base);
14571     return ExprError();
14572 
14573   case OR_Deleted:
14574     CandidateSet.NoteCandidates(
14575         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14576                                        << "->" << Base->getSourceRange()),
14577         *this, OCD_AllCandidates, Base);
14578     return ExprError();
14579   }
14580 
14581   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14582 
14583   // Convert the object parameter.
14584   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14585   ExprResult BaseResult =
14586     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14587                                         Best->FoundDecl, Method);
14588   if (BaseResult.isInvalid())
14589     return ExprError();
14590   Base = BaseResult.get();
14591 
14592   // Build the operator call.
14593   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14594                                             Base, HadMultipleCandidates, OpLoc);
14595   if (FnExpr.isInvalid())
14596     return ExprError();
14597 
14598   QualType ResultTy = Method->getReturnType();
14599   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14600   ResultTy = ResultTy.getNonLValueExprType(Context);
14601   CXXOperatorCallExpr *TheCall =
14602       CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
14603                                   ResultTy, VK, OpLoc, CurFPFeatureOverrides());
14604 
14605   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14606     return ExprError();
14607 
14608   if (CheckFunctionCall(Method, TheCall,
14609                         Method->getType()->castAs<FunctionProtoType>()))
14610     return ExprError();
14611 
14612   return MaybeBindToTemporary(TheCall);
14613 }
14614 
14615 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14616 /// a literal operator described by the provided lookup results.
14617 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14618                                           DeclarationNameInfo &SuffixInfo,
14619                                           ArrayRef<Expr*> Args,
14620                                           SourceLocation LitEndLoc,
14621                                        TemplateArgumentListInfo *TemplateArgs) {
14622   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14623 
14624   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14625                                     OverloadCandidateSet::CSK_Normal);
14626   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14627                                  TemplateArgs);
14628 
14629   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14630 
14631   // Perform overload resolution. This will usually be trivial, but might need
14632   // to perform substitutions for a literal operator template.
14633   OverloadCandidateSet::iterator Best;
14634   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14635   case OR_Success:
14636   case OR_Deleted:
14637     break;
14638 
14639   case OR_No_Viable_Function:
14640     CandidateSet.NoteCandidates(
14641         PartialDiagnosticAt(UDSuffixLoc,
14642                             PDiag(diag::err_ovl_no_viable_function_in_call)
14643                                 << R.getLookupName()),
14644         *this, OCD_AllCandidates, Args);
14645     return ExprError();
14646 
14647   case OR_Ambiguous:
14648     CandidateSet.NoteCandidates(
14649         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14650                                                 << R.getLookupName()),
14651         *this, OCD_AmbiguousCandidates, Args);
14652     return ExprError();
14653   }
14654 
14655   FunctionDecl *FD = Best->Function;
14656   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14657                                         nullptr, HadMultipleCandidates,
14658                                         SuffixInfo.getLoc(),
14659                                         SuffixInfo.getInfo());
14660   if (Fn.isInvalid())
14661     return true;
14662 
14663   // Check the argument types. This should almost always be a no-op, except
14664   // that array-to-pointer decay is applied to string literals.
14665   Expr *ConvArgs[2];
14666   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14667     ExprResult InputInit = PerformCopyInitialization(
14668       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14669       SourceLocation(), Args[ArgIdx]);
14670     if (InputInit.isInvalid())
14671       return true;
14672     ConvArgs[ArgIdx] = InputInit.get();
14673   }
14674 
14675   QualType ResultTy = FD->getReturnType();
14676   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14677   ResultTy = ResultTy.getNonLValueExprType(Context);
14678 
14679   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14680       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14681       VK, LitEndLoc, UDSuffixLoc);
14682 
14683   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14684     return ExprError();
14685 
14686   if (CheckFunctionCall(FD, UDL, nullptr))
14687     return ExprError();
14688 
14689   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14690 }
14691 
14692 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14693 /// given LookupResult is non-empty, it is assumed to describe a member which
14694 /// will be invoked. Otherwise, the function will be found via argument
14695 /// dependent lookup.
14696 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14697 /// otherwise CallExpr is set to ExprError() and some non-success value
14698 /// is returned.
14699 Sema::ForRangeStatus
14700 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14701                                 SourceLocation RangeLoc,
14702                                 const DeclarationNameInfo &NameInfo,
14703                                 LookupResult &MemberLookup,
14704                                 OverloadCandidateSet *CandidateSet,
14705                                 Expr *Range, ExprResult *CallExpr) {
14706   Scope *S = nullptr;
14707 
14708   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14709   if (!MemberLookup.empty()) {
14710     ExprResult MemberRef =
14711         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14712                                  /*IsPtr=*/false, CXXScopeSpec(),
14713                                  /*TemplateKWLoc=*/SourceLocation(),
14714                                  /*FirstQualifierInScope=*/nullptr,
14715                                  MemberLookup,
14716                                  /*TemplateArgs=*/nullptr, S);
14717     if (MemberRef.isInvalid()) {
14718       *CallExpr = ExprError();
14719       return FRS_DiagnosticIssued;
14720     }
14721     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14722     if (CallExpr->isInvalid()) {
14723       *CallExpr = ExprError();
14724       return FRS_DiagnosticIssued;
14725     }
14726   } else {
14727     UnresolvedSet<0> FoundNames;
14728     UnresolvedLookupExpr *Fn =
14729       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14730                                    NestedNameSpecifierLoc(), NameInfo,
14731                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14732                                    FoundNames.begin(), FoundNames.end());
14733 
14734     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14735                                                     CandidateSet, CallExpr);
14736     if (CandidateSet->empty() || CandidateSetError) {
14737       *CallExpr = ExprError();
14738       return FRS_NoViableFunction;
14739     }
14740     OverloadCandidateSet::iterator Best;
14741     OverloadingResult OverloadResult =
14742         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14743 
14744     if (OverloadResult == OR_No_Viable_Function) {
14745       *CallExpr = ExprError();
14746       return FRS_NoViableFunction;
14747     }
14748     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14749                                          Loc, nullptr, CandidateSet, &Best,
14750                                          OverloadResult,
14751                                          /*AllowTypoCorrection=*/false);
14752     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14753       *CallExpr = ExprError();
14754       return FRS_DiagnosticIssued;
14755     }
14756   }
14757   return FRS_Success;
14758 }
14759 
14760 
14761 /// FixOverloadedFunctionReference - E is an expression that refers to
14762 /// a C++ overloaded function (possibly with some parentheses and
14763 /// perhaps a '&' around it). We have resolved the overloaded function
14764 /// to the function declaration Fn, so patch up the expression E to
14765 /// refer (possibly indirectly) to Fn. Returns the new expr.
14766 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14767                                            FunctionDecl *Fn) {
14768   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14769     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14770                                                    Found, Fn);
14771     if (SubExpr == PE->getSubExpr())
14772       return PE;
14773 
14774     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14775   }
14776 
14777   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14778     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14779                                                    Found, Fn);
14780     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14781                                SubExpr->getType()) &&
14782            "Implicit cast type cannot be determined from overload");
14783     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14784     if (SubExpr == ICE->getSubExpr())
14785       return ICE;
14786 
14787     return ImplicitCastExpr::Create(Context, ICE->getType(),
14788                                     ICE->getCastKind(),
14789                                     SubExpr, nullptr,
14790                                     ICE->getValueKind());
14791   }
14792 
14793   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14794     if (!GSE->isResultDependent()) {
14795       Expr *SubExpr =
14796           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14797       if (SubExpr == GSE->getResultExpr())
14798         return GSE;
14799 
14800       // Replace the resulting type information before rebuilding the generic
14801       // selection expression.
14802       ArrayRef<Expr *> A = GSE->getAssocExprs();
14803       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14804       unsigned ResultIdx = GSE->getResultIndex();
14805       AssocExprs[ResultIdx] = SubExpr;
14806 
14807       return GenericSelectionExpr::Create(
14808           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14809           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14810           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14811           ResultIdx);
14812     }
14813     // Rather than fall through to the unreachable, return the original generic
14814     // selection expression.
14815     return GSE;
14816   }
14817 
14818   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14819     assert(UnOp->getOpcode() == UO_AddrOf &&
14820            "Can only take the address of an overloaded function");
14821     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14822       if (Method->isStatic()) {
14823         // Do nothing: static member functions aren't any different
14824         // from non-member functions.
14825       } else {
14826         // Fix the subexpression, which really has to be an
14827         // UnresolvedLookupExpr holding an overloaded member function
14828         // or template.
14829         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14830                                                        Found, Fn);
14831         if (SubExpr == UnOp->getSubExpr())
14832           return UnOp;
14833 
14834         assert(isa<DeclRefExpr>(SubExpr)
14835                && "fixed to something other than a decl ref");
14836         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14837                && "fixed to a member ref with no nested name qualifier");
14838 
14839         // We have taken the address of a pointer to member
14840         // function. Perform the computation here so that we get the
14841         // appropriate pointer to member type.
14842         QualType ClassType
14843           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14844         QualType MemPtrType
14845           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14846         // Under the MS ABI, lock down the inheritance model now.
14847         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14848           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14849 
14850         return UnaryOperator::Create(
14851             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14852             UnOp->getOperatorLoc(), false, CurFPFeatureOverrides());
14853       }
14854     }
14855     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14856                                                    Found, Fn);
14857     if (SubExpr == UnOp->getSubExpr())
14858       return UnOp;
14859 
14860     return UnaryOperator::Create(Context, SubExpr, UO_AddrOf,
14861                                  Context.getPointerType(SubExpr->getType()),
14862                                  VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(),
14863                                  false, CurFPFeatureOverrides());
14864   }
14865 
14866   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14867     // FIXME: avoid copy.
14868     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14869     if (ULE->hasExplicitTemplateArgs()) {
14870       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14871       TemplateArgs = &TemplateArgsBuffer;
14872     }
14873 
14874     DeclRefExpr *DRE =
14875         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14876                          ULE->getQualifierLoc(), Found.getDecl(),
14877                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14878     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14879     return DRE;
14880   }
14881 
14882   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14883     // FIXME: avoid copy.
14884     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14885     if (MemExpr->hasExplicitTemplateArgs()) {
14886       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14887       TemplateArgs = &TemplateArgsBuffer;
14888     }
14889 
14890     Expr *Base;
14891 
14892     // If we're filling in a static method where we used to have an
14893     // implicit member access, rewrite to a simple decl ref.
14894     if (MemExpr->isImplicitAccess()) {
14895       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14896         DeclRefExpr *DRE = BuildDeclRefExpr(
14897             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14898             MemExpr->getQualifierLoc(), Found.getDecl(),
14899             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14900         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14901         return DRE;
14902       } else {
14903         SourceLocation Loc = MemExpr->getMemberLoc();
14904         if (MemExpr->getQualifier())
14905           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14906         Base =
14907             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14908       }
14909     } else
14910       Base = MemExpr->getBase();
14911 
14912     ExprValueKind valueKind;
14913     QualType type;
14914     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14915       valueKind = VK_LValue;
14916       type = Fn->getType();
14917     } else {
14918       valueKind = VK_RValue;
14919       type = Context.BoundMemberTy;
14920     }
14921 
14922     return BuildMemberExpr(
14923         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14924         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14925         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14926         type, valueKind, OK_Ordinary, TemplateArgs);
14927   }
14928 
14929   llvm_unreachable("Invalid reference to overloaded function");
14930 }
14931 
14932 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14933                                                 DeclAccessPair Found,
14934                                                 FunctionDecl *Fn) {
14935   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14936 }
14937