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     if (&S.Context.getFloatTypeSemantics(FromType) !=
1874         &S.Context.getFloatTypeSemantics(ToType)) {
1875       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1876                                     ToType == S.Context.LongDoubleTy) ||
1877                                    (FromType == S.Context.LongDoubleTy &&
1878                                     ToType == S.Context.Float128Ty));
1879       if (Float128AndLongDouble &&
1880           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1881            &llvm::APFloat::PPCDoubleDouble()))
1882         return false;
1883     }
1884     // Floating point conversions (C++ 4.8).
1885     SCS.Second = ICK_Floating_Conversion;
1886     FromType = ToType.getUnqualifiedType();
1887   } else if ((FromType->isRealFloatingType() &&
1888               ToType->isIntegralType(S.Context)) ||
1889              (FromType->isIntegralOrUnscopedEnumerationType() &&
1890               ToType->isRealFloatingType())) {
1891     // Floating-integral conversions (C++ 4.9).
1892     SCS.Second = ICK_Floating_Integral;
1893     FromType = ToType.getUnqualifiedType();
1894   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1895     SCS.Second = ICK_Block_Pointer_Conversion;
1896   } else if (AllowObjCWritebackConversion &&
1897              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1898     SCS.Second = ICK_Writeback_Conversion;
1899   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1900                                    FromType, IncompatibleObjC)) {
1901     // Pointer conversions (C++ 4.10).
1902     SCS.Second = ICK_Pointer_Conversion;
1903     SCS.IncompatibleObjC = IncompatibleObjC;
1904     FromType = FromType.getUnqualifiedType();
1905   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1906                                          InOverloadResolution, FromType)) {
1907     // Pointer to member conversions (4.11).
1908     SCS.Second = ICK_Pointer_Member;
1909   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1910     SCS.Second = SecondICK;
1911     FromType = ToType.getUnqualifiedType();
1912   } else if (!S.getLangOpts().CPlusPlus &&
1913              S.Context.typesAreCompatible(ToType, FromType)) {
1914     // Compatible conversions (Clang extension for C function overloading)
1915     SCS.Second = ICK_Compatible_Conversion;
1916     FromType = ToType.getUnqualifiedType();
1917   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1918                                              InOverloadResolution,
1919                                              SCS, CStyle)) {
1920     SCS.Second = ICK_TransparentUnionConversion;
1921     FromType = ToType;
1922   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1923                                  CStyle)) {
1924     // tryAtomicConversion has updated the standard conversion sequence
1925     // appropriately.
1926     return true;
1927   } else if (ToType->isEventT() &&
1928              From->isIntegerConstantExpr(S.getASTContext()) &&
1929              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1930     SCS.Second = ICK_Zero_Event_Conversion;
1931     FromType = ToType;
1932   } else if (ToType->isQueueT() &&
1933              From->isIntegerConstantExpr(S.getASTContext()) &&
1934              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1935     SCS.Second = ICK_Zero_Queue_Conversion;
1936     FromType = ToType;
1937   } else if (ToType->isSamplerT() &&
1938              From->isIntegerConstantExpr(S.getASTContext())) {
1939     SCS.Second = ICK_Compatible_Conversion;
1940     FromType = ToType;
1941   } else {
1942     // No second conversion required.
1943     SCS.Second = ICK_Identity;
1944   }
1945   SCS.setToType(1, FromType);
1946 
1947   // The third conversion can be a function pointer conversion or a
1948   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1949   bool ObjCLifetimeConversion;
1950   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1951     // Function pointer conversions (removing 'noexcept') including removal of
1952     // 'noreturn' (Clang extension).
1953     SCS.Third = ICK_Function_Conversion;
1954   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1955                                          ObjCLifetimeConversion)) {
1956     SCS.Third = ICK_Qualification;
1957     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1958     FromType = ToType;
1959   } else {
1960     // No conversion required
1961     SCS.Third = ICK_Identity;
1962   }
1963 
1964   // C++ [over.best.ics]p6:
1965   //   [...] Any difference in top-level cv-qualification is
1966   //   subsumed by the initialization itself and does not constitute
1967   //   a conversion. [...]
1968   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1969   QualType CanonTo = S.Context.getCanonicalType(ToType);
1970   if (CanonFrom.getLocalUnqualifiedType()
1971                                      == CanonTo.getLocalUnqualifiedType() &&
1972       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1973     FromType = ToType;
1974     CanonFrom = CanonTo;
1975   }
1976 
1977   SCS.setToType(2, FromType);
1978 
1979   if (CanonFrom == CanonTo)
1980     return true;
1981 
1982   // If we have not converted the argument type to the parameter type,
1983   // this is a bad conversion sequence, unless we're resolving an overload in C.
1984   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1985     return false;
1986 
1987   ExprResult ER = ExprResult{From};
1988   Sema::AssignConvertType Conv =
1989       S.CheckSingleAssignmentConstraints(ToType, ER,
1990                                          /*Diagnose=*/false,
1991                                          /*DiagnoseCFAudited=*/false,
1992                                          /*ConvertRHS=*/false);
1993   ImplicitConversionKind SecondConv;
1994   switch (Conv) {
1995   case Sema::Compatible:
1996     SecondConv = ICK_C_Only_Conversion;
1997     break;
1998   // For our purposes, discarding qualifiers is just as bad as using an
1999   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2000   // qualifiers, as well.
2001   case Sema::CompatiblePointerDiscardsQualifiers:
2002   case Sema::IncompatiblePointer:
2003   case Sema::IncompatiblePointerSign:
2004     SecondConv = ICK_Incompatible_Pointer_Conversion;
2005     break;
2006   default:
2007     return false;
2008   }
2009 
2010   // First can only be an lvalue conversion, so we pretend that this was the
2011   // second conversion. First should already be valid from earlier in the
2012   // function.
2013   SCS.Second = SecondConv;
2014   SCS.setToType(1, ToType);
2015 
2016   // Third is Identity, because Second should rank us worse than any other
2017   // conversion. This could also be ICK_Qualification, but it's simpler to just
2018   // lump everything in with the second conversion, and we don't gain anything
2019   // from making this ICK_Qualification.
2020   SCS.Third = ICK_Identity;
2021   SCS.setToType(2, ToType);
2022   return true;
2023 }
2024 
2025 static bool
2026 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2027                                      QualType &ToType,
2028                                      bool InOverloadResolution,
2029                                      StandardConversionSequence &SCS,
2030                                      bool CStyle) {
2031 
2032   const RecordType *UT = ToType->getAsUnionType();
2033   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2034     return false;
2035   // The field to initialize within the transparent union.
2036   RecordDecl *UD = UT->getDecl();
2037   // It's compatible if the expression matches any of the fields.
2038   for (const auto *it : UD->fields()) {
2039     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2040                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2041       ToType = it->getType();
2042       return true;
2043     }
2044   }
2045   return false;
2046 }
2047 
2048 /// IsIntegralPromotion - Determines whether the conversion from the
2049 /// expression From (whose potentially-adjusted type is FromType) to
2050 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2051 /// sets PromotedType to the promoted type.
2052 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2053   const BuiltinType *To = ToType->getAs<BuiltinType>();
2054   // All integers are built-in.
2055   if (!To) {
2056     return false;
2057   }
2058 
2059   // An rvalue of type char, signed char, unsigned char, short int, or
2060   // unsigned short int can be converted to an rvalue of type int if
2061   // int can represent all the values of the source type; otherwise,
2062   // the source rvalue can be converted to an rvalue of type unsigned
2063   // int (C++ 4.5p1).
2064   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2065       !FromType->isEnumeralType()) {
2066     if (// We can promote any signed, promotable integer type to an int
2067         (FromType->isSignedIntegerType() ||
2068          // We can promote any unsigned integer type whose size is
2069          // less than int to an int.
2070          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2071       return To->getKind() == BuiltinType::Int;
2072     }
2073 
2074     return To->getKind() == BuiltinType::UInt;
2075   }
2076 
2077   // C++11 [conv.prom]p3:
2078   //   A prvalue of an unscoped enumeration type whose underlying type is not
2079   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2080   //   following types that can represent all the values of the enumeration
2081   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2082   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2083   //   long long int. If none of the types in that list can represent all the
2084   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2085   //   type can be converted to an rvalue a prvalue of the extended integer type
2086   //   with lowest integer conversion rank (4.13) greater than the rank of long
2087   //   long in which all the values of the enumeration can be represented. If
2088   //   there are two such extended types, the signed one is chosen.
2089   // C++11 [conv.prom]p4:
2090   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2091   //   can be converted to a prvalue of its underlying type. Moreover, if
2092   //   integral promotion can be applied to its underlying type, a prvalue of an
2093   //   unscoped enumeration type whose underlying type is fixed can also be
2094   //   converted to a prvalue of the promoted underlying type.
2095   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2096     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2097     // provided for a scoped enumeration.
2098     if (FromEnumType->getDecl()->isScoped())
2099       return false;
2100 
2101     // We can perform an integral promotion to the underlying type of the enum,
2102     // even if that's not the promoted type. Note that the check for promoting
2103     // the underlying type is based on the type alone, and does not consider
2104     // the bitfield-ness of the actual source expression.
2105     if (FromEnumType->getDecl()->isFixed()) {
2106       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2107       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2108              IsIntegralPromotion(nullptr, Underlying, ToType);
2109     }
2110 
2111     // We have already pre-calculated the promotion type, so this is trivial.
2112     if (ToType->isIntegerType() &&
2113         isCompleteType(From->getBeginLoc(), FromType))
2114       return Context.hasSameUnqualifiedType(
2115           ToType, FromEnumType->getDecl()->getPromotionType());
2116 
2117     // C++ [conv.prom]p5:
2118     //   If the bit-field has an enumerated type, it is treated as any other
2119     //   value of that type for promotion purposes.
2120     //
2121     // ... so do not fall through into the bit-field checks below in C++.
2122     if (getLangOpts().CPlusPlus)
2123       return false;
2124   }
2125 
2126   // C++0x [conv.prom]p2:
2127   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2128   //   to an rvalue a prvalue of the first of the following types that can
2129   //   represent all the values of its underlying type: int, unsigned int,
2130   //   long int, unsigned long int, long long int, or unsigned long long int.
2131   //   If none of the types in that list can represent all the values of its
2132   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2133   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2134   //   type.
2135   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2136       ToType->isIntegerType()) {
2137     // Determine whether the type we're converting from is signed or
2138     // unsigned.
2139     bool FromIsSigned = FromType->isSignedIntegerType();
2140     uint64_t FromSize = Context.getTypeSize(FromType);
2141 
2142     // The types we'll try to promote to, in the appropriate
2143     // order. Try each of these types.
2144     QualType PromoteTypes[6] = {
2145       Context.IntTy, Context.UnsignedIntTy,
2146       Context.LongTy, Context.UnsignedLongTy ,
2147       Context.LongLongTy, Context.UnsignedLongLongTy
2148     };
2149     for (int Idx = 0; Idx < 6; ++Idx) {
2150       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2151       if (FromSize < ToSize ||
2152           (FromSize == ToSize &&
2153            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2154         // We found the type that we can promote to. If this is the
2155         // type we wanted, we have a promotion. Otherwise, no
2156         // promotion.
2157         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2158       }
2159     }
2160   }
2161 
2162   // An rvalue for an integral bit-field (9.6) can be converted to an
2163   // rvalue of type int if int can represent all the values of the
2164   // bit-field; otherwise, it can be converted to unsigned int if
2165   // unsigned int can represent all the values of the bit-field. If
2166   // the bit-field is larger yet, no integral promotion applies to
2167   // it. If the bit-field has an enumerated type, it is treated as any
2168   // other value of that type for promotion purposes (C++ 4.5p3).
2169   // FIXME: We should delay checking of bit-fields until we actually perform the
2170   // conversion.
2171   //
2172   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2173   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2174   // bit-fields and those whose underlying type is larger than int) for GCC
2175   // compatibility.
2176   if (From) {
2177     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2178       llvm::APSInt BitWidth;
2179       if (FromType->isIntegralType(Context) &&
2180           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2181         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2182         ToSize = Context.getTypeSize(ToType);
2183 
2184         // Are we promoting to an int from a bitfield that fits in an int?
2185         if (BitWidth < ToSize ||
2186             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2187           return To->getKind() == BuiltinType::Int;
2188         }
2189 
2190         // Are we promoting to an unsigned int from an unsigned bitfield
2191         // that fits into an unsigned int?
2192         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2193           return To->getKind() == BuiltinType::UInt;
2194         }
2195 
2196         return false;
2197       }
2198     }
2199   }
2200 
2201   // An rvalue of type bool can be converted to an rvalue of type int,
2202   // with false becoming zero and true becoming one (C++ 4.5p4).
2203   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2204     return true;
2205   }
2206 
2207   return false;
2208 }
2209 
2210 /// IsFloatingPointPromotion - Determines whether the conversion from
2211 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2212 /// returns true and sets PromotedType to the promoted type.
2213 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2214   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2215     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2216       /// An rvalue of type float can be converted to an rvalue of type
2217       /// double. (C++ 4.6p1).
2218       if (FromBuiltin->getKind() == BuiltinType::Float &&
2219           ToBuiltin->getKind() == BuiltinType::Double)
2220         return true;
2221 
2222       // C99 6.3.1.5p1:
2223       //   When a float is promoted to double or long double, or a
2224       //   double is promoted to long double [...].
2225       if (!getLangOpts().CPlusPlus &&
2226           (FromBuiltin->getKind() == BuiltinType::Float ||
2227            FromBuiltin->getKind() == BuiltinType::Double) &&
2228           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2229            ToBuiltin->getKind() == BuiltinType::Float128))
2230         return true;
2231 
2232       // Half can be promoted to float.
2233       if (!getLangOpts().NativeHalfType &&
2234            FromBuiltin->getKind() == BuiltinType::Half &&
2235           ToBuiltin->getKind() == BuiltinType::Float)
2236         return true;
2237     }
2238 
2239   return false;
2240 }
2241 
2242 /// Determine if a conversion is a complex promotion.
2243 ///
2244 /// A complex promotion is defined as a complex -> complex conversion
2245 /// where the conversion between the underlying real types is a
2246 /// floating-point or integral promotion.
2247 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2248   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2249   if (!FromComplex)
2250     return false;
2251 
2252   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2253   if (!ToComplex)
2254     return false;
2255 
2256   return IsFloatingPointPromotion(FromComplex->getElementType(),
2257                                   ToComplex->getElementType()) ||
2258     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2259                         ToComplex->getElementType());
2260 }
2261 
2262 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2263 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2264 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2265 /// if non-empty, will be a pointer to ToType that may or may not have
2266 /// the right set of qualifiers on its pointee.
2267 ///
2268 static QualType
2269 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2270                                    QualType ToPointee, QualType ToType,
2271                                    ASTContext &Context,
2272                                    bool StripObjCLifetime = false) {
2273   assert((FromPtr->getTypeClass() == Type::Pointer ||
2274           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2275          "Invalid similarly-qualified pointer type");
2276 
2277   /// Conversions to 'id' subsume cv-qualifier conversions.
2278   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2279     return ToType.getUnqualifiedType();
2280 
2281   QualType CanonFromPointee
2282     = Context.getCanonicalType(FromPtr->getPointeeType());
2283   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2284   Qualifiers Quals = CanonFromPointee.getQualifiers();
2285 
2286   if (StripObjCLifetime)
2287     Quals.removeObjCLifetime();
2288 
2289   // Exact qualifier match -> return the pointer type we're converting to.
2290   if (CanonToPointee.getLocalQualifiers() == Quals) {
2291     // ToType is exactly what we need. Return it.
2292     if (!ToType.isNull())
2293       return ToType.getUnqualifiedType();
2294 
2295     // Build a pointer to ToPointee. It has the right qualifiers
2296     // already.
2297     if (isa<ObjCObjectPointerType>(ToType))
2298       return Context.getObjCObjectPointerType(ToPointee);
2299     return Context.getPointerType(ToPointee);
2300   }
2301 
2302   // Just build a canonical type that has the right qualifiers.
2303   QualType QualifiedCanonToPointee
2304     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2305 
2306   if (isa<ObjCObjectPointerType>(ToType))
2307     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2308   return Context.getPointerType(QualifiedCanonToPointee);
2309 }
2310 
2311 static bool isNullPointerConstantForConversion(Expr *Expr,
2312                                                bool InOverloadResolution,
2313                                                ASTContext &Context) {
2314   // Handle value-dependent integral null pointer constants correctly.
2315   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2316   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2317       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2318     return !InOverloadResolution;
2319 
2320   return Expr->isNullPointerConstant(Context,
2321                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2322                                         : Expr::NPC_ValueDependentIsNull);
2323 }
2324 
2325 /// IsPointerConversion - Determines whether the conversion of the
2326 /// expression From, which has the (possibly adjusted) type FromType,
2327 /// can be converted to the type ToType via a pointer conversion (C++
2328 /// 4.10). If so, returns true and places the converted type (that
2329 /// might differ from ToType in its cv-qualifiers at some level) into
2330 /// ConvertedType.
2331 ///
2332 /// This routine also supports conversions to and from block pointers
2333 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2334 /// pointers to interfaces. FIXME: Once we've determined the
2335 /// appropriate overloading rules for Objective-C, we may want to
2336 /// split the Objective-C checks into a different routine; however,
2337 /// GCC seems to consider all of these conversions to be pointer
2338 /// conversions, so for now they live here. IncompatibleObjC will be
2339 /// set if the conversion is an allowed Objective-C conversion that
2340 /// should result in a warning.
2341 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2342                                bool InOverloadResolution,
2343                                QualType& ConvertedType,
2344                                bool &IncompatibleObjC) {
2345   IncompatibleObjC = false;
2346   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2347                               IncompatibleObjC))
2348     return true;
2349 
2350   // Conversion from a null pointer constant to any Objective-C pointer type.
2351   if (ToType->isObjCObjectPointerType() &&
2352       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2353     ConvertedType = ToType;
2354     return true;
2355   }
2356 
2357   // Blocks: Block pointers can be converted to void*.
2358   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2359       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2360     ConvertedType = ToType;
2361     return true;
2362   }
2363   // Blocks: A null pointer constant can be converted to a block
2364   // pointer type.
2365   if (ToType->isBlockPointerType() &&
2366       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2367     ConvertedType = ToType;
2368     return true;
2369   }
2370 
2371   // If the left-hand-side is nullptr_t, the right side can be a null
2372   // pointer constant.
2373   if (ToType->isNullPtrType() &&
2374       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2375     ConvertedType = ToType;
2376     return true;
2377   }
2378 
2379   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2380   if (!ToTypePtr)
2381     return false;
2382 
2383   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2384   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2385     ConvertedType = ToType;
2386     return true;
2387   }
2388 
2389   // Beyond this point, both types need to be pointers
2390   // , including objective-c pointers.
2391   QualType ToPointeeType = ToTypePtr->getPointeeType();
2392   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2393       !getLangOpts().ObjCAutoRefCount) {
2394     ConvertedType = BuildSimilarlyQualifiedPointerType(
2395                                       FromType->getAs<ObjCObjectPointerType>(),
2396                                                        ToPointeeType,
2397                                                        ToType, Context);
2398     return true;
2399   }
2400   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2401   if (!FromTypePtr)
2402     return false;
2403 
2404   QualType FromPointeeType = FromTypePtr->getPointeeType();
2405 
2406   // If the unqualified pointee types are the same, this can't be a
2407   // pointer conversion, so don't do all of the work below.
2408   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2409     return false;
2410 
2411   // An rvalue of type "pointer to cv T," where T is an object type,
2412   // can be converted to an rvalue of type "pointer to cv void" (C++
2413   // 4.10p2).
2414   if (FromPointeeType->isIncompleteOrObjectType() &&
2415       ToPointeeType->isVoidType()) {
2416     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2417                                                        ToPointeeType,
2418                                                        ToType, Context,
2419                                                    /*StripObjCLifetime=*/true);
2420     return true;
2421   }
2422 
2423   // MSVC allows implicit function to void* type conversion.
2424   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2425       ToPointeeType->isVoidType()) {
2426     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2427                                                        ToPointeeType,
2428                                                        ToType, Context);
2429     return true;
2430   }
2431 
2432   // When we're overloading in C, we allow a special kind of pointer
2433   // conversion for compatible-but-not-identical pointee types.
2434   if (!getLangOpts().CPlusPlus &&
2435       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2436     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2437                                                        ToPointeeType,
2438                                                        ToType, Context);
2439     return true;
2440   }
2441 
2442   // C++ [conv.ptr]p3:
2443   //
2444   //   An rvalue of type "pointer to cv D," where D is a class type,
2445   //   can be converted to an rvalue of type "pointer to cv B," where
2446   //   B is a base class (clause 10) of D. If B is an inaccessible
2447   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2448   //   necessitates this conversion is ill-formed. The result of the
2449   //   conversion is a pointer to the base class sub-object of the
2450   //   derived class object. The null pointer value is converted to
2451   //   the null pointer value of the destination type.
2452   //
2453   // Note that we do not check for ambiguity or inaccessibility
2454   // here. That is handled by CheckPointerConversion.
2455   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2456       ToPointeeType->isRecordType() &&
2457       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2458       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2459     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2460                                                        ToPointeeType,
2461                                                        ToType, Context);
2462     return true;
2463   }
2464 
2465   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2466       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2467     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2468                                                        ToPointeeType,
2469                                                        ToType, Context);
2470     return true;
2471   }
2472 
2473   return false;
2474 }
2475 
2476 /// Adopt the given qualifiers for the given type.
2477 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2478   Qualifiers TQs = T.getQualifiers();
2479 
2480   // Check whether qualifiers already match.
2481   if (TQs == Qs)
2482     return T;
2483 
2484   if (Qs.compatiblyIncludes(TQs))
2485     return Context.getQualifiedType(T, Qs);
2486 
2487   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2488 }
2489 
2490 /// isObjCPointerConversion - Determines whether this is an
2491 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2492 /// with the same arguments and return values.
2493 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2494                                    QualType& ConvertedType,
2495                                    bool &IncompatibleObjC) {
2496   if (!getLangOpts().ObjC)
2497     return false;
2498 
2499   // The set of qualifiers on the type we're converting from.
2500   Qualifiers FromQualifiers = FromType.getQualifiers();
2501 
2502   // First, we handle all conversions on ObjC object pointer types.
2503   const ObjCObjectPointerType* ToObjCPtr =
2504     ToType->getAs<ObjCObjectPointerType>();
2505   const ObjCObjectPointerType *FromObjCPtr =
2506     FromType->getAs<ObjCObjectPointerType>();
2507 
2508   if (ToObjCPtr && FromObjCPtr) {
2509     // If the pointee types are the same (ignoring qualifications),
2510     // then this is not a pointer conversion.
2511     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2512                                        FromObjCPtr->getPointeeType()))
2513       return false;
2514 
2515     // Conversion between Objective-C pointers.
2516     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2517       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2518       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2519       if (getLangOpts().CPlusPlus && LHS && RHS &&
2520           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2521                                                 FromObjCPtr->getPointeeType()))
2522         return false;
2523       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2524                                                    ToObjCPtr->getPointeeType(),
2525                                                          ToType, Context);
2526       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2527       return true;
2528     }
2529 
2530     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2531       // Okay: this is some kind of implicit downcast of Objective-C
2532       // interfaces, which is permitted. However, we're going to
2533       // complain about it.
2534       IncompatibleObjC = true;
2535       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2536                                                    ToObjCPtr->getPointeeType(),
2537                                                          ToType, Context);
2538       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539       return true;
2540     }
2541   }
2542   // Beyond this point, both types need to be C pointers or block pointers.
2543   QualType ToPointeeType;
2544   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2545     ToPointeeType = ToCPtr->getPointeeType();
2546   else if (const BlockPointerType *ToBlockPtr =
2547             ToType->getAs<BlockPointerType>()) {
2548     // Objective C++: We're able to convert from a pointer to any object
2549     // to a block pointer type.
2550     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2551       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2552       return true;
2553     }
2554     ToPointeeType = ToBlockPtr->getPointeeType();
2555   }
2556   else if (FromType->getAs<BlockPointerType>() &&
2557            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2558     // Objective C++: We're able to convert from a block pointer type to a
2559     // pointer to any object.
2560     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2561     return true;
2562   }
2563   else
2564     return false;
2565 
2566   QualType FromPointeeType;
2567   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2568     FromPointeeType = FromCPtr->getPointeeType();
2569   else if (const BlockPointerType *FromBlockPtr =
2570            FromType->getAs<BlockPointerType>())
2571     FromPointeeType = FromBlockPtr->getPointeeType();
2572   else
2573     return false;
2574 
2575   // If we have pointers to pointers, recursively check whether this
2576   // is an Objective-C conversion.
2577   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2578       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2579                               IncompatibleObjC)) {
2580     // We always complain about this conversion.
2581     IncompatibleObjC = true;
2582     ConvertedType = Context.getPointerType(ConvertedType);
2583     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2584     return true;
2585   }
2586   // Allow conversion of pointee being objective-c pointer to another one;
2587   // as in I* to id.
2588   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2589       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2590       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2591                               IncompatibleObjC)) {
2592 
2593     ConvertedType = Context.getPointerType(ConvertedType);
2594     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595     return true;
2596   }
2597 
2598   // If we have pointers to functions or blocks, check whether the only
2599   // differences in the argument and result types are in Objective-C
2600   // pointer conversions. If so, we permit the conversion (but
2601   // complain about it).
2602   const FunctionProtoType *FromFunctionType
2603     = FromPointeeType->getAs<FunctionProtoType>();
2604   const FunctionProtoType *ToFunctionType
2605     = ToPointeeType->getAs<FunctionProtoType>();
2606   if (FromFunctionType && ToFunctionType) {
2607     // If the function types are exactly the same, this isn't an
2608     // Objective-C pointer conversion.
2609     if (Context.getCanonicalType(FromPointeeType)
2610           == Context.getCanonicalType(ToPointeeType))
2611       return false;
2612 
2613     // Perform the quick checks that will tell us whether these
2614     // function types are obviously different.
2615     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2616         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2617         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2618       return false;
2619 
2620     bool HasObjCConversion = false;
2621     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2622         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2623       // Okay, the types match exactly. Nothing to do.
2624     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2625                                        ToFunctionType->getReturnType(),
2626                                        ConvertedType, IncompatibleObjC)) {
2627       // Okay, we have an Objective-C pointer conversion.
2628       HasObjCConversion = true;
2629     } else {
2630       // Function types are too different. Abort.
2631       return false;
2632     }
2633 
2634     // Check argument types.
2635     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2636          ArgIdx != NumArgs; ++ArgIdx) {
2637       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2638       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2639       if (Context.getCanonicalType(FromArgType)
2640             == Context.getCanonicalType(ToArgType)) {
2641         // Okay, the types match exactly. Nothing to do.
2642       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2643                                          ConvertedType, IncompatibleObjC)) {
2644         // Okay, we have an Objective-C pointer conversion.
2645         HasObjCConversion = true;
2646       } else {
2647         // Argument types are too different. Abort.
2648         return false;
2649       }
2650     }
2651 
2652     if (HasObjCConversion) {
2653       // We had an Objective-C conversion. Allow this pointer
2654       // conversion, but complain about it.
2655       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2656       IncompatibleObjC = true;
2657       return true;
2658     }
2659   }
2660 
2661   return false;
2662 }
2663 
2664 /// Determine whether this is an Objective-C writeback conversion,
2665 /// used for parameter passing when performing automatic reference counting.
2666 ///
2667 /// \param FromType The type we're converting form.
2668 ///
2669 /// \param ToType The type we're converting to.
2670 ///
2671 /// \param ConvertedType The type that will be produced after applying
2672 /// this conversion.
2673 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2674                                      QualType &ConvertedType) {
2675   if (!getLangOpts().ObjCAutoRefCount ||
2676       Context.hasSameUnqualifiedType(FromType, ToType))
2677     return false;
2678 
2679   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2680   QualType ToPointee;
2681   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2682     ToPointee = ToPointer->getPointeeType();
2683   else
2684     return false;
2685 
2686   Qualifiers ToQuals = ToPointee.getQualifiers();
2687   if (!ToPointee->isObjCLifetimeType() ||
2688       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2689       !ToQuals.withoutObjCLifetime().empty())
2690     return false;
2691 
2692   // Argument must be a pointer to __strong to __weak.
2693   QualType FromPointee;
2694   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2695     FromPointee = FromPointer->getPointeeType();
2696   else
2697     return false;
2698 
2699   Qualifiers FromQuals = FromPointee.getQualifiers();
2700   if (!FromPointee->isObjCLifetimeType() ||
2701       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2702        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2703     return false;
2704 
2705   // Make sure that we have compatible qualifiers.
2706   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2707   if (!ToQuals.compatiblyIncludes(FromQuals))
2708     return false;
2709 
2710   // Remove qualifiers from the pointee type we're converting from; they
2711   // aren't used in the compatibility check belong, and we'll be adding back
2712   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2713   FromPointee = FromPointee.getUnqualifiedType();
2714 
2715   // The unqualified form of the pointee types must be compatible.
2716   ToPointee = ToPointee.getUnqualifiedType();
2717   bool IncompatibleObjC;
2718   if (Context.typesAreCompatible(FromPointee, ToPointee))
2719     FromPointee = ToPointee;
2720   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2721                                     IncompatibleObjC))
2722     return false;
2723 
2724   /// Construct the type we're converting to, which is a pointer to
2725   /// __autoreleasing pointee.
2726   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2727   ConvertedType = Context.getPointerType(FromPointee);
2728   return true;
2729 }
2730 
2731 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2732                                     QualType& ConvertedType) {
2733   QualType ToPointeeType;
2734   if (const BlockPointerType *ToBlockPtr =
2735         ToType->getAs<BlockPointerType>())
2736     ToPointeeType = ToBlockPtr->getPointeeType();
2737   else
2738     return false;
2739 
2740   QualType FromPointeeType;
2741   if (const BlockPointerType *FromBlockPtr =
2742       FromType->getAs<BlockPointerType>())
2743     FromPointeeType = FromBlockPtr->getPointeeType();
2744   else
2745     return false;
2746   // We have pointer to blocks, check whether the only
2747   // differences in the argument and result types are in Objective-C
2748   // pointer conversions. If so, we permit the conversion.
2749 
2750   const FunctionProtoType *FromFunctionType
2751     = FromPointeeType->getAs<FunctionProtoType>();
2752   const FunctionProtoType *ToFunctionType
2753     = ToPointeeType->getAs<FunctionProtoType>();
2754 
2755   if (!FromFunctionType || !ToFunctionType)
2756     return false;
2757 
2758   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2759     return true;
2760 
2761   // Perform the quick checks that will tell us whether these
2762   // function types are obviously different.
2763   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2764       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2765     return false;
2766 
2767   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2768   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2769   if (FromEInfo != ToEInfo)
2770     return false;
2771 
2772   bool IncompatibleObjC = false;
2773   if (Context.hasSameType(FromFunctionType->getReturnType(),
2774                           ToFunctionType->getReturnType())) {
2775     // Okay, the types match exactly. Nothing to do.
2776   } else {
2777     QualType RHS = FromFunctionType->getReturnType();
2778     QualType LHS = ToFunctionType->getReturnType();
2779     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2780         !RHS.hasQualifiers() && LHS.hasQualifiers())
2781        LHS = LHS.getUnqualifiedType();
2782 
2783      if (Context.hasSameType(RHS,LHS)) {
2784        // OK exact match.
2785      } else if (isObjCPointerConversion(RHS, LHS,
2786                                         ConvertedType, IncompatibleObjC)) {
2787      if (IncompatibleObjC)
2788        return false;
2789      // Okay, we have an Objective-C pointer conversion.
2790      }
2791      else
2792        return false;
2793    }
2794 
2795    // Check argument types.
2796    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2797         ArgIdx != NumArgs; ++ArgIdx) {
2798      IncompatibleObjC = false;
2799      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2800      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2801      if (Context.hasSameType(FromArgType, ToArgType)) {
2802        // Okay, the types match exactly. Nothing to do.
2803      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2804                                         ConvertedType, IncompatibleObjC)) {
2805        if (IncompatibleObjC)
2806          return false;
2807        // Okay, we have an Objective-C pointer conversion.
2808      } else
2809        // Argument types are too different. Abort.
2810        return false;
2811    }
2812 
2813    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2814    bool CanUseToFPT, CanUseFromFPT;
2815    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2816                                       CanUseToFPT, CanUseFromFPT,
2817                                       NewParamInfos))
2818      return false;
2819 
2820    ConvertedType = ToType;
2821    return true;
2822 }
2823 
2824 enum {
2825   ft_default,
2826   ft_different_class,
2827   ft_parameter_arity,
2828   ft_parameter_mismatch,
2829   ft_return_type,
2830   ft_qualifer_mismatch,
2831   ft_noexcept
2832 };
2833 
2834 /// Attempts to get the FunctionProtoType from a Type. Handles
2835 /// MemberFunctionPointers properly.
2836 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2837   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2838     return FPT;
2839 
2840   if (auto *MPT = FromType->getAs<MemberPointerType>())
2841     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2842 
2843   return nullptr;
2844 }
2845 
2846 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2847 /// function types.  Catches different number of parameter, mismatch in
2848 /// parameter types, and different return types.
2849 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2850                                       QualType FromType, QualType ToType) {
2851   // If either type is not valid, include no extra info.
2852   if (FromType.isNull() || ToType.isNull()) {
2853     PDiag << ft_default;
2854     return;
2855   }
2856 
2857   // Get the function type from the pointers.
2858   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2859     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2860                *ToMember = ToType->castAs<MemberPointerType>();
2861     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2862       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2863             << QualType(FromMember->getClass(), 0);
2864       return;
2865     }
2866     FromType = FromMember->getPointeeType();
2867     ToType = ToMember->getPointeeType();
2868   }
2869 
2870   if (FromType->isPointerType())
2871     FromType = FromType->getPointeeType();
2872   if (ToType->isPointerType())
2873     ToType = ToType->getPointeeType();
2874 
2875   // Remove references.
2876   FromType = FromType.getNonReferenceType();
2877   ToType = ToType.getNonReferenceType();
2878 
2879   // Don't print extra info for non-specialized template functions.
2880   if (FromType->isInstantiationDependentType() &&
2881       !FromType->getAs<TemplateSpecializationType>()) {
2882     PDiag << ft_default;
2883     return;
2884   }
2885 
2886   // No extra info for same types.
2887   if (Context.hasSameType(FromType, ToType)) {
2888     PDiag << ft_default;
2889     return;
2890   }
2891 
2892   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2893                           *ToFunction = tryGetFunctionProtoType(ToType);
2894 
2895   // Both types need to be function types.
2896   if (!FromFunction || !ToFunction) {
2897     PDiag << ft_default;
2898     return;
2899   }
2900 
2901   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2902     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2903           << FromFunction->getNumParams();
2904     return;
2905   }
2906 
2907   // Handle different parameter types.
2908   unsigned ArgPos;
2909   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2910     PDiag << ft_parameter_mismatch << ArgPos + 1
2911           << ToFunction->getParamType(ArgPos)
2912           << FromFunction->getParamType(ArgPos);
2913     return;
2914   }
2915 
2916   // Handle different return type.
2917   if (!Context.hasSameType(FromFunction->getReturnType(),
2918                            ToFunction->getReturnType())) {
2919     PDiag << ft_return_type << ToFunction->getReturnType()
2920           << FromFunction->getReturnType();
2921     return;
2922   }
2923 
2924   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2925     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2926           << FromFunction->getMethodQuals();
2927     return;
2928   }
2929 
2930   // Handle exception specification differences on canonical type (in C++17
2931   // onwards).
2932   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2933           ->isNothrow() !=
2934       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2935           ->isNothrow()) {
2936     PDiag << ft_noexcept;
2937     return;
2938   }
2939 
2940   // Unable to find a difference, so add no extra info.
2941   PDiag << ft_default;
2942 }
2943 
2944 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2945 /// for equality of their argument types. Caller has already checked that
2946 /// they have same number of arguments.  If the parameters are different,
2947 /// ArgPos will have the parameter index of the first different parameter.
2948 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2949                                       const FunctionProtoType *NewType,
2950                                       unsigned *ArgPos) {
2951   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2952                                               N = NewType->param_type_begin(),
2953                                               E = OldType->param_type_end();
2954        O && (O != E); ++O, ++N) {
2955     // Ignore address spaces in pointee type. This is to disallow overloading
2956     // on __ptr32/__ptr64 address spaces.
2957     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2958     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2959 
2960     if (!Context.hasSameType(Old, New)) {
2961       if (ArgPos)
2962         *ArgPos = O - OldType->param_type_begin();
2963       return false;
2964     }
2965   }
2966   return true;
2967 }
2968 
2969 /// CheckPointerConversion - Check the pointer conversion from the
2970 /// expression From to the type ToType. This routine checks for
2971 /// ambiguous or inaccessible derived-to-base pointer
2972 /// conversions for which IsPointerConversion has already returned
2973 /// true. It returns true and produces a diagnostic if there was an
2974 /// error, or returns false otherwise.
2975 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2976                                   CastKind &Kind,
2977                                   CXXCastPath& BasePath,
2978                                   bool IgnoreBaseAccess,
2979                                   bool Diagnose) {
2980   QualType FromType = From->getType();
2981   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2982 
2983   Kind = CK_BitCast;
2984 
2985   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2986       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2987           Expr::NPCK_ZeroExpression) {
2988     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2989       DiagRuntimeBehavior(From->getExprLoc(), From,
2990                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2991                             << ToType << From->getSourceRange());
2992     else if (!isUnevaluatedContext())
2993       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2994         << ToType << From->getSourceRange();
2995   }
2996   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2997     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2998       QualType FromPointeeType = FromPtrType->getPointeeType(),
2999                ToPointeeType   = ToPtrType->getPointeeType();
3000 
3001       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3002           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3003         // We must have a derived-to-base conversion. Check an
3004         // ambiguous or inaccessible conversion.
3005         unsigned InaccessibleID = 0;
3006         unsigned AmbiguousID = 0;
3007         if (Diagnose) {
3008           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3009           AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3010         }
3011         if (CheckDerivedToBaseConversion(
3012                 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3013                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3014                 &BasePath, IgnoreBaseAccess))
3015           return true;
3016 
3017         // The conversion was successful.
3018         Kind = CK_DerivedToBase;
3019       }
3020 
3021       if (Diagnose && !IsCStyleOrFunctionalCast &&
3022           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3023         assert(getLangOpts().MSVCCompat &&
3024                "this should only be possible with MSVCCompat!");
3025         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3026             << From->getSourceRange();
3027       }
3028     }
3029   } else if (const ObjCObjectPointerType *ToPtrType =
3030                ToType->getAs<ObjCObjectPointerType>()) {
3031     if (const ObjCObjectPointerType *FromPtrType =
3032           FromType->getAs<ObjCObjectPointerType>()) {
3033       // Objective-C++ conversions are always okay.
3034       // FIXME: We should have a different class of conversions for the
3035       // Objective-C++ implicit conversions.
3036       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3037         return false;
3038     } else if (FromType->isBlockPointerType()) {
3039       Kind = CK_BlockPointerToObjCPointerCast;
3040     } else {
3041       Kind = CK_CPointerToObjCPointerCast;
3042     }
3043   } else if (ToType->isBlockPointerType()) {
3044     if (!FromType->isBlockPointerType())
3045       Kind = CK_AnyPointerToBlockPointerCast;
3046   }
3047 
3048   // We shouldn't fall into this case unless it's valid for other
3049   // reasons.
3050   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3051     Kind = CK_NullToPointer;
3052 
3053   return false;
3054 }
3055 
3056 /// IsMemberPointerConversion - Determines whether the conversion of the
3057 /// expression From, which has the (possibly adjusted) type FromType, can be
3058 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3059 /// If so, returns true and places the converted type (that might differ from
3060 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3061 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3062                                      QualType ToType,
3063                                      bool InOverloadResolution,
3064                                      QualType &ConvertedType) {
3065   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3066   if (!ToTypePtr)
3067     return false;
3068 
3069   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3070   if (From->isNullPointerConstant(Context,
3071                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3072                                         : Expr::NPC_ValueDependentIsNull)) {
3073     ConvertedType = ToType;
3074     return true;
3075   }
3076 
3077   // Otherwise, both types have to be member pointers.
3078   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3079   if (!FromTypePtr)
3080     return false;
3081 
3082   // A pointer to member of B can be converted to a pointer to member of D,
3083   // where D is derived from B (C++ 4.11p2).
3084   QualType FromClass(FromTypePtr->getClass(), 0);
3085   QualType ToClass(ToTypePtr->getClass(), 0);
3086 
3087   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3088       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3089     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3090                                                  ToClass.getTypePtr());
3091     return true;
3092   }
3093 
3094   return false;
3095 }
3096 
3097 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3098 /// expression From to the type ToType. This routine checks for ambiguous or
3099 /// virtual or inaccessible base-to-derived member pointer conversions
3100 /// for which IsMemberPointerConversion has already returned true. It returns
3101 /// true and produces a diagnostic if there was an error, or returns false
3102 /// otherwise.
3103 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3104                                         CastKind &Kind,
3105                                         CXXCastPath &BasePath,
3106                                         bool IgnoreBaseAccess) {
3107   QualType FromType = From->getType();
3108   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3109   if (!FromPtrType) {
3110     // This must be a null pointer to member pointer conversion
3111     assert(From->isNullPointerConstant(Context,
3112                                        Expr::NPC_ValueDependentIsNull) &&
3113            "Expr must be null pointer constant!");
3114     Kind = CK_NullToMemberPointer;
3115     return false;
3116   }
3117 
3118   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3119   assert(ToPtrType && "No member pointer cast has a target type "
3120                       "that is not a member pointer.");
3121 
3122   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3123   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3124 
3125   // FIXME: What about dependent types?
3126   assert(FromClass->isRecordType() && "Pointer into non-class.");
3127   assert(ToClass->isRecordType() && "Pointer into non-class.");
3128 
3129   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3130                      /*DetectVirtual=*/true);
3131   bool DerivationOkay =
3132       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3133   assert(DerivationOkay &&
3134          "Should not have been called if derivation isn't OK.");
3135   (void)DerivationOkay;
3136 
3137   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3138                                   getUnqualifiedType())) {
3139     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3140     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3141       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3142     return true;
3143   }
3144 
3145   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3146     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3147       << FromClass << ToClass << QualType(VBase, 0)
3148       << From->getSourceRange();
3149     return true;
3150   }
3151 
3152   if (!IgnoreBaseAccess)
3153     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3154                          Paths.front(),
3155                          diag::err_downcast_from_inaccessible_base);
3156 
3157   // Must be a base to derived member conversion.
3158   BuildBasePathArray(Paths, BasePath);
3159   Kind = CK_BaseToDerivedMemberPointer;
3160   return false;
3161 }
3162 
3163 /// Determine whether the lifetime conversion between the two given
3164 /// qualifiers sets is nontrivial.
3165 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3166                                                Qualifiers ToQuals) {
3167   // Converting anything to const __unsafe_unretained is trivial.
3168   if (ToQuals.hasConst() &&
3169       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3170     return false;
3171 
3172   return true;
3173 }
3174 
3175 /// Perform a single iteration of the loop for checking if a qualification
3176 /// conversion is valid.
3177 ///
3178 /// Specifically, check whether any change between the qualifiers of \p
3179 /// FromType and \p ToType is permissible, given knowledge about whether every
3180 /// outer layer is const-qualified.
3181 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3182                                           bool CStyle, bool IsTopLevel,
3183                                           bool &PreviousToQualsIncludeConst,
3184                                           bool &ObjCLifetimeConversion) {
3185   Qualifiers FromQuals = FromType.getQualifiers();
3186   Qualifiers ToQuals = ToType.getQualifiers();
3187 
3188   // Ignore __unaligned qualifier if this type is void.
3189   if (ToType.getUnqualifiedType()->isVoidType())
3190     FromQuals.removeUnaligned();
3191 
3192   // Objective-C ARC:
3193   //   Check Objective-C lifetime conversions.
3194   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3195     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3196       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3197         ObjCLifetimeConversion = true;
3198       FromQuals.removeObjCLifetime();
3199       ToQuals.removeObjCLifetime();
3200     } else {
3201       // Qualification conversions cannot cast between different
3202       // Objective-C lifetime qualifiers.
3203       return false;
3204     }
3205   }
3206 
3207   // Allow addition/removal of GC attributes but not changing GC attributes.
3208   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3209       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3210     FromQuals.removeObjCGCAttr();
3211     ToQuals.removeObjCGCAttr();
3212   }
3213 
3214   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3215   //      2,j, and similarly for volatile.
3216   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3217     return false;
3218 
3219   // If address spaces mismatch:
3220   //  - in top level it is only valid to convert to addr space that is a
3221   //    superset in all cases apart from C-style casts where we allow
3222   //    conversions between overlapping address spaces.
3223   //  - in non-top levels it is not a valid conversion.
3224   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3225       (!IsTopLevel ||
3226        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3227          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3228     return false;
3229 
3230   //   -- if the cv 1,j and cv 2,j are different, then const is in
3231   //      every cv for 0 < k < j.
3232   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3233       !PreviousToQualsIncludeConst)
3234     return false;
3235 
3236   // Keep track of whether all prior cv-qualifiers in the "to" type
3237   // include const.
3238   PreviousToQualsIncludeConst =
3239       PreviousToQualsIncludeConst && ToQuals.hasConst();
3240   return true;
3241 }
3242 
3243 /// IsQualificationConversion - Determines whether the conversion from
3244 /// an rvalue of type FromType to ToType is a qualification conversion
3245 /// (C++ 4.4).
3246 ///
3247 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3248 /// when the qualification conversion involves a change in the Objective-C
3249 /// object lifetime.
3250 bool
3251 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3252                                 bool CStyle, bool &ObjCLifetimeConversion) {
3253   FromType = Context.getCanonicalType(FromType);
3254   ToType = Context.getCanonicalType(ToType);
3255   ObjCLifetimeConversion = false;
3256 
3257   // If FromType and ToType are the same type, this is not a
3258   // qualification conversion.
3259   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3260     return false;
3261 
3262   // (C++ 4.4p4):
3263   //   A conversion can add cv-qualifiers at levels other than the first
3264   //   in multi-level pointers, subject to the following rules: [...]
3265   bool PreviousToQualsIncludeConst = true;
3266   bool UnwrappedAnyPointer = false;
3267   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3268     if (!isQualificationConversionStep(
3269             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3270             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3271       return false;
3272     UnwrappedAnyPointer = true;
3273   }
3274 
3275   // We are left with FromType and ToType being the pointee types
3276   // after unwrapping the original FromType and ToType the same number
3277   // of times. If we unwrapped any pointers, and if FromType and
3278   // ToType have the same unqualified type (since we checked
3279   // qualifiers above), then this is a qualification conversion.
3280   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3281 }
3282 
3283 /// - Determine whether this is a conversion from a scalar type to an
3284 /// atomic type.
3285 ///
3286 /// If successful, updates \c SCS's second and third steps in the conversion
3287 /// sequence to finish the conversion.
3288 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3289                                 bool InOverloadResolution,
3290                                 StandardConversionSequence &SCS,
3291                                 bool CStyle) {
3292   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3293   if (!ToAtomic)
3294     return false;
3295 
3296   StandardConversionSequence InnerSCS;
3297   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3298                             InOverloadResolution, InnerSCS,
3299                             CStyle, /*AllowObjCWritebackConversion=*/false))
3300     return false;
3301 
3302   SCS.Second = InnerSCS.Second;
3303   SCS.setToType(1, InnerSCS.getToType(1));
3304   SCS.Third = InnerSCS.Third;
3305   SCS.QualificationIncludesObjCLifetime
3306     = InnerSCS.QualificationIncludesObjCLifetime;
3307   SCS.setToType(2, InnerSCS.getToType(2));
3308   return true;
3309 }
3310 
3311 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3312                                               CXXConstructorDecl *Constructor,
3313                                               QualType Type) {
3314   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3315   if (CtorType->getNumParams() > 0) {
3316     QualType FirstArg = CtorType->getParamType(0);
3317     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3318       return true;
3319   }
3320   return false;
3321 }
3322 
3323 static OverloadingResult
3324 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3325                                        CXXRecordDecl *To,
3326                                        UserDefinedConversionSequence &User,
3327                                        OverloadCandidateSet &CandidateSet,
3328                                        bool AllowExplicit) {
3329   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3330   for (auto *D : S.LookupConstructors(To)) {
3331     auto Info = getConstructorInfo(D);
3332     if (!Info)
3333       continue;
3334 
3335     bool Usable = !Info.Constructor->isInvalidDecl() &&
3336                   S.isInitListConstructor(Info.Constructor);
3337     if (Usable) {
3338       // If the first argument is (a reference to) the target type,
3339       // suppress conversions.
3340       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3341           S.Context, Info.Constructor, ToType);
3342       if (Info.ConstructorTmpl)
3343         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3344                                        /*ExplicitArgs*/ nullptr, From,
3345                                        CandidateSet, SuppressUserConversions,
3346                                        /*PartialOverloading*/ false,
3347                                        AllowExplicit);
3348       else
3349         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3350                                CandidateSet, SuppressUserConversions,
3351                                /*PartialOverloading*/ false, AllowExplicit);
3352     }
3353   }
3354 
3355   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3356 
3357   OverloadCandidateSet::iterator Best;
3358   switch (auto Result =
3359               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3360   case OR_Deleted:
3361   case OR_Success: {
3362     // Record the standard conversion we used and the conversion function.
3363     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3364     QualType ThisType = Constructor->getThisType();
3365     // Initializer lists don't have conversions as such.
3366     User.Before.setAsIdentityConversion();
3367     User.HadMultipleCandidates = HadMultipleCandidates;
3368     User.ConversionFunction = Constructor;
3369     User.FoundConversionFunction = Best->FoundDecl;
3370     User.After.setAsIdentityConversion();
3371     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3372     User.After.setAllToTypes(ToType);
3373     return Result;
3374   }
3375 
3376   case OR_No_Viable_Function:
3377     return OR_No_Viable_Function;
3378   case OR_Ambiguous:
3379     return OR_Ambiguous;
3380   }
3381 
3382   llvm_unreachable("Invalid OverloadResult!");
3383 }
3384 
3385 /// Determines whether there is a user-defined conversion sequence
3386 /// (C++ [over.ics.user]) that converts expression From to the type
3387 /// ToType. If such a conversion exists, User will contain the
3388 /// user-defined conversion sequence that performs such a conversion
3389 /// and this routine will return true. Otherwise, this routine returns
3390 /// false and User is unspecified.
3391 ///
3392 /// \param AllowExplicit  true if the conversion should consider C++0x
3393 /// "explicit" conversion functions as well as non-explicit conversion
3394 /// functions (C++0x [class.conv.fct]p2).
3395 ///
3396 /// \param AllowObjCConversionOnExplicit true if the conversion should
3397 /// allow an extra Objective-C pointer conversion on uses of explicit
3398 /// constructors. Requires \c AllowExplicit to also be set.
3399 static OverloadingResult
3400 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3401                         UserDefinedConversionSequence &User,
3402                         OverloadCandidateSet &CandidateSet,
3403                         AllowedExplicit AllowExplicit,
3404                         bool AllowObjCConversionOnExplicit) {
3405   assert(AllowExplicit != AllowedExplicit::None ||
3406          !AllowObjCConversionOnExplicit);
3407   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3408 
3409   // Whether we will only visit constructors.
3410   bool ConstructorsOnly = false;
3411 
3412   // If the type we are conversion to is a class type, enumerate its
3413   // constructors.
3414   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3415     // C++ [over.match.ctor]p1:
3416     //   When objects of class type are direct-initialized (8.5), or
3417     //   copy-initialized from an expression of the same or a
3418     //   derived class type (8.5), overload resolution selects the
3419     //   constructor. [...] For copy-initialization, the candidate
3420     //   functions are all the converting constructors (12.3.1) of
3421     //   that class. The argument list is the expression-list within
3422     //   the parentheses of the initializer.
3423     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3424         (From->getType()->getAs<RecordType>() &&
3425          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3426       ConstructorsOnly = true;
3427 
3428     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3429       // We're not going to find any constructors.
3430     } else if (CXXRecordDecl *ToRecordDecl
3431                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3432 
3433       Expr **Args = &From;
3434       unsigned NumArgs = 1;
3435       bool ListInitializing = false;
3436       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3437         // But first, see if there is an init-list-constructor that will work.
3438         OverloadingResult Result = IsInitializerListConstructorConversion(
3439             S, From, ToType, ToRecordDecl, User, CandidateSet,
3440             AllowExplicit == AllowedExplicit::All);
3441         if (Result != OR_No_Viable_Function)
3442           return Result;
3443         // Never mind.
3444         CandidateSet.clear(
3445             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3446 
3447         // If we're list-initializing, we pass the individual elements as
3448         // arguments, not the entire list.
3449         Args = InitList->getInits();
3450         NumArgs = InitList->getNumInits();
3451         ListInitializing = true;
3452       }
3453 
3454       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3455         auto Info = getConstructorInfo(D);
3456         if (!Info)
3457           continue;
3458 
3459         bool Usable = !Info.Constructor->isInvalidDecl();
3460         if (!ListInitializing)
3461           Usable = Usable && Info.Constructor->isConvertingConstructor(
3462                                  /*AllowExplicit*/ true);
3463         if (Usable) {
3464           bool SuppressUserConversions = !ConstructorsOnly;
3465           if (SuppressUserConversions && ListInitializing) {
3466             SuppressUserConversions = false;
3467             if (NumArgs == 1) {
3468               // If the first argument is (a reference to) the target type,
3469               // suppress conversions.
3470               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3471                   S.Context, Info.Constructor, ToType);
3472             }
3473           }
3474           if (Info.ConstructorTmpl)
3475             S.AddTemplateOverloadCandidate(
3476                 Info.ConstructorTmpl, Info.FoundDecl,
3477                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3478                 CandidateSet, SuppressUserConversions,
3479                 /*PartialOverloading*/ false,
3480                 AllowExplicit == AllowedExplicit::All);
3481           else
3482             // Allow one user-defined conversion when user specifies a
3483             // From->ToType conversion via an static cast (c-style, etc).
3484             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3485                                    llvm::makeArrayRef(Args, NumArgs),
3486                                    CandidateSet, SuppressUserConversions,
3487                                    /*PartialOverloading*/ false,
3488                                    AllowExplicit == AllowedExplicit::All);
3489         }
3490       }
3491     }
3492   }
3493 
3494   // Enumerate conversion functions, if we're allowed to.
3495   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3496   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3497     // No conversion functions from incomplete types.
3498   } else if (const RecordType *FromRecordType =
3499                  From->getType()->getAs<RecordType>()) {
3500     if (CXXRecordDecl *FromRecordDecl
3501          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3502       // Add all of the conversion functions as candidates.
3503       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3504       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3505         DeclAccessPair FoundDecl = I.getPair();
3506         NamedDecl *D = FoundDecl.getDecl();
3507         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3508         if (isa<UsingShadowDecl>(D))
3509           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3510 
3511         CXXConversionDecl *Conv;
3512         FunctionTemplateDecl *ConvTemplate;
3513         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3514           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3515         else
3516           Conv = cast<CXXConversionDecl>(D);
3517 
3518         if (ConvTemplate)
3519           S.AddTemplateConversionCandidate(
3520               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3521               CandidateSet, AllowObjCConversionOnExplicit,
3522               AllowExplicit != AllowedExplicit::None);
3523         else
3524           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3525                                    CandidateSet, AllowObjCConversionOnExplicit,
3526                                    AllowExplicit != AllowedExplicit::None);
3527       }
3528     }
3529   }
3530 
3531   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3532 
3533   OverloadCandidateSet::iterator Best;
3534   switch (auto Result =
3535               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3536   case OR_Success:
3537   case OR_Deleted:
3538     // Record the standard conversion we used and the conversion function.
3539     if (CXXConstructorDecl *Constructor
3540           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3541       // C++ [over.ics.user]p1:
3542       //   If the user-defined conversion is specified by a
3543       //   constructor (12.3.1), the initial standard conversion
3544       //   sequence converts the source type to the type required by
3545       //   the argument of the constructor.
3546       //
3547       QualType ThisType = Constructor->getThisType();
3548       if (isa<InitListExpr>(From)) {
3549         // Initializer lists don't have conversions as such.
3550         User.Before.setAsIdentityConversion();
3551       } else {
3552         if (Best->Conversions[0].isEllipsis())
3553           User.EllipsisConversion = true;
3554         else {
3555           User.Before = Best->Conversions[0].Standard;
3556           User.EllipsisConversion = false;
3557         }
3558       }
3559       User.HadMultipleCandidates = HadMultipleCandidates;
3560       User.ConversionFunction = Constructor;
3561       User.FoundConversionFunction = Best->FoundDecl;
3562       User.After.setAsIdentityConversion();
3563       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3564       User.After.setAllToTypes(ToType);
3565       return Result;
3566     }
3567     if (CXXConversionDecl *Conversion
3568                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3569       // C++ [over.ics.user]p1:
3570       //
3571       //   [...] If the user-defined conversion is specified by a
3572       //   conversion function (12.3.2), the initial standard
3573       //   conversion sequence converts the source type to the
3574       //   implicit object parameter of the conversion function.
3575       User.Before = Best->Conversions[0].Standard;
3576       User.HadMultipleCandidates = HadMultipleCandidates;
3577       User.ConversionFunction = Conversion;
3578       User.FoundConversionFunction = Best->FoundDecl;
3579       User.EllipsisConversion = false;
3580 
3581       // C++ [over.ics.user]p2:
3582       //   The second standard conversion sequence converts the
3583       //   result of the user-defined conversion to the target type
3584       //   for the sequence. Since an implicit conversion sequence
3585       //   is an initialization, the special rules for
3586       //   initialization by user-defined conversion apply when
3587       //   selecting the best user-defined conversion for a
3588       //   user-defined conversion sequence (see 13.3.3 and
3589       //   13.3.3.1).
3590       User.After = Best->FinalConversion;
3591       return Result;
3592     }
3593     llvm_unreachable("Not a constructor or conversion function?");
3594 
3595   case OR_No_Viable_Function:
3596     return OR_No_Viable_Function;
3597 
3598   case OR_Ambiguous:
3599     return OR_Ambiguous;
3600   }
3601 
3602   llvm_unreachable("Invalid OverloadResult!");
3603 }
3604 
3605 bool
3606 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3607   ImplicitConversionSequence ICS;
3608   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3609                                     OverloadCandidateSet::CSK_Normal);
3610   OverloadingResult OvResult =
3611     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3612                             CandidateSet, AllowedExplicit::None, false);
3613 
3614   if (!(OvResult == OR_Ambiguous ||
3615         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3616     return false;
3617 
3618   auto Cands = CandidateSet.CompleteCandidates(
3619       *this,
3620       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3621       From);
3622   if (OvResult == OR_Ambiguous)
3623     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3624         << From->getType() << ToType << From->getSourceRange();
3625   else { // OR_No_Viable_Function && !CandidateSet.empty()
3626     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3627                              diag::err_typecheck_nonviable_condition_incomplete,
3628                              From->getType(), From->getSourceRange()))
3629       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3630           << false << From->getType() << From->getSourceRange() << ToType;
3631   }
3632 
3633   CandidateSet.NoteCandidates(
3634                               *this, From, Cands);
3635   return true;
3636 }
3637 
3638 /// Compare the user-defined conversion functions or constructors
3639 /// of two user-defined conversion sequences to determine whether any ordering
3640 /// is possible.
3641 static ImplicitConversionSequence::CompareKind
3642 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3643                            FunctionDecl *Function2) {
3644   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3645     return ImplicitConversionSequence::Indistinguishable;
3646 
3647   // Objective-C++:
3648   //   If both conversion functions are implicitly-declared conversions from
3649   //   a lambda closure type to a function pointer and a block pointer,
3650   //   respectively, always prefer the conversion to a function pointer,
3651   //   because the function pointer is more lightweight and is more likely
3652   //   to keep code working.
3653   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3654   if (!Conv1)
3655     return ImplicitConversionSequence::Indistinguishable;
3656 
3657   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3658   if (!Conv2)
3659     return ImplicitConversionSequence::Indistinguishable;
3660 
3661   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3662     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3663     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3664     if (Block1 != Block2)
3665       return Block1 ? ImplicitConversionSequence::Worse
3666                     : ImplicitConversionSequence::Better;
3667   }
3668 
3669   return ImplicitConversionSequence::Indistinguishable;
3670 }
3671 
3672 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3673     const ImplicitConversionSequence &ICS) {
3674   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3675          (ICS.isUserDefined() &&
3676           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3677 }
3678 
3679 /// CompareImplicitConversionSequences - Compare two implicit
3680 /// conversion sequences to determine whether one is better than the
3681 /// other or if they are indistinguishable (C++ 13.3.3.2).
3682 static ImplicitConversionSequence::CompareKind
3683 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3684                                    const ImplicitConversionSequence& ICS1,
3685                                    const ImplicitConversionSequence& ICS2)
3686 {
3687   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3688   // conversion sequences (as defined in 13.3.3.1)
3689   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3690   //      conversion sequence than a user-defined conversion sequence or
3691   //      an ellipsis conversion sequence, and
3692   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3693   //      conversion sequence than an ellipsis conversion sequence
3694   //      (13.3.3.1.3).
3695   //
3696   // C++0x [over.best.ics]p10:
3697   //   For the purpose of ranking implicit conversion sequences as
3698   //   described in 13.3.3.2, the ambiguous conversion sequence is
3699   //   treated as a user-defined sequence that is indistinguishable
3700   //   from any other user-defined conversion sequence.
3701 
3702   // String literal to 'char *' conversion has been deprecated in C++03. It has
3703   // been removed from C++11. We still accept this conversion, if it happens at
3704   // the best viable function. Otherwise, this conversion is considered worse
3705   // than ellipsis conversion. Consider this as an extension; this is not in the
3706   // standard. For example:
3707   //
3708   // int &f(...);    // #1
3709   // void f(char*);  // #2
3710   // void g() { int &r = f("foo"); }
3711   //
3712   // In C++03, we pick #2 as the best viable function.
3713   // In C++11, we pick #1 as the best viable function, because ellipsis
3714   // conversion is better than string-literal to char* conversion (since there
3715   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3716   // convert arguments, #2 would be the best viable function in C++11.
3717   // If the best viable function has this conversion, a warning will be issued
3718   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3719 
3720   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3721       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3722       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3723     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3724                ? ImplicitConversionSequence::Worse
3725                : ImplicitConversionSequence::Better;
3726 
3727   if (ICS1.getKindRank() < ICS2.getKindRank())
3728     return ImplicitConversionSequence::Better;
3729   if (ICS2.getKindRank() < ICS1.getKindRank())
3730     return ImplicitConversionSequence::Worse;
3731 
3732   // The following checks require both conversion sequences to be of
3733   // the same kind.
3734   if (ICS1.getKind() != ICS2.getKind())
3735     return ImplicitConversionSequence::Indistinguishable;
3736 
3737   ImplicitConversionSequence::CompareKind Result =
3738       ImplicitConversionSequence::Indistinguishable;
3739 
3740   // Two implicit conversion sequences of the same form are
3741   // indistinguishable conversion sequences unless one of the
3742   // following rules apply: (C++ 13.3.3.2p3):
3743 
3744   // List-initialization sequence L1 is a better conversion sequence than
3745   // list-initialization sequence L2 if:
3746   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3747   //   if not that,
3748   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3749   //   and N1 is smaller than N2.,
3750   // even if one of the other rules in this paragraph would otherwise apply.
3751   if (!ICS1.isBad()) {
3752     if (ICS1.isStdInitializerListElement() &&
3753         !ICS2.isStdInitializerListElement())
3754       return ImplicitConversionSequence::Better;
3755     if (!ICS1.isStdInitializerListElement() &&
3756         ICS2.isStdInitializerListElement())
3757       return ImplicitConversionSequence::Worse;
3758   }
3759 
3760   if (ICS1.isStandard())
3761     // Standard conversion sequence S1 is a better conversion sequence than
3762     // standard conversion sequence S2 if [...]
3763     Result = CompareStandardConversionSequences(S, Loc,
3764                                                 ICS1.Standard, ICS2.Standard);
3765   else if (ICS1.isUserDefined()) {
3766     // User-defined conversion sequence U1 is a better conversion
3767     // sequence than another user-defined conversion sequence U2 if
3768     // they contain the same user-defined conversion function or
3769     // constructor and if the second standard conversion sequence of
3770     // U1 is better than the second standard conversion sequence of
3771     // U2 (C++ 13.3.3.2p3).
3772     if (ICS1.UserDefined.ConversionFunction ==
3773           ICS2.UserDefined.ConversionFunction)
3774       Result = CompareStandardConversionSequences(S, Loc,
3775                                                   ICS1.UserDefined.After,
3776                                                   ICS2.UserDefined.After);
3777     else
3778       Result = compareConversionFunctions(S,
3779                                           ICS1.UserDefined.ConversionFunction,
3780                                           ICS2.UserDefined.ConversionFunction);
3781   }
3782 
3783   return Result;
3784 }
3785 
3786 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3787 // determine if one is a proper subset of the other.
3788 static ImplicitConversionSequence::CompareKind
3789 compareStandardConversionSubsets(ASTContext &Context,
3790                                  const StandardConversionSequence& SCS1,
3791                                  const StandardConversionSequence& SCS2) {
3792   ImplicitConversionSequence::CompareKind Result
3793     = ImplicitConversionSequence::Indistinguishable;
3794 
3795   // the identity conversion sequence is considered to be a subsequence of
3796   // any non-identity conversion sequence
3797   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3798     return ImplicitConversionSequence::Better;
3799   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3800     return ImplicitConversionSequence::Worse;
3801 
3802   if (SCS1.Second != SCS2.Second) {
3803     if (SCS1.Second == ICK_Identity)
3804       Result = ImplicitConversionSequence::Better;
3805     else if (SCS2.Second == ICK_Identity)
3806       Result = ImplicitConversionSequence::Worse;
3807     else
3808       return ImplicitConversionSequence::Indistinguishable;
3809   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3810     return ImplicitConversionSequence::Indistinguishable;
3811 
3812   if (SCS1.Third == SCS2.Third) {
3813     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3814                              : ImplicitConversionSequence::Indistinguishable;
3815   }
3816 
3817   if (SCS1.Third == ICK_Identity)
3818     return Result == ImplicitConversionSequence::Worse
3819              ? ImplicitConversionSequence::Indistinguishable
3820              : ImplicitConversionSequence::Better;
3821 
3822   if (SCS2.Third == ICK_Identity)
3823     return Result == ImplicitConversionSequence::Better
3824              ? ImplicitConversionSequence::Indistinguishable
3825              : ImplicitConversionSequence::Worse;
3826 
3827   return ImplicitConversionSequence::Indistinguishable;
3828 }
3829 
3830 /// Determine whether one of the given reference bindings is better
3831 /// than the other based on what kind of bindings they are.
3832 static bool
3833 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3834                              const StandardConversionSequence &SCS2) {
3835   // C++0x [over.ics.rank]p3b4:
3836   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3837   //      implicit object parameter of a non-static member function declared
3838   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3839   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3840   //      lvalue reference to a function lvalue and S2 binds an rvalue
3841   //      reference*.
3842   //
3843   // FIXME: Rvalue references. We're going rogue with the above edits,
3844   // because the semantics in the current C++0x working paper (N3225 at the
3845   // time of this writing) break the standard definition of std::forward
3846   // and std::reference_wrapper when dealing with references to functions.
3847   // Proposed wording changes submitted to CWG for consideration.
3848   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3849       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3850     return false;
3851 
3852   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3853           SCS2.IsLvalueReference) ||
3854          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3855           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3856 }
3857 
3858 enum class FixedEnumPromotion {
3859   None,
3860   ToUnderlyingType,
3861   ToPromotedUnderlyingType
3862 };
3863 
3864 /// Returns kind of fixed enum promotion the \a SCS uses.
3865 static FixedEnumPromotion
3866 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3867 
3868   if (SCS.Second != ICK_Integral_Promotion)
3869     return FixedEnumPromotion::None;
3870 
3871   QualType FromType = SCS.getFromType();
3872   if (!FromType->isEnumeralType())
3873     return FixedEnumPromotion::None;
3874 
3875   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3876   if (!Enum->isFixed())
3877     return FixedEnumPromotion::None;
3878 
3879   QualType UnderlyingType = Enum->getIntegerType();
3880   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3881     return FixedEnumPromotion::ToUnderlyingType;
3882 
3883   return FixedEnumPromotion::ToPromotedUnderlyingType;
3884 }
3885 
3886 /// CompareStandardConversionSequences - Compare two standard
3887 /// conversion sequences to determine whether one is better than the
3888 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3889 static ImplicitConversionSequence::CompareKind
3890 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3891                                    const StandardConversionSequence& SCS1,
3892                                    const StandardConversionSequence& SCS2)
3893 {
3894   // Standard conversion sequence S1 is a better conversion sequence
3895   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3896 
3897   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3898   //     sequences in the canonical form defined by 13.3.3.1.1,
3899   //     excluding any Lvalue Transformation; the identity conversion
3900   //     sequence is considered to be a subsequence of any
3901   //     non-identity conversion sequence) or, if not that,
3902   if (ImplicitConversionSequence::CompareKind CK
3903         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3904     return CK;
3905 
3906   //  -- the rank of S1 is better than the rank of S2 (by the rules
3907   //     defined below), or, if not that,
3908   ImplicitConversionRank Rank1 = SCS1.getRank();
3909   ImplicitConversionRank Rank2 = SCS2.getRank();
3910   if (Rank1 < Rank2)
3911     return ImplicitConversionSequence::Better;
3912   else if (Rank2 < Rank1)
3913     return ImplicitConversionSequence::Worse;
3914 
3915   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3916   // are indistinguishable unless one of the following rules
3917   // applies:
3918 
3919   //   A conversion that is not a conversion of a pointer, or
3920   //   pointer to member, to bool is better than another conversion
3921   //   that is such a conversion.
3922   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3923     return SCS2.isPointerConversionToBool()
3924              ? ImplicitConversionSequence::Better
3925              : ImplicitConversionSequence::Worse;
3926 
3927   // C++14 [over.ics.rank]p4b2:
3928   // This is retroactively applied to C++11 by CWG 1601.
3929   //
3930   //   A conversion that promotes an enumeration whose underlying type is fixed
3931   //   to its underlying type is better than one that promotes to the promoted
3932   //   underlying type, if the two are different.
3933   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3934   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3935   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3936       FEP1 != FEP2)
3937     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3938                ? ImplicitConversionSequence::Better
3939                : ImplicitConversionSequence::Worse;
3940 
3941   // C++ [over.ics.rank]p4b2:
3942   //
3943   //   If class B is derived directly or indirectly from class A,
3944   //   conversion of B* to A* is better than conversion of B* to
3945   //   void*, and conversion of A* to void* is better than conversion
3946   //   of B* to void*.
3947   bool SCS1ConvertsToVoid
3948     = SCS1.isPointerConversionToVoidPointer(S.Context);
3949   bool SCS2ConvertsToVoid
3950     = SCS2.isPointerConversionToVoidPointer(S.Context);
3951   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3952     // Exactly one of the conversion sequences is a conversion to
3953     // a void pointer; it's the worse conversion.
3954     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3955                               : ImplicitConversionSequence::Worse;
3956   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3957     // Neither conversion sequence converts to a void pointer; compare
3958     // their derived-to-base conversions.
3959     if (ImplicitConversionSequence::CompareKind DerivedCK
3960           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3961       return DerivedCK;
3962   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3963              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3964     // Both conversion sequences are conversions to void
3965     // pointers. Compare the source types to determine if there's an
3966     // inheritance relationship in their sources.
3967     QualType FromType1 = SCS1.getFromType();
3968     QualType FromType2 = SCS2.getFromType();
3969 
3970     // Adjust the types we're converting from via the array-to-pointer
3971     // conversion, if we need to.
3972     if (SCS1.First == ICK_Array_To_Pointer)
3973       FromType1 = S.Context.getArrayDecayedType(FromType1);
3974     if (SCS2.First == ICK_Array_To_Pointer)
3975       FromType2 = S.Context.getArrayDecayedType(FromType2);
3976 
3977     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3978     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3979 
3980     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3981       return ImplicitConversionSequence::Better;
3982     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3983       return ImplicitConversionSequence::Worse;
3984 
3985     // Objective-C++: If one interface is more specific than the
3986     // other, it is the better one.
3987     const ObjCObjectPointerType* FromObjCPtr1
3988       = FromType1->getAs<ObjCObjectPointerType>();
3989     const ObjCObjectPointerType* FromObjCPtr2
3990       = FromType2->getAs<ObjCObjectPointerType>();
3991     if (FromObjCPtr1 && FromObjCPtr2) {
3992       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3993                                                           FromObjCPtr2);
3994       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3995                                                            FromObjCPtr1);
3996       if (AssignLeft != AssignRight) {
3997         return AssignLeft? ImplicitConversionSequence::Better
3998                          : ImplicitConversionSequence::Worse;
3999       }
4000     }
4001   }
4002 
4003   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4004     // Check for a better reference binding based on the kind of bindings.
4005     if (isBetterReferenceBindingKind(SCS1, SCS2))
4006       return ImplicitConversionSequence::Better;
4007     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4008       return ImplicitConversionSequence::Worse;
4009   }
4010 
4011   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4012   // bullet 3).
4013   if (ImplicitConversionSequence::CompareKind QualCK
4014         = CompareQualificationConversions(S, SCS1, SCS2))
4015     return QualCK;
4016 
4017   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4018     // C++ [over.ics.rank]p3b4:
4019     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4020     //      which the references refer are the same type except for
4021     //      top-level cv-qualifiers, and the type to which the reference
4022     //      initialized by S2 refers is more cv-qualified than the type
4023     //      to which the reference initialized by S1 refers.
4024     QualType T1 = SCS1.getToType(2);
4025     QualType T2 = SCS2.getToType(2);
4026     T1 = S.Context.getCanonicalType(T1);
4027     T2 = S.Context.getCanonicalType(T2);
4028     Qualifiers T1Quals, T2Quals;
4029     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4030     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4031     if (UnqualT1 == UnqualT2) {
4032       // Objective-C++ ARC: If the references refer to objects with different
4033       // lifetimes, prefer bindings that don't change lifetime.
4034       if (SCS1.ObjCLifetimeConversionBinding !=
4035                                           SCS2.ObjCLifetimeConversionBinding) {
4036         return SCS1.ObjCLifetimeConversionBinding
4037                                            ? ImplicitConversionSequence::Worse
4038                                            : ImplicitConversionSequence::Better;
4039       }
4040 
4041       // If the type is an array type, promote the element qualifiers to the
4042       // type for comparison.
4043       if (isa<ArrayType>(T1) && T1Quals)
4044         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4045       if (isa<ArrayType>(T2) && T2Quals)
4046         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4047       if (T2.isMoreQualifiedThan(T1))
4048         return ImplicitConversionSequence::Better;
4049       if (T1.isMoreQualifiedThan(T2))
4050         return ImplicitConversionSequence::Worse;
4051     }
4052   }
4053 
4054   // In Microsoft mode, prefer an integral conversion to a
4055   // floating-to-integral conversion if the integral conversion
4056   // is between types of the same size.
4057   // For example:
4058   // void f(float);
4059   // void f(int);
4060   // int main {
4061   //    long a;
4062   //    f(a);
4063   // }
4064   // Here, MSVC will call f(int) instead of generating a compile error
4065   // as clang will do in standard mode.
4066   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4067       SCS2.Second == ICK_Floating_Integral &&
4068       S.Context.getTypeSize(SCS1.getFromType()) ==
4069           S.Context.getTypeSize(SCS1.getToType(2)))
4070     return ImplicitConversionSequence::Better;
4071 
4072   // Prefer a compatible vector conversion over a lax vector conversion
4073   // For example:
4074   //
4075   // typedef float __v4sf __attribute__((__vector_size__(16)));
4076   // void f(vector float);
4077   // void f(vector signed int);
4078   // int main() {
4079   //   __v4sf a;
4080   //   f(a);
4081   // }
4082   // Here, we'd like to choose f(vector float) and not
4083   // report an ambiguous call error
4084   if (SCS1.Second == ICK_Vector_Conversion &&
4085       SCS2.Second == ICK_Vector_Conversion) {
4086     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4087         SCS1.getFromType(), SCS1.getToType(2));
4088     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4089         SCS2.getFromType(), SCS2.getToType(2));
4090 
4091     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4092       return SCS1IsCompatibleVectorConversion
4093                  ? ImplicitConversionSequence::Better
4094                  : ImplicitConversionSequence::Worse;
4095   }
4096 
4097   return ImplicitConversionSequence::Indistinguishable;
4098 }
4099 
4100 /// CompareQualificationConversions - Compares two standard conversion
4101 /// sequences to determine whether they can be ranked based on their
4102 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4103 static ImplicitConversionSequence::CompareKind
4104 CompareQualificationConversions(Sema &S,
4105                                 const StandardConversionSequence& SCS1,
4106                                 const StandardConversionSequence& SCS2) {
4107   // C++ 13.3.3.2p3:
4108   //  -- S1 and S2 differ only in their qualification conversion and
4109   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4110   //     cv-qualification signature of type T1 is a proper subset of
4111   //     the cv-qualification signature of type T2, and S1 is not the
4112   //     deprecated string literal array-to-pointer conversion (4.2).
4113   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4114       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4115     return ImplicitConversionSequence::Indistinguishable;
4116 
4117   // FIXME: the example in the standard doesn't use a qualification
4118   // conversion (!)
4119   QualType T1 = SCS1.getToType(2);
4120   QualType T2 = SCS2.getToType(2);
4121   T1 = S.Context.getCanonicalType(T1);
4122   T2 = S.Context.getCanonicalType(T2);
4123   assert(!T1->isReferenceType() && !T2->isReferenceType());
4124   Qualifiers T1Quals, T2Quals;
4125   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4126   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4127 
4128   // If the types are the same, we won't learn anything by unwrapping
4129   // them.
4130   if (UnqualT1 == UnqualT2)
4131     return ImplicitConversionSequence::Indistinguishable;
4132 
4133   ImplicitConversionSequence::CompareKind Result
4134     = ImplicitConversionSequence::Indistinguishable;
4135 
4136   // Objective-C++ ARC:
4137   //   Prefer qualification conversions not involving a change in lifetime
4138   //   to qualification conversions that do not change lifetime.
4139   if (SCS1.QualificationIncludesObjCLifetime !=
4140                                       SCS2.QualificationIncludesObjCLifetime) {
4141     Result = SCS1.QualificationIncludesObjCLifetime
4142                ? ImplicitConversionSequence::Worse
4143                : ImplicitConversionSequence::Better;
4144   }
4145 
4146   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4147     // Within each iteration of the loop, we check the qualifiers to
4148     // determine if this still looks like a qualification
4149     // conversion. Then, if all is well, we unwrap one more level of
4150     // pointers or pointers-to-members and do it all again
4151     // until there are no more pointers or pointers-to-members left
4152     // to unwrap. This essentially mimics what
4153     // IsQualificationConversion does, but here we're checking for a
4154     // strict subset of qualifiers.
4155     if (T1.getQualifiers().withoutObjCLifetime() ==
4156         T2.getQualifiers().withoutObjCLifetime())
4157       // The qualifiers are the same, so this doesn't tell us anything
4158       // about how the sequences rank.
4159       // ObjC ownership quals are omitted above as they interfere with
4160       // the ARC overload rule.
4161       ;
4162     else if (T2.isMoreQualifiedThan(T1)) {
4163       // T1 has fewer qualifiers, so it could be the better sequence.
4164       if (Result == ImplicitConversionSequence::Worse)
4165         // Neither has qualifiers that are a subset of the other's
4166         // qualifiers.
4167         return ImplicitConversionSequence::Indistinguishable;
4168 
4169       Result = ImplicitConversionSequence::Better;
4170     } else if (T1.isMoreQualifiedThan(T2)) {
4171       // T2 has fewer qualifiers, so it could be the better sequence.
4172       if (Result == ImplicitConversionSequence::Better)
4173         // Neither has qualifiers that are a subset of the other's
4174         // qualifiers.
4175         return ImplicitConversionSequence::Indistinguishable;
4176 
4177       Result = ImplicitConversionSequence::Worse;
4178     } else {
4179       // Qualifiers are disjoint.
4180       return ImplicitConversionSequence::Indistinguishable;
4181     }
4182 
4183     // If the types after this point are equivalent, we're done.
4184     if (S.Context.hasSameUnqualifiedType(T1, T2))
4185       break;
4186   }
4187 
4188   // Check that the winning standard conversion sequence isn't using
4189   // the deprecated string literal array to pointer conversion.
4190   switch (Result) {
4191   case ImplicitConversionSequence::Better:
4192     if (SCS1.DeprecatedStringLiteralToCharPtr)
4193       Result = ImplicitConversionSequence::Indistinguishable;
4194     break;
4195 
4196   case ImplicitConversionSequence::Indistinguishable:
4197     break;
4198 
4199   case ImplicitConversionSequence::Worse:
4200     if (SCS2.DeprecatedStringLiteralToCharPtr)
4201       Result = ImplicitConversionSequence::Indistinguishable;
4202     break;
4203   }
4204 
4205   return Result;
4206 }
4207 
4208 /// CompareDerivedToBaseConversions - Compares two standard conversion
4209 /// sequences to determine whether they can be ranked based on their
4210 /// various kinds of derived-to-base conversions (C++
4211 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4212 /// conversions between Objective-C interface types.
4213 static ImplicitConversionSequence::CompareKind
4214 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4215                                 const StandardConversionSequence& SCS1,
4216                                 const StandardConversionSequence& SCS2) {
4217   QualType FromType1 = SCS1.getFromType();
4218   QualType ToType1 = SCS1.getToType(1);
4219   QualType FromType2 = SCS2.getFromType();
4220   QualType ToType2 = SCS2.getToType(1);
4221 
4222   // Adjust the types we're converting from via the array-to-pointer
4223   // conversion, if we need to.
4224   if (SCS1.First == ICK_Array_To_Pointer)
4225     FromType1 = S.Context.getArrayDecayedType(FromType1);
4226   if (SCS2.First == ICK_Array_To_Pointer)
4227     FromType2 = S.Context.getArrayDecayedType(FromType2);
4228 
4229   // Canonicalize all of the types.
4230   FromType1 = S.Context.getCanonicalType(FromType1);
4231   ToType1 = S.Context.getCanonicalType(ToType1);
4232   FromType2 = S.Context.getCanonicalType(FromType2);
4233   ToType2 = S.Context.getCanonicalType(ToType2);
4234 
4235   // C++ [over.ics.rank]p4b3:
4236   //
4237   //   If class B is derived directly or indirectly from class A and
4238   //   class C is derived directly or indirectly from B,
4239   //
4240   // Compare based on pointer conversions.
4241   if (SCS1.Second == ICK_Pointer_Conversion &&
4242       SCS2.Second == ICK_Pointer_Conversion &&
4243       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4244       FromType1->isPointerType() && FromType2->isPointerType() &&
4245       ToType1->isPointerType() && ToType2->isPointerType()) {
4246     QualType FromPointee1 =
4247         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4248     QualType ToPointee1 =
4249         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4250     QualType FromPointee2 =
4251         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4252     QualType ToPointee2 =
4253         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4254 
4255     //   -- conversion of C* to B* is better than conversion of C* to A*,
4256     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4257       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4258         return ImplicitConversionSequence::Better;
4259       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4260         return ImplicitConversionSequence::Worse;
4261     }
4262 
4263     //   -- conversion of B* to A* is better than conversion of C* to A*,
4264     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4265       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4266         return ImplicitConversionSequence::Better;
4267       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4268         return ImplicitConversionSequence::Worse;
4269     }
4270   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4271              SCS2.Second == ICK_Pointer_Conversion) {
4272     const ObjCObjectPointerType *FromPtr1
4273       = FromType1->getAs<ObjCObjectPointerType>();
4274     const ObjCObjectPointerType *FromPtr2
4275       = FromType2->getAs<ObjCObjectPointerType>();
4276     const ObjCObjectPointerType *ToPtr1
4277       = ToType1->getAs<ObjCObjectPointerType>();
4278     const ObjCObjectPointerType *ToPtr2
4279       = ToType2->getAs<ObjCObjectPointerType>();
4280 
4281     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4282       // Apply the same conversion ranking rules for Objective-C pointer types
4283       // that we do for C++ pointers to class types. However, we employ the
4284       // Objective-C pseudo-subtyping relationship used for assignment of
4285       // Objective-C pointer types.
4286       bool FromAssignLeft
4287         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4288       bool FromAssignRight
4289         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4290       bool ToAssignLeft
4291         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4292       bool ToAssignRight
4293         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4294 
4295       // A conversion to an a non-id object pointer type or qualified 'id'
4296       // type is better than a conversion to 'id'.
4297       if (ToPtr1->isObjCIdType() &&
4298           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4299         return ImplicitConversionSequence::Worse;
4300       if (ToPtr2->isObjCIdType() &&
4301           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4302         return ImplicitConversionSequence::Better;
4303 
4304       // A conversion to a non-id object pointer type is better than a
4305       // conversion to a qualified 'id' type
4306       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4307         return ImplicitConversionSequence::Worse;
4308       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4309         return ImplicitConversionSequence::Better;
4310 
4311       // A conversion to an a non-Class object pointer type or qualified 'Class'
4312       // type is better than a conversion to 'Class'.
4313       if (ToPtr1->isObjCClassType() &&
4314           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4315         return ImplicitConversionSequence::Worse;
4316       if (ToPtr2->isObjCClassType() &&
4317           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4318         return ImplicitConversionSequence::Better;
4319 
4320       // A conversion to a non-Class object pointer type is better than a
4321       // conversion to a qualified 'Class' type.
4322       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4323         return ImplicitConversionSequence::Worse;
4324       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4325         return ImplicitConversionSequence::Better;
4326 
4327       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4328       if (S.Context.hasSameType(FromType1, FromType2) &&
4329           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4330           (ToAssignLeft != ToAssignRight)) {
4331         if (FromPtr1->isSpecialized()) {
4332           // "conversion of B<A> * to B * is better than conversion of B * to
4333           // C *.
4334           bool IsFirstSame =
4335               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4336           bool IsSecondSame =
4337               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4338           if (IsFirstSame) {
4339             if (!IsSecondSame)
4340               return ImplicitConversionSequence::Better;
4341           } else if (IsSecondSame)
4342             return ImplicitConversionSequence::Worse;
4343         }
4344         return ToAssignLeft? ImplicitConversionSequence::Worse
4345                            : ImplicitConversionSequence::Better;
4346       }
4347 
4348       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4349       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4350           (FromAssignLeft != FromAssignRight))
4351         return FromAssignLeft? ImplicitConversionSequence::Better
4352         : ImplicitConversionSequence::Worse;
4353     }
4354   }
4355 
4356   // Ranking of member-pointer types.
4357   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4358       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4359       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4360     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4361     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4362     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4363     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4364     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4365     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4366     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4367     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4368     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4369     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4370     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4371     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4372     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4373     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4374       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4375         return ImplicitConversionSequence::Worse;
4376       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4377         return ImplicitConversionSequence::Better;
4378     }
4379     // conversion of B::* to C::* is better than conversion of A::* to C::*
4380     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4381       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4382         return ImplicitConversionSequence::Better;
4383       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4384         return ImplicitConversionSequence::Worse;
4385     }
4386   }
4387 
4388   if (SCS1.Second == ICK_Derived_To_Base) {
4389     //   -- conversion of C to B is better than conversion of C to A,
4390     //   -- binding of an expression of type C to a reference of type
4391     //      B& is better than binding an expression of type C to a
4392     //      reference of type A&,
4393     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4394         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4395       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4396         return ImplicitConversionSequence::Better;
4397       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4398         return ImplicitConversionSequence::Worse;
4399     }
4400 
4401     //   -- conversion of B to A is better than conversion of C to A.
4402     //   -- binding of an expression of type B to a reference of type
4403     //      A& is better than binding an expression of type C to a
4404     //      reference of type A&,
4405     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4406         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4407       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4408         return ImplicitConversionSequence::Better;
4409       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4410         return ImplicitConversionSequence::Worse;
4411     }
4412   }
4413 
4414   return ImplicitConversionSequence::Indistinguishable;
4415 }
4416 
4417 /// Determine whether the given type is valid, e.g., it is not an invalid
4418 /// C++ class.
4419 static bool isTypeValid(QualType T) {
4420   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4421     return !Record->isInvalidDecl();
4422 
4423   return true;
4424 }
4425 
4426 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4427   if (!T.getQualifiers().hasUnaligned())
4428     return T;
4429 
4430   Qualifiers Q;
4431   T = Ctx.getUnqualifiedArrayType(T, Q);
4432   Q.removeUnaligned();
4433   return Ctx.getQualifiedType(T, Q);
4434 }
4435 
4436 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4437 /// determine whether they are reference-compatible,
4438 /// reference-related, or incompatible, for use in C++ initialization by
4439 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4440 /// type, and the first type (T1) is the pointee type of the reference
4441 /// type being initialized.
4442 Sema::ReferenceCompareResult
4443 Sema::CompareReferenceRelationship(SourceLocation Loc,
4444                                    QualType OrigT1, QualType OrigT2,
4445                                    ReferenceConversions *ConvOut) {
4446   assert(!OrigT1->isReferenceType() &&
4447     "T1 must be the pointee type of the reference type");
4448   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4449 
4450   QualType T1 = Context.getCanonicalType(OrigT1);
4451   QualType T2 = Context.getCanonicalType(OrigT2);
4452   Qualifiers T1Quals, T2Quals;
4453   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4454   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4455 
4456   ReferenceConversions ConvTmp;
4457   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4458   Conv = ReferenceConversions();
4459 
4460   // C++2a [dcl.init.ref]p4:
4461   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4462   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4463   //   T1 is a base class of T2.
4464   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4465   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4466   //   "pointer to cv1 T1" via a standard conversion sequence.
4467 
4468   // Check for standard conversions we can apply to pointers: derived-to-base
4469   // conversions, ObjC pointer conversions, and function pointer conversions.
4470   // (Qualification conversions are checked last.)
4471   QualType ConvertedT2;
4472   if (UnqualT1 == UnqualT2) {
4473     // Nothing to do.
4474   } else if (isCompleteType(Loc, OrigT2) &&
4475              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4476              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4477     Conv |= ReferenceConversions::DerivedToBase;
4478   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4479            UnqualT2->isObjCObjectOrInterfaceType() &&
4480            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4481     Conv |= ReferenceConversions::ObjC;
4482   else if (UnqualT2->isFunctionType() &&
4483            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4484     Conv |= ReferenceConversions::Function;
4485     // No need to check qualifiers; function types don't have them.
4486     return Ref_Compatible;
4487   }
4488   bool ConvertedReferent = Conv != 0;
4489 
4490   // We can have a qualification conversion. Compute whether the types are
4491   // similar at the same time.
4492   bool PreviousToQualsIncludeConst = true;
4493   bool TopLevel = true;
4494   do {
4495     if (T1 == T2)
4496       break;
4497 
4498     // We will need a qualification conversion.
4499     Conv |= ReferenceConversions::Qualification;
4500 
4501     // Track whether we performed a qualification conversion anywhere other
4502     // than the top level. This matters for ranking reference bindings in
4503     // overload resolution.
4504     if (!TopLevel)
4505       Conv |= ReferenceConversions::NestedQualification;
4506 
4507     // MS compiler ignores __unaligned qualifier for references; do the same.
4508     T1 = withoutUnaligned(Context, T1);
4509     T2 = withoutUnaligned(Context, T2);
4510 
4511     // If we find a qualifier mismatch, the types are not reference-compatible,
4512     // but are still be reference-related if they're similar.
4513     bool ObjCLifetimeConversion = false;
4514     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4515                                        PreviousToQualsIncludeConst,
4516                                        ObjCLifetimeConversion))
4517       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4518                  ? Ref_Related
4519                  : Ref_Incompatible;
4520 
4521     // FIXME: Should we track this for any level other than the first?
4522     if (ObjCLifetimeConversion)
4523       Conv |= ReferenceConversions::ObjCLifetime;
4524 
4525     TopLevel = false;
4526   } while (Context.UnwrapSimilarTypes(T1, T2));
4527 
4528   // At this point, if the types are reference-related, we must either have the
4529   // same inner type (ignoring qualifiers), or must have already worked out how
4530   // to convert the referent.
4531   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4532              ? Ref_Compatible
4533              : Ref_Incompatible;
4534 }
4535 
4536 /// Look for a user-defined conversion to a value reference-compatible
4537 ///        with DeclType. Return true if something definite is found.
4538 static bool
4539 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4540                          QualType DeclType, SourceLocation DeclLoc,
4541                          Expr *Init, QualType T2, bool AllowRvalues,
4542                          bool AllowExplicit) {
4543   assert(T2->isRecordType() && "Can only find conversions of record types.");
4544   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4545 
4546   OverloadCandidateSet CandidateSet(
4547       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4548   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4549   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4550     NamedDecl *D = *I;
4551     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4552     if (isa<UsingShadowDecl>(D))
4553       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4554 
4555     FunctionTemplateDecl *ConvTemplate
4556       = dyn_cast<FunctionTemplateDecl>(D);
4557     CXXConversionDecl *Conv;
4558     if (ConvTemplate)
4559       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4560     else
4561       Conv = cast<CXXConversionDecl>(D);
4562 
4563     if (AllowRvalues) {
4564       // If we are initializing an rvalue reference, don't permit conversion
4565       // functions that return lvalues.
4566       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4567         const ReferenceType *RefType
4568           = Conv->getConversionType()->getAs<LValueReferenceType>();
4569         if (RefType && !RefType->getPointeeType()->isFunctionType())
4570           continue;
4571       }
4572 
4573       if (!ConvTemplate &&
4574           S.CompareReferenceRelationship(
4575               DeclLoc,
4576               Conv->getConversionType()
4577                   .getNonReferenceType()
4578                   .getUnqualifiedType(),
4579               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4580               Sema::Ref_Incompatible)
4581         continue;
4582     } else {
4583       // If the conversion function doesn't return a reference type,
4584       // it can't be considered for this conversion. An rvalue reference
4585       // is only acceptable if its referencee is a function type.
4586 
4587       const ReferenceType *RefType =
4588         Conv->getConversionType()->getAs<ReferenceType>();
4589       if (!RefType ||
4590           (!RefType->isLValueReferenceType() &&
4591            !RefType->getPointeeType()->isFunctionType()))
4592         continue;
4593     }
4594 
4595     if (ConvTemplate)
4596       S.AddTemplateConversionCandidate(
4597           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4598           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4599     else
4600       S.AddConversionCandidate(
4601           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4602           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4603   }
4604 
4605   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4606 
4607   OverloadCandidateSet::iterator Best;
4608   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4609   case OR_Success:
4610     // C++ [over.ics.ref]p1:
4611     //
4612     //   [...] If the parameter binds directly to the result of
4613     //   applying a conversion function to the argument
4614     //   expression, the implicit conversion sequence is a
4615     //   user-defined conversion sequence (13.3.3.1.2), with the
4616     //   second standard conversion sequence either an identity
4617     //   conversion or, if the conversion function returns an
4618     //   entity of a type that is a derived class of the parameter
4619     //   type, a derived-to-base Conversion.
4620     if (!Best->FinalConversion.DirectBinding)
4621       return false;
4622 
4623     ICS.setUserDefined();
4624     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4625     ICS.UserDefined.After = Best->FinalConversion;
4626     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4627     ICS.UserDefined.ConversionFunction = Best->Function;
4628     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4629     ICS.UserDefined.EllipsisConversion = false;
4630     assert(ICS.UserDefined.After.ReferenceBinding &&
4631            ICS.UserDefined.After.DirectBinding &&
4632            "Expected a direct reference binding!");
4633     return true;
4634 
4635   case OR_Ambiguous:
4636     ICS.setAmbiguous();
4637     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4638          Cand != CandidateSet.end(); ++Cand)
4639       if (Cand->Best)
4640         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4641     return true;
4642 
4643   case OR_No_Viable_Function:
4644   case OR_Deleted:
4645     // There was no suitable conversion, or we found a deleted
4646     // conversion; continue with other checks.
4647     return false;
4648   }
4649 
4650   llvm_unreachable("Invalid OverloadResult!");
4651 }
4652 
4653 /// Compute an implicit conversion sequence for reference
4654 /// initialization.
4655 static ImplicitConversionSequence
4656 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4657                  SourceLocation DeclLoc,
4658                  bool SuppressUserConversions,
4659                  bool AllowExplicit) {
4660   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4661 
4662   // Most paths end in a failed conversion.
4663   ImplicitConversionSequence ICS;
4664   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4665 
4666   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4667   QualType T2 = Init->getType();
4668 
4669   // If the initializer is the address of an overloaded function, try
4670   // to resolve the overloaded function. If all goes well, T2 is the
4671   // type of the resulting function.
4672   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4673     DeclAccessPair Found;
4674     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4675                                                                 false, Found))
4676       T2 = Fn->getType();
4677   }
4678 
4679   // Compute some basic properties of the types and the initializer.
4680   bool isRValRef = DeclType->isRValueReferenceType();
4681   Expr::Classification InitCategory = Init->Classify(S.Context);
4682 
4683   Sema::ReferenceConversions RefConv;
4684   Sema::ReferenceCompareResult RefRelationship =
4685       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4686 
4687   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4688     ICS.setStandard();
4689     ICS.Standard.First = ICK_Identity;
4690     // FIXME: A reference binding can be a function conversion too. We should
4691     // consider that when ordering reference-to-function bindings.
4692     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4693                               ? ICK_Derived_To_Base
4694                               : (RefConv & Sema::ReferenceConversions::ObjC)
4695                                     ? ICK_Compatible_Conversion
4696                                     : ICK_Identity;
4697     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4698     // a reference binding that performs a non-top-level qualification
4699     // conversion as a qualification conversion, not as an identity conversion.
4700     ICS.Standard.Third = (RefConv &
4701                               Sema::ReferenceConversions::NestedQualification)
4702                              ? ICK_Qualification
4703                              : ICK_Identity;
4704     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4705     ICS.Standard.setToType(0, T2);
4706     ICS.Standard.setToType(1, T1);
4707     ICS.Standard.setToType(2, T1);
4708     ICS.Standard.ReferenceBinding = true;
4709     ICS.Standard.DirectBinding = BindsDirectly;
4710     ICS.Standard.IsLvalueReference = !isRValRef;
4711     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4712     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4713     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4714     ICS.Standard.ObjCLifetimeConversionBinding =
4715         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4716     ICS.Standard.CopyConstructor = nullptr;
4717     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4718   };
4719 
4720   // C++0x [dcl.init.ref]p5:
4721   //   A reference to type "cv1 T1" is initialized by an expression
4722   //   of type "cv2 T2" as follows:
4723 
4724   //     -- If reference is an lvalue reference and the initializer expression
4725   if (!isRValRef) {
4726     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4727     //        reference-compatible with "cv2 T2," or
4728     //
4729     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4730     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4731       // C++ [over.ics.ref]p1:
4732       //   When a parameter of reference type binds directly (8.5.3)
4733       //   to an argument expression, the implicit conversion sequence
4734       //   is the identity conversion, unless the argument expression
4735       //   has a type that is a derived class of the parameter type,
4736       //   in which case the implicit conversion sequence is a
4737       //   derived-to-base Conversion (13.3.3.1).
4738       SetAsReferenceBinding(/*BindsDirectly=*/true);
4739 
4740       // Nothing more to do: the inaccessibility/ambiguity check for
4741       // derived-to-base conversions is suppressed when we're
4742       // computing the implicit conversion sequence (C++
4743       // [over.best.ics]p2).
4744       return ICS;
4745     }
4746 
4747     //       -- has a class type (i.e., T2 is a class type), where T1 is
4748     //          not reference-related to T2, and can be implicitly
4749     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4750     //          is reference-compatible with "cv3 T3" 92) (this
4751     //          conversion is selected by enumerating the applicable
4752     //          conversion functions (13.3.1.6) and choosing the best
4753     //          one through overload resolution (13.3)),
4754     if (!SuppressUserConversions && T2->isRecordType() &&
4755         S.isCompleteType(DeclLoc, T2) &&
4756         RefRelationship == Sema::Ref_Incompatible) {
4757       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4758                                    Init, T2, /*AllowRvalues=*/false,
4759                                    AllowExplicit))
4760         return ICS;
4761     }
4762   }
4763 
4764   //     -- Otherwise, the reference shall be an lvalue reference to a
4765   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4766   //        shall be an rvalue reference.
4767   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4768     return ICS;
4769 
4770   //       -- If the initializer expression
4771   //
4772   //            -- is an xvalue, class prvalue, array prvalue or function
4773   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4774   if (RefRelationship == Sema::Ref_Compatible &&
4775       (InitCategory.isXValue() ||
4776        (InitCategory.isPRValue() &&
4777           (T2->isRecordType() || T2->isArrayType())) ||
4778        (InitCategory.isLValue() && T2->isFunctionType()))) {
4779     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4780     // binding unless we're binding to a class prvalue.
4781     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4782     // allow the use of rvalue references in C++98/03 for the benefit of
4783     // standard library implementors; therefore, we need the xvalue check here.
4784     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4785                           !(InitCategory.isPRValue() || T2->isRecordType()));
4786     return ICS;
4787   }
4788 
4789   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4790   //               reference-related to T2, and can be implicitly converted to
4791   //               an xvalue, class prvalue, or function lvalue of type
4792   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4793   //               "cv3 T3",
4794   //
4795   //          then the reference is bound to the value of the initializer
4796   //          expression in the first case and to the result of the conversion
4797   //          in the second case (or, in either case, to an appropriate base
4798   //          class subobject).
4799   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4800       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4801       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4802                                Init, T2, /*AllowRvalues=*/true,
4803                                AllowExplicit)) {
4804     // In the second case, if the reference is an rvalue reference
4805     // and the second standard conversion sequence of the
4806     // user-defined conversion sequence includes an lvalue-to-rvalue
4807     // conversion, the program is ill-formed.
4808     if (ICS.isUserDefined() && isRValRef &&
4809         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4810       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4811 
4812     return ICS;
4813   }
4814 
4815   // A temporary of function type cannot be created; don't even try.
4816   if (T1->isFunctionType())
4817     return ICS;
4818 
4819   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4820   //          initialized from the initializer expression using the
4821   //          rules for a non-reference copy initialization (8.5). The
4822   //          reference is then bound to the temporary. If T1 is
4823   //          reference-related to T2, cv1 must be the same
4824   //          cv-qualification as, or greater cv-qualification than,
4825   //          cv2; otherwise, the program is ill-formed.
4826   if (RefRelationship == Sema::Ref_Related) {
4827     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4828     // we would be reference-compatible or reference-compatible with
4829     // added qualification. But that wasn't the case, so the reference
4830     // initialization fails.
4831     //
4832     // Note that we only want to check address spaces and cvr-qualifiers here.
4833     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4834     Qualifiers T1Quals = T1.getQualifiers();
4835     Qualifiers T2Quals = T2.getQualifiers();
4836     T1Quals.removeObjCGCAttr();
4837     T1Quals.removeObjCLifetime();
4838     T2Quals.removeObjCGCAttr();
4839     T2Quals.removeObjCLifetime();
4840     // MS compiler ignores __unaligned qualifier for references; do the same.
4841     T1Quals.removeUnaligned();
4842     T2Quals.removeUnaligned();
4843     if (!T1Quals.compatiblyIncludes(T2Quals))
4844       return ICS;
4845   }
4846 
4847   // If at least one of the types is a class type, the types are not
4848   // related, and we aren't allowed any user conversions, the
4849   // reference binding fails. This case is important for breaking
4850   // recursion, since TryImplicitConversion below will attempt to
4851   // create a temporary through the use of a copy constructor.
4852   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4853       (T1->isRecordType() || T2->isRecordType()))
4854     return ICS;
4855 
4856   // If T1 is reference-related to T2 and the reference is an rvalue
4857   // reference, the initializer expression shall not be an lvalue.
4858   if (RefRelationship >= Sema::Ref_Related &&
4859       isRValRef && Init->Classify(S.Context).isLValue())
4860     return ICS;
4861 
4862   // C++ [over.ics.ref]p2:
4863   //   When a parameter of reference type is not bound directly to
4864   //   an argument expression, the conversion sequence is the one
4865   //   required to convert the argument expression to the
4866   //   underlying type of the reference according to
4867   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4868   //   to copy-initializing a temporary of the underlying type with
4869   //   the argument expression. Any difference in top-level
4870   //   cv-qualification is subsumed by the initialization itself
4871   //   and does not constitute a conversion.
4872   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4873                               AllowedExplicit::None,
4874                               /*InOverloadResolution=*/false,
4875                               /*CStyle=*/false,
4876                               /*AllowObjCWritebackConversion=*/false,
4877                               /*AllowObjCConversionOnExplicit=*/false);
4878 
4879   // Of course, that's still a reference binding.
4880   if (ICS.isStandard()) {
4881     ICS.Standard.ReferenceBinding = true;
4882     ICS.Standard.IsLvalueReference = !isRValRef;
4883     ICS.Standard.BindsToFunctionLvalue = false;
4884     ICS.Standard.BindsToRvalue = true;
4885     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4886     ICS.Standard.ObjCLifetimeConversionBinding = false;
4887   } else if (ICS.isUserDefined()) {
4888     const ReferenceType *LValRefType =
4889         ICS.UserDefined.ConversionFunction->getReturnType()
4890             ->getAs<LValueReferenceType>();
4891 
4892     // C++ [over.ics.ref]p3:
4893     //   Except for an implicit object parameter, for which see 13.3.1, a
4894     //   standard conversion sequence cannot be formed if it requires [...]
4895     //   binding an rvalue reference to an lvalue other than a function
4896     //   lvalue.
4897     // Note that the function case is not possible here.
4898     if (DeclType->isRValueReferenceType() && LValRefType) {
4899       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4900       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4901       // reference to an rvalue!
4902       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4903       return ICS;
4904     }
4905 
4906     ICS.UserDefined.After.ReferenceBinding = true;
4907     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4908     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4909     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4910     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4911     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4912   }
4913 
4914   return ICS;
4915 }
4916 
4917 static ImplicitConversionSequence
4918 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4919                       bool SuppressUserConversions,
4920                       bool InOverloadResolution,
4921                       bool AllowObjCWritebackConversion,
4922                       bool AllowExplicit = false);
4923 
4924 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4925 /// initializer list From.
4926 static ImplicitConversionSequence
4927 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4928                   bool SuppressUserConversions,
4929                   bool InOverloadResolution,
4930                   bool AllowObjCWritebackConversion) {
4931   // C++11 [over.ics.list]p1:
4932   //   When an argument is an initializer list, it is not an expression and
4933   //   special rules apply for converting it to a parameter type.
4934 
4935   ImplicitConversionSequence Result;
4936   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4937 
4938   // We need a complete type for what follows. Incomplete types can never be
4939   // initialized from init lists.
4940   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4941     return Result;
4942 
4943   // Per DR1467:
4944   //   If the parameter type is a class X and the initializer list has a single
4945   //   element of type cv U, where U is X or a class derived from X, the
4946   //   implicit conversion sequence is the one required to convert the element
4947   //   to the parameter type.
4948   //
4949   //   Otherwise, if the parameter type is a character array [... ]
4950   //   and the initializer list has a single element that is an
4951   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4952   //   implicit conversion sequence is the identity conversion.
4953   if (From->getNumInits() == 1) {
4954     if (ToType->isRecordType()) {
4955       QualType InitType = From->getInit(0)->getType();
4956       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4957           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4958         return TryCopyInitialization(S, From->getInit(0), ToType,
4959                                      SuppressUserConversions,
4960                                      InOverloadResolution,
4961                                      AllowObjCWritebackConversion);
4962     }
4963     // FIXME: Check the other conditions here: array of character type,
4964     // initializer is a string literal.
4965     if (ToType->isArrayType()) {
4966       InitializedEntity Entity =
4967         InitializedEntity::InitializeParameter(S.Context, ToType,
4968                                                /*Consumed=*/false);
4969       if (S.CanPerformCopyInitialization(Entity, From)) {
4970         Result.setStandard();
4971         Result.Standard.setAsIdentityConversion();
4972         Result.Standard.setFromType(ToType);
4973         Result.Standard.setAllToTypes(ToType);
4974         return Result;
4975       }
4976     }
4977   }
4978 
4979   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4980   // C++11 [over.ics.list]p2:
4981   //   If the parameter type is std::initializer_list<X> or "array of X" and
4982   //   all the elements can be implicitly converted to X, the implicit
4983   //   conversion sequence is the worst conversion necessary to convert an
4984   //   element of the list to X.
4985   //
4986   // C++14 [over.ics.list]p3:
4987   //   Otherwise, if the parameter type is "array of N X", if the initializer
4988   //   list has exactly N elements or if it has fewer than N elements and X is
4989   //   default-constructible, and if all the elements of the initializer list
4990   //   can be implicitly converted to X, the implicit conversion sequence is
4991   //   the worst conversion necessary to convert an element of the list to X.
4992   //
4993   // FIXME: We're missing a lot of these checks.
4994   bool toStdInitializerList = false;
4995   QualType X;
4996   if (ToType->isArrayType())
4997     X = S.Context.getAsArrayType(ToType)->getElementType();
4998   else
4999     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5000   if (!X.isNull()) {
5001     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5002       Expr *Init = From->getInit(i);
5003       ImplicitConversionSequence ICS =
5004           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5005                                 InOverloadResolution,
5006                                 AllowObjCWritebackConversion);
5007       // If a single element isn't convertible, fail.
5008       if (ICS.isBad()) {
5009         Result = ICS;
5010         break;
5011       }
5012       // Otherwise, look for the worst conversion.
5013       if (Result.isBad() || CompareImplicitConversionSequences(
5014                                 S, From->getBeginLoc(), ICS, Result) ==
5015                                 ImplicitConversionSequence::Worse)
5016         Result = ICS;
5017     }
5018 
5019     // For an empty list, we won't have computed any conversion sequence.
5020     // Introduce the identity conversion sequence.
5021     if (From->getNumInits() == 0) {
5022       Result.setStandard();
5023       Result.Standard.setAsIdentityConversion();
5024       Result.Standard.setFromType(ToType);
5025       Result.Standard.setAllToTypes(ToType);
5026     }
5027 
5028     Result.setStdInitializerListElement(toStdInitializerList);
5029     return Result;
5030   }
5031 
5032   // C++14 [over.ics.list]p4:
5033   // C++11 [over.ics.list]p3:
5034   //   Otherwise, if the parameter is a non-aggregate class X and overload
5035   //   resolution chooses a single best constructor [...] the implicit
5036   //   conversion sequence is a user-defined conversion sequence. If multiple
5037   //   constructors are viable but none is better than the others, the
5038   //   implicit conversion sequence is a user-defined conversion sequence.
5039   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5040     // This function can deal with initializer lists.
5041     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5042                                     AllowedExplicit::None,
5043                                     InOverloadResolution, /*CStyle=*/false,
5044                                     AllowObjCWritebackConversion,
5045                                     /*AllowObjCConversionOnExplicit=*/false);
5046   }
5047 
5048   // C++14 [over.ics.list]p5:
5049   // C++11 [over.ics.list]p4:
5050   //   Otherwise, if the parameter has an aggregate type which can be
5051   //   initialized from the initializer list [...] the implicit conversion
5052   //   sequence is a user-defined conversion sequence.
5053   if (ToType->isAggregateType()) {
5054     // Type is an aggregate, argument is an init list. At this point it comes
5055     // down to checking whether the initialization works.
5056     // FIXME: Find out whether this parameter is consumed or not.
5057     InitializedEntity Entity =
5058         InitializedEntity::InitializeParameter(S.Context, ToType,
5059                                                /*Consumed=*/false);
5060     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5061                                                                  From)) {
5062       Result.setUserDefined();
5063       Result.UserDefined.Before.setAsIdentityConversion();
5064       // Initializer lists don't have a type.
5065       Result.UserDefined.Before.setFromType(QualType());
5066       Result.UserDefined.Before.setAllToTypes(QualType());
5067 
5068       Result.UserDefined.After.setAsIdentityConversion();
5069       Result.UserDefined.After.setFromType(ToType);
5070       Result.UserDefined.After.setAllToTypes(ToType);
5071       Result.UserDefined.ConversionFunction = nullptr;
5072     }
5073     return Result;
5074   }
5075 
5076   // C++14 [over.ics.list]p6:
5077   // C++11 [over.ics.list]p5:
5078   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5079   if (ToType->isReferenceType()) {
5080     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5081     // mention initializer lists in any way. So we go by what list-
5082     // initialization would do and try to extrapolate from that.
5083 
5084     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5085 
5086     // If the initializer list has a single element that is reference-related
5087     // to the parameter type, we initialize the reference from that.
5088     if (From->getNumInits() == 1) {
5089       Expr *Init = From->getInit(0);
5090 
5091       QualType T2 = Init->getType();
5092 
5093       // If the initializer is the address of an overloaded function, try
5094       // to resolve the overloaded function. If all goes well, T2 is the
5095       // type of the resulting function.
5096       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5097         DeclAccessPair Found;
5098         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5099                                    Init, ToType, false, Found))
5100           T2 = Fn->getType();
5101       }
5102 
5103       // Compute some basic properties of the types and the initializer.
5104       Sema::ReferenceCompareResult RefRelationship =
5105           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5106 
5107       if (RefRelationship >= Sema::Ref_Related) {
5108         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5109                                 SuppressUserConversions,
5110                                 /*AllowExplicit=*/false);
5111       }
5112     }
5113 
5114     // Otherwise, we bind the reference to a temporary created from the
5115     // initializer list.
5116     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5117                                InOverloadResolution,
5118                                AllowObjCWritebackConversion);
5119     if (Result.isFailure())
5120       return Result;
5121     assert(!Result.isEllipsis() &&
5122            "Sub-initialization cannot result in ellipsis conversion.");
5123 
5124     // Can we even bind to a temporary?
5125     if (ToType->isRValueReferenceType() ||
5126         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5127       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5128                                             Result.UserDefined.After;
5129       SCS.ReferenceBinding = true;
5130       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5131       SCS.BindsToRvalue = true;
5132       SCS.BindsToFunctionLvalue = false;
5133       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5134       SCS.ObjCLifetimeConversionBinding = false;
5135     } else
5136       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5137                     From, ToType);
5138     return Result;
5139   }
5140 
5141   // C++14 [over.ics.list]p7:
5142   // C++11 [over.ics.list]p6:
5143   //   Otherwise, if the parameter type is not a class:
5144   if (!ToType->isRecordType()) {
5145     //    - if the initializer list has one element that is not itself an
5146     //      initializer list, the implicit conversion sequence is the one
5147     //      required to convert the element to the parameter type.
5148     unsigned NumInits = From->getNumInits();
5149     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5150       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5151                                      SuppressUserConversions,
5152                                      InOverloadResolution,
5153                                      AllowObjCWritebackConversion);
5154     //    - if the initializer list has no elements, the implicit conversion
5155     //      sequence is the identity conversion.
5156     else if (NumInits == 0) {
5157       Result.setStandard();
5158       Result.Standard.setAsIdentityConversion();
5159       Result.Standard.setFromType(ToType);
5160       Result.Standard.setAllToTypes(ToType);
5161     }
5162     return Result;
5163   }
5164 
5165   // C++14 [over.ics.list]p8:
5166   // C++11 [over.ics.list]p7:
5167   //   In all cases other than those enumerated above, no conversion is possible
5168   return Result;
5169 }
5170 
5171 /// TryCopyInitialization - Try to copy-initialize a value of type
5172 /// ToType from the expression From. Return the implicit conversion
5173 /// sequence required to pass this argument, which may be a bad
5174 /// conversion sequence (meaning that the argument cannot be passed to
5175 /// a parameter of this type). If @p SuppressUserConversions, then we
5176 /// do not permit any user-defined conversion sequences.
5177 static ImplicitConversionSequence
5178 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5179                       bool SuppressUserConversions,
5180                       bool InOverloadResolution,
5181                       bool AllowObjCWritebackConversion,
5182                       bool AllowExplicit) {
5183   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5184     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5185                              InOverloadResolution,AllowObjCWritebackConversion);
5186 
5187   if (ToType->isReferenceType())
5188     return TryReferenceInit(S, From, ToType,
5189                             /*FIXME:*/ From->getBeginLoc(),
5190                             SuppressUserConversions, AllowExplicit);
5191 
5192   return TryImplicitConversion(S, From, ToType,
5193                                SuppressUserConversions,
5194                                AllowedExplicit::None,
5195                                InOverloadResolution,
5196                                /*CStyle=*/false,
5197                                AllowObjCWritebackConversion,
5198                                /*AllowObjCConversionOnExplicit=*/false);
5199 }
5200 
5201 static bool TryCopyInitialization(const CanQualType FromQTy,
5202                                   const CanQualType ToQTy,
5203                                   Sema &S,
5204                                   SourceLocation Loc,
5205                                   ExprValueKind FromVK) {
5206   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5207   ImplicitConversionSequence ICS =
5208     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5209 
5210   return !ICS.isBad();
5211 }
5212 
5213 /// TryObjectArgumentInitialization - Try to initialize the object
5214 /// parameter of the given member function (@c Method) from the
5215 /// expression @p From.
5216 static ImplicitConversionSequence
5217 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5218                                 Expr::Classification FromClassification,
5219                                 CXXMethodDecl *Method,
5220                                 CXXRecordDecl *ActingContext) {
5221   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5222   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5223   //                 const volatile object.
5224   Qualifiers Quals = Method->getMethodQualifiers();
5225   if (isa<CXXDestructorDecl>(Method)) {
5226     Quals.addConst();
5227     Quals.addVolatile();
5228   }
5229 
5230   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5231 
5232   // Set up the conversion sequence as a "bad" conversion, to allow us
5233   // to exit early.
5234   ImplicitConversionSequence ICS;
5235 
5236   // We need to have an object of class type.
5237   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5238     FromType = PT->getPointeeType();
5239 
5240     // When we had a pointer, it's implicitly dereferenced, so we
5241     // better have an lvalue.
5242     assert(FromClassification.isLValue());
5243   }
5244 
5245   assert(FromType->isRecordType());
5246 
5247   // C++0x [over.match.funcs]p4:
5248   //   For non-static member functions, the type of the implicit object
5249   //   parameter is
5250   //
5251   //     - "lvalue reference to cv X" for functions declared without a
5252   //        ref-qualifier or with the & ref-qualifier
5253   //     - "rvalue reference to cv X" for functions declared with the &&
5254   //        ref-qualifier
5255   //
5256   // where X is the class of which the function is a member and cv is the
5257   // cv-qualification on the member function declaration.
5258   //
5259   // However, when finding an implicit conversion sequence for the argument, we
5260   // are not allowed to perform user-defined conversions
5261   // (C++ [over.match.funcs]p5). We perform a simplified version of
5262   // reference binding here, that allows class rvalues to bind to
5263   // non-constant references.
5264 
5265   // First check the qualifiers.
5266   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5267   if (ImplicitParamType.getCVRQualifiers()
5268                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5269       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5270     ICS.setBad(BadConversionSequence::bad_qualifiers,
5271                FromType, ImplicitParamType);
5272     return ICS;
5273   }
5274 
5275   if (FromTypeCanon.hasAddressSpace()) {
5276     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5277     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5278     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5279       ICS.setBad(BadConversionSequence::bad_qualifiers,
5280                  FromType, ImplicitParamType);
5281       return ICS;
5282     }
5283   }
5284 
5285   // Check that we have either the same type or a derived type. It
5286   // affects the conversion rank.
5287   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5288   ImplicitConversionKind SecondKind;
5289   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5290     SecondKind = ICK_Identity;
5291   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5292     SecondKind = ICK_Derived_To_Base;
5293   else {
5294     ICS.setBad(BadConversionSequence::unrelated_class,
5295                FromType, ImplicitParamType);
5296     return ICS;
5297   }
5298 
5299   // Check the ref-qualifier.
5300   switch (Method->getRefQualifier()) {
5301   case RQ_None:
5302     // Do nothing; we don't care about lvalueness or rvalueness.
5303     break;
5304 
5305   case RQ_LValue:
5306     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5307       // non-const lvalue reference cannot bind to an rvalue
5308       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5309                  ImplicitParamType);
5310       return ICS;
5311     }
5312     break;
5313 
5314   case RQ_RValue:
5315     if (!FromClassification.isRValue()) {
5316       // rvalue reference cannot bind to an lvalue
5317       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5318                  ImplicitParamType);
5319       return ICS;
5320     }
5321     break;
5322   }
5323 
5324   // Success. Mark this as a reference binding.
5325   ICS.setStandard();
5326   ICS.Standard.setAsIdentityConversion();
5327   ICS.Standard.Second = SecondKind;
5328   ICS.Standard.setFromType(FromType);
5329   ICS.Standard.setAllToTypes(ImplicitParamType);
5330   ICS.Standard.ReferenceBinding = true;
5331   ICS.Standard.DirectBinding = true;
5332   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5333   ICS.Standard.BindsToFunctionLvalue = false;
5334   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5335   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5336     = (Method->getRefQualifier() == RQ_None);
5337   return ICS;
5338 }
5339 
5340 /// PerformObjectArgumentInitialization - Perform initialization of
5341 /// the implicit object parameter for the given Method with the given
5342 /// expression.
5343 ExprResult
5344 Sema::PerformObjectArgumentInitialization(Expr *From,
5345                                           NestedNameSpecifier *Qualifier,
5346                                           NamedDecl *FoundDecl,
5347                                           CXXMethodDecl *Method) {
5348   QualType FromRecordType, DestType;
5349   QualType ImplicitParamRecordType  =
5350     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5351 
5352   Expr::Classification FromClassification;
5353   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5354     FromRecordType = PT->getPointeeType();
5355     DestType = Method->getThisType();
5356     FromClassification = Expr::Classification::makeSimpleLValue();
5357   } else {
5358     FromRecordType = From->getType();
5359     DestType = ImplicitParamRecordType;
5360     FromClassification = From->Classify(Context);
5361 
5362     // When performing member access on an rvalue, materialize a temporary.
5363     if (From->isRValue()) {
5364       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5365                                             Method->getRefQualifier() !=
5366                                                 RefQualifierKind::RQ_RValue);
5367     }
5368   }
5369 
5370   // Note that we always use the true parent context when performing
5371   // the actual argument initialization.
5372   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5373       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5374       Method->getParent());
5375   if (ICS.isBad()) {
5376     switch (ICS.Bad.Kind) {
5377     case BadConversionSequence::bad_qualifiers: {
5378       Qualifiers FromQs = FromRecordType.getQualifiers();
5379       Qualifiers ToQs = DestType.getQualifiers();
5380       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5381       if (CVR) {
5382         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5383             << Method->getDeclName() << FromRecordType << (CVR - 1)
5384             << From->getSourceRange();
5385         Diag(Method->getLocation(), diag::note_previous_decl)
5386           << Method->getDeclName();
5387         return ExprError();
5388       }
5389       break;
5390     }
5391 
5392     case BadConversionSequence::lvalue_ref_to_rvalue:
5393     case BadConversionSequence::rvalue_ref_to_lvalue: {
5394       bool IsRValueQualified =
5395         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5396       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5397           << Method->getDeclName() << FromClassification.isRValue()
5398           << IsRValueQualified;
5399       Diag(Method->getLocation(), diag::note_previous_decl)
5400         << Method->getDeclName();
5401       return ExprError();
5402     }
5403 
5404     case BadConversionSequence::no_conversion:
5405     case BadConversionSequence::unrelated_class:
5406       break;
5407     }
5408 
5409     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5410            << ImplicitParamRecordType << FromRecordType
5411            << From->getSourceRange();
5412   }
5413 
5414   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5415     ExprResult FromRes =
5416       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5417     if (FromRes.isInvalid())
5418       return ExprError();
5419     From = FromRes.get();
5420   }
5421 
5422   if (!Context.hasSameType(From->getType(), DestType)) {
5423     CastKind CK;
5424     QualType PteeTy = DestType->getPointeeType();
5425     LangAS DestAS =
5426         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5427     if (FromRecordType.getAddressSpace() != DestAS)
5428       CK = CK_AddressSpaceConversion;
5429     else
5430       CK = CK_NoOp;
5431     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5432   }
5433   return From;
5434 }
5435 
5436 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5437 /// expression From to bool (C++0x [conv]p3).
5438 static ImplicitConversionSequence
5439 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5440   // C++ [dcl.init]/17.8:
5441   //   - Otherwise, if the initialization is direct-initialization, the source
5442   //     type is std::nullptr_t, and the destination type is bool, the initial
5443   //     value of the object being initialized is false.
5444   if (From->getType()->isNullPtrType())
5445     return ImplicitConversionSequence::getNullptrToBool(From->getType(),
5446                                                         S.Context.BoolTy,
5447                                                         From->isGLValue());
5448 
5449   // All other direct-initialization of bool is equivalent to an implicit
5450   // conversion to bool in which explicit conversions are permitted.
5451   return TryImplicitConversion(S, From, S.Context.BoolTy,
5452                                /*SuppressUserConversions=*/false,
5453                                AllowedExplicit::Conversions,
5454                                /*InOverloadResolution=*/false,
5455                                /*CStyle=*/false,
5456                                /*AllowObjCWritebackConversion=*/false,
5457                                /*AllowObjCConversionOnExplicit=*/false);
5458 }
5459 
5460 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5461 /// of the expression From to bool (C++0x [conv]p3).
5462 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5463   if (checkPlaceholderForOverload(*this, From))
5464     return ExprError();
5465 
5466   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5467   if (!ICS.isBad())
5468     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5469 
5470   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5471     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5472            << From->getType() << From->getSourceRange();
5473   return ExprError();
5474 }
5475 
5476 /// Check that the specified conversion is permitted in a converted constant
5477 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5478 /// is acceptable.
5479 static bool CheckConvertedConstantConversions(Sema &S,
5480                                               StandardConversionSequence &SCS) {
5481   // Since we know that the target type is an integral or unscoped enumeration
5482   // type, most conversion kinds are impossible. All possible First and Third
5483   // conversions are fine.
5484   switch (SCS.Second) {
5485   case ICK_Identity:
5486   case ICK_Function_Conversion:
5487   case ICK_Integral_Promotion:
5488   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5489   case ICK_Zero_Queue_Conversion:
5490     return true;
5491 
5492   case ICK_Boolean_Conversion:
5493     // Conversion from an integral or unscoped enumeration type to bool is
5494     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5495     // conversion, so we allow it in a converted constant expression.
5496     //
5497     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5498     // a lot of popular code. We should at least add a warning for this
5499     // (non-conforming) extension.
5500     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5501            SCS.getToType(2)->isBooleanType();
5502 
5503   case ICK_Pointer_Conversion:
5504   case ICK_Pointer_Member:
5505     // C++1z: null pointer conversions and null member pointer conversions are
5506     // only permitted if the source type is std::nullptr_t.
5507     return SCS.getFromType()->isNullPtrType();
5508 
5509   case ICK_Floating_Promotion:
5510   case ICK_Complex_Promotion:
5511   case ICK_Floating_Conversion:
5512   case ICK_Complex_Conversion:
5513   case ICK_Floating_Integral:
5514   case ICK_Compatible_Conversion:
5515   case ICK_Derived_To_Base:
5516   case ICK_Vector_Conversion:
5517   case ICK_Vector_Splat:
5518   case ICK_Complex_Real:
5519   case ICK_Block_Pointer_Conversion:
5520   case ICK_TransparentUnionConversion:
5521   case ICK_Writeback_Conversion:
5522   case ICK_Zero_Event_Conversion:
5523   case ICK_C_Only_Conversion:
5524   case ICK_Incompatible_Pointer_Conversion:
5525     return false;
5526 
5527   case ICK_Lvalue_To_Rvalue:
5528   case ICK_Array_To_Pointer:
5529   case ICK_Function_To_Pointer:
5530     llvm_unreachable("found a first conversion kind in Second");
5531 
5532   case ICK_Qualification:
5533     llvm_unreachable("found a third conversion kind in Second");
5534 
5535   case ICK_Num_Conversion_Kinds:
5536     break;
5537   }
5538 
5539   llvm_unreachable("unknown conversion kind");
5540 }
5541 
5542 /// CheckConvertedConstantExpression - Check that the expression From is a
5543 /// converted constant expression of type T, perform the conversion and produce
5544 /// the converted expression, per C++11 [expr.const]p3.
5545 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5546                                                    QualType T, APValue &Value,
5547                                                    Sema::CCEKind CCE,
5548                                                    bool RequireInt) {
5549   assert(S.getLangOpts().CPlusPlus11 &&
5550          "converted constant expression outside C++11");
5551 
5552   if (checkPlaceholderForOverload(S, From))
5553     return ExprError();
5554 
5555   // C++1z [expr.const]p3:
5556   //  A converted constant expression of type T is an expression,
5557   //  implicitly converted to type T, where the converted
5558   //  expression is a constant expression and the implicit conversion
5559   //  sequence contains only [... list of conversions ...].
5560   // C++1z [stmt.if]p2:
5561   //  If the if statement is of the form if constexpr, the value of the
5562   //  condition shall be a contextually converted constant expression of type
5563   //  bool.
5564   ImplicitConversionSequence ICS =
5565       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5566           ? TryContextuallyConvertToBool(S, From)
5567           : TryCopyInitialization(S, From, T,
5568                                   /*SuppressUserConversions=*/false,
5569                                   /*InOverloadResolution=*/false,
5570                                   /*AllowObjCWritebackConversion=*/false,
5571                                   /*AllowExplicit=*/false);
5572   StandardConversionSequence *SCS = nullptr;
5573   switch (ICS.getKind()) {
5574   case ImplicitConversionSequence::StandardConversion:
5575     SCS = &ICS.Standard;
5576     break;
5577   case ImplicitConversionSequence::UserDefinedConversion:
5578     // We are converting to a non-class type, so the Before sequence
5579     // must be trivial.
5580     SCS = &ICS.UserDefined.After;
5581     break;
5582   case ImplicitConversionSequence::AmbiguousConversion:
5583   case ImplicitConversionSequence::BadConversion:
5584     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5585       return S.Diag(From->getBeginLoc(),
5586                     diag::err_typecheck_converted_constant_expression)
5587              << From->getType() << From->getSourceRange() << T;
5588     return ExprError();
5589 
5590   case ImplicitConversionSequence::EllipsisConversion:
5591     llvm_unreachable("ellipsis conversion in converted constant expression");
5592   }
5593 
5594   // Check that we would only use permitted conversions.
5595   if (!CheckConvertedConstantConversions(S, *SCS)) {
5596     return S.Diag(From->getBeginLoc(),
5597                   diag::err_typecheck_converted_constant_expression_disallowed)
5598            << From->getType() << From->getSourceRange() << T;
5599   }
5600   // [...] and where the reference binding (if any) binds directly.
5601   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5602     return S.Diag(From->getBeginLoc(),
5603                   diag::err_typecheck_converted_constant_expression_indirect)
5604            << From->getType() << From->getSourceRange() << T;
5605   }
5606 
5607   ExprResult Result =
5608       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5609   if (Result.isInvalid())
5610     return Result;
5611 
5612   // C++2a [intro.execution]p5:
5613   //   A full-expression is [...] a constant-expression [...]
5614   Result =
5615       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5616                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5617   if (Result.isInvalid())
5618     return Result;
5619 
5620   // Check for a narrowing implicit conversion.
5621   APValue PreNarrowingValue;
5622   QualType PreNarrowingType;
5623   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5624                                 PreNarrowingType)) {
5625   case NK_Dependent_Narrowing:
5626     // Implicit conversion to a narrower type, but the expression is
5627     // value-dependent so we can't tell whether it's actually narrowing.
5628   case NK_Variable_Narrowing:
5629     // Implicit conversion to a narrower type, and the value is not a constant
5630     // expression. We'll diagnose this in a moment.
5631   case NK_Not_Narrowing:
5632     break;
5633 
5634   case NK_Constant_Narrowing:
5635     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5636         << CCE << /*Constant*/ 1
5637         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5638     break;
5639 
5640   case NK_Type_Narrowing:
5641     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5642         << CCE << /*Constant*/ 0 << From->getType() << T;
5643     break;
5644   }
5645 
5646   if (Result.get()->isValueDependent()) {
5647     Value = APValue();
5648     return Result;
5649   }
5650 
5651   // Check the expression is a constant expression.
5652   SmallVector<PartialDiagnosticAt, 8> Notes;
5653   Expr::EvalResult Eval;
5654   Eval.Diag = &Notes;
5655   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5656                                    ? Expr::EvaluateForMangling
5657                                    : Expr::EvaluateForCodeGen;
5658 
5659   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5660       (RequireInt && !Eval.Val.isInt())) {
5661     // The expression can't be folded, so we can't keep it at this position in
5662     // the AST.
5663     Result = ExprError();
5664   } else {
5665     Value = Eval.Val;
5666 
5667     if (Notes.empty()) {
5668       // It's a constant expression.
5669       return ConstantExpr::Create(S.Context, Result.get(), Value);
5670     }
5671   }
5672 
5673   // It's not a constant expression. Produce an appropriate diagnostic.
5674   if (Notes.size() == 1 &&
5675       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5676     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5677   else {
5678     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5679         << CCE << From->getSourceRange();
5680     for (unsigned I = 0; I < Notes.size(); ++I)
5681       S.Diag(Notes[I].first, Notes[I].second);
5682   }
5683   return ExprError();
5684 }
5685 
5686 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5687                                                   APValue &Value, CCEKind CCE) {
5688   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5689 }
5690 
5691 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5692                                                   llvm::APSInt &Value,
5693                                                   CCEKind CCE) {
5694   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5695 
5696   APValue V;
5697   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5698   if (!R.isInvalid() && !R.get()->isValueDependent())
5699     Value = V.getInt();
5700   return R;
5701 }
5702 
5703 
5704 /// dropPointerConversions - If the given standard conversion sequence
5705 /// involves any pointer conversions, remove them.  This may change
5706 /// the result type of the conversion sequence.
5707 static void dropPointerConversion(StandardConversionSequence &SCS) {
5708   if (SCS.Second == ICK_Pointer_Conversion) {
5709     SCS.Second = ICK_Identity;
5710     SCS.Third = ICK_Identity;
5711     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5712   }
5713 }
5714 
5715 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5716 /// convert the expression From to an Objective-C pointer type.
5717 static ImplicitConversionSequence
5718 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5719   // Do an implicit conversion to 'id'.
5720   QualType Ty = S.Context.getObjCIdType();
5721   ImplicitConversionSequence ICS
5722     = TryImplicitConversion(S, From, Ty,
5723                             // FIXME: Are these flags correct?
5724                             /*SuppressUserConversions=*/false,
5725                             AllowedExplicit::Conversions,
5726                             /*InOverloadResolution=*/false,
5727                             /*CStyle=*/false,
5728                             /*AllowObjCWritebackConversion=*/false,
5729                             /*AllowObjCConversionOnExplicit=*/true);
5730 
5731   // Strip off any final conversions to 'id'.
5732   switch (ICS.getKind()) {
5733   case ImplicitConversionSequence::BadConversion:
5734   case ImplicitConversionSequence::AmbiguousConversion:
5735   case ImplicitConversionSequence::EllipsisConversion:
5736     break;
5737 
5738   case ImplicitConversionSequence::UserDefinedConversion:
5739     dropPointerConversion(ICS.UserDefined.After);
5740     break;
5741 
5742   case ImplicitConversionSequence::StandardConversion:
5743     dropPointerConversion(ICS.Standard);
5744     break;
5745   }
5746 
5747   return ICS;
5748 }
5749 
5750 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5751 /// conversion of the expression From to an Objective-C pointer type.
5752 /// Returns a valid but null ExprResult if no conversion sequence exists.
5753 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5754   if (checkPlaceholderForOverload(*this, From))
5755     return ExprError();
5756 
5757   QualType Ty = Context.getObjCIdType();
5758   ImplicitConversionSequence ICS =
5759     TryContextuallyConvertToObjCPointer(*this, From);
5760   if (!ICS.isBad())
5761     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5762   return ExprResult();
5763 }
5764 
5765 /// Determine whether the provided type is an integral type, or an enumeration
5766 /// type of a permitted flavor.
5767 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5768   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5769                                  : T->isIntegralOrUnscopedEnumerationType();
5770 }
5771 
5772 static ExprResult
5773 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5774                             Sema::ContextualImplicitConverter &Converter,
5775                             QualType T, UnresolvedSetImpl &ViableConversions) {
5776 
5777   if (Converter.Suppress)
5778     return ExprError();
5779 
5780   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5781   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5782     CXXConversionDecl *Conv =
5783         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5784     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5785     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5786   }
5787   return From;
5788 }
5789 
5790 static bool
5791 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5792                            Sema::ContextualImplicitConverter &Converter,
5793                            QualType T, bool HadMultipleCandidates,
5794                            UnresolvedSetImpl &ExplicitConversions) {
5795   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5796     DeclAccessPair Found = ExplicitConversions[0];
5797     CXXConversionDecl *Conversion =
5798         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5799 
5800     // The user probably meant to invoke the given explicit
5801     // conversion; use it.
5802     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5803     std::string TypeStr;
5804     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5805 
5806     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5807         << FixItHint::CreateInsertion(From->getBeginLoc(),
5808                                       "static_cast<" + TypeStr + ">(")
5809         << FixItHint::CreateInsertion(
5810                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5811     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5812 
5813     // If we aren't in a SFINAE context, build a call to the
5814     // explicit conversion function.
5815     if (SemaRef.isSFINAEContext())
5816       return true;
5817 
5818     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5819     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5820                                                        HadMultipleCandidates);
5821     if (Result.isInvalid())
5822       return true;
5823     // Record usage of conversion in an implicit cast.
5824     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5825                                     CK_UserDefinedConversion, Result.get(),
5826                                     nullptr, Result.get()->getValueKind());
5827   }
5828   return false;
5829 }
5830 
5831 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5832                              Sema::ContextualImplicitConverter &Converter,
5833                              QualType T, bool HadMultipleCandidates,
5834                              DeclAccessPair &Found) {
5835   CXXConversionDecl *Conversion =
5836       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5837   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5838 
5839   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5840   if (!Converter.SuppressConversion) {
5841     if (SemaRef.isSFINAEContext())
5842       return true;
5843 
5844     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5845         << From->getSourceRange();
5846   }
5847 
5848   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5849                                                      HadMultipleCandidates);
5850   if (Result.isInvalid())
5851     return true;
5852   // Record usage of conversion in an implicit cast.
5853   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5854                                   CK_UserDefinedConversion, Result.get(),
5855                                   nullptr, Result.get()->getValueKind());
5856   return false;
5857 }
5858 
5859 static ExprResult finishContextualImplicitConversion(
5860     Sema &SemaRef, SourceLocation Loc, Expr *From,
5861     Sema::ContextualImplicitConverter &Converter) {
5862   if (!Converter.match(From->getType()) && !Converter.Suppress)
5863     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5864         << From->getSourceRange();
5865 
5866   return SemaRef.DefaultLvalueConversion(From);
5867 }
5868 
5869 static void
5870 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5871                                   UnresolvedSetImpl &ViableConversions,
5872                                   OverloadCandidateSet &CandidateSet) {
5873   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5874     DeclAccessPair FoundDecl = ViableConversions[I];
5875     NamedDecl *D = FoundDecl.getDecl();
5876     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5877     if (isa<UsingShadowDecl>(D))
5878       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5879 
5880     CXXConversionDecl *Conv;
5881     FunctionTemplateDecl *ConvTemplate;
5882     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5883       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5884     else
5885       Conv = cast<CXXConversionDecl>(D);
5886 
5887     if (ConvTemplate)
5888       SemaRef.AddTemplateConversionCandidate(
5889           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5890           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5891     else
5892       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5893                                      ToType, CandidateSet,
5894                                      /*AllowObjCConversionOnExplicit=*/false,
5895                                      /*AllowExplicit*/ true);
5896   }
5897 }
5898 
5899 /// Attempt to convert the given expression to a type which is accepted
5900 /// by the given converter.
5901 ///
5902 /// This routine will attempt to convert an expression of class type to a
5903 /// type accepted by the specified converter. In C++11 and before, the class
5904 /// must have a single non-explicit conversion function converting to a matching
5905 /// type. In C++1y, there can be multiple such conversion functions, but only
5906 /// one target type.
5907 ///
5908 /// \param Loc The source location of the construct that requires the
5909 /// conversion.
5910 ///
5911 /// \param From The expression we're converting from.
5912 ///
5913 /// \param Converter Used to control and diagnose the conversion process.
5914 ///
5915 /// \returns The expression, converted to an integral or enumeration type if
5916 /// successful.
5917 ExprResult Sema::PerformContextualImplicitConversion(
5918     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5919   // We can't perform any more checking for type-dependent expressions.
5920   if (From->isTypeDependent())
5921     return From;
5922 
5923   // Process placeholders immediately.
5924   if (From->hasPlaceholderType()) {
5925     ExprResult result = CheckPlaceholderExpr(From);
5926     if (result.isInvalid())
5927       return result;
5928     From = result.get();
5929   }
5930 
5931   // If the expression already has a matching type, we're golden.
5932   QualType T = From->getType();
5933   if (Converter.match(T))
5934     return DefaultLvalueConversion(From);
5935 
5936   // FIXME: Check for missing '()' if T is a function type?
5937 
5938   // We can only perform contextual implicit conversions on objects of class
5939   // type.
5940   const RecordType *RecordTy = T->getAs<RecordType>();
5941   if (!RecordTy || !getLangOpts().CPlusPlus) {
5942     if (!Converter.Suppress)
5943       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5944     return From;
5945   }
5946 
5947   // We must have a complete class type.
5948   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5949     ContextualImplicitConverter &Converter;
5950     Expr *From;
5951 
5952     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5953         : Converter(Converter), From(From) {}
5954 
5955     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5956       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5957     }
5958   } IncompleteDiagnoser(Converter, From);
5959 
5960   if (Converter.Suppress ? !isCompleteType(Loc, T)
5961                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5962     return From;
5963 
5964   // Look for a conversion to an integral or enumeration type.
5965   UnresolvedSet<4>
5966       ViableConversions; // These are *potentially* viable in C++1y.
5967   UnresolvedSet<4> ExplicitConversions;
5968   const auto &Conversions =
5969       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5970 
5971   bool HadMultipleCandidates =
5972       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5973 
5974   // To check that there is only one target type, in C++1y:
5975   QualType ToType;
5976   bool HasUniqueTargetType = true;
5977 
5978   // Collect explicit or viable (potentially in C++1y) conversions.
5979   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5980     NamedDecl *D = (*I)->getUnderlyingDecl();
5981     CXXConversionDecl *Conversion;
5982     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5983     if (ConvTemplate) {
5984       if (getLangOpts().CPlusPlus14)
5985         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5986       else
5987         continue; // C++11 does not consider conversion operator templates(?).
5988     } else
5989       Conversion = cast<CXXConversionDecl>(D);
5990 
5991     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5992            "Conversion operator templates are considered potentially "
5993            "viable in C++1y");
5994 
5995     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5996     if (Converter.match(CurToType) || ConvTemplate) {
5997 
5998       if (Conversion->isExplicit()) {
5999         // FIXME: For C++1y, do we need this restriction?
6000         // cf. diagnoseNoViableConversion()
6001         if (!ConvTemplate)
6002           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6003       } else {
6004         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6005           if (ToType.isNull())
6006             ToType = CurToType.getUnqualifiedType();
6007           else if (HasUniqueTargetType &&
6008                    (CurToType.getUnqualifiedType() != ToType))
6009             HasUniqueTargetType = false;
6010         }
6011         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6012       }
6013     }
6014   }
6015 
6016   if (getLangOpts().CPlusPlus14) {
6017     // C++1y [conv]p6:
6018     // ... An expression e of class type E appearing in such a context
6019     // is said to be contextually implicitly converted to a specified
6020     // type T and is well-formed if and only if e can be implicitly
6021     // converted to a type T that is determined as follows: E is searched
6022     // for conversion functions whose return type is cv T or reference to
6023     // cv T such that T is allowed by the context. There shall be
6024     // exactly one such T.
6025 
6026     // If no unique T is found:
6027     if (ToType.isNull()) {
6028       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6029                                      HadMultipleCandidates,
6030                                      ExplicitConversions))
6031         return ExprError();
6032       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6033     }
6034 
6035     // If more than one unique Ts are found:
6036     if (!HasUniqueTargetType)
6037       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6038                                          ViableConversions);
6039 
6040     // If one unique T is found:
6041     // First, build a candidate set from the previously recorded
6042     // potentially viable conversions.
6043     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6044     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6045                                       CandidateSet);
6046 
6047     // Then, perform overload resolution over the candidate set.
6048     OverloadCandidateSet::iterator Best;
6049     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6050     case OR_Success: {
6051       // Apply this conversion.
6052       DeclAccessPair Found =
6053           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6054       if (recordConversion(*this, Loc, From, Converter, T,
6055                            HadMultipleCandidates, Found))
6056         return ExprError();
6057       break;
6058     }
6059     case OR_Ambiguous:
6060       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6061                                          ViableConversions);
6062     case OR_No_Viable_Function:
6063       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6064                                      HadMultipleCandidates,
6065                                      ExplicitConversions))
6066         return ExprError();
6067       LLVM_FALLTHROUGH;
6068     case OR_Deleted:
6069       // We'll complain below about a non-integral condition type.
6070       break;
6071     }
6072   } else {
6073     switch (ViableConversions.size()) {
6074     case 0: {
6075       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6076                                      HadMultipleCandidates,
6077                                      ExplicitConversions))
6078         return ExprError();
6079 
6080       // We'll complain below about a non-integral condition type.
6081       break;
6082     }
6083     case 1: {
6084       // Apply this conversion.
6085       DeclAccessPair Found = ViableConversions[0];
6086       if (recordConversion(*this, Loc, From, Converter, T,
6087                            HadMultipleCandidates, Found))
6088         return ExprError();
6089       break;
6090     }
6091     default:
6092       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6093                                          ViableConversions);
6094     }
6095   }
6096 
6097   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6098 }
6099 
6100 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6101 /// an acceptable non-member overloaded operator for a call whose
6102 /// arguments have types T1 (and, if non-empty, T2). This routine
6103 /// implements the check in C++ [over.match.oper]p3b2 concerning
6104 /// enumeration types.
6105 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6106                                                    FunctionDecl *Fn,
6107                                                    ArrayRef<Expr *> Args) {
6108   QualType T1 = Args[0]->getType();
6109   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6110 
6111   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6112     return true;
6113 
6114   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6115     return true;
6116 
6117   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6118   if (Proto->getNumParams() < 1)
6119     return false;
6120 
6121   if (T1->isEnumeralType()) {
6122     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6123     if (Context.hasSameUnqualifiedType(T1, ArgType))
6124       return true;
6125   }
6126 
6127   if (Proto->getNumParams() < 2)
6128     return false;
6129 
6130   if (!T2.isNull() && T2->isEnumeralType()) {
6131     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6132     if (Context.hasSameUnqualifiedType(T2, ArgType))
6133       return true;
6134   }
6135 
6136   return false;
6137 }
6138 
6139 /// AddOverloadCandidate - Adds the given function to the set of
6140 /// candidate functions, using the given function call arguments.  If
6141 /// @p SuppressUserConversions, then don't allow user-defined
6142 /// conversions via constructors or conversion operators.
6143 ///
6144 /// \param PartialOverloading true if we are performing "partial" overloading
6145 /// based on an incomplete set of function arguments. This feature is used by
6146 /// code completion.
6147 void Sema::AddOverloadCandidate(
6148     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6149     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6150     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6151     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6152     OverloadCandidateParamOrder PO) {
6153   const FunctionProtoType *Proto
6154     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6155   assert(Proto && "Functions without a prototype cannot be overloaded");
6156   assert(!Function->getDescribedFunctionTemplate() &&
6157          "Use AddTemplateOverloadCandidate for function templates");
6158 
6159   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6160     if (!isa<CXXConstructorDecl>(Method)) {
6161       // If we get here, it's because we're calling a member function
6162       // that is named without a member access expression (e.g.,
6163       // "this->f") that was either written explicitly or created
6164       // implicitly. This can happen with a qualified call to a member
6165       // function, e.g., X::f(). We use an empty type for the implied
6166       // object argument (C++ [over.call.func]p3), and the acting context
6167       // is irrelevant.
6168       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6169                          Expr::Classification::makeSimpleLValue(), Args,
6170                          CandidateSet, SuppressUserConversions,
6171                          PartialOverloading, EarlyConversions, PO);
6172       return;
6173     }
6174     // We treat a constructor like a non-member function, since its object
6175     // argument doesn't participate in overload resolution.
6176   }
6177 
6178   if (!CandidateSet.isNewCandidate(Function, PO))
6179     return;
6180 
6181   // C++11 [class.copy]p11: [DR1402]
6182   //   A defaulted move constructor that is defined as deleted is ignored by
6183   //   overload resolution.
6184   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6185   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6186       Constructor->isMoveConstructor())
6187     return;
6188 
6189   // Overload resolution is always an unevaluated context.
6190   EnterExpressionEvaluationContext Unevaluated(
6191       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6192 
6193   // C++ [over.match.oper]p3:
6194   //   if no operand has a class type, only those non-member functions in the
6195   //   lookup set that have a first parameter of type T1 or "reference to
6196   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6197   //   is a right operand) a second parameter of type T2 or "reference to
6198   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6199   //   candidate functions.
6200   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6201       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6202     return;
6203 
6204   // Add this candidate
6205   OverloadCandidate &Candidate =
6206       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6207   Candidate.FoundDecl = FoundDecl;
6208   Candidate.Function = Function;
6209   Candidate.Viable = true;
6210   Candidate.RewriteKind =
6211       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6212   Candidate.IsSurrogate = false;
6213   Candidate.IsADLCandidate = IsADLCandidate;
6214   Candidate.IgnoreObjectArgument = false;
6215   Candidate.ExplicitCallArguments = Args.size();
6216 
6217   // Explicit functions are not actually candidates at all if we're not
6218   // allowing them in this context, but keep them around so we can point
6219   // to them in diagnostics.
6220   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6221     Candidate.Viable = false;
6222     Candidate.FailureKind = ovl_fail_explicit;
6223     return;
6224   }
6225 
6226   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6227       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6228     Candidate.Viable = false;
6229     Candidate.FailureKind = ovl_non_default_multiversion_function;
6230     return;
6231   }
6232 
6233   if (Constructor) {
6234     // C++ [class.copy]p3:
6235     //   A member function template is never instantiated to perform the copy
6236     //   of a class object to an object of its class type.
6237     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6238     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6239         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6240          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6241                        ClassType))) {
6242       Candidate.Viable = false;
6243       Candidate.FailureKind = ovl_fail_illegal_constructor;
6244       return;
6245     }
6246 
6247     // C++ [over.match.funcs]p8: (proposed DR resolution)
6248     //   A constructor inherited from class type C that has a first parameter
6249     //   of type "reference to P" (including such a constructor instantiated
6250     //   from a template) is excluded from the set of candidate functions when
6251     //   constructing an object of type cv D if the argument list has exactly
6252     //   one argument and D is reference-related to P and P is reference-related
6253     //   to C.
6254     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6255     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6256         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6257       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6258       QualType C = Context.getRecordType(Constructor->getParent());
6259       QualType D = Context.getRecordType(Shadow->getParent());
6260       SourceLocation Loc = Args.front()->getExprLoc();
6261       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6262           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6263         Candidate.Viable = false;
6264         Candidate.FailureKind = ovl_fail_inhctor_slice;
6265         return;
6266       }
6267     }
6268 
6269     // Check that the constructor is capable of constructing an object in the
6270     // destination address space.
6271     if (!Qualifiers::isAddressSpaceSupersetOf(
6272             Constructor->getMethodQualifiers().getAddressSpace(),
6273             CandidateSet.getDestAS())) {
6274       Candidate.Viable = false;
6275       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6276     }
6277   }
6278 
6279   unsigned NumParams = Proto->getNumParams();
6280 
6281   // (C++ 13.3.2p2): A candidate function having fewer than m
6282   // parameters is viable only if it has an ellipsis in its parameter
6283   // list (8.3.5).
6284   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6285       !Proto->isVariadic()) {
6286     Candidate.Viable = false;
6287     Candidate.FailureKind = ovl_fail_too_many_arguments;
6288     return;
6289   }
6290 
6291   // (C++ 13.3.2p2): A candidate function having more than m parameters
6292   // is viable only if the (m+1)st parameter has a default argument
6293   // (8.3.6). For the purposes of overload resolution, the
6294   // parameter list is truncated on the right, so that there are
6295   // exactly m parameters.
6296   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6297   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6298     // Not enough arguments.
6299     Candidate.Viable = false;
6300     Candidate.FailureKind = ovl_fail_too_few_arguments;
6301     return;
6302   }
6303 
6304   // (CUDA B.1): Check for invalid calls between targets.
6305   if (getLangOpts().CUDA)
6306     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6307       // Skip the check for callers that are implicit members, because in this
6308       // case we may not yet know what the member's target is; the target is
6309       // inferred for the member automatically, based on the bases and fields of
6310       // the class.
6311       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6312         Candidate.Viable = false;
6313         Candidate.FailureKind = ovl_fail_bad_target;
6314         return;
6315       }
6316 
6317   if (Function->getTrailingRequiresClause()) {
6318     ConstraintSatisfaction Satisfaction;
6319     if (CheckFunctionConstraints(Function, Satisfaction) ||
6320         !Satisfaction.IsSatisfied) {
6321       Candidate.Viable = false;
6322       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6323       return;
6324     }
6325   }
6326 
6327   // Determine the implicit conversion sequences for each of the
6328   // arguments.
6329   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6330     unsigned ConvIdx =
6331         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6332     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6333       // We already formed a conversion sequence for this parameter during
6334       // template argument deduction.
6335     } else if (ArgIdx < NumParams) {
6336       // (C++ 13.3.2p3): for F to be a viable function, there shall
6337       // exist for each argument an implicit conversion sequence
6338       // (13.3.3.1) that converts that argument to the corresponding
6339       // parameter of F.
6340       QualType ParamType = Proto->getParamType(ArgIdx);
6341       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6342           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6343           /*InOverloadResolution=*/true,
6344           /*AllowObjCWritebackConversion=*/
6345           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6346       if (Candidate.Conversions[ConvIdx].isBad()) {
6347         Candidate.Viable = false;
6348         Candidate.FailureKind = ovl_fail_bad_conversion;
6349         return;
6350       }
6351     } else {
6352       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6353       // argument for which there is no corresponding parameter is
6354       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6355       Candidate.Conversions[ConvIdx].setEllipsis();
6356     }
6357   }
6358 
6359   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6360     Candidate.Viable = false;
6361     Candidate.FailureKind = ovl_fail_enable_if;
6362     Candidate.DeductionFailure.Data = FailedAttr;
6363     return;
6364   }
6365 
6366   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6367     Candidate.Viable = false;
6368     Candidate.FailureKind = ovl_fail_ext_disabled;
6369     return;
6370   }
6371 }
6372 
6373 ObjCMethodDecl *
6374 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6375                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6376   if (Methods.size() <= 1)
6377     return nullptr;
6378 
6379   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6380     bool Match = true;
6381     ObjCMethodDecl *Method = Methods[b];
6382     unsigned NumNamedArgs = Sel.getNumArgs();
6383     // Method might have more arguments than selector indicates. This is due
6384     // to addition of c-style arguments in method.
6385     if (Method->param_size() > NumNamedArgs)
6386       NumNamedArgs = Method->param_size();
6387     if (Args.size() < NumNamedArgs)
6388       continue;
6389 
6390     for (unsigned i = 0; i < NumNamedArgs; i++) {
6391       // We can't do any type-checking on a type-dependent argument.
6392       if (Args[i]->isTypeDependent()) {
6393         Match = false;
6394         break;
6395       }
6396 
6397       ParmVarDecl *param = Method->parameters()[i];
6398       Expr *argExpr = Args[i];
6399       assert(argExpr && "SelectBestMethod(): missing expression");
6400 
6401       // Strip the unbridged-cast placeholder expression off unless it's
6402       // a consumed argument.
6403       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6404           !param->hasAttr<CFConsumedAttr>())
6405         argExpr = stripARCUnbridgedCast(argExpr);
6406 
6407       // If the parameter is __unknown_anytype, move on to the next method.
6408       if (param->getType() == Context.UnknownAnyTy) {
6409         Match = false;
6410         break;
6411       }
6412 
6413       ImplicitConversionSequence ConversionState
6414         = TryCopyInitialization(*this, argExpr, param->getType(),
6415                                 /*SuppressUserConversions*/false,
6416                                 /*InOverloadResolution=*/true,
6417                                 /*AllowObjCWritebackConversion=*/
6418                                 getLangOpts().ObjCAutoRefCount,
6419                                 /*AllowExplicit*/false);
6420       // This function looks for a reasonably-exact match, so we consider
6421       // incompatible pointer conversions to be a failure here.
6422       if (ConversionState.isBad() ||
6423           (ConversionState.isStandard() &&
6424            ConversionState.Standard.Second ==
6425                ICK_Incompatible_Pointer_Conversion)) {
6426         Match = false;
6427         break;
6428       }
6429     }
6430     // Promote additional arguments to variadic methods.
6431     if (Match && Method->isVariadic()) {
6432       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6433         if (Args[i]->isTypeDependent()) {
6434           Match = false;
6435           break;
6436         }
6437         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6438                                                           nullptr);
6439         if (Arg.isInvalid()) {
6440           Match = false;
6441           break;
6442         }
6443       }
6444     } else {
6445       // Check for extra arguments to non-variadic methods.
6446       if (Args.size() != NumNamedArgs)
6447         Match = false;
6448       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6449         // Special case when selectors have no argument. In this case, select
6450         // one with the most general result type of 'id'.
6451         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6452           QualType ReturnT = Methods[b]->getReturnType();
6453           if (ReturnT->isObjCIdType())
6454             return Methods[b];
6455         }
6456       }
6457     }
6458 
6459     if (Match)
6460       return Method;
6461   }
6462   return nullptr;
6463 }
6464 
6465 static bool
6466 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6467                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6468                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6469                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6470   if (ThisArg) {
6471     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6472     assert(!isa<CXXConstructorDecl>(Method) &&
6473            "Shouldn't have `this` for ctors!");
6474     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6475     ExprResult R = S.PerformObjectArgumentInitialization(
6476         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6477     if (R.isInvalid())
6478       return false;
6479     ConvertedThis = R.get();
6480   } else {
6481     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6482       (void)MD;
6483       assert((MissingImplicitThis || MD->isStatic() ||
6484               isa<CXXConstructorDecl>(MD)) &&
6485              "Expected `this` for non-ctor instance methods");
6486     }
6487     ConvertedThis = nullptr;
6488   }
6489 
6490   // Ignore any variadic arguments. Converting them is pointless, since the
6491   // user can't refer to them in the function condition.
6492   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6493 
6494   // Convert the arguments.
6495   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6496     ExprResult R;
6497     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6498                                         S.Context, Function->getParamDecl(I)),
6499                                     SourceLocation(), Args[I]);
6500 
6501     if (R.isInvalid())
6502       return false;
6503 
6504     ConvertedArgs.push_back(R.get());
6505   }
6506 
6507   if (Trap.hasErrorOccurred())
6508     return false;
6509 
6510   // Push default arguments if needed.
6511   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6512     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6513       ParmVarDecl *P = Function->getParamDecl(i);
6514       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6515                          ? P->getUninstantiatedDefaultArg()
6516                          : P->getDefaultArg();
6517       // This can only happen in code completion, i.e. when PartialOverloading
6518       // is true.
6519       if (!DefArg)
6520         return false;
6521       ExprResult R =
6522           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6523                                           S.Context, Function->getParamDecl(i)),
6524                                       SourceLocation(), DefArg);
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, ArrayRef<Expr *> Args,
6537                                   bool MissingImplicitThis) {
6538   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6539   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6540     return nullptr;
6541 
6542   SFINAETrap Trap(*this);
6543   SmallVector<Expr *, 16> ConvertedArgs;
6544   // FIXME: We should look into making enable_if late-parsed.
6545   Expr *DiscardedThis;
6546   if (!convertArgsForAvailabilityChecks(
6547           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6548           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6549     return *EnableIfAttrs.begin();
6550 
6551   for (auto *EIA : EnableIfAttrs) {
6552     APValue Result;
6553     // FIXME: This doesn't consider value-dependent cases, because doing so is
6554     // very difficult. Ideally, we should handle them more gracefully.
6555     if (EIA->getCond()->isValueDependent() ||
6556         !EIA->getCond()->EvaluateWithSubstitution(
6557             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6558       return EIA;
6559 
6560     if (!Result.isInt() || !Result.getInt().getBoolValue())
6561       return EIA;
6562   }
6563   return nullptr;
6564 }
6565 
6566 template <typename CheckFn>
6567 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6568                                         bool ArgDependent, SourceLocation Loc,
6569                                         CheckFn &&IsSuccessful) {
6570   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6571   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6572     if (ArgDependent == DIA->getArgDependent())
6573       Attrs.push_back(DIA);
6574   }
6575 
6576   // Common case: No diagnose_if attributes, so we can quit early.
6577   if (Attrs.empty())
6578     return false;
6579 
6580   auto WarningBegin = std::stable_partition(
6581       Attrs.begin(), Attrs.end(),
6582       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6583 
6584   // Note that diagnose_if attributes are late-parsed, so they appear in the
6585   // correct order (unlike enable_if attributes).
6586   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6587                                IsSuccessful);
6588   if (ErrAttr != WarningBegin) {
6589     const DiagnoseIfAttr *DIA = *ErrAttr;
6590     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6591     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6592         << DIA->getParent() << DIA->getCond()->getSourceRange();
6593     return true;
6594   }
6595 
6596   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6597     if (IsSuccessful(DIA)) {
6598       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6599       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6600           << DIA->getParent() << DIA->getCond()->getSourceRange();
6601     }
6602 
6603   return false;
6604 }
6605 
6606 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6607                                                const Expr *ThisArg,
6608                                                ArrayRef<const Expr *> Args,
6609                                                SourceLocation Loc) {
6610   return diagnoseDiagnoseIfAttrsWith(
6611       *this, Function, /*ArgDependent=*/true, Loc,
6612       [&](const DiagnoseIfAttr *DIA) {
6613         APValue Result;
6614         // It's sane to use the same Args for any redecl of this function, since
6615         // EvaluateWithSubstitution only cares about the position of each
6616         // argument in the arg list, not the ParmVarDecl* it maps to.
6617         if (!DIA->getCond()->EvaluateWithSubstitution(
6618                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6619           return false;
6620         return Result.isInt() && Result.getInt().getBoolValue();
6621       });
6622 }
6623 
6624 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6625                                                  SourceLocation Loc) {
6626   return diagnoseDiagnoseIfAttrsWith(
6627       *this, ND, /*ArgDependent=*/false, Loc,
6628       [&](const DiagnoseIfAttr *DIA) {
6629         bool Result;
6630         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6631                Result;
6632       });
6633 }
6634 
6635 /// Add all of the function declarations in the given function set to
6636 /// the overload candidate set.
6637 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6638                                  ArrayRef<Expr *> Args,
6639                                  OverloadCandidateSet &CandidateSet,
6640                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6641                                  bool SuppressUserConversions,
6642                                  bool PartialOverloading,
6643                                  bool FirstArgumentIsBase) {
6644   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6645     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6646     ArrayRef<Expr *> FunctionArgs = Args;
6647 
6648     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6649     FunctionDecl *FD =
6650         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6651 
6652     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6653       QualType ObjectType;
6654       Expr::Classification ObjectClassification;
6655       if (Args.size() > 0) {
6656         if (Expr *E = Args[0]) {
6657           // Use the explicit base to restrict the lookup:
6658           ObjectType = E->getType();
6659           // Pointers in the object arguments are implicitly dereferenced, so we
6660           // always classify them as l-values.
6661           if (!ObjectType.isNull() && ObjectType->isPointerType())
6662             ObjectClassification = Expr::Classification::makeSimpleLValue();
6663           else
6664             ObjectClassification = E->Classify(Context);
6665         } // .. else there is an implicit base.
6666         FunctionArgs = Args.slice(1);
6667       }
6668       if (FunTmpl) {
6669         AddMethodTemplateCandidate(
6670             FunTmpl, F.getPair(),
6671             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6672             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6673             FunctionArgs, CandidateSet, SuppressUserConversions,
6674             PartialOverloading);
6675       } else {
6676         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6677                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6678                            ObjectClassification, FunctionArgs, CandidateSet,
6679                            SuppressUserConversions, PartialOverloading);
6680       }
6681     } else {
6682       // This branch handles both standalone functions and static methods.
6683 
6684       // Slice the first argument (which is the base) when we access
6685       // static method as non-static.
6686       if (Args.size() > 0 &&
6687           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6688                         !isa<CXXConstructorDecl>(FD)))) {
6689         assert(cast<CXXMethodDecl>(FD)->isStatic());
6690         FunctionArgs = Args.slice(1);
6691       }
6692       if (FunTmpl) {
6693         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6694                                      ExplicitTemplateArgs, FunctionArgs,
6695                                      CandidateSet, SuppressUserConversions,
6696                                      PartialOverloading);
6697       } else {
6698         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6699                              SuppressUserConversions, PartialOverloading);
6700       }
6701     }
6702   }
6703 }
6704 
6705 /// AddMethodCandidate - Adds a named decl (which is some kind of
6706 /// method) as a method candidate to the given overload set.
6707 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6708                               Expr::Classification ObjectClassification,
6709                               ArrayRef<Expr *> Args,
6710                               OverloadCandidateSet &CandidateSet,
6711                               bool SuppressUserConversions,
6712                               OverloadCandidateParamOrder PO) {
6713   NamedDecl *Decl = FoundDecl.getDecl();
6714   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6715 
6716   if (isa<UsingShadowDecl>(Decl))
6717     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6718 
6719   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6720     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6721            "Expected a member function template");
6722     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6723                                /*ExplicitArgs*/ nullptr, ObjectType,
6724                                ObjectClassification, Args, CandidateSet,
6725                                SuppressUserConversions, false, PO);
6726   } else {
6727     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6728                        ObjectType, ObjectClassification, Args, CandidateSet,
6729                        SuppressUserConversions, false, None, PO);
6730   }
6731 }
6732 
6733 /// AddMethodCandidate - Adds the given C++ member function to the set
6734 /// of candidate functions, using the given function call arguments
6735 /// and the object argument (@c Object). For example, in a call
6736 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6737 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6738 /// allow user-defined conversions via constructors or conversion
6739 /// operators.
6740 void
6741 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6742                          CXXRecordDecl *ActingContext, QualType ObjectType,
6743                          Expr::Classification ObjectClassification,
6744                          ArrayRef<Expr *> Args,
6745                          OverloadCandidateSet &CandidateSet,
6746                          bool SuppressUserConversions,
6747                          bool PartialOverloading,
6748                          ConversionSequenceList EarlyConversions,
6749                          OverloadCandidateParamOrder PO) {
6750   const FunctionProtoType *Proto
6751     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6752   assert(Proto && "Methods without a prototype cannot be overloaded");
6753   assert(!isa<CXXConstructorDecl>(Method) &&
6754          "Use AddOverloadCandidate for constructors");
6755 
6756   if (!CandidateSet.isNewCandidate(Method, PO))
6757     return;
6758 
6759   // C++11 [class.copy]p23: [DR1402]
6760   //   A defaulted move assignment operator that is defined as deleted is
6761   //   ignored by overload resolution.
6762   if (Method->isDefaulted() && Method->isDeleted() &&
6763       Method->isMoveAssignmentOperator())
6764     return;
6765 
6766   // Overload resolution is always an unevaluated context.
6767   EnterExpressionEvaluationContext Unevaluated(
6768       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6769 
6770   // Add this candidate
6771   OverloadCandidate &Candidate =
6772       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6773   Candidate.FoundDecl = FoundDecl;
6774   Candidate.Function = Method;
6775   Candidate.RewriteKind =
6776       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6777   Candidate.IsSurrogate = false;
6778   Candidate.IgnoreObjectArgument = false;
6779   Candidate.ExplicitCallArguments = Args.size();
6780 
6781   unsigned NumParams = Proto->getNumParams();
6782 
6783   // (C++ 13.3.2p2): A candidate function having fewer than m
6784   // parameters is viable only if it has an ellipsis in its parameter
6785   // list (8.3.5).
6786   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6787       !Proto->isVariadic()) {
6788     Candidate.Viable = false;
6789     Candidate.FailureKind = ovl_fail_too_many_arguments;
6790     return;
6791   }
6792 
6793   // (C++ 13.3.2p2): A candidate function having more than m parameters
6794   // is viable only if the (m+1)st parameter has a default argument
6795   // (8.3.6). For the purposes of overload resolution, the
6796   // parameter list is truncated on the right, so that there are
6797   // exactly m parameters.
6798   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6799   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6800     // Not enough arguments.
6801     Candidate.Viable = false;
6802     Candidate.FailureKind = ovl_fail_too_few_arguments;
6803     return;
6804   }
6805 
6806   Candidate.Viable = true;
6807 
6808   if (Method->isStatic() || ObjectType.isNull())
6809     // The implicit object argument is ignored.
6810     Candidate.IgnoreObjectArgument = true;
6811   else {
6812     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6813     // Determine the implicit conversion sequence for the object
6814     // parameter.
6815     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6816         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6817         Method, ActingContext);
6818     if (Candidate.Conversions[ConvIdx].isBad()) {
6819       Candidate.Viable = false;
6820       Candidate.FailureKind = ovl_fail_bad_conversion;
6821       return;
6822     }
6823   }
6824 
6825   // (CUDA B.1): Check for invalid calls between targets.
6826   if (getLangOpts().CUDA)
6827     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6828       if (!IsAllowedCUDACall(Caller, Method)) {
6829         Candidate.Viable = false;
6830         Candidate.FailureKind = ovl_fail_bad_target;
6831         return;
6832       }
6833 
6834   if (Method->getTrailingRequiresClause()) {
6835     ConstraintSatisfaction Satisfaction;
6836     if (CheckFunctionConstraints(Method, Satisfaction) ||
6837         !Satisfaction.IsSatisfied) {
6838       Candidate.Viable = false;
6839       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6840       return;
6841     }
6842   }
6843 
6844   // Determine the implicit conversion sequences for each of the
6845   // arguments.
6846   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6847     unsigned ConvIdx =
6848         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6849     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6850       // We already formed a conversion sequence for this parameter during
6851       // template argument deduction.
6852     } else if (ArgIdx < NumParams) {
6853       // (C++ 13.3.2p3): for F to be a viable function, there shall
6854       // exist for each argument an implicit conversion sequence
6855       // (13.3.3.1) that converts that argument to the corresponding
6856       // parameter of F.
6857       QualType ParamType = Proto->getParamType(ArgIdx);
6858       Candidate.Conversions[ConvIdx]
6859         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6860                                 SuppressUserConversions,
6861                                 /*InOverloadResolution=*/true,
6862                                 /*AllowObjCWritebackConversion=*/
6863                                   getLangOpts().ObjCAutoRefCount);
6864       if (Candidate.Conversions[ConvIdx].isBad()) {
6865         Candidate.Viable = false;
6866         Candidate.FailureKind = ovl_fail_bad_conversion;
6867         return;
6868       }
6869     } else {
6870       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6871       // argument for which there is no corresponding parameter is
6872       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6873       Candidate.Conversions[ConvIdx].setEllipsis();
6874     }
6875   }
6876 
6877   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6878     Candidate.Viable = false;
6879     Candidate.FailureKind = ovl_fail_enable_if;
6880     Candidate.DeductionFailure.Data = FailedAttr;
6881     return;
6882   }
6883 
6884   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6885       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6886     Candidate.Viable = false;
6887     Candidate.FailureKind = ovl_non_default_multiversion_function;
6888   }
6889 }
6890 
6891 /// Add a C++ member function template as a candidate to the candidate
6892 /// set, using template argument deduction to produce an appropriate member
6893 /// function template specialization.
6894 void Sema::AddMethodTemplateCandidate(
6895     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6896     CXXRecordDecl *ActingContext,
6897     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6898     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6899     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6900     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6901   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6902     return;
6903 
6904   // C++ [over.match.funcs]p7:
6905   //   In each case where a candidate is a function template, candidate
6906   //   function template specializations are generated using template argument
6907   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6908   //   candidate functions in the usual way.113) A given name can refer to one
6909   //   or more function templates and also to a set of overloaded non-template
6910   //   functions. In such a case, the candidate functions generated from each
6911   //   function template are combined with the set of non-template candidate
6912   //   functions.
6913   TemplateDeductionInfo Info(CandidateSet.getLocation());
6914   FunctionDecl *Specialization = nullptr;
6915   ConversionSequenceList Conversions;
6916   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6917           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6918           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6919             return CheckNonDependentConversions(
6920                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6921                 SuppressUserConversions, ActingContext, ObjectType,
6922                 ObjectClassification, PO);
6923           })) {
6924     OverloadCandidate &Candidate =
6925         CandidateSet.addCandidate(Conversions.size(), Conversions);
6926     Candidate.FoundDecl = FoundDecl;
6927     Candidate.Function = MethodTmpl->getTemplatedDecl();
6928     Candidate.Viable = false;
6929     Candidate.RewriteKind =
6930       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6931     Candidate.IsSurrogate = false;
6932     Candidate.IgnoreObjectArgument =
6933         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6934         ObjectType.isNull();
6935     Candidate.ExplicitCallArguments = Args.size();
6936     if (Result == TDK_NonDependentConversionFailure)
6937       Candidate.FailureKind = ovl_fail_bad_conversion;
6938     else {
6939       Candidate.FailureKind = ovl_fail_bad_deduction;
6940       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6941                                                             Info);
6942     }
6943     return;
6944   }
6945 
6946   // Add the function template specialization produced by template argument
6947   // deduction as a candidate.
6948   assert(Specialization && "Missing member function template specialization?");
6949   assert(isa<CXXMethodDecl>(Specialization) &&
6950          "Specialization is not a member function?");
6951   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6952                      ActingContext, ObjectType, ObjectClassification, Args,
6953                      CandidateSet, SuppressUserConversions, PartialOverloading,
6954                      Conversions, PO);
6955 }
6956 
6957 /// Determine whether a given function template has a simple explicit specifier
6958 /// or a non-value-dependent explicit-specification that evaluates to true.
6959 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6960   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6961 }
6962 
6963 /// Add a C++ function template specialization as a candidate
6964 /// in the candidate set, using template argument deduction to produce
6965 /// an appropriate function template specialization.
6966 void Sema::AddTemplateOverloadCandidate(
6967     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6968     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6969     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6970     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6971     OverloadCandidateParamOrder PO) {
6972   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6973     return;
6974 
6975   // If the function template has a non-dependent explicit specification,
6976   // exclude it now if appropriate; we are not permitted to perform deduction
6977   // and substitution in this case.
6978   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6979     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6980     Candidate.FoundDecl = FoundDecl;
6981     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6982     Candidate.Viable = false;
6983     Candidate.FailureKind = ovl_fail_explicit;
6984     return;
6985   }
6986 
6987   // C++ [over.match.funcs]p7:
6988   //   In each case where a candidate is a function template, candidate
6989   //   function template specializations are generated using template argument
6990   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6991   //   candidate functions in the usual way.113) A given name can refer to one
6992   //   or more function templates and also to a set of overloaded non-template
6993   //   functions. In such a case, the candidate functions generated from each
6994   //   function template are combined with the set of non-template candidate
6995   //   functions.
6996   TemplateDeductionInfo Info(CandidateSet.getLocation());
6997   FunctionDecl *Specialization = nullptr;
6998   ConversionSequenceList Conversions;
6999   if (TemplateDeductionResult Result = DeduceTemplateArguments(
7000           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7001           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
7002             return CheckNonDependentConversions(
7003                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7004                 SuppressUserConversions, nullptr, QualType(), {}, PO);
7005           })) {
7006     OverloadCandidate &Candidate =
7007         CandidateSet.addCandidate(Conversions.size(), Conversions);
7008     Candidate.FoundDecl = FoundDecl;
7009     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7010     Candidate.Viable = false;
7011     Candidate.RewriteKind =
7012       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7013     Candidate.IsSurrogate = false;
7014     Candidate.IsADLCandidate = IsADLCandidate;
7015     // Ignore the object argument if there is one, since we don't have an object
7016     // type.
7017     Candidate.IgnoreObjectArgument =
7018         isa<CXXMethodDecl>(Candidate.Function) &&
7019         !isa<CXXConstructorDecl>(Candidate.Function);
7020     Candidate.ExplicitCallArguments = Args.size();
7021     if (Result == TDK_NonDependentConversionFailure)
7022       Candidate.FailureKind = ovl_fail_bad_conversion;
7023     else {
7024       Candidate.FailureKind = ovl_fail_bad_deduction;
7025       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7026                                                             Info);
7027     }
7028     return;
7029   }
7030 
7031   // Add the function template specialization produced by template argument
7032   // deduction as a candidate.
7033   assert(Specialization && "Missing function template specialization?");
7034   AddOverloadCandidate(
7035       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7036       PartialOverloading, AllowExplicit,
7037       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7038 }
7039 
7040 /// Check that implicit conversion sequences can be formed for each argument
7041 /// whose corresponding parameter has a non-dependent type, per DR1391's
7042 /// [temp.deduct.call]p10.
7043 bool Sema::CheckNonDependentConversions(
7044     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7045     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7046     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7047     CXXRecordDecl *ActingContext, QualType ObjectType,
7048     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7049   // FIXME: The cases in which we allow explicit conversions for constructor
7050   // arguments never consider calling a constructor template. It's not clear
7051   // that is correct.
7052   const bool AllowExplicit = false;
7053 
7054   auto *FD = FunctionTemplate->getTemplatedDecl();
7055   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7056   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7057   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7058 
7059   Conversions =
7060       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7061 
7062   // Overload resolution is always an unevaluated context.
7063   EnterExpressionEvaluationContext Unevaluated(
7064       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7065 
7066   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7067   // require that, but this check should never result in a hard error, and
7068   // overload resolution is permitted to sidestep instantiations.
7069   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7070       !ObjectType.isNull()) {
7071     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7072     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7073         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7074         Method, ActingContext);
7075     if (Conversions[ConvIdx].isBad())
7076       return true;
7077   }
7078 
7079   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7080        ++I) {
7081     QualType ParamType = ParamTypes[I];
7082     if (!ParamType->isDependentType()) {
7083       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7084                              ? 0
7085                              : (ThisConversions + I);
7086       Conversions[ConvIdx]
7087         = TryCopyInitialization(*this, Args[I], ParamType,
7088                                 SuppressUserConversions,
7089                                 /*InOverloadResolution=*/true,
7090                                 /*AllowObjCWritebackConversion=*/
7091                                   getLangOpts().ObjCAutoRefCount,
7092                                 AllowExplicit);
7093       if (Conversions[ConvIdx].isBad())
7094         return true;
7095     }
7096   }
7097 
7098   return false;
7099 }
7100 
7101 /// Determine whether this is an allowable conversion from the result
7102 /// of an explicit conversion operator to the expected type, per C++
7103 /// [over.match.conv]p1 and [over.match.ref]p1.
7104 ///
7105 /// \param ConvType The return type of the conversion function.
7106 ///
7107 /// \param ToType The type we are converting to.
7108 ///
7109 /// \param AllowObjCPointerConversion Allow a conversion from one
7110 /// Objective-C pointer to another.
7111 ///
7112 /// \returns true if the conversion is allowable, false otherwise.
7113 static bool isAllowableExplicitConversion(Sema &S,
7114                                           QualType ConvType, QualType ToType,
7115                                           bool AllowObjCPointerConversion) {
7116   QualType ToNonRefType = ToType.getNonReferenceType();
7117 
7118   // Easy case: the types are the same.
7119   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7120     return true;
7121 
7122   // Allow qualification conversions.
7123   bool ObjCLifetimeConversion;
7124   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7125                                   ObjCLifetimeConversion))
7126     return true;
7127 
7128   // If we're not allowed to consider Objective-C pointer conversions,
7129   // we're done.
7130   if (!AllowObjCPointerConversion)
7131     return false;
7132 
7133   // Is this an Objective-C pointer conversion?
7134   bool IncompatibleObjC = false;
7135   QualType ConvertedType;
7136   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7137                                    IncompatibleObjC);
7138 }
7139 
7140 /// AddConversionCandidate - Add a C++ conversion function as a
7141 /// candidate in the candidate set (C++ [over.match.conv],
7142 /// C++ [over.match.copy]). From is the expression we're converting from,
7143 /// and ToType is the type that we're eventually trying to convert to
7144 /// (which may or may not be the same type as the type that the
7145 /// conversion function produces).
7146 void Sema::AddConversionCandidate(
7147     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7148     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7149     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7150     bool AllowExplicit, bool AllowResultConversion) {
7151   assert(!Conversion->getDescribedFunctionTemplate() &&
7152          "Conversion function templates use AddTemplateConversionCandidate");
7153   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7154   if (!CandidateSet.isNewCandidate(Conversion))
7155     return;
7156 
7157   // If the conversion function has an undeduced return type, trigger its
7158   // deduction now.
7159   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7160     if (DeduceReturnType(Conversion, From->getExprLoc()))
7161       return;
7162     ConvType = Conversion->getConversionType().getNonReferenceType();
7163   }
7164 
7165   // If we don't allow any conversion of the result type, ignore conversion
7166   // functions that don't convert to exactly (possibly cv-qualified) T.
7167   if (!AllowResultConversion &&
7168       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7169     return;
7170 
7171   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7172   // operator is only a candidate if its return type is the target type or
7173   // can be converted to the target type with a qualification conversion.
7174   //
7175   // FIXME: Include such functions in the candidate list and explain why we
7176   // can't select them.
7177   if (Conversion->isExplicit() &&
7178       !isAllowableExplicitConversion(*this, ConvType, ToType,
7179                                      AllowObjCConversionOnExplicit))
7180     return;
7181 
7182   // Overload resolution is always an unevaluated context.
7183   EnterExpressionEvaluationContext Unevaluated(
7184       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7185 
7186   // Add this candidate
7187   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7188   Candidate.FoundDecl = FoundDecl;
7189   Candidate.Function = Conversion;
7190   Candidate.IsSurrogate = false;
7191   Candidate.IgnoreObjectArgument = false;
7192   Candidate.FinalConversion.setAsIdentityConversion();
7193   Candidate.FinalConversion.setFromType(ConvType);
7194   Candidate.FinalConversion.setAllToTypes(ToType);
7195   Candidate.Viable = true;
7196   Candidate.ExplicitCallArguments = 1;
7197 
7198   // Explicit functions are not actually candidates at all if we're not
7199   // allowing them in this context, but keep them around so we can point
7200   // to them in diagnostics.
7201   if (!AllowExplicit && Conversion->isExplicit()) {
7202     Candidate.Viable = false;
7203     Candidate.FailureKind = ovl_fail_explicit;
7204     return;
7205   }
7206 
7207   // C++ [over.match.funcs]p4:
7208   //   For conversion functions, the function is considered to be a member of
7209   //   the class of the implicit implied object argument for the purpose of
7210   //   defining the type of the implicit object parameter.
7211   //
7212   // Determine the implicit conversion sequence for the implicit
7213   // object parameter.
7214   QualType ImplicitParamType = From->getType();
7215   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7216     ImplicitParamType = FromPtrType->getPointeeType();
7217   CXXRecordDecl *ConversionContext
7218     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7219 
7220   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7221       *this, CandidateSet.getLocation(), From->getType(),
7222       From->Classify(Context), Conversion, ConversionContext);
7223 
7224   if (Candidate.Conversions[0].isBad()) {
7225     Candidate.Viable = false;
7226     Candidate.FailureKind = ovl_fail_bad_conversion;
7227     return;
7228   }
7229 
7230   if (Conversion->getTrailingRequiresClause()) {
7231     ConstraintSatisfaction Satisfaction;
7232     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7233         !Satisfaction.IsSatisfied) {
7234       Candidate.Viable = false;
7235       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7236       return;
7237     }
7238   }
7239 
7240   // We won't go through a user-defined type conversion function to convert a
7241   // derived to base as such conversions are given Conversion Rank. They only
7242   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7243   QualType FromCanon
7244     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7245   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7246   if (FromCanon == ToCanon ||
7247       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7248     Candidate.Viable = false;
7249     Candidate.FailureKind = ovl_fail_trivial_conversion;
7250     return;
7251   }
7252 
7253   // To determine what the conversion from the result of calling the
7254   // conversion function to the type we're eventually trying to
7255   // convert to (ToType), we need to synthesize a call to the
7256   // conversion function and attempt copy initialization from it. This
7257   // makes sure that we get the right semantics with respect to
7258   // lvalues/rvalues and the type. Fortunately, we can allocate this
7259   // call on the stack and we don't need its arguments to be
7260   // well-formed.
7261   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7262                             VK_LValue, From->getBeginLoc());
7263   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7264                                 Context.getPointerType(Conversion->getType()),
7265                                 CK_FunctionToPointerDecay,
7266                                 &ConversionRef, VK_RValue);
7267 
7268   QualType ConversionType = Conversion->getConversionType();
7269   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7270     Candidate.Viable = false;
7271     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7272     return;
7273   }
7274 
7275   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7276 
7277   // Note that it is safe to allocate CallExpr on the stack here because
7278   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7279   // allocator).
7280   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7281 
7282   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7283   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7284       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7285 
7286   ImplicitConversionSequence ICS =
7287       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7288                             /*SuppressUserConversions=*/true,
7289                             /*InOverloadResolution=*/false,
7290                             /*AllowObjCWritebackConversion=*/false);
7291 
7292   switch (ICS.getKind()) {
7293   case ImplicitConversionSequence::StandardConversion:
7294     Candidate.FinalConversion = ICS.Standard;
7295 
7296     // C++ [over.ics.user]p3:
7297     //   If the user-defined conversion is specified by a specialization of a
7298     //   conversion function template, the second standard conversion sequence
7299     //   shall have exact match rank.
7300     if (Conversion->getPrimaryTemplate() &&
7301         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7302       Candidate.Viable = false;
7303       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7304       return;
7305     }
7306 
7307     // C++0x [dcl.init.ref]p5:
7308     //    In the second case, if the reference is an rvalue reference and
7309     //    the second standard conversion sequence of the user-defined
7310     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7311     //    program is ill-formed.
7312     if (ToType->isRValueReferenceType() &&
7313         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7314       Candidate.Viable = false;
7315       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7316       return;
7317     }
7318     break;
7319 
7320   case ImplicitConversionSequence::BadConversion:
7321     Candidate.Viable = false;
7322     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7323     return;
7324 
7325   default:
7326     llvm_unreachable(
7327            "Can only end up with a standard conversion sequence or failure");
7328   }
7329 
7330   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7331     Candidate.Viable = false;
7332     Candidate.FailureKind = ovl_fail_enable_if;
7333     Candidate.DeductionFailure.Data = FailedAttr;
7334     return;
7335   }
7336 
7337   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7338       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7339     Candidate.Viable = false;
7340     Candidate.FailureKind = ovl_non_default_multiversion_function;
7341   }
7342 }
7343 
7344 /// Adds a conversion function template specialization
7345 /// candidate to the overload set, using template argument deduction
7346 /// to deduce the template arguments of the conversion function
7347 /// template from the type that we are converting to (C++
7348 /// [temp.deduct.conv]).
7349 void Sema::AddTemplateConversionCandidate(
7350     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7351     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7352     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7353     bool AllowExplicit, bool AllowResultConversion) {
7354   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7355          "Only conversion function templates permitted here");
7356 
7357   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7358     return;
7359 
7360   // If the function template has a non-dependent explicit specification,
7361   // exclude it now if appropriate; we are not permitted to perform deduction
7362   // and substitution in this case.
7363   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7364     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7365     Candidate.FoundDecl = FoundDecl;
7366     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7367     Candidate.Viable = false;
7368     Candidate.FailureKind = ovl_fail_explicit;
7369     return;
7370   }
7371 
7372   TemplateDeductionInfo Info(CandidateSet.getLocation());
7373   CXXConversionDecl *Specialization = nullptr;
7374   if (TemplateDeductionResult Result
7375         = DeduceTemplateArguments(FunctionTemplate, ToType,
7376                                   Specialization, Info)) {
7377     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7378     Candidate.FoundDecl = FoundDecl;
7379     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7380     Candidate.Viable = false;
7381     Candidate.FailureKind = ovl_fail_bad_deduction;
7382     Candidate.IsSurrogate = false;
7383     Candidate.IgnoreObjectArgument = false;
7384     Candidate.ExplicitCallArguments = 1;
7385     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7386                                                           Info);
7387     return;
7388   }
7389 
7390   // Add the conversion function template specialization produced by
7391   // template argument deduction as a candidate.
7392   assert(Specialization && "Missing function template specialization?");
7393   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7394                          CandidateSet, AllowObjCConversionOnExplicit,
7395                          AllowExplicit, AllowResultConversion);
7396 }
7397 
7398 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7399 /// converts the given @c Object to a function pointer via the
7400 /// conversion function @c Conversion, and then attempts to call it
7401 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7402 /// the type of function that we'll eventually be calling.
7403 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7404                                  DeclAccessPair FoundDecl,
7405                                  CXXRecordDecl *ActingContext,
7406                                  const FunctionProtoType *Proto,
7407                                  Expr *Object,
7408                                  ArrayRef<Expr *> Args,
7409                                  OverloadCandidateSet& CandidateSet) {
7410   if (!CandidateSet.isNewCandidate(Conversion))
7411     return;
7412 
7413   // Overload resolution is always an unevaluated context.
7414   EnterExpressionEvaluationContext Unevaluated(
7415       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7416 
7417   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7418   Candidate.FoundDecl = FoundDecl;
7419   Candidate.Function = nullptr;
7420   Candidate.Surrogate = Conversion;
7421   Candidate.Viable = true;
7422   Candidate.IsSurrogate = true;
7423   Candidate.IgnoreObjectArgument = false;
7424   Candidate.ExplicitCallArguments = Args.size();
7425 
7426   // Determine the implicit conversion sequence for the implicit
7427   // object parameter.
7428   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7429       *this, CandidateSet.getLocation(), Object->getType(),
7430       Object->Classify(Context), Conversion, ActingContext);
7431   if (ObjectInit.isBad()) {
7432     Candidate.Viable = false;
7433     Candidate.FailureKind = ovl_fail_bad_conversion;
7434     Candidate.Conversions[0] = ObjectInit;
7435     return;
7436   }
7437 
7438   // The first conversion is actually a user-defined conversion whose
7439   // first conversion is ObjectInit's standard conversion (which is
7440   // effectively a reference binding). Record it as such.
7441   Candidate.Conversions[0].setUserDefined();
7442   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7443   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7444   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7445   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7446   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7447   Candidate.Conversions[0].UserDefined.After
7448     = Candidate.Conversions[0].UserDefined.Before;
7449   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7450 
7451   // Find the
7452   unsigned NumParams = Proto->getNumParams();
7453 
7454   // (C++ 13.3.2p2): A candidate function having fewer than m
7455   // parameters is viable only if it has an ellipsis in its parameter
7456   // list (8.3.5).
7457   if (Args.size() > NumParams && !Proto->isVariadic()) {
7458     Candidate.Viable = false;
7459     Candidate.FailureKind = ovl_fail_too_many_arguments;
7460     return;
7461   }
7462 
7463   // Function types don't have any default arguments, so just check if
7464   // we have enough arguments.
7465   if (Args.size() < NumParams) {
7466     // Not enough arguments.
7467     Candidate.Viable = false;
7468     Candidate.FailureKind = ovl_fail_too_few_arguments;
7469     return;
7470   }
7471 
7472   // Determine the implicit conversion sequences for each of the
7473   // arguments.
7474   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7475     if (ArgIdx < NumParams) {
7476       // (C++ 13.3.2p3): for F to be a viable function, there shall
7477       // exist for each argument an implicit conversion sequence
7478       // (13.3.3.1) that converts that argument to the corresponding
7479       // parameter of F.
7480       QualType ParamType = Proto->getParamType(ArgIdx);
7481       Candidate.Conversions[ArgIdx + 1]
7482         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7483                                 /*SuppressUserConversions=*/false,
7484                                 /*InOverloadResolution=*/false,
7485                                 /*AllowObjCWritebackConversion=*/
7486                                   getLangOpts().ObjCAutoRefCount);
7487       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7488         Candidate.Viable = false;
7489         Candidate.FailureKind = ovl_fail_bad_conversion;
7490         return;
7491       }
7492     } else {
7493       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7494       // argument for which there is no corresponding parameter is
7495       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7496       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7497     }
7498   }
7499 
7500   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7501     Candidate.Viable = false;
7502     Candidate.FailureKind = ovl_fail_enable_if;
7503     Candidate.DeductionFailure.Data = FailedAttr;
7504     return;
7505   }
7506 }
7507 
7508 /// Add all of the non-member operator function declarations in the given
7509 /// function set to the overload candidate set.
7510 void Sema::AddNonMemberOperatorCandidates(
7511     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7512     OverloadCandidateSet &CandidateSet,
7513     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7514   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7515     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7516     ArrayRef<Expr *> FunctionArgs = Args;
7517 
7518     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7519     FunctionDecl *FD =
7520         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7521 
7522     // Don't consider rewritten functions if we're not rewriting.
7523     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7524       continue;
7525 
7526     assert(!isa<CXXMethodDecl>(FD) &&
7527            "unqualified operator lookup found a member function");
7528 
7529     if (FunTmpl) {
7530       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7531                                    FunctionArgs, CandidateSet);
7532       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7533         AddTemplateOverloadCandidate(
7534             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7535             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7536             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7537     } else {
7538       if (ExplicitTemplateArgs)
7539         continue;
7540       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7541       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7542         AddOverloadCandidate(FD, F.getPair(),
7543                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7544                              false, false, true, false, ADLCallKind::NotADL,
7545                              None, OverloadCandidateParamOrder::Reversed);
7546     }
7547   }
7548 }
7549 
7550 /// Add overload candidates for overloaded operators that are
7551 /// member functions.
7552 ///
7553 /// Add the overloaded operator candidates that are member functions
7554 /// for the operator Op that was used in an operator expression such
7555 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7556 /// CandidateSet will store the added overload candidates. (C++
7557 /// [over.match.oper]).
7558 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7559                                        SourceLocation OpLoc,
7560                                        ArrayRef<Expr *> Args,
7561                                        OverloadCandidateSet &CandidateSet,
7562                                        OverloadCandidateParamOrder PO) {
7563   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7564 
7565   // C++ [over.match.oper]p3:
7566   //   For a unary operator @ with an operand of a type whose
7567   //   cv-unqualified version is T1, and for a binary operator @ with
7568   //   a left operand of a type whose cv-unqualified version is T1 and
7569   //   a right operand of a type whose cv-unqualified version is T2,
7570   //   three sets of candidate functions, designated member
7571   //   candidates, non-member candidates and built-in candidates, are
7572   //   constructed as follows:
7573   QualType T1 = Args[0]->getType();
7574 
7575   //     -- If T1 is a complete class type or a class currently being
7576   //        defined, the set of member candidates is the result of the
7577   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7578   //        the set of member candidates is empty.
7579   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7580     // Complete the type if it can be completed.
7581     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7582       return;
7583     // If the type is neither complete nor being defined, bail out now.
7584     if (!T1Rec->getDecl()->getDefinition())
7585       return;
7586 
7587     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7588     LookupQualifiedName(Operators, T1Rec->getDecl());
7589     Operators.suppressDiagnostics();
7590 
7591     for (LookupResult::iterator Oper = Operators.begin(),
7592                              OperEnd = Operators.end();
7593          Oper != OperEnd;
7594          ++Oper)
7595       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7596                          Args[0]->Classify(Context), Args.slice(1),
7597                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7598   }
7599 }
7600 
7601 /// AddBuiltinCandidate - Add a candidate for a built-in
7602 /// operator. ResultTy and ParamTys are the result and parameter types
7603 /// of the built-in candidate, respectively. Args and NumArgs are the
7604 /// arguments being passed to the candidate. IsAssignmentOperator
7605 /// should be true when this built-in candidate is an assignment
7606 /// operator. NumContextualBoolArguments is the number of arguments
7607 /// (at the beginning of the argument list) that will be contextually
7608 /// converted to bool.
7609 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7610                                OverloadCandidateSet& CandidateSet,
7611                                bool IsAssignmentOperator,
7612                                unsigned NumContextualBoolArguments) {
7613   // Overload resolution is always an unevaluated context.
7614   EnterExpressionEvaluationContext Unevaluated(
7615       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7616 
7617   // Add this candidate
7618   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7619   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7620   Candidate.Function = nullptr;
7621   Candidate.IsSurrogate = false;
7622   Candidate.IgnoreObjectArgument = false;
7623   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7624 
7625   // Determine the implicit conversion sequences for each of the
7626   // arguments.
7627   Candidate.Viable = true;
7628   Candidate.ExplicitCallArguments = Args.size();
7629   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7630     // C++ [over.match.oper]p4:
7631     //   For the built-in assignment operators, conversions of the
7632     //   left operand are restricted as follows:
7633     //     -- no temporaries are introduced to hold the left operand, and
7634     //     -- no user-defined conversions are applied to the left
7635     //        operand to achieve a type match with the left-most
7636     //        parameter of a built-in candidate.
7637     //
7638     // We block these conversions by turning off user-defined
7639     // conversions, since that is the only way that initialization of
7640     // a reference to a non-class type can occur from something that
7641     // is not of the same type.
7642     if (ArgIdx < NumContextualBoolArguments) {
7643       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7644              "Contextual conversion to bool requires bool type");
7645       Candidate.Conversions[ArgIdx]
7646         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7647     } else {
7648       Candidate.Conversions[ArgIdx]
7649         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7650                                 ArgIdx == 0 && IsAssignmentOperator,
7651                                 /*InOverloadResolution=*/false,
7652                                 /*AllowObjCWritebackConversion=*/
7653                                   getLangOpts().ObjCAutoRefCount);
7654     }
7655     if (Candidate.Conversions[ArgIdx].isBad()) {
7656       Candidate.Viable = false;
7657       Candidate.FailureKind = ovl_fail_bad_conversion;
7658       break;
7659     }
7660   }
7661 }
7662 
7663 namespace {
7664 
7665 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7666 /// candidate operator functions for built-in operators (C++
7667 /// [over.built]). The types are separated into pointer types and
7668 /// enumeration types.
7669 class BuiltinCandidateTypeSet  {
7670   /// TypeSet - A set of types.
7671   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7672                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7673 
7674   /// PointerTypes - The set of pointer types that will be used in the
7675   /// built-in candidates.
7676   TypeSet PointerTypes;
7677 
7678   /// MemberPointerTypes - The set of member pointer types that will be
7679   /// used in the built-in candidates.
7680   TypeSet MemberPointerTypes;
7681 
7682   /// EnumerationTypes - The set of enumeration types that will be
7683   /// used in the built-in candidates.
7684   TypeSet EnumerationTypes;
7685 
7686   /// The set of vector types that will be used in the built-in
7687   /// candidates.
7688   TypeSet VectorTypes;
7689 
7690   /// A flag indicating non-record types are viable candidates
7691   bool HasNonRecordTypes;
7692 
7693   /// A flag indicating whether either arithmetic or enumeration types
7694   /// were present in the candidate set.
7695   bool HasArithmeticOrEnumeralTypes;
7696 
7697   /// A flag indicating whether the nullptr type was present in the
7698   /// candidate set.
7699   bool HasNullPtrType;
7700 
7701   /// Sema - The semantic analysis instance where we are building the
7702   /// candidate type set.
7703   Sema &SemaRef;
7704 
7705   /// Context - The AST context in which we will build the type sets.
7706   ASTContext &Context;
7707 
7708   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7709                                                const Qualifiers &VisibleQuals);
7710   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7711 
7712 public:
7713   /// iterator - Iterates through the types that are part of the set.
7714   typedef TypeSet::iterator iterator;
7715 
7716   BuiltinCandidateTypeSet(Sema &SemaRef)
7717     : HasNonRecordTypes(false),
7718       HasArithmeticOrEnumeralTypes(false),
7719       HasNullPtrType(false),
7720       SemaRef(SemaRef),
7721       Context(SemaRef.Context) { }
7722 
7723   void AddTypesConvertedFrom(QualType Ty,
7724                              SourceLocation Loc,
7725                              bool AllowUserConversions,
7726                              bool AllowExplicitConversions,
7727                              const Qualifiers &VisibleTypeConversionsQuals);
7728 
7729   /// pointer_begin - First pointer type found;
7730   iterator pointer_begin() { return PointerTypes.begin(); }
7731 
7732   /// pointer_end - Past the last pointer type found;
7733   iterator pointer_end() { return PointerTypes.end(); }
7734 
7735   /// member_pointer_begin - First member pointer type found;
7736   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7737 
7738   /// member_pointer_end - Past the last member pointer type found;
7739   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7740 
7741   /// enumeration_begin - First enumeration type found;
7742   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7743 
7744   /// enumeration_end - Past the last enumeration type found;
7745   iterator enumeration_end() { return EnumerationTypes.end(); }
7746 
7747   iterator vector_begin() { return VectorTypes.begin(); }
7748   iterator vector_end() { return VectorTypes.end(); }
7749 
7750   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7751   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7752   bool hasNullPtrType() const { return HasNullPtrType; }
7753 };
7754 
7755 } // end anonymous namespace
7756 
7757 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7758 /// the set of pointer types along with any more-qualified variants of
7759 /// that type. For example, if @p Ty is "int const *", this routine
7760 /// will add "int const *", "int const volatile *", "int const
7761 /// restrict *", and "int const volatile restrict *" to the set of
7762 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7763 /// false otherwise.
7764 ///
7765 /// FIXME: what to do about extended qualifiers?
7766 bool
7767 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7768                                              const Qualifiers &VisibleQuals) {
7769 
7770   // Insert this type.
7771   if (!PointerTypes.insert(Ty))
7772     return false;
7773 
7774   QualType PointeeTy;
7775   const PointerType *PointerTy = Ty->getAs<PointerType>();
7776   bool buildObjCPtr = false;
7777   if (!PointerTy) {
7778     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7779     PointeeTy = PTy->getPointeeType();
7780     buildObjCPtr = true;
7781   } else {
7782     PointeeTy = PointerTy->getPointeeType();
7783   }
7784 
7785   // Don't add qualified variants of arrays. For one, they're not allowed
7786   // (the qualifier would sink to the element type), and for another, the
7787   // only overload situation where it matters is subscript or pointer +- int,
7788   // and those shouldn't have qualifier variants anyway.
7789   if (PointeeTy->isArrayType())
7790     return true;
7791 
7792   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7793   bool hasVolatile = VisibleQuals.hasVolatile();
7794   bool hasRestrict = VisibleQuals.hasRestrict();
7795 
7796   // Iterate through all strict supersets of BaseCVR.
7797   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7798     if ((CVR | BaseCVR) != CVR) continue;
7799     // Skip over volatile if no volatile found anywhere in the types.
7800     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7801 
7802     // Skip over restrict if no restrict found anywhere in the types, or if
7803     // the type cannot be restrict-qualified.
7804     if ((CVR & Qualifiers::Restrict) &&
7805         (!hasRestrict ||
7806          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7807       continue;
7808 
7809     // Build qualified pointee type.
7810     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7811 
7812     // Build qualified pointer type.
7813     QualType QPointerTy;
7814     if (!buildObjCPtr)
7815       QPointerTy = Context.getPointerType(QPointeeTy);
7816     else
7817       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7818 
7819     // Insert qualified pointer type.
7820     PointerTypes.insert(QPointerTy);
7821   }
7822 
7823   return true;
7824 }
7825 
7826 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7827 /// to the set of pointer types along with any more-qualified variants of
7828 /// that type. For example, if @p Ty is "int const *", this routine
7829 /// will add "int const *", "int const volatile *", "int const
7830 /// restrict *", and "int const volatile restrict *" to the set of
7831 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7832 /// false otherwise.
7833 ///
7834 /// FIXME: what to do about extended qualifiers?
7835 bool
7836 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7837     QualType Ty) {
7838   // Insert this type.
7839   if (!MemberPointerTypes.insert(Ty))
7840     return false;
7841 
7842   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7843   assert(PointerTy && "type was not a member pointer type!");
7844 
7845   QualType PointeeTy = PointerTy->getPointeeType();
7846   // Don't add qualified variants of arrays. For one, they're not allowed
7847   // (the qualifier would sink to the element type), and for another, the
7848   // only overload situation where it matters is subscript or pointer +- int,
7849   // and those shouldn't have qualifier variants anyway.
7850   if (PointeeTy->isArrayType())
7851     return true;
7852   const Type *ClassTy = PointerTy->getClass();
7853 
7854   // Iterate through all strict supersets of the pointee type's CVR
7855   // qualifiers.
7856   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7857   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7858     if ((CVR | BaseCVR) != CVR) continue;
7859 
7860     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7861     MemberPointerTypes.insert(
7862       Context.getMemberPointerType(QPointeeTy, ClassTy));
7863   }
7864 
7865   return true;
7866 }
7867 
7868 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7869 /// Ty can be implicit converted to the given set of @p Types. We're
7870 /// primarily interested in pointer types and enumeration types. We also
7871 /// take member pointer types, for the conditional operator.
7872 /// AllowUserConversions is true if we should look at the conversion
7873 /// functions of a class type, and AllowExplicitConversions if we
7874 /// should also include the explicit conversion functions of a class
7875 /// type.
7876 void
7877 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7878                                                SourceLocation Loc,
7879                                                bool AllowUserConversions,
7880                                                bool AllowExplicitConversions,
7881                                                const Qualifiers &VisibleQuals) {
7882   // Only deal with canonical types.
7883   Ty = Context.getCanonicalType(Ty);
7884 
7885   // Look through reference types; they aren't part of the type of an
7886   // expression for the purposes of conversions.
7887   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7888     Ty = RefTy->getPointeeType();
7889 
7890   // If we're dealing with an array type, decay to the pointer.
7891   if (Ty->isArrayType())
7892     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7893 
7894   // Otherwise, we don't care about qualifiers on the type.
7895   Ty = Ty.getLocalUnqualifiedType();
7896 
7897   // Flag if we ever add a non-record type.
7898   const RecordType *TyRec = Ty->getAs<RecordType>();
7899   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7900 
7901   // Flag if we encounter an arithmetic type.
7902   HasArithmeticOrEnumeralTypes =
7903     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7904 
7905   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7906     PointerTypes.insert(Ty);
7907   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7908     // Insert our type, and its more-qualified variants, into the set
7909     // of types.
7910     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7911       return;
7912   } else if (Ty->isMemberPointerType()) {
7913     // Member pointers are far easier, since the pointee can't be converted.
7914     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7915       return;
7916   } else if (Ty->isEnumeralType()) {
7917     HasArithmeticOrEnumeralTypes = true;
7918     EnumerationTypes.insert(Ty);
7919   } else if (Ty->isVectorType()) {
7920     // We treat vector types as arithmetic types in many contexts as an
7921     // extension.
7922     HasArithmeticOrEnumeralTypes = true;
7923     VectorTypes.insert(Ty);
7924   } else if (Ty->isNullPtrType()) {
7925     HasNullPtrType = true;
7926   } else if (AllowUserConversions && TyRec) {
7927     // No conversion functions in incomplete types.
7928     if (!SemaRef.isCompleteType(Loc, Ty))
7929       return;
7930 
7931     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7932     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7933       if (isa<UsingShadowDecl>(D))
7934         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7935 
7936       // Skip conversion function templates; they don't tell us anything
7937       // about which builtin types we can convert to.
7938       if (isa<FunctionTemplateDecl>(D))
7939         continue;
7940 
7941       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7942       if (AllowExplicitConversions || !Conv->isExplicit()) {
7943         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7944                               VisibleQuals);
7945       }
7946     }
7947   }
7948 }
7949 /// Helper function for adjusting address spaces for the pointer or reference
7950 /// operands of builtin operators depending on the argument.
7951 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7952                                                         Expr *Arg) {
7953   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7954 }
7955 
7956 /// Helper function for AddBuiltinOperatorCandidates() that adds
7957 /// the volatile- and non-volatile-qualified assignment operators for the
7958 /// given type to the candidate set.
7959 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7960                                                    QualType T,
7961                                                    ArrayRef<Expr *> Args,
7962                                     OverloadCandidateSet &CandidateSet) {
7963   QualType ParamTypes[2];
7964 
7965   // T& operator=(T&, T)
7966   ParamTypes[0] = S.Context.getLValueReferenceType(
7967       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7968   ParamTypes[1] = T;
7969   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7970                         /*IsAssignmentOperator=*/true);
7971 
7972   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7973     // volatile T& operator=(volatile T&, T)
7974     ParamTypes[0] = S.Context.getLValueReferenceType(
7975         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7976                                                 Args[0]));
7977     ParamTypes[1] = T;
7978     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7979                           /*IsAssignmentOperator=*/true);
7980   }
7981 }
7982 
7983 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7984 /// if any, found in visible type conversion functions found in ArgExpr's type.
7985 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7986     Qualifiers VRQuals;
7987     const RecordType *TyRec;
7988     if (const MemberPointerType *RHSMPType =
7989         ArgExpr->getType()->getAs<MemberPointerType>())
7990       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7991     else
7992       TyRec = ArgExpr->getType()->getAs<RecordType>();
7993     if (!TyRec) {
7994       // Just to be safe, assume the worst case.
7995       VRQuals.addVolatile();
7996       VRQuals.addRestrict();
7997       return VRQuals;
7998     }
7999 
8000     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8001     if (!ClassDecl->hasDefinition())
8002       return VRQuals;
8003 
8004     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8005       if (isa<UsingShadowDecl>(D))
8006         D = cast<UsingShadowDecl>(D)->getTargetDecl();
8007       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8008         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8009         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8010           CanTy = ResTypeRef->getPointeeType();
8011         // Need to go down the pointer/mempointer chain and add qualifiers
8012         // as see them.
8013         bool done = false;
8014         while (!done) {
8015           if (CanTy.isRestrictQualified())
8016             VRQuals.addRestrict();
8017           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8018             CanTy = ResTypePtr->getPointeeType();
8019           else if (const MemberPointerType *ResTypeMPtr =
8020                 CanTy->getAs<MemberPointerType>())
8021             CanTy = ResTypeMPtr->getPointeeType();
8022           else
8023             done = true;
8024           if (CanTy.isVolatileQualified())
8025             VRQuals.addVolatile();
8026           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8027             return VRQuals;
8028         }
8029       }
8030     }
8031     return VRQuals;
8032 }
8033 
8034 namespace {
8035 
8036 /// Helper class to manage the addition of builtin operator overload
8037 /// candidates. It provides shared state and utility methods used throughout
8038 /// the process, as well as a helper method to add each group of builtin
8039 /// operator overloads from the standard to a candidate set.
8040 class BuiltinOperatorOverloadBuilder {
8041   // Common instance state available to all overload candidate addition methods.
8042   Sema &S;
8043   ArrayRef<Expr *> Args;
8044   Qualifiers VisibleTypeConversionsQuals;
8045   bool HasArithmeticOrEnumeralCandidateType;
8046   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8047   OverloadCandidateSet &CandidateSet;
8048 
8049   static constexpr int ArithmeticTypesCap = 24;
8050   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8051 
8052   // Define some indices used to iterate over the arithmetic types in
8053   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8054   // types are that preserved by promotion (C++ [over.built]p2).
8055   unsigned FirstIntegralType,
8056            LastIntegralType;
8057   unsigned FirstPromotedIntegralType,
8058            LastPromotedIntegralType;
8059   unsigned FirstPromotedArithmeticType,
8060            LastPromotedArithmeticType;
8061   unsigned NumArithmeticTypes;
8062 
8063   void InitArithmeticTypes() {
8064     // Start of promoted types.
8065     FirstPromotedArithmeticType = 0;
8066     ArithmeticTypes.push_back(S.Context.FloatTy);
8067     ArithmeticTypes.push_back(S.Context.DoubleTy);
8068     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8069     if (S.Context.getTargetInfo().hasFloat128Type())
8070       ArithmeticTypes.push_back(S.Context.Float128Ty);
8071 
8072     // Start of integral types.
8073     FirstIntegralType = ArithmeticTypes.size();
8074     FirstPromotedIntegralType = ArithmeticTypes.size();
8075     ArithmeticTypes.push_back(S.Context.IntTy);
8076     ArithmeticTypes.push_back(S.Context.LongTy);
8077     ArithmeticTypes.push_back(S.Context.LongLongTy);
8078     if (S.Context.getTargetInfo().hasInt128Type())
8079       ArithmeticTypes.push_back(S.Context.Int128Ty);
8080     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8081     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8082     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8083     if (S.Context.getTargetInfo().hasInt128Type())
8084       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8085     LastPromotedIntegralType = ArithmeticTypes.size();
8086     LastPromotedArithmeticType = ArithmeticTypes.size();
8087     // End of promoted types.
8088 
8089     ArithmeticTypes.push_back(S.Context.BoolTy);
8090     ArithmeticTypes.push_back(S.Context.CharTy);
8091     ArithmeticTypes.push_back(S.Context.WCharTy);
8092     if (S.Context.getLangOpts().Char8)
8093       ArithmeticTypes.push_back(S.Context.Char8Ty);
8094     ArithmeticTypes.push_back(S.Context.Char16Ty);
8095     ArithmeticTypes.push_back(S.Context.Char32Ty);
8096     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8097     ArithmeticTypes.push_back(S.Context.ShortTy);
8098     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8099     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8100     LastIntegralType = ArithmeticTypes.size();
8101     NumArithmeticTypes = ArithmeticTypes.size();
8102     // End of integral types.
8103     // FIXME: What about complex? What about half?
8104 
8105     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8106            "Enough inline storage for all arithmetic types.");
8107   }
8108 
8109   /// Helper method to factor out the common pattern of adding overloads
8110   /// for '++' and '--' builtin operators.
8111   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8112                                            bool HasVolatile,
8113                                            bool HasRestrict) {
8114     QualType ParamTypes[2] = {
8115       S.Context.getLValueReferenceType(CandidateTy),
8116       S.Context.IntTy
8117     };
8118 
8119     // Non-volatile version.
8120     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8121 
8122     // Use a heuristic to reduce number of builtin candidates in the set:
8123     // add volatile version only if there are conversions to a volatile type.
8124     if (HasVolatile) {
8125       ParamTypes[0] =
8126         S.Context.getLValueReferenceType(
8127           S.Context.getVolatileType(CandidateTy));
8128       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129     }
8130 
8131     // Add restrict version only if there are conversions to a restrict type
8132     // and our candidate type is a non-restrict-qualified pointer.
8133     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8134         !CandidateTy.isRestrictQualified()) {
8135       ParamTypes[0]
8136         = S.Context.getLValueReferenceType(
8137             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8138       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8139 
8140       if (HasVolatile) {
8141         ParamTypes[0]
8142           = S.Context.getLValueReferenceType(
8143               S.Context.getCVRQualifiedType(CandidateTy,
8144                                             (Qualifiers::Volatile |
8145                                              Qualifiers::Restrict)));
8146         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8147       }
8148     }
8149 
8150   }
8151 
8152 public:
8153   BuiltinOperatorOverloadBuilder(
8154     Sema &S, ArrayRef<Expr *> Args,
8155     Qualifiers VisibleTypeConversionsQuals,
8156     bool HasArithmeticOrEnumeralCandidateType,
8157     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8158     OverloadCandidateSet &CandidateSet)
8159     : S(S), Args(Args),
8160       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8161       HasArithmeticOrEnumeralCandidateType(
8162         HasArithmeticOrEnumeralCandidateType),
8163       CandidateTypes(CandidateTypes),
8164       CandidateSet(CandidateSet) {
8165 
8166     InitArithmeticTypes();
8167   }
8168 
8169   // Increment is deprecated for bool since C++17.
8170   //
8171   // C++ [over.built]p3:
8172   //
8173   //   For every pair (T, VQ), where T is an arithmetic type other
8174   //   than bool, and VQ is either volatile or empty, there exist
8175   //   candidate operator functions of the form
8176   //
8177   //       VQ T&      operator++(VQ T&);
8178   //       T          operator++(VQ T&, int);
8179   //
8180   // C++ [over.built]p4:
8181   //
8182   //   For every pair (T, VQ), where T is an arithmetic type other
8183   //   than bool, and VQ is either volatile or empty, there exist
8184   //   candidate operator functions of the form
8185   //
8186   //       VQ T&      operator--(VQ T&);
8187   //       T          operator--(VQ T&, int);
8188   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8189     if (!HasArithmeticOrEnumeralCandidateType)
8190       return;
8191 
8192     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8193       const auto TypeOfT = ArithmeticTypes[Arith];
8194       if (TypeOfT == S.Context.BoolTy) {
8195         if (Op == OO_MinusMinus)
8196           continue;
8197         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8198           continue;
8199       }
8200       addPlusPlusMinusMinusStyleOverloads(
8201         TypeOfT,
8202         VisibleTypeConversionsQuals.hasVolatile(),
8203         VisibleTypeConversionsQuals.hasRestrict());
8204     }
8205   }
8206 
8207   // C++ [over.built]p5:
8208   //
8209   //   For every pair (T, VQ), where T is a cv-qualified or
8210   //   cv-unqualified object type, and VQ is either volatile or
8211   //   empty, there exist candidate operator functions of the form
8212   //
8213   //       T*VQ&      operator++(T*VQ&);
8214   //       T*VQ&      operator--(T*VQ&);
8215   //       T*         operator++(T*VQ&, int);
8216   //       T*         operator--(T*VQ&, int);
8217   void addPlusPlusMinusMinusPointerOverloads() {
8218     for (BuiltinCandidateTypeSet::iterator
8219               Ptr = CandidateTypes[0].pointer_begin(),
8220            PtrEnd = CandidateTypes[0].pointer_end();
8221          Ptr != PtrEnd; ++Ptr) {
8222       // Skip pointer types that aren't pointers to object types.
8223       if (!(*Ptr)->getPointeeType()->isObjectType())
8224         continue;
8225 
8226       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8227         (!(*Ptr).isVolatileQualified() &&
8228          VisibleTypeConversionsQuals.hasVolatile()),
8229         (!(*Ptr).isRestrictQualified() &&
8230          VisibleTypeConversionsQuals.hasRestrict()));
8231     }
8232   }
8233 
8234   // C++ [over.built]p6:
8235   //   For every cv-qualified or cv-unqualified object type T, there
8236   //   exist candidate operator functions of the form
8237   //
8238   //       T&         operator*(T*);
8239   //
8240   // C++ [over.built]p7:
8241   //   For every function type T that does not have cv-qualifiers or a
8242   //   ref-qualifier, there exist candidate operator functions of the form
8243   //       T&         operator*(T*);
8244   void addUnaryStarPointerOverloads() {
8245     for (BuiltinCandidateTypeSet::iterator
8246               Ptr = CandidateTypes[0].pointer_begin(),
8247            PtrEnd = CandidateTypes[0].pointer_end();
8248          Ptr != PtrEnd; ++Ptr) {
8249       QualType ParamTy = *Ptr;
8250       QualType PointeeTy = ParamTy->getPointeeType();
8251       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8252         continue;
8253 
8254       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8255         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8256           continue;
8257 
8258       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8259     }
8260   }
8261 
8262   // C++ [over.built]p9:
8263   //  For every promoted arithmetic type T, there exist candidate
8264   //  operator functions of the form
8265   //
8266   //       T         operator+(T);
8267   //       T         operator-(T);
8268   void addUnaryPlusOrMinusArithmeticOverloads() {
8269     if (!HasArithmeticOrEnumeralCandidateType)
8270       return;
8271 
8272     for (unsigned Arith = FirstPromotedArithmeticType;
8273          Arith < LastPromotedArithmeticType; ++Arith) {
8274       QualType ArithTy = ArithmeticTypes[Arith];
8275       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8276     }
8277 
8278     // Extension: We also add these operators for vector types.
8279     for (BuiltinCandidateTypeSet::iterator
8280               Vec = CandidateTypes[0].vector_begin(),
8281            VecEnd = CandidateTypes[0].vector_end();
8282          Vec != VecEnd; ++Vec) {
8283       QualType VecTy = *Vec;
8284       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8285     }
8286   }
8287 
8288   // C++ [over.built]p8:
8289   //   For every type T, there exist candidate operator functions of
8290   //   the form
8291   //
8292   //       T*         operator+(T*);
8293   void addUnaryPlusPointerOverloads() {
8294     for (BuiltinCandidateTypeSet::iterator
8295               Ptr = CandidateTypes[0].pointer_begin(),
8296            PtrEnd = CandidateTypes[0].pointer_end();
8297          Ptr != PtrEnd; ++Ptr) {
8298       QualType ParamTy = *Ptr;
8299       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8300     }
8301   }
8302 
8303   // C++ [over.built]p10:
8304   //   For every promoted integral type T, there exist candidate
8305   //   operator functions of the form
8306   //
8307   //        T         operator~(T);
8308   void addUnaryTildePromotedIntegralOverloads() {
8309     if (!HasArithmeticOrEnumeralCandidateType)
8310       return;
8311 
8312     for (unsigned Int = FirstPromotedIntegralType;
8313          Int < LastPromotedIntegralType; ++Int) {
8314       QualType IntTy = ArithmeticTypes[Int];
8315       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8316     }
8317 
8318     // Extension: We also add this operator for vector types.
8319     for (BuiltinCandidateTypeSet::iterator
8320               Vec = CandidateTypes[0].vector_begin(),
8321            VecEnd = CandidateTypes[0].vector_end();
8322          Vec != VecEnd; ++Vec) {
8323       QualType VecTy = *Vec;
8324       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8325     }
8326   }
8327 
8328   // C++ [over.match.oper]p16:
8329   //   For every pointer to member type T or type std::nullptr_t, there
8330   //   exist candidate operator functions of the form
8331   //
8332   //        bool operator==(T,T);
8333   //        bool operator!=(T,T);
8334   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8335     /// Set of (canonical) types that we've already handled.
8336     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8337 
8338     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8339       for (BuiltinCandidateTypeSet::iterator
8340                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8341              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8342            MemPtr != MemPtrEnd;
8343            ++MemPtr) {
8344         // Don't add the same builtin candidate twice.
8345         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8346           continue;
8347 
8348         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8349         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8350       }
8351 
8352       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8353         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8354         if (AddedTypes.insert(NullPtrTy).second) {
8355           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8356           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8357         }
8358       }
8359     }
8360   }
8361 
8362   // C++ [over.built]p15:
8363   //
8364   //   For every T, where T is an enumeration type or a pointer type,
8365   //   there exist candidate operator functions of the form
8366   //
8367   //        bool       operator<(T, T);
8368   //        bool       operator>(T, T);
8369   //        bool       operator<=(T, T);
8370   //        bool       operator>=(T, T);
8371   //        bool       operator==(T, T);
8372   //        bool       operator!=(T, T);
8373   //           R       operator<=>(T, T)
8374   void addGenericBinaryPointerOrEnumeralOverloads() {
8375     // C++ [over.match.oper]p3:
8376     //   [...]the built-in candidates include all of the candidate operator
8377     //   functions defined in 13.6 that, compared to the given operator, [...]
8378     //   do not have the same parameter-type-list as any non-template non-member
8379     //   candidate.
8380     //
8381     // Note that in practice, this only affects enumeration types because there
8382     // aren't any built-in candidates of record type, and a user-defined operator
8383     // must have an operand of record or enumeration type. Also, the only other
8384     // overloaded operator with enumeration arguments, operator=,
8385     // cannot be overloaded for enumeration types, so this is the only place
8386     // where we must suppress candidates like this.
8387     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8388       UserDefinedBinaryOperators;
8389 
8390     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8391       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8392           CandidateTypes[ArgIdx].enumeration_end()) {
8393         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8394                                          CEnd = CandidateSet.end();
8395              C != CEnd; ++C) {
8396           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8397             continue;
8398 
8399           if (C->Function->isFunctionTemplateSpecialization())
8400             continue;
8401 
8402           // We interpret "same parameter-type-list" as applying to the
8403           // "synthesized candidate, with the order of the two parameters
8404           // reversed", not to the original function.
8405           bool Reversed = C->isReversed();
8406           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8407                                         ->getType()
8408                                         .getUnqualifiedType();
8409           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8410                                          ->getType()
8411                                          .getUnqualifiedType();
8412 
8413           // Skip if either parameter isn't of enumeral type.
8414           if (!FirstParamType->isEnumeralType() ||
8415               !SecondParamType->isEnumeralType())
8416             continue;
8417 
8418           // Add this operator to the set of known user-defined operators.
8419           UserDefinedBinaryOperators.insert(
8420             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8421                            S.Context.getCanonicalType(SecondParamType)));
8422         }
8423       }
8424     }
8425 
8426     /// Set of (canonical) types that we've already handled.
8427     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8428 
8429     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8430       for (BuiltinCandidateTypeSet::iterator
8431                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8432              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8433            Ptr != PtrEnd; ++Ptr) {
8434         // Don't add the same builtin candidate twice.
8435         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8436           continue;
8437 
8438         QualType ParamTypes[2] = { *Ptr, *Ptr };
8439         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8440       }
8441       for (BuiltinCandidateTypeSet::iterator
8442                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8443              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8444            Enum != EnumEnd; ++Enum) {
8445         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8446 
8447         // Don't add the same builtin candidate twice, or if a user defined
8448         // candidate exists.
8449         if (!AddedTypes.insert(CanonType).second ||
8450             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8451                                                             CanonType)))
8452           continue;
8453         QualType ParamTypes[2] = { *Enum, *Enum };
8454         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8455       }
8456     }
8457   }
8458 
8459   // C++ [over.built]p13:
8460   //
8461   //   For every cv-qualified or cv-unqualified object type T
8462   //   there exist candidate operator functions of the form
8463   //
8464   //      T*         operator+(T*, ptrdiff_t);
8465   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8466   //      T*         operator-(T*, ptrdiff_t);
8467   //      T*         operator+(ptrdiff_t, T*);
8468   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8469   //
8470   // C++ [over.built]p14:
8471   //
8472   //   For every T, where T is a pointer to object type, there
8473   //   exist candidate operator functions of the form
8474   //
8475   //      ptrdiff_t  operator-(T, T);
8476   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8477     /// Set of (canonical) types that we've already handled.
8478     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8479 
8480     for (int Arg = 0; Arg < 2; ++Arg) {
8481       QualType AsymmetricParamTypes[2] = {
8482         S.Context.getPointerDiffType(),
8483         S.Context.getPointerDiffType(),
8484       };
8485       for (BuiltinCandidateTypeSet::iterator
8486                 Ptr = CandidateTypes[Arg].pointer_begin(),
8487              PtrEnd = CandidateTypes[Arg].pointer_end();
8488            Ptr != PtrEnd; ++Ptr) {
8489         QualType PointeeTy = (*Ptr)->getPointeeType();
8490         if (!PointeeTy->isObjectType())
8491           continue;
8492 
8493         AsymmetricParamTypes[Arg] = *Ptr;
8494         if (Arg == 0 || Op == OO_Plus) {
8495           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8496           // T* operator+(ptrdiff_t, T*);
8497           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8498         }
8499         if (Op == OO_Minus) {
8500           // ptrdiff_t operator-(T, T);
8501           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8502             continue;
8503 
8504           QualType ParamTypes[2] = { *Ptr, *Ptr };
8505           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8506         }
8507       }
8508     }
8509   }
8510 
8511   // C++ [over.built]p12:
8512   //
8513   //   For every pair of promoted arithmetic types L and R, there
8514   //   exist candidate operator functions of the form
8515   //
8516   //        LR         operator*(L, R);
8517   //        LR         operator/(L, R);
8518   //        LR         operator+(L, R);
8519   //        LR         operator-(L, R);
8520   //        bool       operator<(L, R);
8521   //        bool       operator>(L, R);
8522   //        bool       operator<=(L, R);
8523   //        bool       operator>=(L, R);
8524   //        bool       operator==(L, R);
8525   //        bool       operator!=(L, R);
8526   //
8527   //   where LR is the result of the usual arithmetic conversions
8528   //   between types L and R.
8529   //
8530   // C++ [over.built]p24:
8531   //
8532   //   For every pair of promoted arithmetic types L and R, there exist
8533   //   candidate operator functions of the form
8534   //
8535   //        LR       operator?(bool, L, R);
8536   //
8537   //   where LR is the result of the usual arithmetic conversions
8538   //   between types L and R.
8539   // Our candidates ignore the first parameter.
8540   void addGenericBinaryArithmeticOverloads() {
8541     if (!HasArithmeticOrEnumeralCandidateType)
8542       return;
8543 
8544     for (unsigned Left = FirstPromotedArithmeticType;
8545          Left < LastPromotedArithmeticType; ++Left) {
8546       for (unsigned Right = FirstPromotedArithmeticType;
8547            Right < LastPromotedArithmeticType; ++Right) {
8548         QualType LandR[2] = { ArithmeticTypes[Left],
8549                               ArithmeticTypes[Right] };
8550         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8551       }
8552     }
8553 
8554     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8555     // conditional operator for vector types.
8556     for (BuiltinCandidateTypeSet::iterator
8557               Vec1 = CandidateTypes[0].vector_begin(),
8558            Vec1End = CandidateTypes[0].vector_end();
8559          Vec1 != Vec1End; ++Vec1) {
8560       for (BuiltinCandidateTypeSet::iterator
8561                 Vec2 = CandidateTypes[1].vector_begin(),
8562              Vec2End = CandidateTypes[1].vector_end();
8563            Vec2 != Vec2End; ++Vec2) {
8564         QualType LandR[2] = { *Vec1, *Vec2 };
8565         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8566       }
8567     }
8568   }
8569 
8570   // C++2a [over.built]p14:
8571   //
8572   //   For every integral type T there exists a candidate operator function
8573   //   of the form
8574   //
8575   //        std::strong_ordering operator<=>(T, T)
8576   //
8577   // C++2a [over.built]p15:
8578   //
8579   //   For every pair of floating-point types L and R, there exists a candidate
8580   //   operator function of the form
8581   //
8582   //       std::partial_ordering operator<=>(L, R);
8583   //
8584   // FIXME: The current specification for integral types doesn't play nice with
8585   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8586   // comparisons. Under the current spec this can lead to ambiguity during
8587   // overload resolution. For example:
8588   //
8589   //   enum A : int {a};
8590   //   auto x = (a <=> (long)42);
8591   //
8592   //   error: call is ambiguous for arguments 'A' and 'long'.
8593   //   note: candidate operator<=>(int, int)
8594   //   note: candidate operator<=>(long, long)
8595   //
8596   // To avoid this error, this function deviates from the specification and adds
8597   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8598   // arithmetic types (the same as the generic relational overloads).
8599   //
8600   // For now this function acts as a placeholder.
8601   void addThreeWayArithmeticOverloads() {
8602     addGenericBinaryArithmeticOverloads();
8603   }
8604 
8605   // C++ [over.built]p17:
8606   //
8607   //   For every pair of promoted integral types L and R, there
8608   //   exist candidate operator functions of the form
8609   //
8610   //      LR         operator%(L, R);
8611   //      LR         operator&(L, R);
8612   //      LR         operator^(L, R);
8613   //      LR         operator|(L, R);
8614   //      L          operator<<(L, R);
8615   //      L          operator>>(L, R);
8616   //
8617   //   where LR is the result of the usual arithmetic conversions
8618   //   between types L and R.
8619   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8620     if (!HasArithmeticOrEnumeralCandidateType)
8621       return;
8622 
8623     for (unsigned Left = FirstPromotedIntegralType;
8624          Left < LastPromotedIntegralType; ++Left) {
8625       for (unsigned Right = FirstPromotedIntegralType;
8626            Right < LastPromotedIntegralType; ++Right) {
8627         QualType LandR[2] = { ArithmeticTypes[Left],
8628                               ArithmeticTypes[Right] };
8629         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8630       }
8631     }
8632   }
8633 
8634   // C++ [over.built]p20:
8635   //
8636   //   For every pair (T, VQ), where T is an enumeration or
8637   //   pointer to member type and VQ is either volatile or
8638   //   empty, there exist candidate operator functions of the form
8639   //
8640   //        VQ T&      operator=(VQ T&, T);
8641   void addAssignmentMemberPointerOrEnumeralOverloads() {
8642     /// Set of (canonical) types that we've already handled.
8643     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8644 
8645     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8646       for (BuiltinCandidateTypeSet::iterator
8647                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8648              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8649            Enum != EnumEnd; ++Enum) {
8650         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8651           continue;
8652 
8653         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8654       }
8655 
8656       for (BuiltinCandidateTypeSet::iterator
8657                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8658              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8659            MemPtr != MemPtrEnd; ++MemPtr) {
8660         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8661           continue;
8662 
8663         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8664       }
8665     }
8666   }
8667 
8668   // C++ [over.built]p19:
8669   //
8670   //   For every pair (T, VQ), where T is any type and VQ is either
8671   //   volatile or empty, there exist candidate operator functions
8672   //   of the form
8673   //
8674   //        T*VQ&      operator=(T*VQ&, T*);
8675   //
8676   // C++ [over.built]p21:
8677   //
8678   //   For every pair (T, VQ), where T is a cv-qualified or
8679   //   cv-unqualified object type and VQ is either volatile or
8680   //   empty, there exist candidate operator functions of the form
8681   //
8682   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8683   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8684   void addAssignmentPointerOverloads(bool isEqualOp) {
8685     /// Set of (canonical) types that we've already handled.
8686     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8687 
8688     for (BuiltinCandidateTypeSet::iterator
8689               Ptr = CandidateTypes[0].pointer_begin(),
8690            PtrEnd = CandidateTypes[0].pointer_end();
8691          Ptr != PtrEnd; ++Ptr) {
8692       // If this is operator=, keep track of the builtin candidates we added.
8693       if (isEqualOp)
8694         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8695       else if (!(*Ptr)->getPointeeType()->isObjectType())
8696         continue;
8697 
8698       // non-volatile version
8699       QualType ParamTypes[2] = {
8700         S.Context.getLValueReferenceType(*Ptr),
8701         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8702       };
8703       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8704                             /*IsAssignmentOperator=*/ isEqualOp);
8705 
8706       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8707                           VisibleTypeConversionsQuals.hasVolatile();
8708       if (NeedVolatile) {
8709         // volatile version
8710         ParamTypes[0] =
8711           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8712         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8713                               /*IsAssignmentOperator=*/isEqualOp);
8714       }
8715 
8716       if (!(*Ptr).isRestrictQualified() &&
8717           VisibleTypeConversionsQuals.hasRestrict()) {
8718         // restrict version
8719         ParamTypes[0]
8720           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8721         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8722                               /*IsAssignmentOperator=*/isEqualOp);
8723 
8724         if (NeedVolatile) {
8725           // volatile restrict version
8726           ParamTypes[0]
8727             = S.Context.getLValueReferenceType(
8728                 S.Context.getCVRQualifiedType(*Ptr,
8729                                               (Qualifiers::Volatile |
8730                                                Qualifiers::Restrict)));
8731           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8732                                 /*IsAssignmentOperator=*/isEqualOp);
8733         }
8734       }
8735     }
8736 
8737     if (isEqualOp) {
8738       for (BuiltinCandidateTypeSet::iterator
8739                 Ptr = CandidateTypes[1].pointer_begin(),
8740              PtrEnd = CandidateTypes[1].pointer_end();
8741            Ptr != PtrEnd; ++Ptr) {
8742         // Make sure we don't add the same candidate twice.
8743         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8744           continue;
8745 
8746         QualType ParamTypes[2] = {
8747           S.Context.getLValueReferenceType(*Ptr),
8748           *Ptr,
8749         };
8750 
8751         // non-volatile version
8752         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8753                               /*IsAssignmentOperator=*/true);
8754 
8755         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8756                            VisibleTypeConversionsQuals.hasVolatile();
8757         if (NeedVolatile) {
8758           // volatile version
8759           ParamTypes[0] =
8760             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8761           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8762                                 /*IsAssignmentOperator=*/true);
8763         }
8764 
8765         if (!(*Ptr).isRestrictQualified() &&
8766             VisibleTypeConversionsQuals.hasRestrict()) {
8767           // restrict version
8768           ParamTypes[0]
8769             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8770           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8771                                 /*IsAssignmentOperator=*/true);
8772 
8773           if (NeedVolatile) {
8774             // volatile restrict version
8775             ParamTypes[0]
8776               = S.Context.getLValueReferenceType(
8777                   S.Context.getCVRQualifiedType(*Ptr,
8778                                                 (Qualifiers::Volatile |
8779                                                  Qualifiers::Restrict)));
8780             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8781                                   /*IsAssignmentOperator=*/true);
8782           }
8783         }
8784       }
8785     }
8786   }
8787 
8788   // C++ [over.built]p18:
8789   //
8790   //   For every triple (L, VQ, R), where L is an arithmetic type,
8791   //   VQ is either volatile or empty, and R is a promoted
8792   //   arithmetic type, there exist candidate operator functions of
8793   //   the form
8794   //
8795   //        VQ L&      operator=(VQ L&, R);
8796   //        VQ L&      operator*=(VQ L&, R);
8797   //        VQ L&      operator/=(VQ L&, R);
8798   //        VQ L&      operator+=(VQ L&, R);
8799   //        VQ L&      operator-=(VQ L&, R);
8800   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8801     if (!HasArithmeticOrEnumeralCandidateType)
8802       return;
8803 
8804     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8805       for (unsigned Right = FirstPromotedArithmeticType;
8806            Right < LastPromotedArithmeticType; ++Right) {
8807         QualType ParamTypes[2];
8808         ParamTypes[1] = ArithmeticTypes[Right];
8809         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8810             S, ArithmeticTypes[Left], Args[0]);
8811         // Add this built-in operator as a candidate (VQ is empty).
8812         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8813         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8814                               /*IsAssignmentOperator=*/isEqualOp);
8815 
8816         // Add this built-in operator as a candidate (VQ is 'volatile').
8817         if (VisibleTypeConversionsQuals.hasVolatile()) {
8818           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8819           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8820           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8821                                 /*IsAssignmentOperator=*/isEqualOp);
8822         }
8823       }
8824     }
8825 
8826     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8827     for (BuiltinCandidateTypeSet::iterator
8828               Vec1 = CandidateTypes[0].vector_begin(),
8829            Vec1End = CandidateTypes[0].vector_end();
8830          Vec1 != Vec1End; ++Vec1) {
8831       for (BuiltinCandidateTypeSet::iterator
8832                 Vec2 = CandidateTypes[1].vector_begin(),
8833              Vec2End = CandidateTypes[1].vector_end();
8834            Vec2 != Vec2End; ++Vec2) {
8835         QualType ParamTypes[2];
8836         ParamTypes[1] = *Vec2;
8837         // Add this built-in operator as a candidate (VQ is empty).
8838         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8839         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8840                               /*IsAssignmentOperator=*/isEqualOp);
8841 
8842         // Add this built-in operator as a candidate (VQ is 'volatile').
8843         if (VisibleTypeConversionsQuals.hasVolatile()) {
8844           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8845           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8846           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8847                                 /*IsAssignmentOperator=*/isEqualOp);
8848         }
8849       }
8850     }
8851   }
8852 
8853   // C++ [over.built]p22:
8854   //
8855   //   For every triple (L, VQ, R), where L is an integral type, VQ
8856   //   is either volatile or empty, and R is a promoted integral
8857   //   type, there exist candidate operator functions of the form
8858   //
8859   //        VQ L&       operator%=(VQ L&, R);
8860   //        VQ L&       operator<<=(VQ L&, R);
8861   //        VQ L&       operator>>=(VQ L&, R);
8862   //        VQ L&       operator&=(VQ L&, R);
8863   //        VQ L&       operator^=(VQ L&, R);
8864   //        VQ L&       operator|=(VQ L&, R);
8865   void addAssignmentIntegralOverloads() {
8866     if (!HasArithmeticOrEnumeralCandidateType)
8867       return;
8868 
8869     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8870       for (unsigned Right = FirstPromotedIntegralType;
8871            Right < LastPromotedIntegralType; ++Right) {
8872         QualType ParamTypes[2];
8873         ParamTypes[1] = ArithmeticTypes[Right];
8874         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8875             S, ArithmeticTypes[Left], Args[0]);
8876         // Add this built-in operator as a candidate (VQ is empty).
8877         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8878         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8879         if (VisibleTypeConversionsQuals.hasVolatile()) {
8880           // Add this built-in operator as a candidate (VQ is 'volatile').
8881           ParamTypes[0] = LeftBaseTy;
8882           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8883           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8884           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8885         }
8886       }
8887     }
8888   }
8889 
8890   // C++ [over.operator]p23:
8891   //
8892   //   There also exist candidate operator functions of the form
8893   //
8894   //        bool        operator!(bool);
8895   //        bool        operator&&(bool, bool);
8896   //        bool        operator||(bool, bool);
8897   void addExclaimOverload() {
8898     QualType ParamTy = S.Context.BoolTy;
8899     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8900                           /*IsAssignmentOperator=*/false,
8901                           /*NumContextualBoolArguments=*/1);
8902   }
8903   void addAmpAmpOrPipePipeOverload() {
8904     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8905     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8906                           /*IsAssignmentOperator=*/false,
8907                           /*NumContextualBoolArguments=*/2);
8908   }
8909 
8910   // C++ [over.built]p13:
8911   //
8912   //   For every cv-qualified or cv-unqualified object type T there
8913   //   exist candidate operator functions of the form
8914   //
8915   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8916   //        T&         operator[](T*, ptrdiff_t);
8917   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8918   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8919   //        T&         operator[](ptrdiff_t, T*);
8920   void addSubscriptOverloads() {
8921     for (BuiltinCandidateTypeSet::iterator
8922               Ptr = CandidateTypes[0].pointer_begin(),
8923            PtrEnd = CandidateTypes[0].pointer_end();
8924          Ptr != PtrEnd; ++Ptr) {
8925       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8926       QualType PointeeType = (*Ptr)->getPointeeType();
8927       if (!PointeeType->isObjectType())
8928         continue;
8929 
8930       // T& operator[](T*, ptrdiff_t)
8931       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8932     }
8933 
8934     for (BuiltinCandidateTypeSet::iterator
8935               Ptr = CandidateTypes[1].pointer_begin(),
8936            PtrEnd = CandidateTypes[1].pointer_end();
8937          Ptr != PtrEnd; ++Ptr) {
8938       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8939       QualType PointeeType = (*Ptr)->getPointeeType();
8940       if (!PointeeType->isObjectType())
8941         continue;
8942 
8943       // T& operator[](ptrdiff_t, T*)
8944       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8945     }
8946   }
8947 
8948   // C++ [over.built]p11:
8949   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8950   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8951   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8952   //    there exist candidate operator functions of the form
8953   //
8954   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8955   //
8956   //    where CV12 is the union of CV1 and CV2.
8957   void addArrowStarOverloads() {
8958     for (BuiltinCandidateTypeSet::iterator
8959              Ptr = CandidateTypes[0].pointer_begin(),
8960            PtrEnd = CandidateTypes[0].pointer_end();
8961          Ptr != PtrEnd; ++Ptr) {
8962       QualType C1Ty = (*Ptr);
8963       QualType C1;
8964       QualifierCollector Q1;
8965       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8966       if (!isa<RecordType>(C1))
8967         continue;
8968       // heuristic to reduce number of builtin candidates in the set.
8969       // Add volatile/restrict version only if there are conversions to a
8970       // volatile/restrict type.
8971       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8972         continue;
8973       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8974         continue;
8975       for (BuiltinCandidateTypeSet::iterator
8976                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8977              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8978            MemPtr != MemPtrEnd; ++MemPtr) {
8979         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8980         QualType C2 = QualType(mptr->getClass(), 0);
8981         C2 = C2.getUnqualifiedType();
8982         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8983           break;
8984         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8985         // build CV12 T&
8986         QualType T = mptr->getPointeeType();
8987         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8988             T.isVolatileQualified())
8989           continue;
8990         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8991             T.isRestrictQualified())
8992           continue;
8993         T = Q1.apply(S.Context, T);
8994         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8995       }
8996     }
8997   }
8998 
8999   // Note that we don't consider the first argument, since it has been
9000   // contextually converted to bool long ago. The candidates below are
9001   // therefore added as binary.
9002   //
9003   // C++ [over.built]p25:
9004   //   For every type T, where T is a pointer, pointer-to-member, or scoped
9005   //   enumeration type, there exist candidate operator functions of the form
9006   //
9007   //        T        operator?(bool, T, T);
9008   //
9009   void addConditionalOperatorOverloads() {
9010     /// Set of (canonical) types that we've already handled.
9011     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9012 
9013     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9014       for (BuiltinCandidateTypeSet::iterator
9015                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9016              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9017            Ptr != PtrEnd; ++Ptr) {
9018         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9019           continue;
9020 
9021         QualType ParamTypes[2] = { *Ptr, *Ptr };
9022         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9023       }
9024 
9025       for (BuiltinCandidateTypeSet::iterator
9026                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9027              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9028            MemPtr != MemPtrEnd; ++MemPtr) {
9029         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9030           continue;
9031 
9032         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9033         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9034       }
9035 
9036       if (S.getLangOpts().CPlusPlus11) {
9037         for (BuiltinCandidateTypeSet::iterator
9038                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9039                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9040              Enum != EnumEnd; ++Enum) {
9041           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9042             continue;
9043 
9044           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9045             continue;
9046 
9047           QualType ParamTypes[2] = { *Enum, *Enum };
9048           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9049         }
9050       }
9051     }
9052   }
9053 };
9054 
9055 } // end anonymous namespace
9056 
9057 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9058 /// operator overloads to the candidate set (C++ [over.built]), based
9059 /// on the operator @p Op and the arguments given. For example, if the
9060 /// operator is a binary '+', this routine might add "int
9061 /// operator+(int, int)" to cover integer addition.
9062 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9063                                         SourceLocation OpLoc,
9064                                         ArrayRef<Expr *> Args,
9065                                         OverloadCandidateSet &CandidateSet) {
9066   // Find all of the types that the arguments can convert to, but only
9067   // if the operator we're looking at has built-in operator candidates
9068   // that make use of these types. Also record whether we encounter non-record
9069   // candidate types or either arithmetic or enumeral candidate types.
9070   Qualifiers VisibleTypeConversionsQuals;
9071   VisibleTypeConversionsQuals.addConst();
9072   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9073     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9074 
9075   bool HasNonRecordCandidateType = false;
9076   bool HasArithmeticOrEnumeralCandidateType = false;
9077   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9078   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9079     CandidateTypes.emplace_back(*this);
9080     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9081                                                  OpLoc,
9082                                                  true,
9083                                                  (Op == OO_Exclaim ||
9084                                                   Op == OO_AmpAmp ||
9085                                                   Op == OO_PipePipe),
9086                                                  VisibleTypeConversionsQuals);
9087     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9088         CandidateTypes[ArgIdx].hasNonRecordTypes();
9089     HasArithmeticOrEnumeralCandidateType =
9090         HasArithmeticOrEnumeralCandidateType ||
9091         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9092   }
9093 
9094   // Exit early when no non-record types have been added to the candidate set
9095   // for any of the arguments to the operator.
9096   //
9097   // We can't exit early for !, ||, or &&, since there we have always have
9098   // 'bool' overloads.
9099   if (!HasNonRecordCandidateType &&
9100       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9101     return;
9102 
9103   // Setup an object to manage the common state for building overloads.
9104   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9105                                            VisibleTypeConversionsQuals,
9106                                            HasArithmeticOrEnumeralCandidateType,
9107                                            CandidateTypes, CandidateSet);
9108 
9109   // Dispatch over the operation to add in only those overloads which apply.
9110   switch (Op) {
9111   case OO_None:
9112   case NUM_OVERLOADED_OPERATORS:
9113     llvm_unreachable("Expected an overloaded operator");
9114 
9115   case OO_New:
9116   case OO_Delete:
9117   case OO_Array_New:
9118   case OO_Array_Delete:
9119   case OO_Call:
9120     llvm_unreachable(
9121                     "Special operators don't use AddBuiltinOperatorCandidates");
9122 
9123   case OO_Comma:
9124   case OO_Arrow:
9125   case OO_Coawait:
9126     // C++ [over.match.oper]p3:
9127     //   -- For the operator ',', the unary operator '&', the
9128     //      operator '->', or the operator 'co_await', the
9129     //      built-in candidates set is empty.
9130     break;
9131 
9132   case OO_Plus: // '+' is either unary or binary
9133     if (Args.size() == 1)
9134       OpBuilder.addUnaryPlusPointerOverloads();
9135     LLVM_FALLTHROUGH;
9136 
9137   case OO_Minus: // '-' is either unary or binary
9138     if (Args.size() == 1) {
9139       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9140     } else {
9141       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9142       OpBuilder.addGenericBinaryArithmeticOverloads();
9143     }
9144     break;
9145 
9146   case OO_Star: // '*' is either unary or binary
9147     if (Args.size() == 1)
9148       OpBuilder.addUnaryStarPointerOverloads();
9149     else
9150       OpBuilder.addGenericBinaryArithmeticOverloads();
9151     break;
9152 
9153   case OO_Slash:
9154     OpBuilder.addGenericBinaryArithmeticOverloads();
9155     break;
9156 
9157   case OO_PlusPlus:
9158   case OO_MinusMinus:
9159     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9160     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9161     break;
9162 
9163   case OO_EqualEqual:
9164   case OO_ExclaimEqual:
9165     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9166     LLVM_FALLTHROUGH;
9167 
9168   case OO_Less:
9169   case OO_Greater:
9170   case OO_LessEqual:
9171   case OO_GreaterEqual:
9172     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9173     OpBuilder.addGenericBinaryArithmeticOverloads();
9174     break;
9175 
9176   case OO_Spaceship:
9177     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9178     OpBuilder.addThreeWayArithmeticOverloads();
9179     break;
9180 
9181   case OO_Percent:
9182   case OO_Caret:
9183   case OO_Pipe:
9184   case OO_LessLess:
9185   case OO_GreaterGreater:
9186     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9187     break;
9188 
9189   case OO_Amp: // '&' is either unary or binary
9190     if (Args.size() == 1)
9191       // C++ [over.match.oper]p3:
9192       //   -- For the operator ',', the unary operator '&', or the
9193       //      operator '->', the built-in candidates set is empty.
9194       break;
9195 
9196     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9197     break;
9198 
9199   case OO_Tilde:
9200     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9201     break;
9202 
9203   case OO_Equal:
9204     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9205     LLVM_FALLTHROUGH;
9206 
9207   case OO_PlusEqual:
9208   case OO_MinusEqual:
9209     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9210     LLVM_FALLTHROUGH;
9211 
9212   case OO_StarEqual:
9213   case OO_SlashEqual:
9214     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9215     break;
9216 
9217   case OO_PercentEqual:
9218   case OO_LessLessEqual:
9219   case OO_GreaterGreaterEqual:
9220   case OO_AmpEqual:
9221   case OO_CaretEqual:
9222   case OO_PipeEqual:
9223     OpBuilder.addAssignmentIntegralOverloads();
9224     break;
9225 
9226   case OO_Exclaim:
9227     OpBuilder.addExclaimOverload();
9228     break;
9229 
9230   case OO_AmpAmp:
9231   case OO_PipePipe:
9232     OpBuilder.addAmpAmpOrPipePipeOverload();
9233     break;
9234 
9235   case OO_Subscript:
9236     OpBuilder.addSubscriptOverloads();
9237     break;
9238 
9239   case OO_ArrowStar:
9240     OpBuilder.addArrowStarOverloads();
9241     break;
9242 
9243   case OO_Conditional:
9244     OpBuilder.addConditionalOperatorOverloads();
9245     OpBuilder.addGenericBinaryArithmeticOverloads();
9246     break;
9247   }
9248 }
9249 
9250 /// Add function candidates found via argument-dependent lookup
9251 /// to the set of overloading candidates.
9252 ///
9253 /// This routine performs argument-dependent name lookup based on the
9254 /// given function name (which may also be an operator name) and adds
9255 /// all of the overload candidates found by ADL to the overload
9256 /// candidate set (C++ [basic.lookup.argdep]).
9257 void
9258 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9259                                            SourceLocation Loc,
9260                                            ArrayRef<Expr *> Args,
9261                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9262                                            OverloadCandidateSet& CandidateSet,
9263                                            bool PartialOverloading) {
9264   ADLResult Fns;
9265 
9266   // FIXME: This approach for uniquing ADL results (and removing
9267   // redundant candidates from the set) relies on pointer-equality,
9268   // which means we need to key off the canonical decl.  However,
9269   // always going back to the canonical decl might not get us the
9270   // right set of default arguments.  What default arguments are
9271   // we supposed to consider on ADL candidates, anyway?
9272 
9273   // FIXME: Pass in the explicit template arguments?
9274   ArgumentDependentLookup(Name, Loc, Args, Fns);
9275 
9276   // Erase all of the candidates we already knew about.
9277   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9278                                    CandEnd = CandidateSet.end();
9279        Cand != CandEnd; ++Cand)
9280     if (Cand->Function) {
9281       Fns.erase(Cand->Function);
9282       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9283         Fns.erase(FunTmpl);
9284     }
9285 
9286   // For each of the ADL candidates we found, add it to the overload
9287   // set.
9288   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9289     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9290 
9291     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9292       if (ExplicitTemplateArgs)
9293         continue;
9294 
9295       AddOverloadCandidate(
9296           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9297           PartialOverloading, /*AllowExplicit=*/true,
9298           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9299       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9300         AddOverloadCandidate(
9301             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9302             /*SuppressUserConversions=*/false, PartialOverloading,
9303             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9304             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9305       }
9306     } else {
9307       auto *FTD = cast<FunctionTemplateDecl>(*I);
9308       AddTemplateOverloadCandidate(
9309           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9310           /*SuppressUserConversions=*/false, PartialOverloading,
9311           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9312       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9313               Context, FTD->getTemplatedDecl())) {
9314         AddTemplateOverloadCandidate(
9315             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9316             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9317             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9318             OverloadCandidateParamOrder::Reversed);
9319       }
9320     }
9321   }
9322 }
9323 
9324 namespace {
9325 enum class Comparison { Equal, Better, Worse };
9326 }
9327 
9328 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9329 /// overload resolution.
9330 ///
9331 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9332 /// Cand1's first N enable_if attributes have precisely the same conditions as
9333 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9334 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9335 ///
9336 /// Note that you can have a pair of candidates such that Cand1's enable_if
9337 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9338 /// worse than Cand1's.
9339 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9340                                        const FunctionDecl *Cand2) {
9341   // Common case: One (or both) decls don't have enable_if attrs.
9342   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9343   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9344   if (!Cand1Attr || !Cand2Attr) {
9345     if (Cand1Attr == Cand2Attr)
9346       return Comparison::Equal;
9347     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9348   }
9349 
9350   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9351   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9352 
9353   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9354   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9355     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9356     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9357 
9358     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9359     // has fewer enable_if attributes than Cand2, and vice versa.
9360     if (!Cand1A)
9361       return Comparison::Worse;
9362     if (!Cand2A)
9363       return Comparison::Better;
9364 
9365     Cand1ID.clear();
9366     Cand2ID.clear();
9367 
9368     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9369     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9370     if (Cand1ID != Cand2ID)
9371       return Comparison::Worse;
9372   }
9373 
9374   return Comparison::Equal;
9375 }
9376 
9377 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9378                                           const OverloadCandidate &Cand2) {
9379   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9380       !Cand2.Function->isMultiVersion())
9381     return false;
9382 
9383   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9384   // is obviously better.
9385   if (Cand1.Function->isInvalidDecl()) return false;
9386   if (Cand2.Function->isInvalidDecl()) return true;
9387 
9388   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9389   // cpu_dispatch, else arbitrarily based on the identifiers.
9390   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9391   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9392   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9393   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9394 
9395   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9396     return false;
9397 
9398   if (Cand1CPUDisp && !Cand2CPUDisp)
9399     return true;
9400   if (Cand2CPUDisp && !Cand1CPUDisp)
9401     return false;
9402 
9403   if (Cand1CPUSpec && Cand2CPUSpec) {
9404     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9405       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9406 
9407     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9408         FirstDiff = std::mismatch(
9409             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9410             Cand2CPUSpec->cpus_begin(),
9411             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9412               return LHS->getName() == RHS->getName();
9413             });
9414 
9415     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9416            "Two different cpu-specific versions should not have the same "
9417            "identifier list, otherwise they'd be the same decl!");
9418     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9419   }
9420   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9421 }
9422 
9423 /// Compute the type of the implicit object parameter for the given function,
9424 /// if any. Returns None if there is no implicit object parameter, and a null
9425 /// QualType if there is a 'matches anything' implicit object parameter.
9426 static Optional<QualType> getImplicitObjectParamType(ASTContext &Context,
9427                                                      const FunctionDecl *F) {
9428   if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
9429     return llvm::None;
9430 
9431   auto *M = cast<CXXMethodDecl>(F);
9432   // Static member functions' object parameters match all types.
9433   if (M->isStatic())
9434     return QualType();
9435 
9436   QualType T = M->getThisObjectType();
9437   if (M->getRefQualifier() == RQ_RValue)
9438     return Context.getRValueReferenceType(T);
9439   return Context.getLValueReferenceType(T);
9440 }
9441 
9442 static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
9443                                    const FunctionDecl *F2, unsigned NumParams) {
9444   if (declaresSameEntity(F1, F2))
9445     return true;
9446 
9447   auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
9448     if (First) {
9449       if (Optional<QualType> T = getImplicitObjectParamType(Context, F))
9450         return *T;
9451     }
9452     assert(I < F->getNumParams());
9453     return F->getParamDecl(I++)->getType();
9454   };
9455 
9456   unsigned I1 = 0, I2 = 0;
9457   for (unsigned I = 0; I != NumParams; ++I) {
9458     QualType T1 = NextParam(F1, I1, I == 0);
9459     QualType T2 = NextParam(F2, I2, I == 0);
9460     if (!T1.isNull() && !T1.isNull() && !Context.hasSameUnqualifiedType(T1, T2))
9461       return false;
9462   }
9463   return true;
9464 }
9465 
9466 /// isBetterOverloadCandidate - Determines whether the first overload
9467 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9468 bool clang::isBetterOverloadCandidate(
9469     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9470     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9471   // Define viable functions to be better candidates than non-viable
9472   // functions.
9473   if (!Cand2.Viable)
9474     return Cand1.Viable;
9475   else if (!Cand1.Viable)
9476     return false;
9477 
9478   // C++ [over.match.best]p1:
9479   //
9480   //   -- if F is a static member function, ICS1(F) is defined such
9481   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9482   //      any function G, and, symmetrically, ICS1(G) is neither
9483   //      better nor worse than ICS1(F).
9484   unsigned StartArg = 0;
9485   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9486     StartArg = 1;
9487 
9488   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9489     // We don't allow incompatible pointer conversions in C++.
9490     if (!S.getLangOpts().CPlusPlus)
9491       return ICS.isStandard() &&
9492              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9493 
9494     // The only ill-formed conversion we allow in C++ is the string literal to
9495     // char* conversion, which is only considered ill-formed after C++11.
9496     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9497            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9498   };
9499 
9500   // Define functions that don't require ill-formed conversions for a given
9501   // argument to be better candidates than functions that do.
9502   unsigned NumArgs = Cand1.Conversions.size();
9503   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9504   bool HasBetterConversion = false;
9505   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9506     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9507     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9508     if (Cand1Bad != Cand2Bad) {
9509       if (Cand1Bad)
9510         return false;
9511       HasBetterConversion = true;
9512     }
9513   }
9514 
9515   if (HasBetterConversion)
9516     return true;
9517 
9518   // C++ [over.match.best]p1:
9519   //   A viable function F1 is defined to be a better function than another
9520   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9521   //   conversion sequence than ICSi(F2), and then...
9522   bool HasWorseConversion = false;
9523   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9524     switch (CompareImplicitConversionSequences(S, Loc,
9525                                                Cand1.Conversions[ArgIdx],
9526                                                Cand2.Conversions[ArgIdx])) {
9527     case ImplicitConversionSequence::Better:
9528       // Cand1 has a better conversion sequence.
9529       HasBetterConversion = true;
9530       break;
9531 
9532     case ImplicitConversionSequence::Worse:
9533       if (Cand1.Function && Cand2.Function &&
9534           Cand1.isReversed() != Cand2.isReversed() &&
9535           haveSameParameterTypes(S.Context, Cand1.Function, Cand2.Function,
9536                                  NumArgs)) {
9537         // Work around large-scale breakage caused by considering reversed
9538         // forms of operator== in C++20:
9539         //
9540         // When comparing a function against a reversed function with the same
9541         // parameter types, if we have a better conversion for one argument and
9542         // a worse conversion for the other, the implicit conversion sequences
9543         // are treated as being equally good.
9544         //
9545         // This prevents a comparison function from being considered ambiguous
9546         // with a reversed form that is written in the same way.
9547         //
9548         // We diagnose this as an extension from CreateOverloadedBinOp.
9549         HasWorseConversion = true;
9550         break;
9551       }
9552 
9553       // Cand1 can't be better than Cand2.
9554       return false;
9555 
9556     case ImplicitConversionSequence::Indistinguishable:
9557       // Do nothing.
9558       break;
9559     }
9560   }
9561 
9562   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9563   //       ICSj(F2), or, if not that,
9564   if (HasBetterConversion && !HasWorseConversion)
9565     return true;
9566 
9567   //   -- the context is an initialization by user-defined conversion
9568   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9569   //      from the return type of F1 to the destination type (i.e.,
9570   //      the type of the entity being initialized) is a better
9571   //      conversion sequence than the standard conversion sequence
9572   //      from the return type of F2 to the destination type.
9573   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9574       Cand1.Function && Cand2.Function &&
9575       isa<CXXConversionDecl>(Cand1.Function) &&
9576       isa<CXXConversionDecl>(Cand2.Function)) {
9577     // First check whether we prefer one of the conversion functions over the
9578     // other. This only distinguishes the results in non-standard, extension
9579     // cases such as the conversion from a lambda closure type to a function
9580     // pointer or block.
9581     ImplicitConversionSequence::CompareKind Result =
9582         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9583     if (Result == ImplicitConversionSequence::Indistinguishable)
9584       Result = CompareStandardConversionSequences(S, Loc,
9585                                                   Cand1.FinalConversion,
9586                                                   Cand2.FinalConversion);
9587 
9588     if (Result != ImplicitConversionSequence::Indistinguishable)
9589       return Result == ImplicitConversionSequence::Better;
9590 
9591     // FIXME: Compare kind of reference binding if conversion functions
9592     // convert to a reference type used in direct reference binding, per
9593     // C++14 [over.match.best]p1 section 2 bullet 3.
9594   }
9595 
9596   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9597   // as combined with the resolution to CWG issue 243.
9598   //
9599   // When the context is initialization by constructor ([over.match.ctor] or
9600   // either phase of [over.match.list]), a constructor is preferred over
9601   // a conversion function.
9602   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9603       Cand1.Function && Cand2.Function &&
9604       isa<CXXConstructorDecl>(Cand1.Function) !=
9605           isa<CXXConstructorDecl>(Cand2.Function))
9606     return isa<CXXConstructorDecl>(Cand1.Function);
9607 
9608   //    -- F1 is a non-template function and F2 is a function template
9609   //       specialization, or, if not that,
9610   bool Cand1IsSpecialization = Cand1.Function &&
9611                                Cand1.Function->getPrimaryTemplate();
9612   bool Cand2IsSpecialization = Cand2.Function &&
9613                                Cand2.Function->getPrimaryTemplate();
9614   if (Cand1IsSpecialization != Cand2IsSpecialization)
9615     return Cand2IsSpecialization;
9616 
9617   //   -- F1 and F2 are function template specializations, and the function
9618   //      template for F1 is more specialized than the template for F2
9619   //      according to the partial ordering rules described in 14.5.5.2, or,
9620   //      if not that,
9621   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9622     if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
9623             Cand1.Function->getPrimaryTemplate(),
9624             Cand2.Function->getPrimaryTemplate(), Loc,
9625             isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
9626                                                    : TPOC_Call,
9627             Cand1.ExplicitCallArguments, Cand2.ExplicitCallArguments,
9628             Cand1.isReversed() ^ Cand2.isReversed()))
9629       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9630   }
9631 
9632   //   -— F1 and F2 are non-template functions with the same
9633   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9634   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9635       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9636       Cand2.Function->hasPrototype()) {
9637     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9638     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9639     if (PT1->getNumParams() == PT2->getNumParams() &&
9640         PT1->isVariadic() == PT2->isVariadic() &&
9641         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9642       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9643       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9644       if (RC1 && RC2) {
9645         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9646         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9647                                      {RC2}, AtLeastAsConstrained1) ||
9648             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9649                                      {RC1}, AtLeastAsConstrained2))
9650           return false;
9651         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9652           return AtLeastAsConstrained1;
9653       } else if (RC1 || RC2) {
9654         return RC1 != nullptr;
9655       }
9656     }
9657   }
9658 
9659   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9660   //      class B of D, and for all arguments the corresponding parameters of
9661   //      F1 and F2 have the same type.
9662   // FIXME: Implement the "all parameters have the same type" check.
9663   bool Cand1IsInherited =
9664       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9665   bool Cand2IsInherited =
9666       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9667   if (Cand1IsInherited != Cand2IsInherited)
9668     return Cand2IsInherited;
9669   else if (Cand1IsInherited) {
9670     assert(Cand2IsInherited);
9671     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9672     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9673     if (Cand1Class->isDerivedFrom(Cand2Class))
9674       return true;
9675     if (Cand2Class->isDerivedFrom(Cand1Class))
9676       return false;
9677     // Inherited from sibling base classes: still ambiguous.
9678   }
9679 
9680   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9681   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9682   //      with reversed order of parameters and F1 is not
9683   //
9684   // We rank reversed + different operator as worse than just reversed, but
9685   // that comparison can never happen, because we only consider reversing for
9686   // the maximally-rewritten operator (== or <=>).
9687   if (Cand1.RewriteKind != Cand2.RewriteKind)
9688     return Cand1.RewriteKind < Cand2.RewriteKind;
9689 
9690   // Check C++17 tie-breakers for deduction guides.
9691   {
9692     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9693     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9694     if (Guide1 && Guide2) {
9695       //  -- F1 is generated from a deduction-guide and F2 is not
9696       if (Guide1->isImplicit() != Guide2->isImplicit())
9697         return Guide2->isImplicit();
9698 
9699       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9700       if (Guide1->isCopyDeductionCandidate())
9701         return true;
9702     }
9703   }
9704 
9705   // Check for enable_if value-based overload resolution.
9706   if (Cand1.Function && Cand2.Function) {
9707     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9708     if (Cmp != Comparison::Equal)
9709       return Cmp == Comparison::Better;
9710   }
9711 
9712   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9713     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9714     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9715            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9716   }
9717 
9718   bool HasPS1 = Cand1.Function != nullptr &&
9719                 functionHasPassObjectSizeParams(Cand1.Function);
9720   bool HasPS2 = Cand2.Function != nullptr &&
9721                 functionHasPassObjectSizeParams(Cand2.Function);
9722   if (HasPS1 != HasPS2 && HasPS1)
9723     return true;
9724 
9725   return isBetterMultiversionCandidate(Cand1, Cand2);
9726 }
9727 
9728 /// Determine whether two declarations are "equivalent" for the purposes of
9729 /// name lookup and overload resolution. This applies when the same internal/no
9730 /// linkage entity is defined by two modules (probably by textually including
9731 /// the same header). In such a case, we don't consider the declarations to
9732 /// declare the same entity, but we also don't want lookups with both
9733 /// declarations visible to be ambiguous in some cases (this happens when using
9734 /// a modularized libstdc++).
9735 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9736                                                   const NamedDecl *B) {
9737   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9738   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9739   if (!VA || !VB)
9740     return false;
9741 
9742   // The declarations must be declaring the same name as an internal linkage
9743   // entity in different modules.
9744   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9745           VB->getDeclContext()->getRedeclContext()) ||
9746       getOwningModule(VA) == getOwningModule(VB) ||
9747       VA->isExternallyVisible() || VB->isExternallyVisible())
9748     return false;
9749 
9750   // Check that the declarations appear to be equivalent.
9751   //
9752   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9753   // For constants and functions, we should check the initializer or body is
9754   // the same. For non-constant variables, we shouldn't allow it at all.
9755   if (Context.hasSameType(VA->getType(), VB->getType()))
9756     return true;
9757 
9758   // Enum constants within unnamed enumerations will have different types, but
9759   // may still be similar enough to be interchangeable for our purposes.
9760   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9761     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9762       // Only handle anonymous enums. If the enumerations were named and
9763       // equivalent, they would have been merged to the same type.
9764       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9765       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9766       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9767           !Context.hasSameType(EnumA->getIntegerType(),
9768                                EnumB->getIntegerType()))
9769         return false;
9770       // Allow this only if the value is the same for both enumerators.
9771       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9772     }
9773   }
9774 
9775   // Nothing else is sufficiently similar.
9776   return false;
9777 }
9778 
9779 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9780     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9781   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9782 
9783   Module *M = getOwningModule(D);
9784   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9785       << !M << (M ? M->getFullModuleName() : "");
9786 
9787   for (auto *E : Equiv) {
9788     Module *M = getOwningModule(E);
9789     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9790         << !M << (M ? M->getFullModuleName() : "");
9791   }
9792 }
9793 
9794 /// Computes the best viable function (C++ 13.3.3)
9795 /// within an overload candidate set.
9796 ///
9797 /// \param Loc The location of the function name (or operator symbol) for
9798 /// which overload resolution occurs.
9799 ///
9800 /// \param Best If overload resolution was successful or found a deleted
9801 /// function, \p Best points to the candidate function found.
9802 ///
9803 /// \returns The result of overload resolution.
9804 OverloadingResult
9805 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9806                                          iterator &Best) {
9807   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9808   std::transform(begin(), end(), std::back_inserter(Candidates),
9809                  [](OverloadCandidate &Cand) { return &Cand; });
9810 
9811   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9812   // are accepted by both clang and NVCC. However, during a particular
9813   // compilation mode only one call variant is viable. We need to
9814   // exclude non-viable overload candidates from consideration based
9815   // only on their host/device attributes. Specifically, if one
9816   // candidate call is WrongSide and the other is SameSide, we ignore
9817   // the WrongSide candidate.
9818   if (S.getLangOpts().CUDA) {
9819     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9820     bool ContainsSameSideCandidate =
9821         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9822           // Check viable function only.
9823           return Cand->Viable && Cand->Function &&
9824                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9825                      Sema::CFP_SameSide;
9826         });
9827     if (ContainsSameSideCandidate) {
9828       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9829         // Check viable function only to avoid unnecessary data copying/moving.
9830         return Cand->Viable && Cand->Function &&
9831                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9832                    Sema::CFP_WrongSide;
9833       };
9834       llvm::erase_if(Candidates, IsWrongSideCandidate);
9835     }
9836   }
9837 
9838   // Find the best viable function.
9839   Best = end();
9840   for (auto *Cand : Candidates) {
9841     Cand->Best = false;
9842     if (Cand->Viable)
9843       if (Best == end() ||
9844           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9845         Best = Cand;
9846   }
9847 
9848   // If we didn't find any viable functions, abort.
9849   if (Best == end())
9850     return OR_No_Viable_Function;
9851 
9852   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9853 
9854   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9855   PendingBest.push_back(&*Best);
9856   Best->Best = true;
9857 
9858   // Make sure that this function is better than every other viable
9859   // function. If not, we have an ambiguity.
9860   while (!PendingBest.empty()) {
9861     auto *Curr = PendingBest.pop_back_val();
9862     for (auto *Cand : Candidates) {
9863       if (Cand->Viable && !Cand->Best &&
9864           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9865         PendingBest.push_back(Cand);
9866         Cand->Best = true;
9867 
9868         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9869                                                      Curr->Function))
9870           EquivalentCands.push_back(Cand->Function);
9871         else
9872           Best = end();
9873       }
9874     }
9875   }
9876 
9877   // If we found more than one best candidate, this is ambiguous.
9878   if (Best == end())
9879     return OR_Ambiguous;
9880 
9881   // Best is the best viable function.
9882   if (Best->Function && Best->Function->isDeleted())
9883     return OR_Deleted;
9884 
9885   if (!EquivalentCands.empty())
9886     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9887                                                     EquivalentCands);
9888 
9889   return OR_Success;
9890 }
9891 
9892 namespace {
9893 
9894 enum OverloadCandidateKind {
9895   oc_function,
9896   oc_method,
9897   oc_reversed_binary_operator,
9898   oc_constructor,
9899   oc_implicit_default_constructor,
9900   oc_implicit_copy_constructor,
9901   oc_implicit_move_constructor,
9902   oc_implicit_copy_assignment,
9903   oc_implicit_move_assignment,
9904   oc_implicit_equality_comparison,
9905   oc_inherited_constructor
9906 };
9907 
9908 enum OverloadCandidateSelect {
9909   ocs_non_template,
9910   ocs_template,
9911   ocs_described_template,
9912 };
9913 
9914 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9915 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9916                           OverloadCandidateRewriteKind CRK,
9917                           std::string &Description) {
9918 
9919   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9920   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9921     isTemplate = true;
9922     Description = S.getTemplateArgumentBindingsText(
9923         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9924   }
9925 
9926   OverloadCandidateSelect Select = [&]() {
9927     if (!Description.empty())
9928       return ocs_described_template;
9929     return isTemplate ? ocs_template : ocs_non_template;
9930   }();
9931 
9932   OverloadCandidateKind Kind = [&]() {
9933     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9934       return oc_implicit_equality_comparison;
9935 
9936     if (CRK & CRK_Reversed)
9937       return oc_reversed_binary_operator;
9938 
9939     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9940       if (!Ctor->isImplicit()) {
9941         if (isa<ConstructorUsingShadowDecl>(Found))
9942           return oc_inherited_constructor;
9943         else
9944           return oc_constructor;
9945       }
9946 
9947       if (Ctor->isDefaultConstructor())
9948         return oc_implicit_default_constructor;
9949 
9950       if (Ctor->isMoveConstructor())
9951         return oc_implicit_move_constructor;
9952 
9953       assert(Ctor->isCopyConstructor() &&
9954              "unexpected sort of implicit constructor");
9955       return oc_implicit_copy_constructor;
9956     }
9957 
9958     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9959       // This actually gets spelled 'candidate function' for now, but
9960       // it doesn't hurt to split it out.
9961       if (!Meth->isImplicit())
9962         return oc_method;
9963 
9964       if (Meth->isMoveAssignmentOperator())
9965         return oc_implicit_move_assignment;
9966 
9967       if (Meth->isCopyAssignmentOperator())
9968         return oc_implicit_copy_assignment;
9969 
9970       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9971       return oc_method;
9972     }
9973 
9974     return oc_function;
9975   }();
9976 
9977   return std::make_pair(Kind, Select);
9978 }
9979 
9980 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9981   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9982   // set.
9983   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9984     S.Diag(FoundDecl->getLocation(),
9985            diag::note_ovl_candidate_inherited_constructor)
9986       << Shadow->getNominatedBaseClass();
9987 }
9988 
9989 } // end anonymous namespace
9990 
9991 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9992                                     const FunctionDecl *FD) {
9993   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9994     bool AlwaysTrue;
9995     if (EnableIf->getCond()->isValueDependent() ||
9996         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9997       return false;
9998     if (!AlwaysTrue)
9999       return false;
10000   }
10001   return true;
10002 }
10003 
10004 /// Returns true if we can take the address of the function.
10005 ///
10006 /// \param Complain - If true, we'll emit a diagnostic
10007 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10008 ///   we in overload resolution?
10009 /// \param Loc - The location of the statement we're complaining about. Ignored
10010 ///   if we're not complaining, or if we're in overload resolution.
10011 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
10012                                               bool Complain,
10013                                               bool InOverloadResolution,
10014                                               SourceLocation Loc) {
10015   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
10016     if (Complain) {
10017       if (InOverloadResolution)
10018         S.Diag(FD->getBeginLoc(),
10019                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
10020       else
10021         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
10022     }
10023     return false;
10024   }
10025 
10026   if (FD->getTrailingRequiresClause()) {
10027     ConstraintSatisfaction Satisfaction;
10028     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
10029       return false;
10030     if (!Satisfaction.IsSatisfied) {
10031       if (Complain) {
10032         if (InOverloadResolution)
10033           S.Diag(FD->getBeginLoc(),
10034                  diag::note_ovl_candidate_unsatisfied_constraints);
10035         else
10036           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
10037               << FD;
10038         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10039       }
10040       return false;
10041     }
10042   }
10043 
10044   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
10045     return P->hasAttr<PassObjectSizeAttr>();
10046   });
10047   if (I == FD->param_end())
10048     return true;
10049 
10050   if (Complain) {
10051     // Add one to ParamNo because it's user-facing
10052     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10053     if (InOverloadResolution)
10054       S.Diag(FD->getLocation(),
10055              diag::note_ovl_candidate_has_pass_object_size_params)
10056           << ParamNo;
10057     else
10058       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10059           << FD << ParamNo;
10060   }
10061   return false;
10062 }
10063 
10064 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10065                                                const FunctionDecl *FD) {
10066   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10067                                            /*InOverloadResolution=*/true,
10068                                            /*Loc=*/SourceLocation());
10069 }
10070 
10071 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10072                                              bool Complain,
10073                                              SourceLocation Loc) {
10074   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10075                                              /*InOverloadResolution=*/false,
10076                                              Loc);
10077 }
10078 
10079 // Notes the location of an overload candidate.
10080 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10081                                  OverloadCandidateRewriteKind RewriteKind,
10082                                  QualType DestType, bool TakingAddress) {
10083   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10084     return;
10085   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10086       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10087     return;
10088 
10089   std::string FnDesc;
10090   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10091       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10092   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10093                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10094                          << Fn << FnDesc;
10095 
10096   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10097   Diag(Fn->getLocation(), PD);
10098   MaybeEmitInheritedConstructorNote(*this, Found);
10099 }
10100 
10101 static void
10102 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10103   // Perhaps the ambiguity was caused by two atomic constraints that are
10104   // 'identical' but not equivalent:
10105   //
10106   // void foo() requires (sizeof(T) > 4) { } // #1
10107   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10108   //
10109   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10110   // #2 to subsume #1, but these constraint are not considered equivalent
10111   // according to the subsumption rules because they are not the same
10112   // source-level construct. This behavior is quite confusing and we should try
10113   // to help the user figure out what happened.
10114 
10115   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10116   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10117   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10118     if (!I->Function)
10119       continue;
10120     SmallVector<const Expr *, 3> AC;
10121     if (auto *Template = I->Function->getPrimaryTemplate())
10122       Template->getAssociatedConstraints(AC);
10123     else
10124       I->Function->getAssociatedConstraints(AC);
10125     if (AC.empty())
10126       continue;
10127     if (FirstCand == nullptr) {
10128       FirstCand = I->Function;
10129       FirstAC = AC;
10130     } else if (SecondCand == nullptr) {
10131       SecondCand = I->Function;
10132       SecondAC = AC;
10133     } else {
10134       // We have more than one pair of constrained functions - this check is
10135       // expensive and we'd rather not try to diagnose it.
10136       return;
10137     }
10138   }
10139   if (!SecondCand)
10140     return;
10141   // The diagnostic can only happen if there are associated constraints on
10142   // both sides (there needs to be some identical atomic constraint).
10143   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10144                                                       SecondCand, SecondAC))
10145     // Just show the user one diagnostic, they'll probably figure it out
10146     // from here.
10147     return;
10148 }
10149 
10150 // Notes the location of all overload candidates designated through
10151 // OverloadedExpr
10152 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10153                                      bool TakingAddress) {
10154   assert(OverloadedExpr->getType() == Context.OverloadTy);
10155 
10156   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10157   OverloadExpr *OvlExpr = Ovl.Expression;
10158 
10159   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10160                             IEnd = OvlExpr->decls_end();
10161        I != IEnd; ++I) {
10162     if (FunctionTemplateDecl *FunTmpl =
10163                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10164       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10165                             TakingAddress);
10166     } else if (FunctionDecl *Fun
10167                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10168       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10169     }
10170   }
10171 }
10172 
10173 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10174 /// "lead" diagnostic; it will be given two arguments, the source and
10175 /// target types of the conversion.
10176 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10177                                  Sema &S,
10178                                  SourceLocation CaretLoc,
10179                                  const PartialDiagnostic &PDiag) const {
10180   S.Diag(CaretLoc, PDiag)
10181     << Ambiguous.getFromType() << Ambiguous.getToType();
10182   // FIXME: The note limiting machinery is borrowed from
10183   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10184   // refactoring here.
10185   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10186   unsigned CandsShown = 0;
10187   AmbiguousConversionSequence::const_iterator I, E;
10188   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10189     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10190       break;
10191     ++CandsShown;
10192     S.NoteOverloadCandidate(I->first, I->second);
10193   }
10194   if (I != E)
10195     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10196 }
10197 
10198 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10199                                   unsigned I, bool TakingCandidateAddress) {
10200   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10201   assert(Conv.isBad());
10202   assert(Cand->Function && "for now, candidate must be a function");
10203   FunctionDecl *Fn = Cand->Function;
10204 
10205   // There's a conversion slot for the object argument if this is a
10206   // non-constructor method.  Note that 'I' corresponds the
10207   // conversion-slot index.
10208   bool isObjectArgument = false;
10209   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10210     if (I == 0)
10211       isObjectArgument = true;
10212     else
10213       I--;
10214   }
10215 
10216   std::string FnDesc;
10217   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10218       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10219                                 FnDesc);
10220 
10221   Expr *FromExpr = Conv.Bad.FromExpr;
10222   QualType FromTy = Conv.Bad.getFromType();
10223   QualType ToTy = Conv.Bad.getToType();
10224 
10225   if (FromTy == S.Context.OverloadTy) {
10226     assert(FromExpr && "overload set argument came from implicit argument?");
10227     Expr *E = FromExpr->IgnoreParens();
10228     if (isa<UnaryOperator>(E))
10229       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10230     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10231 
10232     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10233         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10234         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10235         << Name << I + 1;
10236     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10237     return;
10238   }
10239 
10240   // Do some hand-waving analysis to see if the non-viability is due
10241   // to a qualifier mismatch.
10242   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10243   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10244   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10245     CToTy = RT->getPointeeType();
10246   else {
10247     // TODO: detect and diagnose the full richness of const mismatches.
10248     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10249       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10250         CFromTy = FromPT->getPointeeType();
10251         CToTy = ToPT->getPointeeType();
10252       }
10253   }
10254 
10255   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10256       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10257     Qualifiers FromQs = CFromTy.getQualifiers();
10258     Qualifiers ToQs = CToTy.getQualifiers();
10259 
10260     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10261       if (isObjectArgument)
10262         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10263             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10264             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10265             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10266       else
10267         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10268             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10269             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10270             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10271             << ToTy->isReferenceType() << I + 1;
10272       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10273       return;
10274     }
10275 
10276     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10277       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10278           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10279           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10280           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10281           << (unsigned)isObjectArgument << I + 1;
10282       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10283       return;
10284     }
10285 
10286     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10287       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10288           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10289           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10290           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10291           << (unsigned)isObjectArgument << I + 1;
10292       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10293       return;
10294     }
10295 
10296     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10297       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10298           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10299           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10300           << FromQs.hasUnaligned() << I + 1;
10301       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10302       return;
10303     }
10304 
10305     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10306     assert(CVR && "unexpected qualifiers mismatch");
10307 
10308     if (isObjectArgument) {
10309       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10310           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10311           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10312           << (CVR - 1);
10313     } else {
10314       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10315           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10316           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10317           << (CVR - 1) << I + 1;
10318     }
10319     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10320     return;
10321   }
10322 
10323   // Special diagnostic for failure to convert an initializer list, since
10324   // telling the user that it has type void is not useful.
10325   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10326     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10327         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10328         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10329         << ToTy << (unsigned)isObjectArgument << I + 1;
10330     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10331     return;
10332   }
10333 
10334   // Diagnose references or pointers to incomplete types differently,
10335   // since it's far from impossible that the incompleteness triggered
10336   // the failure.
10337   QualType TempFromTy = FromTy.getNonReferenceType();
10338   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10339     TempFromTy = PTy->getPointeeType();
10340   if (TempFromTy->isIncompleteType()) {
10341     // Emit the generic diagnostic and, optionally, add the hints to it.
10342     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10343         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10344         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10345         << ToTy << (unsigned)isObjectArgument << I + 1
10346         << (unsigned)(Cand->Fix.Kind);
10347 
10348     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10349     return;
10350   }
10351 
10352   // Diagnose base -> derived pointer conversions.
10353   unsigned BaseToDerivedConversion = 0;
10354   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10355     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10356       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10357                                                FromPtrTy->getPointeeType()) &&
10358           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10359           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10360           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10361                           FromPtrTy->getPointeeType()))
10362         BaseToDerivedConversion = 1;
10363     }
10364   } else if (const ObjCObjectPointerType *FromPtrTy
10365                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10366     if (const ObjCObjectPointerType *ToPtrTy
10367                                         = ToTy->getAs<ObjCObjectPointerType>())
10368       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10369         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10370           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10371                                                 FromPtrTy->getPointeeType()) &&
10372               FromIface->isSuperClassOf(ToIface))
10373             BaseToDerivedConversion = 2;
10374   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10375     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10376         !FromTy->isIncompleteType() &&
10377         !ToRefTy->getPointeeType()->isIncompleteType() &&
10378         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10379       BaseToDerivedConversion = 3;
10380     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10381                ToTy.getNonReferenceType().getCanonicalType() ==
10382                FromTy.getNonReferenceType().getCanonicalType()) {
10383       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10384           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10385           << (unsigned)isObjectArgument << I + 1
10386           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10387       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10388       return;
10389     }
10390   }
10391 
10392   if (BaseToDerivedConversion) {
10393     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10394         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10395         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10396         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10397     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10398     return;
10399   }
10400 
10401   if (isa<ObjCObjectPointerType>(CFromTy) &&
10402       isa<PointerType>(CToTy)) {
10403       Qualifiers FromQs = CFromTy.getQualifiers();
10404       Qualifiers ToQs = CToTy.getQualifiers();
10405       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10406         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10407             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10408             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10409             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10410         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10411         return;
10412       }
10413   }
10414 
10415   if (TakingCandidateAddress &&
10416       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10417     return;
10418 
10419   // Emit the generic diagnostic and, optionally, add the hints to it.
10420   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10421   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10422         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10423         << ToTy << (unsigned)isObjectArgument << I + 1
10424         << (unsigned)(Cand->Fix.Kind);
10425 
10426   // If we can fix the conversion, suggest the FixIts.
10427   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10428        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10429     FDiag << *HI;
10430   S.Diag(Fn->getLocation(), FDiag);
10431 
10432   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10433 }
10434 
10435 /// Additional arity mismatch diagnosis specific to a function overload
10436 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10437 /// over a candidate in any candidate set.
10438 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10439                                unsigned NumArgs) {
10440   FunctionDecl *Fn = Cand->Function;
10441   unsigned MinParams = Fn->getMinRequiredArguments();
10442 
10443   // With invalid overloaded operators, it's possible that we think we
10444   // have an arity mismatch when in fact it looks like we have the
10445   // right number of arguments, because only overloaded operators have
10446   // the weird behavior of overloading member and non-member functions.
10447   // Just don't report anything.
10448   if (Fn->isInvalidDecl() &&
10449       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10450     return true;
10451 
10452   if (NumArgs < MinParams) {
10453     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10454            (Cand->FailureKind == ovl_fail_bad_deduction &&
10455             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10456   } else {
10457     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10458            (Cand->FailureKind == ovl_fail_bad_deduction &&
10459             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10460   }
10461 
10462   return false;
10463 }
10464 
10465 /// General arity mismatch diagnosis over a candidate in a candidate set.
10466 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10467                                   unsigned NumFormalArgs) {
10468   assert(isa<FunctionDecl>(D) &&
10469       "The templated declaration should at least be a function"
10470       " when diagnosing bad template argument deduction due to too many"
10471       " or too few arguments");
10472 
10473   FunctionDecl *Fn = cast<FunctionDecl>(D);
10474 
10475   // TODO: treat calls to a missing default constructor as a special case
10476   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10477   unsigned MinParams = Fn->getMinRequiredArguments();
10478 
10479   // at least / at most / exactly
10480   unsigned mode, modeCount;
10481   if (NumFormalArgs < MinParams) {
10482     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10483         FnTy->isTemplateVariadic())
10484       mode = 0; // "at least"
10485     else
10486       mode = 2; // "exactly"
10487     modeCount = MinParams;
10488   } else {
10489     if (MinParams != FnTy->getNumParams())
10490       mode = 1; // "at most"
10491     else
10492       mode = 2; // "exactly"
10493     modeCount = FnTy->getNumParams();
10494   }
10495 
10496   std::string Description;
10497   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10498       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10499 
10500   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10501     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10502         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10503         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10504   else
10505     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10506         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10507         << Description << mode << modeCount << NumFormalArgs;
10508 
10509   MaybeEmitInheritedConstructorNote(S, Found);
10510 }
10511 
10512 /// Arity mismatch diagnosis specific to a function overload candidate.
10513 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10514                                   unsigned NumFormalArgs) {
10515   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10516     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10517 }
10518 
10519 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10520   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10521     return TD;
10522   llvm_unreachable("Unsupported: Getting the described template declaration"
10523                    " for bad deduction diagnosis");
10524 }
10525 
10526 /// Diagnose a failed template-argument deduction.
10527 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10528                                  DeductionFailureInfo &DeductionFailure,
10529                                  unsigned NumArgs,
10530                                  bool TakingCandidateAddress) {
10531   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10532   NamedDecl *ParamD;
10533   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10534   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10535   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10536   switch (DeductionFailure.Result) {
10537   case Sema::TDK_Success:
10538     llvm_unreachable("TDK_success while diagnosing bad deduction");
10539 
10540   case Sema::TDK_Incomplete: {
10541     assert(ParamD && "no parameter found for incomplete deduction result");
10542     S.Diag(Templated->getLocation(),
10543            diag::note_ovl_candidate_incomplete_deduction)
10544         << ParamD->getDeclName();
10545     MaybeEmitInheritedConstructorNote(S, Found);
10546     return;
10547   }
10548 
10549   case Sema::TDK_IncompletePack: {
10550     assert(ParamD && "no parameter found for incomplete deduction result");
10551     S.Diag(Templated->getLocation(),
10552            diag::note_ovl_candidate_incomplete_deduction_pack)
10553         << ParamD->getDeclName()
10554         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10555         << *DeductionFailure.getFirstArg();
10556     MaybeEmitInheritedConstructorNote(S, Found);
10557     return;
10558   }
10559 
10560   case Sema::TDK_Underqualified: {
10561     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10562     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10563 
10564     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10565 
10566     // Param will have been canonicalized, but it should just be a
10567     // qualified version of ParamD, so move the qualifiers to that.
10568     QualifierCollector Qs;
10569     Qs.strip(Param);
10570     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10571     assert(S.Context.hasSameType(Param, NonCanonParam));
10572 
10573     // Arg has also been canonicalized, but there's nothing we can do
10574     // about that.  It also doesn't matter as much, because it won't
10575     // have any template parameters in it (because deduction isn't
10576     // done on dependent types).
10577     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10578 
10579     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10580         << ParamD->getDeclName() << Arg << NonCanonParam;
10581     MaybeEmitInheritedConstructorNote(S, Found);
10582     return;
10583   }
10584 
10585   case Sema::TDK_Inconsistent: {
10586     assert(ParamD && "no parameter found for inconsistent deduction result");
10587     int which = 0;
10588     if (isa<TemplateTypeParmDecl>(ParamD))
10589       which = 0;
10590     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10591       // Deduction might have failed because we deduced arguments of two
10592       // different types for a non-type template parameter.
10593       // FIXME: Use a different TDK value for this.
10594       QualType T1 =
10595           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10596       QualType T2 =
10597           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10598       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10599         S.Diag(Templated->getLocation(),
10600                diag::note_ovl_candidate_inconsistent_deduction_types)
10601           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10602           << *DeductionFailure.getSecondArg() << T2;
10603         MaybeEmitInheritedConstructorNote(S, Found);
10604         return;
10605       }
10606 
10607       which = 1;
10608     } else {
10609       which = 2;
10610     }
10611 
10612     // Tweak the diagnostic if the problem is that we deduced packs of
10613     // different arities. We'll print the actual packs anyway in case that
10614     // includes additional useful information.
10615     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10616         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10617         DeductionFailure.getFirstArg()->pack_size() !=
10618             DeductionFailure.getSecondArg()->pack_size()) {
10619       which = 3;
10620     }
10621 
10622     S.Diag(Templated->getLocation(),
10623            diag::note_ovl_candidate_inconsistent_deduction)
10624         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10625         << *DeductionFailure.getSecondArg();
10626     MaybeEmitInheritedConstructorNote(S, Found);
10627     return;
10628   }
10629 
10630   case Sema::TDK_InvalidExplicitArguments:
10631     assert(ParamD && "no parameter found for invalid explicit arguments");
10632     if (ParamD->getDeclName())
10633       S.Diag(Templated->getLocation(),
10634              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10635           << ParamD->getDeclName();
10636     else {
10637       int index = 0;
10638       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10639         index = TTP->getIndex();
10640       else if (NonTypeTemplateParmDecl *NTTP
10641                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10642         index = NTTP->getIndex();
10643       else
10644         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10645       S.Diag(Templated->getLocation(),
10646              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10647           << (index + 1);
10648     }
10649     MaybeEmitInheritedConstructorNote(S, Found);
10650     return;
10651 
10652   case Sema::TDK_ConstraintsNotSatisfied: {
10653     // Format the template argument list into the argument string.
10654     SmallString<128> TemplateArgString;
10655     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10656     TemplateArgString = " ";
10657     TemplateArgString += S.getTemplateArgumentBindingsText(
10658         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10659     if (TemplateArgString.size() == 1)
10660       TemplateArgString.clear();
10661     S.Diag(Templated->getLocation(),
10662            diag::note_ovl_candidate_unsatisfied_constraints)
10663         << TemplateArgString;
10664 
10665     S.DiagnoseUnsatisfiedConstraint(
10666         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10667     return;
10668   }
10669   case Sema::TDK_TooManyArguments:
10670   case Sema::TDK_TooFewArguments:
10671     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10672     return;
10673 
10674   case Sema::TDK_InstantiationDepth:
10675     S.Diag(Templated->getLocation(),
10676            diag::note_ovl_candidate_instantiation_depth);
10677     MaybeEmitInheritedConstructorNote(S, Found);
10678     return;
10679 
10680   case Sema::TDK_SubstitutionFailure: {
10681     // Format the template argument list into the argument string.
10682     SmallString<128> TemplateArgString;
10683     if (TemplateArgumentList *Args =
10684             DeductionFailure.getTemplateArgumentList()) {
10685       TemplateArgString = " ";
10686       TemplateArgString += S.getTemplateArgumentBindingsText(
10687           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10688       if (TemplateArgString.size() == 1)
10689         TemplateArgString.clear();
10690     }
10691 
10692     // If this candidate was disabled by enable_if, say so.
10693     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10694     if (PDiag && PDiag->second.getDiagID() ==
10695           diag::err_typename_nested_not_found_enable_if) {
10696       // FIXME: Use the source range of the condition, and the fully-qualified
10697       //        name of the enable_if template. These are both present in PDiag.
10698       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10699         << "'enable_if'" << TemplateArgString;
10700       return;
10701     }
10702 
10703     // We found a specific requirement that disabled the enable_if.
10704     if (PDiag && PDiag->second.getDiagID() ==
10705         diag::err_typename_nested_not_found_requirement) {
10706       S.Diag(Templated->getLocation(),
10707              diag::note_ovl_candidate_disabled_by_requirement)
10708         << PDiag->second.getStringArg(0) << TemplateArgString;
10709       return;
10710     }
10711 
10712     // Format the SFINAE diagnostic into the argument string.
10713     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10714     //        formatted message in another diagnostic.
10715     SmallString<128> SFINAEArgString;
10716     SourceRange R;
10717     if (PDiag) {
10718       SFINAEArgString = ": ";
10719       R = SourceRange(PDiag->first, PDiag->first);
10720       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10721     }
10722 
10723     S.Diag(Templated->getLocation(),
10724            diag::note_ovl_candidate_substitution_failure)
10725         << TemplateArgString << SFINAEArgString << R;
10726     MaybeEmitInheritedConstructorNote(S, Found);
10727     return;
10728   }
10729 
10730   case Sema::TDK_DeducedMismatch:
10731   case Sema::TDK_DeducedMismatchNested: {
10732     // Format the template argument list into the argument string.
10733     SmallString<128> TemplateArgString;
10734     if (TemplateArgumentList *Args =
10735             DeductionFailure.getTemplateArgumentList()) {
10736       TemplateArgString = " ";
10737       TemplateArgString += S.getTemplateArgumentBindingsText(
10738           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10739       if (TemplateArgString.size() == 1)
10740         TemplateArgString.clear();
10741     }
10742 
10743     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10744         << (*DeductionFailure.getCallArgIndex() + 1)
10745         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10746         << TemplateArgString
10747         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10748     break;
10749   }
10750 
10751   case Sema::TDK_NonDeducedMismatch: {
10752     // FIXME: Provide a source location to indicate what we couldn't match.
10753     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10754     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10755     if (FirstTA.getKind() == TemplateArgument::Template &&
10756         SecondTA.getKind() == TemplateArgument::Template) {
10757       TemplateName FirstTN = FirstTA.getAsTemplate();
10758       TemplateName SecondTN = SecondTA.getAsTemplate();
10759       if (FirstTN.getKind() == TemplateName::Template &&
10760           SecondTN.getKind() == TemplateName::Template) {
10761         if (FirstTN.getAsTemplateDecl()->getName() ==
10762             SecondTN.getAsTemplateDecl()->getName()) {
10763           // FIXME: This fixes a bad diagnostic where both templates are named
10764           // the same.  This particular case is a bit difficult since:
10765           // 1) It is passed as a string to the diagnostic printer.
10766           // 2) The diagnostic printer only attempts to find a better
10767           //    name for types, not decls.
10768           // Ideally, this should folded into the diagnostic printer.
10769           S.Diag(Templated->getLocation(),
10770                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10771               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10772           return;
10773         }
10774       }
10775     }
10776 
10777     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10778         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10779       return;
10780 
10781     // FIXME: For generic lambda parameters, check if the function is a lambda
10782     // call operator, and if so, emit a prettier and more informative
10783     // diagnostic that mentions 'auto' and lambda in addition to
10784     // (or instead of?) the canonical template type parameters.
10785     S.Diag(Templated->getLocation(),
10786            diag::note_ovl_candidate_non_deduced_mismatch)
10787         << FirstTA << SecondTA;
10788     return;
10789   }
10790   // TODO: diagnose these individually, then kill off
10791   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10792   case Sema::TDK_MiscellaneousDeductionFailure:
10793     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10794     MaybeEmitInheritedConstructorNote(S, Found);
10795     return;
10796   case Sema::TDK_CUDATargetMismatch:
10797     S.Diag(Templated->getLocation(),
10798            diag::note_cuda_ovl_candidate_target_mismatch);
10799     return;
10800   }
10801 }
10802 
10803 /// Diagnose a failed template-argument deduction, for function calls.
10804 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10805                                  unsigned NumArgs,
10806                                  bool TakingCandidateAddress) {
10807   unsigned TDK = Cand->DeductionFailure.Result;
10808   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10809     if (CheckArityMismatch(S, Cand, NumArgs))
10810       return;
10811   }
10812   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10813                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10814 }
10815 
10816 /// CUDA: diagnose an invalid call across targets.
10817 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10818   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10819   FunctionDecl *Callee = Cand->Function;
10820 
10821   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10822                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10823 
10824   std::string FnDesc;
10825   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10826       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10827                                 Cand->getRewriteKind(), FnDesc);
10828 
10829   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10830       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10831       << FnDesc /* Ignored */
10832       << CalleeTarget << CallerTarget;
10833 
10834   // This could be an implicit constructor for which we could not infer the
10835   // target due to a collsion. Diagnose that case.
10836   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10837   if (Meth != nullptr && Meth->isImplicit()) {
10838     CXXRecordDecl *ParentClass = Meth->getParent();
10839     Sema::CXXSpecialMember CSM;
10840 
10841     switch (FnKindPair.first) {
10842     default:
10843       return;
10844     case oc_implicit_default_constructor:
10845       CSM = Sema::CXXDefaultConstructor;
10846       break;
10847     case oc_implicit_copy_constructor:
10848       CSM = Sema::CXXCopyConstructor;
10849       break;
10850     case oc_implicit_move_constructor:
10851       CSM = Sema::CXXMoveConstructor;
10852       break;
10853     case oc_implicit_copy_assignment:
10854       CSM = Sema::CXXCopyAssignment;
10855       break;
10856     case oc_implicit_move_assignment:
10857       CSM = Sema::CXXMoveAssignment;
10858       break;
10859     };
10860 
10861     bool ConstRHS = false;
10862     if (Meth->getNumParams()) {
10863       if (const ReferenceType *RT =
10864               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10865         ConstRHS = RT->getPointeeType().isConstQualified();
10866       }
10867     }
10868 
10869     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10870                                               /* ConstRHS */ ConstRHS,
10871                                               /* Diagnose */ true);
10872   }
10873 }
10874 
10875 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10876   FunctionDecl *Callee = Cand->Function;
10877   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10878 
10879   S.Diag(Callee->getLocation(),
10880          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10881       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10882 }
10883 
10884 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10885   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10886   assert(ES.isExplicit() && "not an explicit candidate");
10887 
10888   unsigned Kind;
10889   switch (Cand->Function->getDeclKind()) {
10890   case Decl::Kind::CXXConstructor:
10891     Kind = 0;
10892     break;
10893   case Decl::Kind::CXXConversion:
10894     Kind = 1;
10895     break;
10896   case Decl::Kind::CXXDeductionGuide:
10897     Kind = Cand->Function->isImplicit() ? 0 : 2;
10898     break;
10899   default:
10900     llvm_unreachable("invalid Decl");
10901   }
10902 
10903   // Note the location of the first (in-class) declaration; a redeclaration
10904   // (particularly an out-of-class definition) will typically lack the
10905   // 'explicit' specifier.
10906   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10907   FunctionDecl *First = Cand->Function->getFirstDecl();
10908   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10909     First = Pattern->getFirstDecl();
10910 
10911   S.Diag(First->getLocation(),
10912          diag::note_ovl_candidate_explicit)
10913       << Kind << (ES.getExpr() ? 1 : 0)
10914       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10915 }
10916 
10917 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10918   FunctionDecl *Callee = Cand->Function;
10919 
10920   S.Diag(Callee->getLocation(),
10921          diag::note_ovl_candidate_disabled_by_extension)
10922     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10923 }
10924 
10925 /// Generates a 'note' diagnostic for an overload candidate.  We've
10926 /// already generated a primary error at the call site.
10927 ///
10928 /// It really does need to be a single diagnostic with its caret
10929 /// pointed at the candidate declaration.  Yes, this creates some
10930 /// major challenges of technical writing.  Yes, this makes pointing
10931 /// out problems with specific arguments quite awkward.  It's still
10932 /// better than generating twenty screens of text for every failed
10933 /// overload.
10934 ///
10935 /// It would be great to be able to express per-candidate problems
10936 /// more richly for those diagnostic clients that cared, but we'd
10937 /// still have to be just as careful with the default diagnostics.
10938 /// \param CtorDestAS Addr space of object being constructed (for ctor
10939 /// candidates only).
10940 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10941                                   unsigned NumArgs,
10942                                   bool TakingCandidateAddress,
10943                                   LangAS CtorDestAS = LangAS::Default) {
10944   FunctionDecl *Fn = Cand->Function;
10945 
10946   // Note deleted candidates, but only if they're viable.
10947   if (Cand->Viable) {
10948     if (Fn->isDeleted()) {
10949       std::string FnDesc;
10950       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10951           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10952                                     Cand->getRewriteKind(), FnDesc);
10953 
10954       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10955           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10956           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10957       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10958       return;
10959     }
10960 
10961     // We don't really have anything else to say about viable candidates.
10962     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10963     return;
10964   }
10965 
10966   switch (Cand->FailureKind) {
10967   case ovl_fail_too_many_arguments:
10968   case ovl_fail_too_few_arguments:
10969     return DiagnoseArityMismatch(S, Cand, NumArgs);
10970 
10971   case ovl_fail_bad_deduction:
10972     return DiagnoseBadDeduction(S, Cand, NumArgs,
10973                                 TakingCandidateAddress);
10974 
10975   case ovl_fail_illegal_constructor: {
10976     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10977       << (Fn->getPrimaryTemplate() ? 1 : 0);
10978     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10979     return;
10980   }
10981 
10982   case ovl_fail_object_addrspace_mismatch: {
10983     Qualifiers QualsForPrinting;
10984     QualsForPrinting.setAddressSpace(CtorDestAS);
10985     S.Diag(Fn->getLocation(),
10986            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10987         << QualsForPrinting;
10988     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10989     return;
10990   }
10991 
10992   case ovl_fail_trivial_conversion:
10993   case ovl_fail_bad_final_conversion:
10994   case ovl_fail_final_conversion_not_exact:
10995     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10996 
10997   case ovl_fail_bad_conversion: {
10998     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10999     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
11000       if (Cand->Conversions[I].isBad())
11001         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
11002 
11003     // FIXME: this currently happens when we're called from SemaInit
11004     // when user-conversion overload fails.  Figure out how to handle
11005     // those conditions and diagnose them well.
11006     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
11007   }
11008 
11009   case ovl_fail_bad_target:
11010     return DiagnoseBadTarget(S, Cand);
11011 
11012   case ovl_fail_enable_if:
11013     return DiagnoseFailedEnableIfAttr(S, Cand);
11014 
11015   case ovl_fail_explicit:
11016     return DiagnoseFailedExplicitSpec(S, Cand);
11017 
11018   case ovl_fail_ext_disabled:
11019     return DiagnoseOpenCLExtensionDisabled(S, Cand);
11020 
11021   case ovl_fail_inhctor_slice:
11022     // It's generally not interesting to note copy/move constructors here.
11023     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
11024       return;
11025     S.Diag(Fn->getLocation(),
11026            diag::note_ovl_candidate_inherited_constructor_slice)
11027       << (Fn->getPrimaryTemplate() ? 1 : 0)
11028       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
11029     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11030     return;
11031 
11032   case ovl_fail_addr_not_available: {
11033     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
11034     (void)Available;
11035     assert(!Available);
11036     break;
11037   }
11038   case ovl_non_default_multiversion_function:
11039     // Do nothing, these should simply be ignored.
11040     break;
11041 
11042   case ovl_fail_constraints_not_satisfied: {
11043     std::string FnDesc;
11044     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11045         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
11046                                   Cand->getRewriteKind(), FnDesc);
11047 
11048     S.Diag(Fn->getLocation(),
11049            diag::note_ovl_candidate_constraints_not_satisfied)
11050         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11051         << FnDesc /* Ignored */;
11052     ConstraintSatisfaction Satisfaction;
11053     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11054       break;
11055     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11056   }
11057   }
11058 }
11059 
11060 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11061   // Desugar the type of the surrogate down to a function type,
11062   // retaining as many typedefs as possible while still showing
11063   // the function type (and, therefore, its parameter types).
11064   QualType FnType = Cand->Surrogate->getConversionType();
11065   bool isLValueReference = false;
11066   bool isRValueReference = false;
11067   bool isPointer = false;
11068   if (const LValueReferenceType *FnTypeRef =
11069         FnType->getAs<LValueReferenceType>()) {
11070     FnType = FnTypeRef->getPointeeType();
11071     isLValueReference = true;
11072   } else if (const RValueReferenceType *FnTypeRef =
11073                FnType->getAs<RValueReferenceType>()) {
11074     FnType = FnTypeRef->getPointeeType();
11075     isRValueReference = true;
11076   }
11077   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11078     FnType = FnTypePtr->getPointeeType();
11079     isPointer = true;
11080   }
11081   // Desugar down to a function type.
11082   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11083   // Reconstruct the pointer/reference as appropriate.
11084   if (isPointer) FnType = S.Context.getPointerType(FnType);
11085   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11086   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11087 
11088   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11089     << FnType;
11090 }
11091 
11092 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11093                                          SourceLocation OpLoc,
11094                                          OverloadCandidate *Cand) {
11095   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11096   std::string TypeStr("operator");
11097   TypeStr += Opc;
11098   TypeStr += "(";
11099   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11100   if (Cand->Conversions.size() == 1) {
11101     TypeStr += ")";
11102     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11103   } else {
11104     TypeStr += ", ";
11105     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11106     TypeStr += ")";
11107     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11108   }
11109 }
11110 
11111 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11112                                          OverloadCandidate *Cand) {
11113   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11114     if (ICS.isBad()) break; // all meaningless after first invalid
11115     if (!ICS.isAmbiguous()) continue;
11116 
11117     ICS.DiagnoseAmbiguousConversion(
11118         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11119   }
11120 }
11121 
11122 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11123   if (Cand->Function)
11124     return Cand->Function->getLocation();
11125   if (Cand->IsSurrogate)
11126     return Cand->Surrogate->getLocation();
11127   return SourceLocation();
11128 }
11129 
11130 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11131   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11132   case Sema::TDK_Success:
11133   case Sema::TDK_NonDependentConversionFailure:
11134     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11135 
11136   case Sema::TDK_Invalid:
11137   case Sema::TDK_Incomplete:
11138   case Sema::TDK_IncompletePack:
11139     return 1;
11140 
11141   case Sema::TDK_Underqualified:
11142   case Sema::TDK_Inconsistent:
11143     return 2;
11144 
11145   case Sema::TDK_SubstitutionFailure:
11146   case Sema::TDK_DeducedMismatch:
11147   case Sema::TDK_ConstraintsNotSatisfied:
11148   case Sema::TDK_DeducedMismatchNested:
11149   case Sema::TDK_NonDeducedMismatch:
11150   case Sema::TDK_MiscellaneousDeductionFailure:
11151   case Sema::TDK_CUDATargetMismatch:
11152     return 3;
11153 
11154   case Sema::TDK_InstantiationDepth:
11155     return 4;
11156 
11157   case Sema::TDK_InvalidExplicitArguments:
11158     return 5;
11159 
11160   case Sema::TDK_TooManyArguments:
11161   case Sema::TDK_TooFewArguments:
11162     return 6;
11163   }
11164   llvm_unreachable("Unhandled deduction result");
11165 }
11166 
11167 namespace {
11168 struct CompareOverloadCandidatesForDisplay {
11169   Sema &S;
11170   SourceLocation Loc;
11171   size_t NumArgs;
11172   OverloadCandidateSet::CandidateSetKind CSK;
11173 
11174   CompareOverloadCandidatesForDisplay(
11175       Sema &S, SourceLocation Loc, size_t NArgs,
11176       OverloadCandidateSet::CandidateSetKind CSK)
11177       : S(S), NumArgs(NArgs), CSK(CSK) {}
11178 
11179   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11180     // If there are too many or too few arguments, that's the high-order bit we
11181     // want to sort by, even if the immediate failure kind was something else.
11182     if (C->FailureKind == ovl_fail_too_many_arguments ||
11183         C->FailureKind == ovl_fail_too_few_arguments)
11184       return static_cast<OverloadFailureKind>(C->FailureKind);
11185 
11186     if (C->Function) {
11187       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11188         return ovl_fail_too_many_arguments;
11189       if (NumArgs < C->Function->getMinRequiredArguments())
11190         return ovl_fail_too_few_arguments;
11191     }
11192 
11193     return static_cast<OverloadFailureKind>(C->FailureKind);
11194   }
11195 
11196   bool operator()(const OverloadCandidate *L,
11197                   const OverloadCandidate *R) {
11198     // Fast-path this check.
11199     if (L == R) return false;
11200 
11201     // Order first by viability.
11202     if (L->Viable) {
11203       if (!R->Viable) return true;
11204 
11205       // TODO: introduce a tri-valued comparison for overload
11206       // candidates.  Would be more worthwhile if we had a sort
11207       // that could exploit it.
11208       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11209         return true;
11210       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11211         return false;
11212     } else if (R->Viable)
11213       return false;
11214 
11215     assert(L->Viable == R->Viable);
11216 
11217     // Criteria by which we can sort non-viable candidates:
11218     if (!L->Viable) {
11219       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11220       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11221 
11222       // 1. Arity mismatches come after other candidates.
11223       if (LFailureKind == ovl_fail_too_many_arguments ||
11224           LFailureKind == ovl_fail_too_few_arguments) {
11225         if (RFailureKind == ovl_fail_too_many_arguments ||
11226             RFailureKind == ovl_fail_too_few_arguments) {
11227           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11228           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11229           if (LDist == RDist) {
11230             if (LFailureKind == RFailureKind)
11231               // Sort non-surrogates before surrogates.
11232               return !L->IsSurrogate && R->IsSurrogate;
11233             // Sort candidates requiring fewer parameters than there were
11234             // arguments given after candidates requiring more parameters
11235             // than there were arguments given.
11236             return LFailureKind == ovl_fail_too_many_arguments;
11237           }
11238           return LDist < RDist;
11239         }
11240         return false;
11241       }
11242       if (RFailureKind == ovl_fail_too_many_arguments ||
11243           RFailureKind == ovl_fail_too_few_arguments)
11244         return true;
11245 
11246       // 2. Bad conversions come first and are ordered by the number
11247       // of bad conversions and quality of good conversions.
11248       if (LFailureKind == ovl_fail_bad_conversion) {
11249         if (RFailureKind != ovl_fail_bad_conversion)
11250           return true;
11251 
11252         // The conversion that can be fixed with a smaller number of changes,
11253         // comes first.
11254         unsigned numLFixes = L->Fix.NumConversionsFixed;
11255         unsigned numRFixes = R->Fix.NumConversionsFixed;
11256         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11257         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11258         if (numLFixes != numRFixes) {
11259           return numLFixes < numRFixes;
11260         }
11261 
11262         // If there's any ordering between the defined conversions...
11263         // FIXME: this might not be transitive.
11264         assert(L->Conversions.size() == R->Conversions.size());
11265 
11266         int leftBetter = 0;
11267         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11268         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11269           switch (CompareImplicitConversionSequences(S, Loc,
11270                                                      L->Conversions[I],
11271                                                      R->Conversions[I])) {
11272           case ImplicitConversionSequence::Better:
11273             leftBetter++;
11274             break;
11275 
11276           case ImplicitConversionSequence::Worse:
11277             leftBetter--;
11278             break;
11279 
11280           case ImplicitConversionSequence::Indistinguishable:
11281             break;
11282           }
11283         }
11284         if (leftBetter > 0) return true;
11285         if (leftBetter < 0) return false;
11286 
11287       } else if (RFailureKind == ovl_fail_bad_conversion)
11288         return false;
11289 
11290       if (LFailureKind == ovl_fail_bad_deduction) {
11291         if (RFailureKind != ovl_fail_bad_deduction)
11292           return true;
11293 
11294         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11295           return RankDeductionFailure(L->DeductionFailure)
11296                < RankDeductionFailure(R->DeductionFailure);
11297       } else if (RFailureKind == ovl_fail_bad_deduction)
11298         return false;
11299 
11300       // TODO: others?
11301     }
11302 
11303     // Sort everything else by location.
11304     SourceLocation LLoc = GetLocationForCandidate(L);
11305     SourceLocation RLoc = GetLocationForCandidate(R);
11306 
11307     // Put candidates without locations (e.g. builtins) at the end.
11308     if (LLoc.isInvalid()) return false;
11309     if (RLoc.isInvalid()) return true;
11310 
11311     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11312   }
11313 };
11314 }
11315 
11316 /// CompleteNonViableCandidate - Normally, overload resolution only
11317 /// computes up to the first bad conversion. Produces the FixIt set if
11318 /// possible.
11319 static void
11320 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11321                            ArrayRef<Expr *> Args,
11322                            OverloadCandidateSet::CandidateSetKind CSK) {
11323   assert(!Cand->Viable);
11324 
11325   // Don't do anything on failures other than bad conversion.
11326   if (Cand->FailureKind != ovl_fail_bad_conversion)
11327     return;
11328 
11329   // We only want the FixIts if all the arguments can be corrected.
11330   bool Unfixable = false;
11331   // Use a implicit copy initialization to check conversion fixes.
11332   Cand->Fix.setConversionChecker(TryCopyInitialization);
11333 
11334   // Attempt to fix the bad conversion.
11335   unsigned ConvCount = Cand->Conversions.size();
11336   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11337        ++ConvIdx) {
11338     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11339     if (Cand->Conversions[ConvIdx].isInitialized() &&
11340         Cand->Conversions[ConvIdx].isBad()) {
11341       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11342       break;
11343     }
11344   }
11345 
11346   // FIXME: this should probably be preserved from the overload
11347   // operation somehow.
11348   bool SuppressUserConversions = false;
11349 
11350   unsigned ConvIdx = 0;
11351   unsigned ArgIdx = 0;
11352   ArrayRef<QualType> ParamTypes;
11353   bool Reversed = Cand->isReversed();
11354 
11355   if (Cand->IsSurrogate) {
11356     QualType ConvType
11357       = Cand->Surrogate->getConversionType().getNonReferenceType();
11358     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11359       ConvType = ConvPtrType->getPointeeType();
11360     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11361     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11362     ConvIdx = 1;
11363   } else if (Cand->Function) {
11364     ParamTypes =
11365         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11366     if (isa<CXXMethodDecl>(Cand->Function) &&
11367         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11368       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11369       ConvIdx = 1;
11370       if (CSK == OverloadCandidateSet::CSK_Operator &&
11371           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11372         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11373         ArgIdx = 1;
11374     }
11375   } else {
11376     // Builtin operator.
11377     assert(ConvCount <= 3);
11378     ParamTypes = Cand->BuiltinParamTypes;
11379   }
11380 
11381   // Fill in the rest of the conversions.
11382   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11383        ConvIdx != ConvCount;
11384        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11385     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11386     if (Cand->Conversions[ConvIdx].isInitialized()) {
11387       // We've already checked this conversion.
11388     } else if (ParamIdx < ParamTypes.size()) {
11389       if (ParamTypes[ParamIdx]->isDependentType())
11390         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11391             Args[ArgIdx]->getType());
11392       else {
11393         Cand->Conversions[ConvIdx] =
11394             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11395                                   SuppressUserConversions,
11396                                   /*InOverloadResolution=*/true,
11397                                   /*AllowObjCWritebackConversion=*/
11398                                   S.getLangOpts().ObjCAutoRefCount);
11399         // Store the FixIt in the candidate if it exists.
11400         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11401           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11402       }
11403     } else
11404       Cand->Conversions[ConvIdx].setEllipsis();
11405   }
11406 }
11407 
11408 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11409     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11410     SourceLocation OpLoc,
11411     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11412   // Sort the candidates by viability and position.  Sorting directly would
11413   // be prohibitive, so we make a set of pointers and sort those.
11414   SmallVector<OverloadCandidate*, 32> Cands;
11415   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11416   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11417     if (!Filter(*Cand))
11418       continue;
11419     switch (OCD) {
11420     case OCD_AllCandidates:
11421       if (!Cand->Viable) {
11422         if (!Cand->Function && !Cand->IsSurrogate) {
11423           // This a non-viable builtin candidate.  We do not, in general,
11424           // want to list every possible builtin candidate.
11425           continue;
11426         }
11427         CompleteNonViableCandidate(S, Cand, Args, Kind);
11428       }
11429       break;
11430 
11431     case OCD_ViableCandidates:
11432       if (!Cand->Viable)
11433         continue;
11434       break;
11435 
11436     case OCD_AmbiguousCandidates:
11437       if (!Cand->Best)
11438         continue;
11439       break;
11440     }
11441 
11442     Cands.push_back(Cand);
11443   }
11444 
11445   llvm::stable_sort(
11446       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11447 
11448   return Cands;
11449 }
11450 
11451 /// When overload resolution fails, prints diagnostic messages containing the
11452 /// candidates in the candidate set.
11453 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11454     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11455     StringRef Opc, SourceLocation OpLoc,
11456     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11457 
11458   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11459 
11460   S.Diag(PD.first, PD.second);
11461 
11462   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11463 
11464   if (OCD == OCD_AmbiguousCandidates)
11465     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11466 }
11467 
11468 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11469                                           ArrayRef<OverloadCandidate *> Cands,
11470                                           StringRef Opc, SourceLocation OpLoc) {
11471   bool ReportedAmbiguousConversions = false;
11472 
11473   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11474   unsigned CandsShown = 0;
11475   auto I = Cands.begin(), E = Cands.end();
11476   for (; I != E; ++I) {
11477     OverloadCandidate *Cand = *I;
11478 
11479     // Set an arbitrary limit on the number of candidate functions we'll spam
11480     // the user with.  FIXME: This limit should depend on details of the
11481     // candidate list.
11482     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11483       break;
11484     }
11485     ++CandsShown;
11486 
11487     if (Cand->Function)
11488       NoteFunctionCandidate(S, Cand, Args.size(),
11489                             /*TakingCandidateAddress=*/false, DestAS);
11490     else if (Cand->IsSurrogate)
11491       NoteSurrogateCandidate(S, Cand);
11492     else {
11493       assert(Cand->Viable &&
11494              "Non-viable built-in candidates are not added to Cands.");
11495       // Generally we only see ambiguities including viable builtin
11496       // operators if overload resolution got screwed up by an
11497       // ambiguous user-defined conversion.
11498       //
11499       // FIXME: It's quite possible for different conversions to see
11500       // different ambiguities, though.
11501       if (!ReportedAmbiguousConversions) {
11502         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11503         ReportedAmbiguousConversions = true;
11504       }
11505 
11506       // If this is a viable builtin, print it.
11507       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11508     }
11509   }
11510 
11511   if (I != E)
11512     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11513 }
11514 
11515 static SourceLocation
11516 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11517   return Cand->Specialization ? Cand->Specialization->getLocation()
11518                               : SourceLocation();
11519 }
11520 
11521 namespace {
11522 struct CompareTemplateSpecCandidatesForDisplay {
11523   Sema &S;
11524   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11525 
11526   bool operator()(const TemplateSpecCandidate *L,
11527                   const TemplateSpecCandidate *R) {
11528     // Fast-path this check.
11529     if (L == R)
11530       return false;
11531 
11532     // Assuming that both candidates are not matches...
11533 
11534     // Sort by the ranking of deduction failures.
11535     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11536       return RankDeductionFailure(L->DeductionFailure) <
11537              RankDeductionFailure(R->DeductionFailure);
11538 
11539     // Sort everything else by location.
11540     SourceLocation LLoc = GetLocationForCandidate(L);
11541     SourceLocation RLoc = GetLocationForCandidate(R);
11542 
11543     // Put candidates without locations (e.g. builtins) at the end.
11544     if (LLoc.isInvalid())
11545       return false;
11546     if (RLoc.isInvalid())
11547       return true;
11548 
11549     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11550   }
11551 };
11552 }
11553 
11554 /// Diagnose a template argument deduction failure.
11555 /// We are treating these failures as overload failures due to bad
11556 /// deductions.
11557 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11558                                                  bool ForTakingAddress) {
11559   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11560                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11561 }
11562 
11563 void TemplateSpecCandidateSet::destroyCandidates() {
11564   for (iterator i = begin(), e = end(); i != e; ++i) {
11565     i->DeductionFailure.Destroy();
11566   }
11567 }
11568 
11569 void TemplateSpecCandidateSet::clear() {
11570   destroyCandidates();
11571   Candidates.clear();
11572 }
11573 
11574 /// NoteCandidates - When no template specialization match is found, prints
11575 /// diagnostic messages containing the non-matching specializations that form
11576 /// the candidate set.
11577 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11578 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11579 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11580   // Sort the candidates by position (assuming no candidate is a match).
11581   // Sorting directly would be prohibitive, so we make a set of pointers
11582   // and sort those.
11583   SmallVector<TemplateSpecCandidate *, 32> Cands;
11584   Cands.reserve(size());
11585   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11586     if (Cand->Specialization)
11587       Cands.push_back(Cand);
11588     // Otherwise, this is a non-matching builtin candidate.  We do not,
11589     // in general, want to list every possible builtin candidate.
11590   }
11591 
11592   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11593 
11594   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11595   // for generalization purposes (?).
11596   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11597 
11598   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11599   unsigned CandsShown = 0;
11600   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11601     TemplateSpecCandidate *Cand = *I;
11602 
11603     // Set an arbitrary limit on the number of candidates we'll spam
11604     // the user with.  FIXME: This limit should depend on details of the
11605     // candidate list.
11606     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11607       break;
11608     ++CandsShown;
11609 
11610     assert(Cand->Specialization &&
11611            "Non-matching built-in candidates are not added to Cands.");
11612     Cand->NoteDeductionFailure(S, ForTakingAddress);
11613   }
11614 
11615   if (I != E)
11616     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11617 }
11618 
11619 // [PossiblyAFunctionType]  -->   [Return]
11620 // NonFunctionType --> NonFunctionType
11621 // R (A) --> R(A)
11622 // R (*)(A) --> R (A)
11623 // R (&)(A) --> R (A)
11624 // R (S::*)(A) --> R (A)
11625 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11626   QualType Ret = PossiblyAFunctionType;
11627   if (const PointerType *ToTypePtr =
11628     PossiblyAFunctionType->getAs<PointerType>())
11629     Ret = ToTypePtr->getPointeeType();
11630   else if (const ReferenceType *ToTypeRef =
11631     PossiblyAFunctionType->getAs<ReferenceType>())
11632     Ret = ToTypeRef->getPointeeType();
11633   else if (const MemberPointerType *MemTypePtr =
11634     PossiblyAFunctionType->getAs<MemberPointerType>())
11635     Ret = MemTypePtr->getPointeeType();
11636   Ret =
11637     Context.getCanonicalType(Ret).getUnqualifiedType();
11638   return Ret;
11639 }
11640 
11641 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11642                                  bool Complain = true) {
11643   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11644       S.DeduceReturnType(FD, Loc, Complain))
11645     return true;
11646 
11647   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11648   if (S.getLangOpts().CPlusPlus17 &&
11649       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11650       !S.ResolveExceptionSpec(Loc, FPT))
11651     return true;
11652 
11653   return false;
11654 }
11655 
11656 namespace {
11657 // A helper class to help with address of function resolution
11658 // - allows us to avoid passing around all those ugly parameters
11659 class AddressOfFunctionResolver {
11660   Sema& S;
11661   Expr* SourceExpr;
11662   const QualType& TargetType;
11663   QualType TargetFunctionType; // Extracted function type from target type
11664 
11665   bool Complain;
11666   //DeclAccessPair& ResultFunctionAccessPair;
11667   ASTContext& Context;
11668 
11669   bool TargetTypeIsNonStaticMemberFunction;
11670   bool FoundNonTemplateFunction;
11671   bool StaticMemberFunctionFromBoundPointer;
11672   bool HasComplained;
11673 
11674   OverloadExpr::FindResult OvlExprInfo;
11675   OverloadExpr *OvlExpr;
11676   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11677   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11678   TemplateSpecCandidateSet FailedCandidates;
11679 
11680 public:
11681   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11682                             const QualType &TargetType, bool Complain)
11683       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11684         Complain(Complain), Context(S.getASTContext()),
11685         TargetTypeIsNonStaticMemberFunction(
11686             !!TargetType->getAs<MemberPointerType>()),
11687         FoundNonTemplateFunction(false),
11688         StaticMemberFunctionFromBoundPointer(false),
11689         HasComplained(false),
11690         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11691         OvlExpr(OvlExprInfo.Expression),
11692         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11693     ExtractUnqualifiedFunctionTypeFromTargetType();
11694 
11695     if (TargetFunctionType->isFunctionType()) {
11696       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11697         if (!UME->isImplicitAccess() &&
11698             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11699           StaticMemberFunctionFromBoundPointer = true;
11700     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11701       DeclAccessPair dap;
11702       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11703               OvlExpr, false, &dap)) {
11704         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11705           if (!Method->isStatic()) {
11706             // If the target type is a non-function type and the function found
11707             // is a non-static member function, pretend as if that was the
11708             // target, it's the only possible type to end up with.
11709             TargetTypeIsNonStaticMemberFunction = true;
11710 
11711             // And skip adding the function if its not in the proper form.
11712             // We'll diagnose this due to an empty set of functions.
11713             if (!OvlExprInfo.HasFormOfMemberPointer)
11714               return;
11715           }
11716 
11717         Matches.push_back(std::make_pair(dap, Fn));
11718       }
11719       return;
11720     }
11721 
11722     if (OvlExpr->hasExplicitTemplateArgs())
11723       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11724 
11725     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11726       // C++ [over.over]p4:
11727       //   If more than one function is selected, [...]
11728       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11729         if (FoundNonTemplateFunction)
11730           EliminateAllTemplateMatches();
11731         else
11732           EliminateAllExceptMostSpecializedTemplate();
11733       }
11734     }
11735 
11736     if (S.getLangOpts().CUDA && Matches.size() > 1)
11737       EliminateSuboptimalCudaMatches();
11738   }
11739 
11740   bool hasComplained() const { return HasComplained; }
11741 
11742 private:
11743   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11744     QualType Discard;
11745     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11746            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11747   }
11748 
11749   /// \return true if A is considered a better overload candidate for the
11750   /// desired type than B.
11751   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11752     // If A doesn't have exactly the correct type, we don't want to classify it
11753     // as "better" than anything else. This way, the user is required to
11754     // disambiguate for us if there are multiple candidates and no exact match.
11755     return candidateHasExactlyCorrectType(A) &&
11756            (!candidateHasExactlyCorrectType(B) ||
11757             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11758   }
11759 
11760   /// \return true if we were able to eliminate all but one overload candidate,
11761   /// false otherwise.
11762   bool eliminiateSuboptimalOverloadCandidates() {
11763     // Same algorithm as overload resolution -- one pass to pick the "best",
11764     // another pass to be sure that nothing is better than the best.
11765     auto Best = Matches.begin();
11766     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11767       if (isBetterCandidate(I->second, Best->second))
11768         Best = I;
11769 
11770     const FunctionDecl *BestFn = Best->second;
11771     auto IsBestOrInferiorToBest = [this, BestFn](
11772         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11773       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11774     };
11775 
11776     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11777     // option, so we can potentially give the user a better error
11778     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11779       return false;
11780     Matches[0] = *Best;
11781     Matches.resize(1);
11782     return true;
11783   }
11784 
11785   bool isTargetTypeAFunction() const {
11786     return TargetFunctionType->isFunctionType();
11787   }
11788 
11789   // [ToType]     [Return]
11790 
11791   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11792   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11793   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11794   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11795     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11796   }
11797 
11798   // return true if any matching specializations were found
11799   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11800                                    const DeclAccessPair& CurAccessFunPair) {
11801     if (CXXMethodDecl *Method
11802               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11803       // Skip non-static function templates when converting to pointer, and
11804       // static when converting to member pointer.
11805       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11806         return false;
11807     }
11808     else if (TargetTypeIsNonStaticMemberFunction)
11809       return false;
11810 
11811     // C++ [over.over]p2:
11812     //   If the name is a function template, template argument deduction is
11813     //   done (14.8.2.2), and if the argument deduction succeeds, the
11814     //   resulting template argument list is used to generate a single
11815     //   function template specialization, which is added to the set of
11816     //   overloaded functions considered.
11817     FunctionDecl *Specialization = nullptr;
11818     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11819     if (Sema::TemplateDeductionResult Result
11820           = S.DeduceTemplateArguments(FunctionTemplate,
11821                                       &OvlExplicitTemplateArgs,
11822                                       TargetFunctionType, Specialization,
11823                                       Info, /*IsAddressOfFunction*/true)) {
11824       // Make a note of the failed deduction for diagnostics.
11825       FailedCandidates.addCandidate()
11826           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11827                MakeDeductionFailureInfo(Context, Result, Info));
11828       return false;
11829     }
11830 
11831     // Template argument deduction ensures that we have an exact match or
11832     // compatible pointer-to-function arguments that would be adjusted by ICS.
11833     // This function template specicalization works.
11834     assert(S.isSameOrCompatibleFunctionType(
11835               Context.getCanonicalType(Specialization->getType()),
11836               Context.getCanonicalType(TargetFunctionType)));
11837 
11838     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11839       return false;
11840 
11841     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11842     return true;
11843   }
11844 
11845   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11846                                       const DeclAccessPair& CurAccessFunPair) {
11847     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11848       // Skip non-static functions when converting to pointer, and static
11849       // when converting to member pointer.
11850       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11851         return false;
11852     }
11853     else if (TargetTypeIsNonStaticMemberFunction)
11854       return false;
11855 
11856     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11857       if (S.getLangOpts().CUDA)
11858         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11859           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11860             return false;
11861       if (FunDecl->isMultiVersion()) {
11862         const auto *TA = FunDecl->getAttr<TargetAttr>();
11863         if (TA && !TA->isDefaultVersion())
11864           return false;
11865       }
11866 
11867       // If any candidate has a placeholder return type, trigger its deduction
11868       // now.
11869       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11870                                Complain)) {
11871         HasComplained |= Complain;
11872         return false;
11873       }
11874 
11875       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11876         return false;
11877 
11878       // If we're in C, we need to support types that aren't exactly identical.
11879       if (!S.getLangOpts().CPlusPlus ||
11880           candidateHasExactlyCorrectType(FunDecl)) {
11881         Matches.push_back(std::make_pair(
11882             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11883         FoundNonTemplateFunction = true;
11884         return true;
11885       }
11886     }
11887 
11888     return false;
11889   }
11890 
11891   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11892     bool Ret = false;
11893 
11894     // If the overload expression doesn't have the form of a pointer to
11895     // member, don't try to convert it to a pointer-to-member type.
11896     if (IsInvalidFormOfPointerToMemberFunction())
11897       return false;
11898 
11899     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11900                                E = OvlExpr->decls_end();
11901          I != E; ++I) {
11902       // Look through any using declarations to find the underlying function.
11903       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11904 
11905       // C++ [over.over]p3:
11906       //   Non-member functions and static member functions match
11907       //   targets of type "pointer-to-function" or "reference-to-function."
11908       //   Nonstatic member functions match targets of
11909       //   type "pointer-to-member-function."
11910       // Note that according to DR 247, the containing class does not matter.
11911       if (FunctionTemplateDecl *FunctionTemplate
11912                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11913         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11914           Ret = true;
11915       }
11916       // If we have explicit template arguments supplied, skip non-templates.
11917       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11918                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11919         Ret = true;
11920     }
11921     assert(Ret || Matches.empty());
11922     return Ret;
11923   }
11924 
11925   void EliminateAllExceptMostSpecializedTemplate() {
11926     //   [...] and any given function template specialization F1 is
11927     //   eliminated if the set contains a second function template
11928     //   specialization whose function template is more specialized
11929     //   than the function template of F1 according to the partial
11930     //   ordering rules of 14.5.5.2.
11931 
11932     // The algorithm specified above is quadratic. We instead use a
11933     // two-pass algorithm (similar to the one used to identify the
11934     // best viable function in an overload set) that identifies the
11935     // best function template (if it exists).
11936 
11937     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11938     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11939       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11940 
11941     // TODO: It looks like FailedCandidates does not serve much purpose
11942     // here, since the no_viable diagnostic has index 0.
11943     UnresolvedSetIterator Result = S.getMostSpecialized(
11944         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11945         SourceExpr->getBeginLoc(), S.PDiag(),
11946         S.PDiag(diag::err_addr_ovl_ambiguous)
11947             << Matches[0].second->getDeclName(),
11948         S.PDiag(diag::note_ovl_candidate)
11949             << (unsigned)oc_function << (unsigned)ocs_described_template,
11950         Complain, TargetFunctionType);
11951 
11952     if (Result != MatchesCopy.end()) {
11953       // Make it the first and only element
11954       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11955       Matches[0].second = cast<FunctionDecl>(*Result);
11956       Matches.resize(1);
11957     } else
11958       HasComplained |= Complain;
11959   }
11960 
11961   void EliminateAllTemplateMatches() {
11962     //   [...] any function template specializations in the set are
11963     //   eliminated if the set also contains a non-template function, [...]
11964     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11965       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11966         ++I;
11967       else {
11968         Matches[I] = Matches[--N];
11969         Matches.resize(N);
11970       }
11971     }
11972   }
11973 
11974   void EliminateSuboptimalCudaMatches() {
11975     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11976   }
11977 
11978 public:
11979   void ComplainNoMatchesFound() const {
11980     assert(Matches.empty());
11981     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11982         << OvlExpr->getName() << TargetFunctionType
11983         << OvlExpr->getSourceRange();
11984     if (FailedCandidates.empty())
11985       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11986                                   /*TakingAddress=*/true);
11987     else {
11988       // We have some deduction failure messages. Use them to diagnose
11989       // the function templates, and diagnose the non-template candidates
11990       // normally.
11991       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11992                                  IEnd = OvlExpr->decls_end();
11993            I != IEnd; ++I)
11994         if (FunctionDecl *Fun =
11995                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11996           if (!functionHasPassObjectSizeParams(Fun))
11997             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11998                                     /*TakingAddress=*/true);
11999       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
12000     }
12001   }
12002 
12003   bool IsInvalidFormOfPointerToMemberFunction() const {
12004     return TargetTypeIsNonStaticMemberFunction &&
12005       !OvlExprInfo.HasFormOfMemberPointer;
12006   }
12007 
12008   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12009       // TODO: Should we condition this on whether any functions might
12010       // have matched, or is it more appropriate to do that in callers?
12011       // TODO: a fixit wouldn't hurt.
12012       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
12013         << TargetType << OvlExpr->getSourceRange();
12014   }
12015 
12016   bool IsStaticMemberFunctionFromBoundPointer() const {
12017     return StaticMemberFunctionFromBoundPointer;
12018   }
12019 
12020   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12021     S.Diag(OvlExpr->getBeginLoc(),
12022            diag::err_invalid_form_pointer_member_function)
12023         << OvlExpr->getSourceRange();
12024   }
12025 
12026   void ComplainOfInvalidConversion() const {
12027     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
12028         << OvlExpr->getName() << TargetType;
12029   }
12030 
12031   void ComplainMultipleMatchesFound() const {
12032     assert(Matches.size() > 1);
12033     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
12034         << OvlExpr->getName() << OvlExpr->getSourceRange();
12035     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
12036                                 /*TakingAddress=*/true);
12037   }
12038 
12039   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
12040 
12041   int getNumMatches() const { return Matches.size(); }
12042 
12043   FunctionDecl* getMatchingFunctionDecl() const {
12044     if (Matches.size() != 1) return nullptr;
12045     return Matches[0].second;
12046   }
12047 
12048   const DeclAccessPair* getMatchingFunctionAccessPair() const {
12049     if (Matches.size() != 1) return nullptr;
12050     return &Matches[0].first;
12051   }
12052 };
12053 }
12054 
12055 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12056 /// an overloaded function (C++ [over.over]), where @p From is an
12057 /// expression with overloaded function type and @p ToType is the type
12058 /// we're trying to resolve to. For example:
12059 ///
12060 /// @code
12061 /// int f(double);
12062 /// int f(int);
12063 ///
12064 /// int (*pfd)(double) = f; // selects f(double)
12065 /// @endcode
12066 ///
12067 /// This routine returns the resulting FunctionDecl if it could be
12068 /// resolved, and NULL otherwise. When @p Complain is true, this
12069 /// routine will emit diagnostics if there is an error.
12070 FunctionDecl *
12071 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12072                                          QualType TargetType,
12073                                          bool Complain,
12074                                          DeclAccessPair &FoundResult,
12075                                          bool *pHadMultipleCandidates) {
12076   assert(AddressOfExpr->getType() == Context.OverloadTy);
12077 
12078   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12079                                      Complain);
12080   int NumMatches = Resolver.getNumMatches();
12081   FunctionDecl *Fn = nullptr;
12082   bool ShouldComplain = Complain && !Resolver.hasComplained();
12083   if (NumMatches == 0 && ShouldComplain) {
12084     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12085       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12086     else
12087       Resolver.ComplainNoMatchesFound();
12088   }
12089   else if (NumMatches > 1 && ShouldComplain)
12090     Resolver.ComplainMultipleMatchesFound();
12091   else if (NumMatches == 1) {
12092     Fn = Resolver.getMatchingFunctionDecl();
12093     assert(Fn);
12094     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12095       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12096     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12097     if (Complain) {
12098       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12099         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12100       else
12101         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12102     }
12103   }
12104 
12105   if (pHadMultipleCandidates)
12106     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12107   return Fn;
12108 }
12109 
12110 /// Given an expression that refers to an overloaded function, try to
12111 /// resolve that function to a single function that can have its address taken.
12112 /// This will modify `Pair` iff it returns non-null.
12113 ///
12114 /// This routine can only succeed if from all of the candidates in the overload
12115 /// set for SrcExpr that can have their addresses taken, there is one candidate
12116 /// that is more constrained than the rest.
12117 FunctionDecl *
12118 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12119   OverloadExpr::FindResult R = OverloadExpr::find(E);
12120   OverloadExpr *Ovl = R.Expression;
12121   bool IsResultAmbiguous = false;
12122   FunctionDecl *Result = nullptr;
12123   DeclAccessPair DAP;
12124   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12125 
12126   auto CheckMoreConstrained =
12127       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12128         SmallVector<const Expr *, 1> AC1, AC2;
12129         FD1->getAssociatedConstraints(AC1);
12130         FD2->getAssociatedConstraints(AC2);
12131         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12132         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12133           return None;
12134         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12135           return None;
12136         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12137           return None;
12138         return AtLeastAsConstrained1;
12139       };
12140 
12141   // Don't use the AddressOfResolver because we're specifically looking for
12142   // cases where we have one overload candidate that lacks
12143   // enable_if/pass_object_size/...
12144   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12145     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12146     if (!FD)
12147       return nullptr;
12148 
12149     if (!checkAddressOfFunctionIsAvailable(FD))
12150       continue;
12151 
12152     // We have more than one result - see if it is more constrained than the
12153     // previous one.
12154     if (Result) {
12155       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12156                                                                         Result);
12157       if (!MoreConstrainedThanPrevious) {
12158         IsResultAmbiguous = true;
12159         AmbiguousDecls.push_back(FD);
12160         continue;
12161       }
12162       if (!*MoreConstrainedThanPrevious)
12163         continue;
12164       // FD is more constrained - replace Result with it.
12165     }
12166     IsResultAmbiguous = false;
12167     DAP = I.getPair();
12168     Result = FD;
12169   }
12170 
12171   if (IsResultAmbiguous)
12172     return nullptr;
12173 
12174   if (Result) {
12175     SmallVector<const Expr *, 1> ResultAC;
12176     // We skipped over some ambiguous declarations which might be ambiguous with
12177     // the selected result.
12178     for (FunctionDecl *Skipped : AmbiguousDecls)
12179       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12180         return nullptr;
12181     Pair = DAP;
12182   }
12183   return Result;
12184 }
12185 
12186 /// Given an overloaded function, tries to turn it into a non-overloaded
12187 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12188 /// will perform access checks, diagnose the use of the resultant decl, and, if
12189 /// requested, potentially perform a function-to-pointer decay.
12190 ///
12191 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12192 /// Otherwise, returns true. This may emit diagnostics and return true.
12193 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12194     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12195   Expr *E = SrcExpr.get();
12196   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12197 
12198   DeclAccessPair DAP;
12199   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12200   if (!Found || Found->isCPUDispatchMultiVersion() ||
12201       Found->isCPUSpecificMultiVersion())
12202     return false;
12203 
12204   // Emitting multiple diagnostics for a function that is both inaccessible and
12205   // unavailable is consistent with our behavior elsewhere. So, always check
12206   // for both.
12207   DiagnoseUseOfDecl(Found, E->getExprLoc());
12208   CheckAddressOfMemberAccess(E, DAP);
12209   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12210   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12211     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12212   else
12213     SrcExpr = Fixed;
12214   return true;
12215 }
12216 
12217 /// Given an expression that refers to an overloaded function, try to
12218 /// resolve that overloaded function expression down to a single function.
12219 ///
12220 /// This routine can only resolve template-ids that refer to a single function
12221 /// template, where that template-id refers to a single template whose template
12222 /// arguments are either provided by the template-id or have defaults,
12223 /// as described in C++0x [temp.arg.explicit]p3.
12224 ///
12225 /// If no template-ids are found, no diagnostics are emitted and NULL is
12226 /// returned.
12227 FunctionDecl *
12228 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12229                                                   bool Complain,
12230                                                   DeclAccessPair *FoundResult) {
12231   // C++ [over.over]p1:
12232   //   [...] [Note: any redundant set of parentheses surrounding the
12233   //   overloaded function name is ignored (5.1). ]
12234   // C++ [over.over]p1:
12235   //   [...] The overloaded function name can be preceded by the &
12236   //   operator.
12237 
12238   // If we didn't actually find any template-ids, we're done.
12239   if (!ovl->hasExplicitTemplateArgs())
12240     return nullptr;
12241 
12242   TemplateArgumentListInfo ExplicitTemplateArgs;
12243   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12244   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12245 
12246   // Look through all of the overloaded functions, searching for one
12247   // whose type matches exactly.
12248   FunctionDecl *Matched = nullptr;
12249   for (UnresolvedSetIterator I = ovl->decls_begin(),
12250          E = ovl->decls_end(); I != E; ++I) {
12251     // C++0x [temp.arg.explicit]p3:
12252     //   [...] In contexts where deduction is done and fails, or in contexts
12253     //   where deduction is not done, if a template argument list is
12254     //   specified and it, along with any default template arguments,
12255     //   identifies a single function template specialization, then the
12256     //   template-id is an lvalue for the function template specialization.
12257     FunctionTemplateDecl *FunctionTemplate
12258       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12259 
12260     // C++ [over.over]p2:
12261     //   If the name is a function template, template argument deduction is
12262     //   done (14.8.2.2), and if the argument deduction succeeds, the
12263     //   resulting template argument list is used to generate a single
12264     //   function template specialization, which is added to the set of
12265     //   overloaded functions considered.
12266     FunctionDecl *Specialization = nullptr;
12267     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12268     if (TemplateDeductionResult Result
12269           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12270                                     Specialization, Info,
12271                                     /*IsAddressOfFunction*/true)) {
12272       // Make a note of the failed deduction for diagnostics.
12273       // TODO: Actually use the failed-deduction info?
12274       FailedCandidates.addCandidate()
12275           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12276                MakeDeductionFailureInfo(Context, Result, Info));
12277       continue;
12278     }
12279 
12280     assert(Specialization && "no specialization and no error?");
12281 
12282     // Multiple matches; we can't resolve to a single declaration.
12283     if (Matched) {
12284       if (Complain) {
12285         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12286           << ovl->getName();
12287         NoteAllOverloadCandidates(ovl);
12288       }
12289       return nullptr;
12290     }
12291 
12292     Matched = Specialization;
12293     if (FoundResult) *FoundResult = I.getPair();
12294   }
12295 
12296   if (Matched &&
12297       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12298     return nullptr;
12299 
12300   return Matched;
12301 }
12302 
12303 // Resolve and fix an overloaded expression that can be resolved
12304 // because it identifies a single function template specialization.
12305 //
12306 // Last three arguments should only be supplied if Complain = true
12307 //
12308 // Return true if it was logically possible to so resolve the
12309 // expression, regardless of whether or not it succeeded.  Always
12310 // returns true if 'complain' is set.
12311 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12312                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12313                       bool complain, SourceRange OpRangeForComplaining,
12314                                            QualType DestTypeForComplaining,
12315                                             unsigned DiagIDForComplaining) {
12316   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12317 
12318   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12319 
12320   DeclAccessPair found;
12321   ExprResult SingleFunctionExpression;
12322   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12323                            ovl.Expression, /*complain*/ false, &found)) {
12324     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12325       SrcExpr = ExprError();
12326       return true;
12327     }
12328 
12329     // It is only correct to resolve to an instance method if we're
12330     // resolving a form that's permitted to be a pointer to member.
12331     // Otherwise we'll end up making a bound member expression, which
12332     // is illegal in all the contexts we resolve like this.
12333     if (!ovl.HasFormOfMemberPointer &&
12334         isa<CXXMethodDecl>(fn) &&
12335         cast<CXXMethodDecl>(fn)->isInstance()) {
12336       if (!complain) return false;
12337 
12338       Diag(ovl.Expression->getExprLoc(),
12339            diag::err_bound_member_function)
12340         << 0 << ovl.Expression->getSourceRange();
12341 
12342       // TODO: I believe we only end up here if there's a mix of
12343       // static and non-static candidates (otherwise the expression
12344       // would have 'bound member' type, not 'overload' type).
12345       // Ideally we would note which candidate was chosen and why
12346       // the static candidates were rejected.
12347       SrcExpr = ExprError();
12348       return true;
12349     }
12350 
12351     // Fix the expression to refer to 'fn'.
12352     SingleFunctionExpression =
12353         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12354 
12355     // If desired, do function-to-pointer decay.
12356     if (doFunctionPointerConverion) {
12357       SingleFunctionExpression =
12358         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12359       if (SingleFunctionExpression.isInvalid()) {
12360         SrcExpr = ExprError();
12361         return true;
12362       }
12363     }
12364   }
12365 
12366   if (!SingleFunctionExpression.isUsable()) {
12367     if (complain) {
12368       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12369         << ovl.Expression->getName()
12370         << DestTypeForComplaining
12371         << OpRangeForComplaining
12372         << ovl.Expression->getQualifierLoc().getSourceRange();
12373       NoteAllOverloadCandidates(SrcExpr.get());
12374 
12375       SrcExpr = ExprError();
12376       return true;
12377     }
12378 
12379     return false;
12380   }
12381 
12382   SrcExpr = SingleFunctionExpression;
12383   return true;
12384 }
12385 
12386 /// Add a single candidate to the overload set.
12387 static void AddOverloadedCallCandidate(Sema &S,
12388                                        DeclAccessPair FoundDecl,
12389                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12390                                        ArrayRef<Expr *> Args,
12391                                        OverloadCandidateSet &CandidateSet,
12392                                        bool PartialOverloading,
12393                                        bool KnownValid) {
12394   NamedDecl *Callee = FoundDecl.getDecl();
12395   if (isa<UsingShadowDecl>(Callee))
12396     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12397 
12398   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12399     if (ExplicitTemplateArgs) {
12400       assert(!KnownValid && "Explicit template arguments?");
12401       return;
12402     }
12403     // Prevent ill-formed function decls to be added as overload candidates.
12404     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12405       return;
12406 
12407     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12408                            /*SuppressUserConversions=*/false,
12409                            PartialOverloading);
12410     return;
12411   }
12412 
12413   if (FunctionTemplateDecl *FuncTemplate
12414       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12415     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12416                                    ExplicitTemplateArgs, Args, CandidateSet,
12417                                    /*SuppressUserConversions=*/false,
12418                                    PartialOverloading);
12419     return;
12420   }
12421 
12422   assert(!KnownValid && "unhandled case in overloaded call candidate");
12423 }
12424 
12425 /// Add the overload candidates named by callee and/or found by argument
12426 /// dependent lookup to the given overload set.
12427 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12428                                        ArrayRef<Expr *> Args,
12429                                        OverloadCandidateSet &CandidateSet,
12430                                        bool PartialOverloading) {
12431 
12432 #ifndef NDEBUG
12433   // Verify that ArgumentDependentLookup is consistent with the rules
12434   // in C++0x [basic.lookup.argdep]p3:
12435   //
12436   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12437   //   and let Y be the lookup set produced by argument dependent
12438   //   lookup (defined as follows). If X contains
12439   //
12440   //     -- a declaration of a class member, or
12441   //
12442   //     -- a block-scope function declaration that is not a
12443   //        using-declaration, or
12444   //
12445   //     -- a declaration that is neither a function or a function
12446   //        template
12447   //
12448   //   then Y is empty.
12449 
12450   if (ULE->requiresADL()) {
12451     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12452            E = ULE->decls_end(); I != E; ++I) {
12453       assert(!(*I)->getDeclContext()->isRecord());
12454       assert(isa<UsingShadowDecl>(*I) ||
12455              !(*I)->getDeclContext()->isFunctionOrMethod());
12456       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12457     }
12458   }
12459 #endif
12460 
12461   // It would be nice to avoid this copy.
12462   TemplateArgumentListInfo TABuffer;
12463   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12464   if (ULE->hasExplicitTemplateArgs()) {
12465     ULE->copyTemplateArgumentsInto(TABuffer);
12466     ExplicitTemplateArgs = &TABuffer;
12467   }
12468 
12469   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12470          E = ULE->decls_end(); I != E; ++I)
12471     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12472                                CandidateSet, PartialOverloading,
12473                                /*KnownValid*/ true);
12474 
12475   if (ULE->requiresADL())
12476     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12477                                          Args, ExplicitTemplateArgs,
12478                                          CandidateSet, PartialOverloading);
12479 }
12480 
12481 /// Determine whether a declaration with the specified name could be moved into
12482 /// a different namespace.
12483 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12484   switch (Name.getCXXOverloadedOperator()) {
12485   case OO_New: case OO_Array_New:
12486   case OO_Delete: case OO_Array_Delete:
12487     return false;
12488 
12489   default:
12490     return true;
12491   }
12492 }
12493 
12494 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12495 /// template, where the non-dependent name was declared after the template
12496 /// was defined. This is common in code written for a compilers which do not
12497 /// correctly implement two-stage name lookup.
12498 ///
12499 /// Returns true if a viable candidate was found and a diagnostic was issued.
12500 static bool
12501 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12502                        const CXXScopeSpec &SS, LookupResult &R,
12503                        OverloadCandidateSet::CandidateSetKind CSK,
12504                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12505                        ArrayRef<Expr *> Args,
12506                        bool *DoDiagnoseEmptyLookup = nullptr) {
12507   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12508     return false;
12509 
12510   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12511     if (DC->isTransparentContext())
12512       continue;
12513 
12514     SemaRef.LookupQualifiedName(R, DC);
12515 
12516     if (!R.empty()) {
12517       R.suppressDiagnostics();
12518 
12519       if (isa<CXXRecordDecl>(DC)) {
12520         // Don't diagnose names we find in classes; we get much better
12521         // diagnostics for these from DiagnoseEmptyLookup.
12522         R.clear();
12523         if (DoDiagnoseEmptyLookup)
12524           *DoDiagnoseEmptyLookup = true;
12525         return false;
12526       }
12527 
12528       OverloadCandidateSet Candidates(FnLoc, CSK);
12529       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12530         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12531                                    ExplicitTemplateArgs, Args,
12532                                    Candidates, false, /*KnownValid*/ false);
12533 
12534       OverloadCandidateSet::iterator Best;
12535       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12536         // No viable functions. Don't bother the user with notes for functions
12537         // which don't work and shouldn't be found anyway.
12538         R.clear();
12539         return false;
12540       }
12541 
12542       // Find the namespaces where ADL would have looked, and suggest
12543       // declaring the function there instead.
12544       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12545       Sema::AssociatedClassSet AssociatedClasses;
12546       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12547                                                  AssociatedNamespaces,
12548                                                  AssociatedClasses);
12549       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12550       if (canBeDeclaredInNamespace(R.getLookupName())) {
12551         DeclContext *Std = SemaRef.getStdNamespace();
12552         for (Sema::AssociatedNamespaceSet::iterator
12553                it = AssociatedNamespaces.begin(),
12554                end = AssociatedNamespaces.end(); it != end; ++it) {
12555           // Never suggest declaring a function within namespace 'std'.
12556           if (Std && Std->Encloses(*it))
12557             continue;
12558 
12559           // Never suggest declaring a function within a namespace with a
12560           // reserved name, like __gnu_cxx.
12561           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12562           if (NS &&
12563               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12564             continue;
12565 
12566           SuggestedNamespaces.insert(*it);
12567         }
12568       }
12569 
12570       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12571         << R.getLookupName();
12572       if (SuggestedNamespaces.empty()) {
12573         SemaRef.Diag(Best->Function->getLocation(),
12574                      diag::note_not_found_by_two_phase_lookup)
12575           << R.getLookupName() << 0;
12576       } else if (SuggestedNamespaces.size() == 1) {
12577         SemaRef.Diag(Best->Function->getLocation(),
12578                      diag::note_not_found_by_two_phase_lookup)
12579           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12580       } else {
12581         // FIXME: It would be useful to list the associated namespaces here,
12582         // but the diagnostics infrastructure doesn't provide a way to produce
12583         // a localized representation of a list of items.
12584         SemaRef.Diag(Best->Function->getLocation(),
12585                      diag::note_not_found_by_two_phase_lookup)
12586           << R.getLookupName() << 2;
12587       }
12588 
12589       // Try to recover by calling this function.
12590       return true;
12591     }
12592 
12593     R.clear();
12594   }
12595 
12596   return false;
12597 }
12598 
12599 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12600 /// template, where the non-dependent operator was declared after the template
12601 /// was defined.
12602 ///
12603 /// Returns true if a viable candidate was found and a diagnostic was issued.
12604 static bool
12605 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12606                                SourceLocation OpLoc,
12607                                ArrayRef<Expr *> Args) {
12608   DeclarationName OpName =
12609     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12610   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12611   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12612                                 OverloadCandidateSet::CSK_Operator,
12613                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12614 }
12615 
12616 namespace {
12617 class BuildRecoveryCallExprRAII {
12618   Sema &SemaRef;
12619 public:
12620   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12621     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12622     SemaRef.IsBuildingRecoveryCallExpr = true;
12623   }
12624 
12625   ~BuildRecoveryCallExprRAII() {
12626     SemaRef.IsBuildingRecoveryCallExpr = false;
12627   }
12628 };
12629 
12630 }
12631 
12632 /// Attempts to recover from a call where no functions were found.
12633 ///
12634 /// Returns true if new candidates were found.
12635 static ExprResult
12636 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12637                       UnresolvedLookupExpr *ULE,
12638                       SourceLocation LParenLoc,
12639                       MutableArrayRef<Expr *> Args,
12640                       SourceLocation RParenLoc,
12641                       bool EmptyLookup, bool AllowTypoCorrection) {
12642   // Do not try to recover if it is already building a recovery call.
12643   // This stops infinite loops for template instantiations like
12644   //
12645   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12646   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12647   //
12648   if (SemaRef.IsBuildingRecoveryCallExpr)
12649     return ExprError();
12650   BuildRecoveryCallExprRAII RCE(SemaRef);
12651 
12652   CXXScopeSpec SS;
12653   SS.Adopt(ULE->getQualifierLoc());
12654   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12655 
12656   TemplateArgumentListInfo TABuffer;
12657   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12658   if (ULE->hasExplicitTemplateArgs()) {
12659     ULE->copyTemplateArgumentsInto(TABuffer);
12660     ExplicitTemplateArgs = &TABuffer;
12661   }
12662 
12663   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12664                  Sema::LookupOrdinaryName);
12665   bool DoDiagnoseEmptyLookup = EmptyLookup;
12666   if (!DiagnoseTwoPhaseLookup(
12667           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12668           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12669     NoTypoCorrectionCCC NoTypoValidator{};
12670     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12671                                                 ExplicitTemplateArgs != nullptr,
12672                                                 dyn_cast<MemberExpr>(Fn));
12673     CorrectionCandidateCallback &Validator =
12674         AllowTypoCorrection
12675             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12676             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12677     if (!DoDiagnoseEmptyLookup ||
12678         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12679                                     Args))
12680       return ExprError();
12681   }
12682 
12683   assert(!R.empty() && "lookup results empty despite recovery");
12684 
12685   // If recovery created an ambiguity, just bail out.
12686   if (R.isAmbiguous()) {
12687     R.suppressDiagnostics();
12688     return ExprError();
12689   }
12690 
12691   // Build an implicit member call if appropriate.  Just drop the
12692   // casts and such from the call, we don't really care.
12693   ExprResult NewFn = ExprError();
12694   if ((*R.begin())->isCXXClassMember())
12695     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12696                                                     ExplicitTemplateArgs, S);
12697   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12698     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12699                                         ExplicitTemplateArgs);
12700   else
12701     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12702 
12703   if (NewFn.isInvalid())
12704     return ExprError();
12705 
12706   // This shouldn't cause an infinite loop because we're giving it
12707   // an expression with viable lookup results, which should never
12708   // end up here.
12709   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12710                                MultiExprArg(Args.data(), Args.size()),
12711                                RParenLoc);
12712 }
12713 
12714 /// Constructs and populates an OverloadedCandidateSet from
12715 /// the given function.
12716 /// \returns true when an the ExprResult output parameter has been set.
12717 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12718                                   UnresolvedLookupExpr *ULE,
12719                                   MultiExprArg Args,
12720                                   SourceLocation RParenLoc,
12721                                   OverloadCandidateSet *CandidateSet,
12722                                   ExprResult *Result) {
12723 #ifndef NDEBUG
12724   if (ULE->requiresADL()) {
12725     // To do ADL, we must have found an unqualified name.
12726     assert(!ULE->getQualifier() && "qualified name with ADL");
12727 
12728     // We don't perform ADL for implicit declarations of builtins.
12729     // Verify that this was correctly set up.
12730     FunctionDecl *F;
12731     if (ULE->decls_begin() != ULE->decls_end() &&
12732         ULE->decls_begin() + 1 == ULE->decls_end() &&
12733         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12734         F->getBuiltinID() && F->isImplicit())
12735       llvm_unreachable("performing ADL for builtin");
12736 
12737     // We don't perform ADL in C.
12738     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12739   }
12740 #endif
12741 
12742   UnbridgedCastsSet UnbridgedCasts;
12743   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12744     *Result = ExprError();
12745     return true;
12746   }
12747 
12748   // Add the functions denoted by the callee to the set of candidate
12749   // functions, including those from argument-dependent lookup.
12750   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12751 
12752   if (getLangOpts().MSVCCompat &&
12753       CurContext->isDependentContext() && !isSFINAEContext() &&
12754       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12755 
12756     OverloadCandidateSet::iterator Best;
12757     if (CandidateSet->empty() ||
12758         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12759             OR_No_Viable_Function) {
12760       // In Microsoft mode, if we are inside a template class member function
12761       // then create a type dependent CallExpr. The goal is to postpone name
12762       // lookup to instantiation time to be able to search into type dependent
12763       // base classes.
12764       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12765                                       VK_RValue, RParenLoc);
12766       CE->markDependentForPostponedNameLookup();
12767       *Result = CE;
12768       return true;
12769     }
12770   }
12771 
12772   if (CandidateSet->empty())
12773     return false;
12774 
12775   UnbridgedCasts.restore();
12776   return false;
12777 }
12778 
12779 // Guess at what the return type for an unresolvable overload should be.
12780 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
12781                                    OverloadCandidateSet::iterator *Best) {
12782   llvm::Optional<QualType> Result;
12783   // Adjust Type after seeing a candidate.
12784   auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
12785     if (!Candidate.Function)
12786       return;
12787     QualType T = Candidate.Function->getCallResultType();
12788     if (T.isNull())
12789       return;
12790     if (!Result)
12791       Result = T;
12792     else if (Result != T)
12793       Result = QualType();
12794   };
12795 
12796   // Look for an unambiguous type from a progressively larger subset.
12797   // e.g. if types disagree, but all *viable* overloads return int, choose int.
12798   //
12799   // First, consider only the best candidate.
12800   if (Best && *Best != CS.end())
12801     ConsiderCandidate(**Best);
12802   // Next, consider only viable candidates.
12803   if (!Result)
12804     for (const auto &C : CS)
12805       if (C.Viable)
12806         ConsiderCandidate(C);
12807   // Finally, consider all candidates.
12808   if (!Result)
12809     for (const auto &C : CS)
12810       ConsiderCandidate(C);
12811 
12812   return Result.getValueOr(QualType());
12813 }
12814 
12815 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12816 /// the completed call expression. If overload resolution fails, emits
12817 /// diagnostics and returns ExprError()
12818 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12819                                            UnresolvedLookupExpr *ULE,
12820                                            SourceLocation LParenLoc,
12821                                            MultiExprArg Args,
12822                                            SourceLocation RParenLoc,
12823                                            Expr *ExecConfig,
12824                                            OverloadCandidateSet *CandidateSet,
12825                                            OverloadCandidateSet::iterator *Best,
12826                                            OverloadingResult OverloadResult,
12827                                            bool AllowTypoCorrection) {
12828   if (CandidateSet->empty())
12829     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12830                                  RParenLoc, /*EmptyLookup=*/true,
12831                                  AllowTypoCorrection);
12832 
12833   switch (OverloadResult) {
12834   case OR_Success: {
12835     FunctionDecl *FDecl = (*Best)->Function;
12836     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12837     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12838       return ExprError();
12839     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12840     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12841                                          ExecConfig, /*IsExecConfig=*/false,
12842                                          (*Best)->IsADLCandidate);
12843   }
12844 
12845   case OR_No_Viable_Function: {
12846     // Try to recover by looking for viable functions which the user might
12847     // have meant to call.
12848     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12849                                                 Args, RParenLoc,
12850                                                 /*EmptyLookup=*/false,
12851                                                 AllowTypoCorrection);
12852     if (!Recovery.isInvalid())
12853       return Recovery;
12854 
12855     // If the user passes in a function that we can't take the address of, we
12856     // generally end up emitting really bad error messages. Here, we attempt to
12857     // emit better ones.
12858     for (const Expr *Arg : Args) {
12859       if (!Arg->getType()->isFunctionType())
12860         continue;
12861       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12862         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12863         if (FD &&
12864             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12865                                                        Arg->getExprLoc()))
12866           return ExprError();
12867       }
12868     }
12869 
12870     CandidateSet->NoteCandidates(
12871         PartialDiagnosticAt(
12872             Fn->getBeginLoc(),
12873             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12874                 << ULE->getName() << Fn->getSourceRange()),
12875         SemaRef, OCD_AllCandidates, Args);
12876     break;
12877   }
12878 
12879   case OR_Ambiguous:
12880     CandidateSet->NoteCandidates(
12881         PartialDiagnosticAt(Fn->getBeginLoc(),
12882                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12883                                 << ULE->getName() << Fn->getSourceRange()),
12884         SemaRef, OCD_AmbiguousCandidates, Args);
12885     break;
12886 
12887   case OR_Deleted: {
12888     CandidateSet->NoteCandidates(
12889         PartialDiagnosticAt(Fn->getBeginLoc(),
12890                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12891                                 << ULE->getName() << Fn->getSourceRange()),
12892         SemaRef, OCD_AllCandidates, Args);
12893 
12894     // We emitted an error for the unavailable/deleted function call but keep
12895     // the call in the AST.
12896     FunctionDecl *FDecl = (*Best)->Function;
12897     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12898     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12899                                          ExecConfig, /*IsExecConfig=*/false,
12900                                          (*Best)->IsADLCandidate);
12901   }
12902   }
12903 
12904   // Overload resolution failed, try to recover.
12905   SmallVector<Expr *, 8> SubExprs = {Fn};
12906   SubExprs.append(Args.begin(), Args.end());
12907   return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
12908                                     chooseRecoveryType(*CandidateSet, Best));
12909 }
12910 
12911 static void markUnaddressableCandidatesUnviable(Sema &S,
12912                                                 OverloadCandidateSet &CS) {
12913   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12914     if (I->Viable &&
12915         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12916       I->Viable = false;
12917       I->FailureKind = ovl_fail_addr_not_available;
12918     }
12919   }
12920 }
12921 
12922 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12923 /// (which eventually refers to the declaration Func) and the call
12924 /// arguments Args/NumArgs, attempt to resolve the function call down
12925 /// to a specific function. If overload resolution succeeds, returns
12926 /// the call expression produced by overload resolution.
12927 /// Otherwise, emits diagnostics and returns ExprError.
12928 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12929                                          UnresolvedLookupExpr *ULE,
12930                                          SourceLocation LParenLoc,
12931                                          MultiExprArg Args,
12932                                          SourceLocation RParenLoc,
12933                                          Expr *ExecConfig,
12934                                          bool AllowTypoCorrection,
12935                                          bool CalleesAddressIsTaken) {
12936   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12937                                     OverloadCandidateSet::CSK_Normal);
12938   ExprResult result;
12939 
12940   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12941                              &result))
12942     return result;
12943 
12944   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12945   // functions that aren't addressible are considered unviable.
12946   if (CalleesAddressIsTaken)
12947     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12948 
12949   OverloadCandidateSet::iterator Best;
12950   OverloadingResult OverloadResult =
12951       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12952 
12953   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12954                                   ExecConfig, &CandidateSet, &Best,
12955                                   OverloadResult, AllowTypoCorrection);
12956 }
12957 
12958 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12959   return Functions.size() > 1 ||
12960     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12961 }
12962 
12963 /// Create a unary operation that may resolve to an overloaded
12964 /// operator.
12965 ///
12966 /// \param OpLoc The location of the operator itself (e.g., '*').
12967 ///
12968 /// \param Opc The UnaryOperatorKind that describes this operator.
12969 ///
12970 /// \param Fns The set of non-member functions that will be
12971 /// considered by overload resolution. The caller needs to build this
12972 /// set based on the context using, e.g.,
12973 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12974 /// set should not contain any member functions; those will be added
12975 /// by CreateOverloadedUnaryOp().
12976 ///
12977 /// \param Input The input argument.
12978 ExprResult
12979 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12980                               const UnresolvedSetImpl &Fns,
12981                               Expr *Input, bool PerformADL) {
12982   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12983   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12984   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12985   // TODO: provide better source location info.
12986   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12987 
12988   if (checkPlaceholderForOverload(*this, Input))
12989     return ExprError();
12990 
12991   Expr *Args[2] = { Input, nullptr };
12992   unsigned NumArgs = 1;
12993 
12994   // For post-increment and post-decrement, add the implicit '0' as
12995   // the second argument, so that we know this is a post-increment or
12996   // post-decrement.
12997   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12998     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12999     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
13000                                      SourceLocation());
13001     NumArgs = 2;
13002   }
13003 
13004   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
13005 
13006   if (Input->isTypeDependent()) {
13007     if (Fns.empty())
13008       return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
13009                                    VK_RValue, OK_Ordinary, OpLoc, false,
13010                                    CurFPFeatures);
13011 
13012     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13013     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13014         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13015         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
13016     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
13017                                        Context.DependentTy, VK_RValue, OpLoc,
13018                                        CurFPFeatures);
13019   }
13020 
13021   // Build an empty overload set.
13022   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
13023 
13024   // Add the candidates from the given function set.
13025   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
13026 
13027   // Add operator candidates that are member functions.
13028   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13029 
13030   // Add candidates from ADL.
13031   if (PerformADL) {
13032     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
13033                                          /*ExplicitTemplateArgs*/nullptr,
13034                                          CandidateSet);
13035   }
13036 
13037   // Add builtin operator candidates.
13038   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
13039 
13040   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13041 
13042   // Perform overload resolution.
13043   OverloadCandidateSet::iterator Best;
13044   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13045   case OR_Success: {
13046     // We found a built-in operator or an overloaded operator.
13047     FunctionDecl *FnDecl = Best->Function;
13048 
13049     if (FnDecl) {
13050       Expr *Base = nullptr;
13051       // We matched an overloaded operator. Build a call to that
13052       // operator.
13053 
13054       // Convert the arguments.
13055       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13056         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
13057 
13058         ExprResult InputRes =
13059           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
13060                                               Best->FoundDecl, Method);
13061         if (InputRes.isInvalid())
13062           return ExprError();
13063         Base = Input = InputRes.get();
13064       } else {
13065         // Convert the arguments.
13066         ExprResult InputInit
13067           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13068                                                       Context,
13069                                                       FnDecl->getParamDecl(0)),
13070                                       SourceLocation(),
13071                                       Input);
13072         if (InputInit.isInvalid())
13073           return ExprError();
13074         Input = InputInit.get();
13075       }
13076 
13077       // Build the actual expression node.
13078       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
13079                                                 Base, HadMultipleCandidates,
13080                                                 OpLoc);
13081       if (FnExpr.isInvalid())
13082         return ExprError();
13083 
13084       // Determine the result type.
13085       QualType ResultTy = FnDecl->getReturnType();
13086       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13087       ResultTy = ResultTy.getNonLValueExprType(Context);
13088 
13089       Args[0] = Input;
13090       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13091           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13092           CurFPFeatures, Best->IsADLCandidate);
13093 
13094       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13095         return ExprError();
13096 
13097       if (CheckFunctionCall(FnDecl, TheCall,
13098                             FnDecl->getType()->castAs<FunctionProtoType>()))
13099         return ExprError();
13100       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13101     } else {
13102       // We matched a built-in operator. Convert the arguments, then
13103       // break out so that we will build the appropriate built-in
13104       // operator node.
13105       ExprResult InputRes = PerformImplicitConversion(
13106           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13107           CCK_ForBuiltinOverloadedOp);
13108       if (InputRes.isInvalid())
13109         return ExprError();
13110       Input = InputRes.get();
13111       break;
13112     }
13113   }
13114 
13115   case OR_No_Viable_Function:
13116     // This is an erroneous use of an operator which can be overloaded by
13117     // a non-member function. Check for non-member operators which were
13118     // defined too late to be candidates.
13119     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13120       // FIXME: Recover by calling the found function.
13121       return ExprError();
13122 
13123     // No viable function; fall through to handling this as a
13124     // built-in operator, which will produce an error message for us.
13125     break;
13126 
13127   case OR_Ambiguous:
13128     CandidateSet.NoteCandidates(
13129         PartialDiagnosticAt(OpLoc,
13130                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13131                                 << UnaryOperator::getOpcodeStr(Opc)
13132                                 << Input->getType() << Input->getSourceRange()),
13133         *this, OCD_AmbiguousCandidates, ArgsArray,
13134         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13135     return ExprError();
13136 
13137   case OR_Deleted:
13138     CandidateSet.NoteCandidates(
13139         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13140                                        << UnaryOperator::getOpcodeStr(Opc)
13141                                        << Input->getSourceRange()),
13142         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13143         OpLoc);
13144     return ExprError();
13145   }
13146 
13147   // Either we found no viable overloaded operator or we matched a
13148   // built-in operator. In either case, fall through to trying to
13149   // build a built-in operation.
13150   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13151 }
13152 
13153 /// Perform lookup for an overloaded binary operator.
13154 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13155                                  OverloadedOperatorKind Op,
13156                                  const UnresolvedSetImpl &Fns,
13157                                  ArrayRef<Expr *> Args, bool PerformADL) {
13158   SourceLocation OpLoc = CandidateSet.getLocation();
13159 
13160   OverloadedOperatorKind ExtraOp =
13161       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13162           ? getRewrittenOverloadedOperator(Op)
13163           : OO_None;
13164 
13165   // Add the candidates from the given function set. This also adds the
13166   // rewritten candidates using these functions if necessary.
13167   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13168 
13169   // Add operator candidates that are member functions.
13170   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13171   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13172     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13173                                 OverloadCandidateParamOrder::Reversed);
13174 
13175   // In C++20, also add any rewritten member candidates.
13176   if (ExtraOp) {
13177     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13178     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13179       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13180                                   CandidateSet,
13181                                   OverloadCandidateParamOrder::Reversed);
13182   }
13183 
13184   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13185   // performed for an assignment operator (nor for operator[] nor operator->,
13186   // which don't get here).
13187   if (Op != OO_Equal && PerformADL) {
13188     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13189     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13190                                          /*ExplicitTemplateArgs*/ nullptr,
13191                                          CandidateSet);
13192     if (ExtraOp) {
13193       DeclarationName ExtraOpName =
13194           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13195       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13196                                            /*ExplicitTemplateArgs*/ nullptr,
13197                                            CandidateSet);
13198     }
13199   }
13200 
13201   // Add builtin operator candidates.
13202   //
13203   // FIXME: We don't add any rewritten candidates here. This is strictly
13204   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13205   // resulting in our selecting a rewritten builtin candidate. For example:
13206   //
13207   //   enum class E { e };
13208   //   bool operator!=(E, E) requires false;
13209   //   bool k = E::e != E::e;
13210   //
13211   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13212   // it seems unreasonable to consider rewritten builtin candidates. A core
13213   // issue has been filed proposing to removed this requirement.
13214   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13215 }
13216 
13217 /// Create a binary operation that may resolve to an overloaded
13218 /// operator.
13219 ///
13220 /// \param OpLoc The location of the operator itself (e.g., '+').
13221 ///
13222 /// \param Opc The BinaryOperatorKind that describes this operator.
13223 ///
13224 /// \param Fns The set of non-member functions that will be
13225 /// considered by overload resolution. The caller needs to build this
13226 /// set based on the context using, e.g.,
13227 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13228 /// set should not contain any member functions; those will be added
13229 /// by CreateOverloadedBinOp().
13230 ///
13231 /// \param LHS Left-hand argument.
13232 /// \param RHS Right-hand argument.
13233 /// \param PerformADL Whether to consider operator candidates found by ADL.
13234 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13235 ///        C++20 operator rewrites.
13236 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13237 ///        the function in question. Such a function is never a candidate in
13238 ///        our overload resolution. This also enables synthesizing a three-way
13239 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13240 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13241                                        BinaryOperatorKind Opc,
13242                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13243                                        Expr *RHS, bool PerformADL,
13244                                        bool AllowRewrittenCandidates,
13245                                        FunctionDecl *DefaultedFn) {
13246   Expr *Args[2] = { LHS, RHS };
13247   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13248 
13249   if (!getLangOpts().CPlusPlus20)
13250     AllowRewrittenCandidates = false;
13251 
13252   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13253 
13254   // If either side is type-dependent, create an appropriate dependent
13255   // expression.
13256   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13257     if (Fns.empty()) {
13258       // If there are no functions to store, just build a dependent
13259       // BinaryOperator or CompoundAssignment.
13260       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13261         return BinaryOperator::Create(Context, Args[0], Args[1], Opc,
13262                                       Context.DependentTy, VK_RValue,
13263                                       OK_Ordinary, OpLoc, CurFPFeatures);
13264       return CompoundAssignOperator::Create(
13265           Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
13266           OK_Ordinary, OpLoc, CurFPFeatures, Context.DependentTy,
13267           Context.DependentTy);
13268     }
13269 
13270     // FIXME: save results of ADL from here?
13271     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13272     // TODO: provide better source location info in DNLoc component.
13273     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13274     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13275     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13276         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13277         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13278     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13279                                        Context.DependentTy, VK_RValue, OpLoc,
13280                                        CurFPFeatures);
13281   }
13282 
13283   // Always do placeholder-like conversions on the RHS.
13284   if (checkPlaceholderForOverload(*this, Args[1]))
13285     return ExprError();
13286 
13287   // Do placeholder-like conversion on the LHS; note that we should
13288   // not get here with a PseudoObject LHS.
13289   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13290   if (checkPlaceholderForOverload(*this, Args[0]))
13291     return ExprError();
13292 
13293   // If this is the assignment operator, we only perform overload resolution
13294   // if the left-hand side is a class or enumeration type. This is actually
13295   // a hack. The standard requires that we do overload resolution between the
13296   // various built-in candidates, but as DR507 points out, this can lead to
13297   // problems. So we do it this way, which pretty much follows what GCC does.
13298   // Note that we go the traditional code path for compound assignment forms.
13299   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13300     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13301 
13302   // If this is the .* operator, which is not overloadable, just
13303   // create a built-in binary operator.
13304   if (Opc == BO_PtrMemD)
13305     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13306 
13307   // Build the overload set.
13308   OverloadCandidateSet CandidateSet(
13309       OpLoc, OverloadCandidateSet::CSK_Operator,
13310       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13311   if (DefaultedFn)
13312     CandidateSet.exclude(DefaultedFn);
13313   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13314 
13315   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13316 
13317   // Perform overload resolution.
13318   OverloadCandidateSet::iterator Best;
13319   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13320     case OR_Success: {
13321       // We found a built-in operator or an overloaded operator.
13322       FunctionDecl *FnDecl = Best->Function;
13323 
13324       bool IsReversed = Best->isReversed();
13325       if (IsReversed)
13326         std::swap(Args[0], Args[1]);
13327 
13328       if (FnDecl) {
13329         Expr *Base = nullptr;
13330         // We matched an overloaded operator. Build a call to that
13331         // operator.
13332 
13333         OverloadedOperatorKind ChosenOp =
13334             FnDecl->getDeclName().getCXXOverloadedOperator();
13335 
13336         // C++2a [over.match.oper]p9:
13337         //   If a rewritten operator== candidate is selected by overload
13338         //   resolution for an operator@, its return type shall be cv bool
13339         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13340             !FnDecl->getReturnType()->isBooleanType()) {
13341           bool IsExtension =
13342               FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
13343           Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
13344                                   : diag::err_ovl_rewrite_equalequal_not_bool)
13345               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13346               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13347           Diag(FnDecl->getLocation(), diag::note_declared_at);
13348           if (!IsExtension)
13349             return ExprError();
13350         }
13351 
13352         if (AllowRewrittenCandidates && !IsReversed &&
13353             CandidateSet.getRewriteInfo().isReversible()) {
13354           // We could have reversed this operator, but didn't. Check if some
13355           // reversed form was a viable candidate, and if so, if it had a
13356           // better conversion for either parameter. If so, this call is
13357           // formally ambiguous, and allowing it is an extension.
13358           llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
13359           for (OverloadCandidate &Cand : CandidateSet) {
13360             if (Cand.Viable && Cand.Function && Cand.isReversed() &&
13361                 haveSameParameterTypes(Context, Cand.Function, FnDecl, 2)) {
13362               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13363                 if (CompareImplicitConversionSequences(
13364                         *this, OpLoc, Cand.Conversions[ArgIdx],
13365                         Best->Conversions[ArgIdx]) ==
13366                     ImplicitConversionSequence::Better) {
13367                   AmbiguousWith.push_back(Cand.Function);
13368                   break;
13369                 }
13370               }
13371             }
13372           }
13373 
13374           if (!AmbiguousWith.empty()) {
13375             bool AmbiguousWithSelf =
13376                 AmbiguousWith.size() == 1 &&
13377                 declaresSameEntity(AmbiguousWith.front(), FnDecl);
13378             Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13379                 << BinaryOperator::getOpcodeStr(Opc)
13380                 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
13381                 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13382             if (AmbiguousWithSelf) {
13383               Diag(FnDecl->getLocation(),
13384                    diag::note_ovl_ambiguous_oper_binary_reversed_self);
13385             } else {
13386               Diag(FnDecl->getLocation(),
13387                    diag::note_ovl_ambiguous_oper_binary_selected_candidate);
13388               for (auto *F : AmbiguousWith)
13389                 Diag(F->getLocation(),
13390                      diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13391             }
13392           }
13393         }
13394 
13395         // Convert the arguments.
13396         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13397           // Best->Access is only meaningful for class members.
13398           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13399 
13400           ExprResult Arg1 =
13401             PerformCopyInitialization(
13402               InitializedEntity::InitializeParameter(Context,
13403                                                      FnDecl->getParamDecl(0)),
13404               SourceLocation(), Args[1]);
13405           if (Arg1.isInvalid())
13406             return ExprError();
13407 
13408           ExprResult Arg0 =
13409             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13410                                                 Best->FoundDecl, Method);
13411           if (Arg0.isInvalid())
13412             return ExprError();
13413           Base = Args[0] = Arg0.getAs<Expr>();
13414           Args[1] = RHS = Arg1.getAs<Expr>();
13415         } else {
13416           // Convert the arguments.
13417           ExprResult Arg0 = PerformCopyInitialization(
13418             InitializedEntity::InitializeParameter(Context,
13419                                                    FnDecl->getParamDecl(0)),
13420             SourceLocation(), Args[0]);
13421           if (Arg0.isInvalid())
13422             return ExprError();
13423 
13424           ExprResult Arg1 =
13425             PerformCopyInitialization(
13426               InitializedEntity::InitializeParameter(Context,
13427                                                      FnDecl->getParamDecl(1)),
13428               SourceLocation(), Args[1]);
13429           if (Arg1.isInvalid())
13430             return ExprError();
13431           Args[0] = LHS = Arg0.getAs<Expr>();
13432           Args[1] = RHS = Arg1.getAs<Expr>();
13433         }
13434 
13435         // Build the actual expression node.
13436         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13437                                                   Best->FoundDecl, Base,
13438                                                   HadMultipleCandidates, OpLoc);
13439         if (FnExpr.isInvalid())
13440           return ExprError();
13441 
13442         // Determine the result type.
13443         QualType ResultTy = FnDecl->getReturnType();
13444         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13445         ResultTy = ResultTy.getNonLValueExprType(Context);
13446 
13447         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13448             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13449             CurFPFeatures, Best->IsADLCandidate);
13450 
13451         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13452                                 FnDecl))
13453           return ExprError();
13454 
13455         ArrayRef<const Expr *> ArgsArray(Args, 2);
13456         const Expr *ImplicitThis = nullptr;
13457         // Cut off the implicit 'this'.
13458         if (isa<CXXMethodDecl>(FnDecl)) {
13459           ImplicitThis = ArgsArray[0];
13460           ArgsArray = ArgsArray.slice(1);
13461         }
13462 
13463         // Check for a self move.
13464         if (Op == OO_Equal)
13465           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13466 
13467         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13468                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13469                   VariadicDoesNotApply);
13470 
13471         ExprResult R = MaybeBindToTemporary(TheCall);
13472         if (R.isInvalid())
13473           return ExprError();
13474 
13475         // For a rewritten candidate, we've already reversed the arguments
13476         // if needed. Perform the rest of the rewrite now.
13477         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13478             (Op == OO_Spaceship && IsReversed)) {
13479           if (Op == OO_ExclaimEqual) {
13480             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13481             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13482           } else {
13483             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13484             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13485             Expr *ZeroLiteral =
13486                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13487 
13488             Sema::CodeSynthesisContext Ctx;
13489             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13490             Ctx.Entity = FnDecl;
13491             pushCodeSynthesisContext(Ctx);
13492 
13493             R = CreateOverloadedBinOp(
13494                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13495                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13496                 /*AllowRewrittenCandidates=*/false);
13497 
13498             popCodeSynthesisContext();
13499           }
13500           if (R.isInvalid())
13501             return ExprError();
13502         } else {
13503           assert(ChosenOp == Op && "unexpected operator name");
13504         }
13505 
13506         // Make a note in the AST if we did any rewriting.
13507         if (Best->RewriteKind != CRK_None)
13508           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13509 
13510         return CheckForImmediateInvocation(R, FnDecl);
13511       } else {
13512         // We matched a built-in operator. Convert the arguments, then
13513         // break out so that we will build the appropriate built-in
13514         // operator node.
13515         ExprResult ArgsRes0 = PerformImplicitConversion(
13516             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13517             AA_Passing, CCK_ForBuiltinOverloadedOp);
13518         if (ArgsRes0.isInvalid())
13519           return ExprError();
13520         Args[0] = ArgsRes0.get();
13521 
13522         ExprResult ArgsRes1 = PerformImplicitConversion(
13523             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13524             AA_Passing, CCK_ForBuiltinOverloadedOp);
13525         if (ArgsRes1.isInvalid())
13526           return ExprError();
13527         Args[1] = ArgsRes1.get();
13528         break;
13529       }
13530     }
13531 
13532     case OR_No_Viable_Function: {
13533       // C++ [over.match.oper]p9:
13534       //   If the operator is the operator , [...] and there are no
13535       //   viable functions, then the operator is assumed to be the
13536       //   built-in operator and interpreted according to clause 5.
13537       if (Opc == BO_Comma)
13538         break;
13539 
13540       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13541       // compare result using '==' and '<'.
13542       if (DefaultedFn && Opc == BO_Cmp) {
13543         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13544                                                           Args[1], DefaultedFn);
13545         if (E.isInvalid() || E.isUsable())
13546           return E;
13547       }
13548 
13549       // For class as left operand for assignment or compound assignment
13550       // operator do not fall through to handling in built-in, but report that
13551       // no overloaded assignment operator found
13552       ExprResult Result = ExprError();
13553       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13554       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13555                                                    Args, OpLoc);
13556       if (Args[0]->getType()->isRecordType() &&
13557           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13558         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13559              << BinaryOperator::getOpcodeStr(Opc)
13560              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13561         if (Args[0]->getType()->isIncompleteType()) {
13562           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13563             << Args[0]->getType()
13564             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13565         }
13566       } else {
13567         // This is an erroneous use of an operator which can be overloaded by
13568         // a non-member function. Check for non-member operators which were
13569         // defined too late to be candidates.
13570         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13571           // FIXME: Recover by calling the found function.
13572           return ExprError();
13573 
13574         // No viable function; try to create a built-in operation, which will
13575         // produce an error. Then, show the non-viable candidates.
13576         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13577       }
13578       assert(Result.isInvalid() &&
13579              "C++ binary operator overloading is missing candidates!");
13580       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13581       return Result;
13582     }
13583 
13584     case OR_Ambiguous:
13585       CandidateSet.NoteCandidates(
13586           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13587                                          << BinaryOperator::getOpcodeStr(Opc)
13588                                          << Args[0]->getType()
13589                                          << Args[1]->getType()
13590                                          << Args[0]->getSourceRange()
13591                                          << Args[1]->getSourceRange()),
13592           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13593           OpLoc);
13594       return ExprError();
13595 
13596     case OR_Deleted:
13597       if (isImplicitlyDeleted(Best->Function)) {
13598         FunctionDecl *DeletedFD = Best->Function;
13599         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13600         if (DFK.isSpecialMember()) {
13601           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13602             << Args[0]->getType() << DFK.asSpecialMember();
13603         } else {
13604           assert(DFK.isComparison());
13605           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13606             << Args[0]->getType() << DeletedFD;
13607         }
13608 
13609         // The user probably meant to call this special member. Just
13610         // explain why it's deleted.
13611         NoteDeletedFunction(DeletedFD);
13612         return ExprError();
13613       }
13614       CandidateSet.NoteCandidates(
13615           PartialDiagnosticAt(
13616               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13617                          << getOperatorSpelling(Best->Function->getDeclName()
13618                                                     .getCXXOverloadedOperator())
13619                          << Args[0]->getSourceRange()
13620                          << Args[1]->getSourceRange()),
13621           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13622           OpLoc);
13623       return ExprError();
13624   }
13625 
13626   // We matched a built-in operator; build it.
13627   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13628 }
13629 
13630 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13631     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13632     FunctionDecl *DefaultedFn) {
13633   const ComparisonCategoryInfo *Info =
13634       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13635   // If we're not producing a known comparison category type, we can't
13636   // synthesize a three-way comparison. Let the caller diagnose this.
13637   if (!Info)
13638     return ExprResult((Expr*)nullptr);
13639 
13640   // If we ever want to perform this synthesis more generally, we will need to
13641   // apply the temporary materialization conversion to the operands.
13642   assert(LHS->isGLValue() && RHS->isGLValue() &&
13643          "cannot use prvalue expressions more than once");
13644   Expr *OrigLHS = LHS;
13645   Expr *OrigRHS = RHS;
13646 
13647   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13648   // each of them multiple times below.
13649   LHS = new (Context)
13650       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13651                       LHS->getObjectKind(), LHS);
13652   RHS = new (Context)
13653       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13654                       RHS->getObjectKind(), RHS);
13655 
13656   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13657                                         DefaultedFn);
13658   if (Eq.isInvalid())
13659     return ExprError();
13660 
13661   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13662                                           true, DefaultedFn);
13663   if (Less.isInvalid())
13664     return ExprError();
13665 
13666   ExprResult Greater;
13667   if (Info->isPartial()) {
13668     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13669                                     DefaultedFn);
13670     if (Greater.isInvalid())
13671       return ExprError();
13672   }
13673 
13674   // Form the list of comparisons we're going to perform.
13675   struct Comparison {
13676     ExprResult Cmp;
13677     ComparisonCategoryResult Result;
13678   } Comparisons[4] =
13679   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13680                           : ComparisonCategoryResult::Equivalent},
13681     {Less, ComparisonCategoryResult::Less},
13682     {Greater, ComparisonCategoryResult::Greater},
13683     {ExprResult(), ComparisonCategoryResult::Unordered},
13684   };
13685 
13686   int I = Info->isPartial() ? 3 : 2;
13687 
13688   // Combine the comparisons with suitable conditional expressions.
13689   ExprResult Result;
13690   for (; I >= 0; --I) {
13691     // Build a reference to the comparison category constant.
13692     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13693     // FIXME: Missing a constant for a comparison category. Diagnose this?
13694     if (!VI)
13695       return ExprResult((Expr*)nullptr);
13696     ExprResult ThisResult =
13697         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13698     if (ThisResult.isInvalid())
13699       return ExprError();
13700 
13701     // Build a conditional unless this is the final case.
13702     if (Result.get()) {
13703       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13704                                   ThisResult.get(), Result.get());
13705       if (Result.isInvalid())
13706         return ExprError();
13707     } else {
13708       Result = ThisResult;
13709     }
13710   }
13711 
13712   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13713   // bind the OpaqueValueExprs before they're (repeatedly) used.
13714   Expr *SyntacticForm = BinaryOperator::Create(
13715       Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13716       Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
13717       CurFPFeatures);
13718   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13719   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13720 }
13721 
13722 ExprResult
13723 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13724                                          SourceLocation RLoc,
13725                                          Expr *Base, Expr *Idx) {
13726   Expr *Args[2] = { Base, Idx };
13727   DeclarationName OpName =
13728       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13729 
13730   // If either side is type-dependent, create an appropriate dependent
13731   // expression.
13732   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13733 
13734     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13735     // CHECKME: no 'operator' keyword?
13736     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13737     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13738     UnresolvedLookupExpr *Fn
13739       = UnresolvedLookupExpr::Create(Context, NamingClass,
13740                                      NestedNameSpecifierLoc(), OpNameInfo,
13741                                      /*ADL*/ true, /*Overloaded*/ false,
13742                                      UnresolvedSetIterator(),
13743                                      UnresolvedSetIterator());
13744     // Can't add any actual overloads yet
13745 
13746     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13747                                        Context.DependentTy, VK_RValue, RLoc,
13748                                        CurFPFeatures);
13749   }
13750 
13751   // Handle placeholders on both operands.
13752   if (checkPlaceholderForOverload(*this, Args[0]))
13753     return ExprError();
13754   if (checkPlaceholderForOverload(*this, Args[1]))
13755     return ExprError();
13756 
13757   // Build an empty overload set.
13758   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13759 
13760   // Subscript can only be overloaded as a member function.
13761 
13762   // Add operator candidates that are member functions.
13763   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13764 
13765   // Add builtin operator candidates.
13766   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13767 
13768   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13769 
13770   // Perform overload resolution.
13771   OverloadCandidateSet::iterator Best;
13772   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13773     case OR_Success: {
13774       // We found a built-in operator or an overloaded operator.
13775       FunctionDecl *FnDecl = Best->Function;
13776 
13777       if (FnDecl) {
13778         // We matched an overloaded operator. Build a call to that
13779         // operator.
13780 
13781         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13782 
13783         // Convert the arguments.
13784         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13785         ExprResult Arg0 =
13786           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13787                                               Best->FoundDecl, Method);
13788         if (Arg0.isInvalid())
13789           return ExprError();
13790         Args[0] = Arg0.get();
13791 
13792         // Convert the arguments.
13793         ExprResult InputInit
13794           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13795                                                       Context,
13796                                                       FnDecl->getParamDecl(0)),
13797                                       SourceLocation(),
13798                                       Args[1]);
13799         if (InputInit.isInvalid())
13800           return ExprError();
13801 
13802         Args[1] = InputInit.getAs<Expr>();
13803 
13804         // Build the actual expression node.
13805         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13806         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13807         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13808                                                   Best->FoundDecl,
13809                                                   Base,
13810                                                   HadMultipleCandidates,
13811                                                   OpLocInfo.getLoc(),
13812                                                   OpLocInfo.getInfo());
13813         if (FnExpr.isInvalid())
13814           return ExprError();
13815 
13816         // Determine the result type
13817         QualType ResultTy = FnDecl->getReturnType();
13818         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13819         ResultTy = ResultTy.getNonLValueExprType(Context);
13820 
13821         CXXOperatorCallExpr *TheCall =
13822             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13823                                         Args, ResultTy, VK, RLoc, CurFPFeatures);
13824         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13825           return ExprError();
13826 
13827         if (CheckFunctionCall(Method, TheCall,
13828                               Method->getType()->castAs<FunctionProtoType>()))
13829           return ExprError();
13830 
13831         return MaybeBindToTemporary(TheCall);
13832       } else {
13833         // We matched a built-in operator. Convert the arguments, then
13834         // break out so that we will build the appropriate built-in
13835         // operator node.
13836         ExprResult ArgsRes0 = PerformImplicitConversion(
13837             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13838             AA_Passing, CCK_ForBuiltinOverloadedOp);
13839         if (ArgsRes0.isInvalid())
13840           return ExprError();
13841         Args[0] = ArgsRes0.get();
13842 
13843         ExprResult ArgsRes1 = PerformImplicitConversion(
13844             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13845             AA_Passing, CCK_ForBuiltinOverloadedOp);
13846         if (ArgsRes1.isInvalid())
13847           return ExprError();
13848         Args[1] = ArgsRes1.get();
13849 
13850         break;
13851       }
13852     }
13853 
13854     case OR_No_Viable_Function: {
13855       PartialDiagnostic PD = CandidateSet.empty()
13856           ? (PDiag(diag::err_ovl_no_oper)
13857              << Args[0]->getType() << /*subscript*/ 0
13858              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13859           : (PDiag(diag::err_ovl_no_viable_subscript)
13860              << Args[0]->getType() << Args[0]->getSourceRange()
13861              << Args[1]->getSourceRange());
13862       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13863                                   OCD_AllCandidates, Args, "[]", LLoc);
13864       return ExprError();
13865     }
13866 
13867     case OR_Ambiguous:
13868       CandidateSet.NoteCandidates(
13869           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13870                                         << "[]" << Args[0]->getType()
13871                                         << Args[1]->getType()
13872                                         << Args[0]->getSourceRange()
13873                                         << Args[1]->getSourceRange()),
13874           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13875       return ExprError();
13876 
13877     case OR_Deleted:
13878       CandidateSet.NoteCandidates(
13879           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13880                                         << "[]" << Args[0]->getSourceRange()
13881                                         << Args[1]->getSourceRange()),
13882           *this, OCD_AllCandidates, Args, "[]", LLoc);
13883       return ExprError();
13884     }
13885 
13886   // We matched a built-in operator; build it.
13887   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13888 }
13889 
13890 /// BuildCallToMemberFunction - Build a call to a member
13891 /// function. MemExpr is the expression that refers to the member
13892 /// function (and includes the object parameter), Args/NumArgs are the
13893 /// arguments to the function call (not including the object
13894 /// parameter). The caller needs to validate that the member
13895 /// expression refers to a non-static member function or an overloaded
13896 /// member function.
13897 ExprResult
13898 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13899                                 SourceLocation LParenLoc,
13900                                 MultiExprArg Args,
13901                                 SourceLocation RParenLoc) {
13902   assert(MemExprE->getType() == Context.BoundMemberTy ||
13903          MemExprE->getType() == Context.OverloadTy);
13904 
13905   // Dig out the member expression. This holds both the object
13906   // argument and the member function we're referring to.
13907   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13908 
13909   // Determine whether this is a call to a pointer-to-member function.
13910   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13911     assert(op->getType() == Context.BoundMemberTy);
13912     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13913 
13914     QualType fnType =
13915       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13916 
13917     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13918     QualType resultType = proto->getCallResultType(Context);
13919     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13920 
13921     // Check that the object type isn't more qualified than the
13922     // member function we're calling.
13923     Qualifiers funcQuals = proto->getMethodQuals();
13924 
13925     QualType objectType = op->getLHS()->getType();
13926     if (op->getOpcode() == BO_PtrMemI)
13927       objectType = objectType->castAs<PointerType>()->getPointeeType();
13928     Qualifiers objectQuals = objectType.getQualifiers();
13929 
13930     Qualifiers difference = objectQuals - funcQuals;
13931     difference.removeObjCGCAttr();
13932     difference.removeAddressSpace();
13933     if (difference) {
13934       std::string qualsString = difference.getAsString();
13935       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13936         << fnType.getUnqualifiedType()
13937         << qualsString
13938         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13939     }
13940 
13941     CXXMemberCallExpr *call =
13942         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13943                                   valueKind, RParenLoc, proto->getNumParams());
13944 
13945     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13946                             call, nullptr))
13947       return ExprError();
13948 
13949     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13950       return ExprError();
13951 
13952     if (CheckOtherCall(call, proto))
13953       return ExprError();
13954 
13955     return MaybeBindToTemporary(call);
13956   }
13957 
13958   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13959     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13960                             RParenLoc);
13961 
13962   UnbridgedCastsSet UnbridgedCasts;
13963   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13964     return ExprError();
13965 
13966   MemberExpr *MemExpr;
13967   CXXMethodDecl *Method = nullptr;
13968   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13969   NestedNameSpecifier *Qualifier = nullptr;
13970   if (isa<MemberExpr>(NakedMemExpr)) {
13971     MemExpr = cast<MemberExpr>(NakedMemExpr);
13972     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13973     FoundDecl = MemExpr->getFoundDecl();
13974     Qualifier = MemExpr->getQualifier();
13975     UnbridgedCasts.restore();
13976   } else {
13977     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13978     Qualifier = UnresExpr->getQualifier();
13979 
13980     QualType ObjectType = UnresExpr->getBaseType();
13981     Expr::Classification ObjectClassification
13982       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13983                             : UnresExpr->getBase()->Classify(Context);
13984 
13985     // Add overload candidates
13986     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13987                                       OverloadCandidateSet::CSK_Normal);
13988 
13989     // FIXME: avoid copy.
13990     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13991     if (UnresExpr->hasExplicitTemplateArgs()) {
13992       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13993       TemplateArgs = &TemplateArgsBuffer;
13994     }
13995 
13996     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13997            E = UnresExpr->decls_end(); I != E; ++I) {
13998 
13999       NamedDecl *Func = *I;
14000       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
14001       if (isa<UsingShadowDecl>(Func))
14002         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
14003 
14004 
14005       // Microsoft supports direct constructor calls.
14006       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
14007         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
14008                              CandidateSet,
14009                              /*SuppressUserConversions*/ false);
14010       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
14011         // If explicit template arguments were provided, we can't call a
14012         // non-template member function.
14013         if (TemplateArgs)
14014           continue;
14015 
14016         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
14017                            ObjectClassification, Args, CandidateSet,
14018                            /*SuppressUserConversions=*/false);
14019       } else {
14020         AddMethodTemplateCandidate(
14021             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
14022             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
14023             /*SuppressUserConversions=*/false);
14024       }
14025     }
14026 
14027     DeclarationName DeclName = UnresExpr->getMemberName();
14028 
14029     UnbridgedCasts.restore();
14030 
14031     OverloadCandidateSet::iterator Best;
14032     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
14033                                             Best)) {
14034     case OR_Success:
14035       Method = cast<CXXMethodDecl>(Best->Function);
14036       FoundDecl = Best->FoundDecl;
14037       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
14038       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
14039         return ExprError();
14040       // If FoundDecl is different from Method (such as if one is a template
14041       // and the other a specialization), make sure DiagnoseUseOfDecl is
14042       // called on both.
14043       // FIXME: This would be more comprehensively addressed by modifying
14044       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
14045       // being used.
14046       if (Method != FoundDecl.getDecl() &&
14047                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
14048         return ExprError();
14049       break;
14050 
14051     case OR_No_Viable_Function:
14052       CandidateSet.NoteCandidates(
14053           PartialDiagnosticAt(
14054               UnresExpr->getMemberLoc(),
14055               PDiag(diag::err_ovl_no_viable_member_function_in_call)
14056                   << DeclName << MemExprE->getSourceRange()),
14057           *this, OCD_AllCandidates, Args);
14058       // FIXME: Leaking incoming expressions!
14059       return ExprError();
14060 
14061     case OR_Ambiguous:
14062       CandidateSet.NoteCandidates(
14063           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14064                               PDiag(diag::err_ovl_ambiguous_member_call)
14065                                   << DeclName << MemExprE->getSourceRange()),
14066           *this, OCD_AmbiguousCandidates, Args);
14067       // FIXME: Leaking incoming expressions!
14068       return ExprError();
14069 
14070     case OR_Deleted:
14071       CandidateSet.NoteCandidates(
14072           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
14073                               PDiag(diag::err_ovl_deleted_member_call)
14074                                   << DeclName << MemExprE->getSourceRange()),
14075           *this, OCD_AllCandidates, Args);
14076       // FIXME: Leaking incoming expressions!
14077       return ExprError();
14078     }
14079 
14080     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
14081 
14082     // If overload resolution picked a static member, build a
14083     // non-member call based on that function.
14084     if (Method->isStatic()) {
14085       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
14086                                    RParenLoc);
14087     }
14088 
14089     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
14090   }
14091 
14092   QualType ResultType = Method->getReturnType();
14093   ExprValueKind VK = Expr::getValueKindForType(ResultType);
14094   ResultType = ResultType.getNonLValueExprType(Context);
14095 
14096   assert(Method && "Member call to something that isn't a method?");
14097   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14098   CXXMemberCallExpr *TheCall =
14099       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
14100                                 RParenLoc, Proto->getNumParams());
14101 
14102   // Check for a valid return type.
14103   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
14104                           TheCall, Method))
14105     return ExprError();
14106 
14107   // Convert the object argument (for a non-static member function call).
14108   // We only need to do this if there was actually an overload; otherwise
14109   // it was done at lookup.
14110   if (!Method->isStatic()) {
14111     ExprResult ObjectArg =
14112       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14113                                           FoundDecl, Method);
14114     if (ObjectArg.isInvalid())
14115       return ExprError();
14116     MemExpr->setBase(ObjectArg.get());
14117   }
14118 
14119   // Convert the rest of the arguments
14120   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14121                               RParenLoc))
14122     return ExprError();
14123 
14124   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14125 
14126   if (CheckFunctionCall(Method, TheCall, Proto))
14127     return ExprError();
14128 
14129   // In the case the method to call was not selected by the overloading
14130   // resolution process, we still need to handle the enable_if attribute. Do
14131   // that here, so it will not hide previous -- and more relevant -- errors.
14132   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14133     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14134       Diag(MemE->getMemberLoc(),
14135            diag::err_ovl_no_viable_member_function_in_call)
14136           << Method << Method->getSourceRange();
14137       Diag(Method->getLocation(),
14138            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14139           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14140       return ExprError();
14141     }
14142   }
14143 
14144   if ((isa<CXXConstructorDecl>(CurContext) ||
14145        isa<CXXDestructorDecl>(CurContext)) &&
14146       TheCall->getMethodDecl()->isPure()) {
14147     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14148 
14149     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14150         MemExpr->performsVirtualDispatch(getLangOpts())) {
14151       Diag(MemExpr->getBeginLoc(),
14152            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14153           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14154           << MD->getParent()->getDeclName();
14155 
14156       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14157       if (getLangOpts().AppleKext)
14158         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14159             << MD->getParent()->getDeclName() << MD->getDeclName();
14160     }
14161   }
14162 
14163   if (CXXDestructorDecl *DD =
14164           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14165     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14166     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14167     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14168                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14169                          MemExpr->getMemberLoc());
14170   }
14171 
14172   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14173                                      TheCall->getMethodDecl());
14174 }
14175 
14176 /// BuildCallToObjectOfClassType - Build a call to an object of class
14177 /// type (C++ [over.call.object]), which can end up invoking an
14178 /// overloaded function call operator (@c operator()) or performing a
14179 /// user-defined conversion on the object argument.
14180 ExprResult
14181 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14182                                    SourceLocation LParenLoc,
14183                                    MultiExprArg Args,
14184                                    SourceLocation RParenLoc) {
14185   if (checkPlaceholderForOverload(*this, Obj))
14186     return ExprError();
14187   ExprResult Object = Obj;
14188 
14189   UnbridgedCastsSet UnbridgedCasts;
14190   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14191     return ExprError();
14192 
14193   assert(Object.get()->getType()->isRecordType() &&
14194          "Requires object type argument");
14195 
14196   // C++ [over.call.object]p1:
14197   //  If the primary-expression E in the function call syntax
14198   //  evaluates to a class object of type "cv T", then the set of
14199   //  candidate functions includes at least the function call
14200   //  operators of T. The function call operators of T are obtained by
14201   //  ordinary lookup of the name operator() in the context of
14202   //  (E).operator().
14203   OverloadCandidateSet CandidateSet(LParenLoc,
14204                                     OverloadCandidateSet::CSK_Operator);
14205   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14206 
14207   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14208                           diag::err_incomplete_object_call, Object.get()))
14209     return true;
14210 
14211   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14212   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14213   LookupQualifiedName(R, Record->getDecl());
14214   R.suppressDiagnostics();
14215 
14216   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14217        Oper != OperEnd; ++Oper) {
14218     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14219                        Object.get()->Classify(Context), Args, CandidateSet,
14220                        /*SuppressUserConversion=*/false);
14221   }
14222 
14223   // C++ [over.call.object]p2:
14224   //   In addition, for each (non-explicit in C++0x) conversion function
14225   //   declared in T of the form
14226   //
14227   //        operator conversion-type-id () cv-qualifier;
14228   //
14229   //   where cv-qualifier is the same cv-qualification as, or a
14230   //   greater cv-qualification than, cv, and where conversion-type-id
14231   //   denotes the type "pointer to function of (P1,...,Pn) returning
14232   //   R", or the type "reference to pointer to function of
14233   //   (P1,...,Pn) returning R", or the type "reference to function
14234   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14235   //   is also considered as a candidate function. Similarly,
14236   //   surrogate call functions are added to the set of candidate
14237   //   functions for each conversion function declared in an
14238   //   accessible base class provided the function is not hidden
14239   //   within T by another intervening declaration.
14240   const auto &Conversions =
14241       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14242   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14243     NamedDecl *D = *I;
14244     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14245     if (isa<UsingShadowDecl>(D))
14246       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14247 
14248     // Skip over templated conversion functions; they aren't
14249     // surrogates.
14250     if (isa<FunctionTemplateDecl>(D))
14251       continue;
14252 
14253     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14254     if (!Conv->isExplicit()) {
14255       // Strip the reference type (if any) and then the pointer type (if
14256       // any) to get down to what might be a function type.
14257       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14258       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14259         ConvType = ConvPtrType->getPointeeType();
14260 
14261       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14262       {
14263         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14264                               Object.get(), Args, CandidateSet);
14265       }
14266     }
14267   }
14268 
14269   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14270 
14271   // Perform overload resolution.
14272   OverloadCandidateSet::iterator Best;
14273   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14274                                           Best)) {
14275   case OR_Success:
14276     // Overload resolution succeeded; we'll build the appropriate call
14277     // below.
14278     break;
14279 
14280   case OR_No_Viable_Function: {
14281     PartialDiagnostic PD =
14282         CandidateSet.empty()
14283             ? (PDiag(diag::err_ovl_no_oper)
14284                << Object.get()->getType() << /*call*/ 1
14285                << Object.get()->getSourceRange())
14286             : (PDiag(diag::err_ovl_no_viable_object_call)
14287                << Object.get()->getType() << Object.get()->getSourceRange());
14288     CandidateSet.NoteCandidates(
14289         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14290         OCD_AllCandidates, Args);
14291     break;
14292   }
14293   case OR_Ambiguous:
14294     CandidateSet.NoteCandidates(
14295         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14296                             PDiag(diag::err_ovl_ambiguous_object_call)
14297                                 << Object.get()->getType()
14298                                 << Object.get()->getSourceRange()),
14299         *this, OCD_AmbiguousCandidates, Args);
14300     break;
14301 
14302   case OR_Deleted:
14303     CandidateSet.NoteCandidates(
14304         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14305                             PDiag(diag::err_ovl_deleted_object_call)
14306                                 << Object.get()->getType()
14307                                 << Object.get()->getSourceRange()),
14308         *this, OCD_AllCandidates, Args);
14309     break;
14310   }
14311 
14312   if (Best == CandidateSet.end())
14313     return true;
14314 
14315   UnbridgedCasts.restore();
14316 
14317   if (Best->Function == nullptr) {
14318     // Since there is no function declaration, this is one of the
14319     // surrogate candidates. Dig out the conversion function.
14320     CXXConversionDecl *Conv
14321       = cast<CXXConversionDecl>(
14322                          Best->Conversions[0].UserDefined.ConversionFunction);
14323 
14324     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14325                               Best->FoundDecl);
14326     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14327       return ExprError();
14328     assert(Conv == Best->FoundDecl.getDecl() &&
14329              "Found Decl & conversion-to-functionptr should be same, right?!");
14330     // We selected one of the surrogate functions that converts the
14331     // object parameter to a function pointer. Perform the conversion
14332     // on the object argument, then let BuildCallExpr finish the job.
14333 
14334     // Create an implicit member expr to refer to the conversion operator.
14335     // and then call it.
14336     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14337                                              Conv, HadMultipleCandidates);
14338     if (Call.isInvalid())
14339       return ExprError();
14340     // Record usage of conversion in an implicit cast.
14341     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14342                                     CK_UserDefinedConversion, Call.get(),
14343                                     nullptr, VK_RValue);
14344 
14345     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14346   }
14347 
14348   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14349 
14350   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14351   // that calls this method, using Object for the implicit object
14352   // parameter and passing along the remaining arguments.
14353   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14354 
14355   // An error diagnostic has already been printed when parsing the declaration.
14356   if (Method->isInvalidDecl())
14357     return ExprError();
14358 
14359   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14360   unsigned NumParams = Proto->getNumParams();
14361 
14362   DeclarationNameInfo OpLocInfo(
14363                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14364   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14365   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14366                                            Obj, HadMultipleCandidates,
14367                                            OpLocInfo.getLoc(),
14368                                            OpLocInfo.getInfo());
14369   if (NewFn.isInvalid())
14370     return true;
14371 
14372   // The number of argument slots to allocate in the call. If we have default
14373   // arguments we need to allocate space for them as well. We additionally
14374   // need one more slot for the object parameter.
14375   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14376 
14377   // Build the full argument list for the method call (the implicit object
14378   // parameter is placed at the beginning of the list).
14379   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14380 
14381   bool IsError = false;
14382 
14383   // Initialize the implicit object parameter.
14384   ExprResult ObjRes =
14385     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14386                                         Best->FoundDecl, Method);
14387   if (ObjRes.isInvalid())
14388     IsError = true;
14389   else
14390     Object = ObjRes;
14391   MethodArgs[0] = Object.get();
14392 
14393   // Check the argument types.
14394   for (unsigned i = 0; i != NumParams; i++) {
14395     Expr *Arg;
14396     if (i < Args.size()) {
14397       Arg = Args[i];
14398 
14399       // Pass the argument.
14400 
14401       ExprResult InputInit
14402         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14403                                                     Context,
14404                                                     Method->getParamDecl(i)),
14405                                     SourceLocation(), Arg);
14406 
14407       IsError |= InputInit.isInvalid();
14408       Arg = InputInit.getAs<Expr>();
14409     } else {
14410       ExprResult DefArg
14411         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14412       if (DefArg.isInvalid()) {
14413         IsError = true;
14414         break;
14415       }
14416 
14417       Arg = DefArg.getAs<Expr>();
14418     }
14419 
14420     MethodArgs[i + 1] = Arg;
14421   }
14422 
14423   // If this is a variadic call, handle args passed through "...".
14424   if (Proto->isVariadic()) {
14425     // Promote the arguments (C99 6.5.2.2p7).
14426     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14427       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14428                                                         nullptr);
14429       IsError |= Arg.isInvalid();
14430       MethodArgs[i + 1] = Arg.get();
14431     }
14432   }
14433 
14434   if (IsError)
14435     return true;
14436 
14437   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14438 
14439   // Once we've built TheCall, all of the expressions are properly owned.
14440   QualType ResultTy = Method->getReturnType();
14441   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14442   ResultTy = ResultTy.getNonLValueExprType(Context);
14443 
14444   CXXOperatorCallExpr *TheCall =
14445       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14446                                   ResultTy, VK, RParenLoc, CurFPFeatures);
14447 
14448   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14449     return true;
14450 
14451   if (CheckFunctionCall(Method, TheCall, Proto))
14452     return true;
14453 
14454   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14455 }
14456 
14457 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14458 ///  (if one exists), where @c Base is an expression of class type and
14459 /// @c Member is the name of the member we're trying to find.
14460 ExprResult
14461 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14462                                bool *NoArrowOperatorFound) {
14463   assert(Base->getType()->isRecordType() &&
14464          "left-hand side must have class type");
14465 
14466   if (checkPlaceholderForOverload(*this, Base))
14467     return ExprError();
14468 
14469   SourceLocation Loc = Base->getExprLoc();
14470 
14471   // C++ [over.ref]p1:
14472   //
14473   //   [...] An expression x->m is interpreted as (x.operator->())->m
14474   //   for a class object x of type T if T::operator->() exists and if
14475   //   the operator is selected as the best match function by the
14476   //   overload resolution mechanism (13.3).
14477   DeclarationName OpName =
14478     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14479   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14480 
14481   if (RequireCompleteType(Loc, Base->getType(),
14482                           diag::err_typecheck_incomplete_tag, Base))
14483     return ExprError();
14484 
14485   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14486   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14487   R.suppressDiagnostics();
14488 
14489   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14490        Oper != OperEnd; ++Oper) {
14491     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14492                        None, CandidateSet, /*SuppressUserConversion=*/false);
14493   }
14494 
14495   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14496 
14497   // Perform overload resolution.
14498   OverloadCandidateSet::iterator Best;
14499   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14500   case OR_Success:
14501     // Overload resolution succeeded; we'll build the call below.
14502     break;
14503 
14504   case OR_No_Viable_Function: {
14505     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14506     if (CandidateSet.empty()) {
14507       QualType BaseType = Base->getType();
14508       if (NoArrowOperatorFound) {
14509         // Report this specific error to the caller instead of emitting a
14510         // diagnostic, as requested.
14511         *NoArrowOperatorFound = true;
14512         return ExprError();
14513       }
14514       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14515         << BaseType << Base->getSourceRange();
14516       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14517         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14518           << FixItHint::CreateReplacement(OpLoc, ".");
14519       }
14520     } else
14521       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14522         << "operator->" << Base->getSourceRange();
14523     CandidateSet.NoteCandidates(*this, Base, Cands);
14524     return ExprError();
14525   }
14526   case OR_Ambiguous:
14527     CandidateSet.NoteCandidates(
14528         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14529                                        << "->" << Base->getType()
14530                                        << Base->getSourceRange()),
14531         *this, OCD_AmbiguousCandidates, Base);
14532     return ExprError();
14533 
14534   case OR_Deleted:
14535     CandidateSet.NoteCandidates(
14536         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14537                                        << "->" << Base->getSourceRange()),
14538         *this, OCD_AllCandidates, Base);
14539     return ExprError();
14540   }
14541 
14542   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14543 
14544   // Convert the object parameter.
14545   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14546   ExprResult BaseResult =
14547     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14548                                         Best->FoundDecl, Method);
14549   if (BaseResult.isInvalid())
14550     return ExprError();
14551   Base = BaseResult.get();
14552 
14553   // Build the operator call.
14554   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14555                                             Base, HadMultipleCandidates, OpLoc);
14556   if (FnExpr.isInvalid())
14557     return ExprError();
14558 
14559   QualType ResultTy = Method->getReturnType();
14560   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14561   ResultTy = ResultTy.getNonLValueExprType(Context);
14562   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14563       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, CurFPFeatures);
14564 
14565   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14566     return ExprError();
14567 
14568   if (CheckFunctionCall(Method, TheCall,
14569                         Method->getType()->castAs<FunctionProtoType>()))
14570     return ExprError();
14571 
14572   return MaybeBindToTemporary(TheCall);
14573 }
14574 
14575 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14576 /// a literal operator described by the provided lookup results.
14577 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14578                                           DeclarationNameInfo &SuffixInfo,
14579                                           ArrayRef<Expr*> Args,
14580                                           SourceLocation LitEndLoc,
14581                                        TemplateArgumentListInfo *TemplateArgs) {
14582   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14583 
14584   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14585                                     OverloadCandidateSet::CSK_Normal);
14586   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14587                                  TemplateArgs);
14588 
14589   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14590 
14591   // Perform overload resolution. This will usually be trivial, but might need
14592   // to perform substitutions for a literal operator template.
14593   OverloadCandidateSet::iterator Best;
14594   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14595   case OR_Success:
14596   case OR_Deleted:
14597     break;
14598 
14599   case OR_No_Viable_Function:
14600     CandidateSet.NoteCandidates(
14601         PartialDiagnosticAt(UDSuffixLoc,
14602                             PDiag(diag::err_ovl_no_viable_function_in_call)
14603                                 << R.getLookupName()),
14604         *this, OCD_AllCandidates, Args);
14605     return ExprError();
14606 
14607   case OR_Ambiguous:
14608     CandidateSet.NoteCandidates(
14609         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14610                                                 << R.getLookupName()),
14611         *this, OCD_AmbiguousCandidates, Args);
14612     return ExprError();
14613   }
14614 
14615   FunctionDecl *FD = Best->Function;
14616   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14617                                         nullptr, HadMultipleCandidates,
14618                                         SuffixInfo.getLoc(),
14619                                         SuffixInfo.getInfo());
14620   if (Fn.isInvalid())
14621     return true;
14622 
14623   // Check the argument types. This should almost always be a no-op, except
14624   // that array-to-pointer decay is applied to string literals.
14625   Expr *ConvArgs[2];
14626   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14627     ExprResult InputInit = PerformCopyInitialization(
14628       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14629       SourceLocation(), Args[ArgIdx]);
14630     if (InputInit.isInvalid())
14631       return true;
14632     ConvArgs[ArgIdx] = InputInit.get();
14633   }
14634 
14635   QualType ResultTy = FD->getReturnType();
14636   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14637   ResultTy = ResultTy.getNonLValueExprType(Context);
14638 
14639   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14640       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14641       VK, LitEndLoc, UDSuffixLoc);
14642 
14643   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14644     return ExprError();
14645 
14646   if (CheckFunctionCall(FD, UDL, nullptr))
14647     return ExprError();
14648 
14649   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14650 }
14651 
14652 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14653 /// given LookupResult is non-empty, it is assumed to describe a member which
14654 /// will be invoked. Otherwise, the function will be found via argument
14655 /// dependent lookup.
14656 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14657 /// otherwise CallExpr is set to ExprError() and some non-success value
14658 /// is returned.
14659 Sema::ForRangeStatus
14660 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14661                                 SourceLocation RangeLoc,
14662                                 const DeclarationNameInfo &NameInfo,
14663                                 LookupResult &MemberLookup,
14664                                 OverloadCandidateSet *CandidateSet,
14665                                 Expr *Range, ExprResult *CallExpr) {
14666   Scope *S = nullptr;
14667 
14668   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14669   if (!MemberLookup.empty()) {
14670     ExprResult MemberRef =
14671         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14672                                  /*IsPtr=*/false, CXXScopeSpec(),
14673                                  /*TemplateKWLoc=*/SourceLocation(),
14674                                  /*FirstQualifierInScope=*/nullptr,
14675                                  MemberLookup,
14676                                  /*TemplateArgs=*/nullptr, S);
14677     if (MemberRef.isInvalid()) {
14678       *CallExpr = ExprError();
14679       return FRS_DiagnosticIssued;
14680     }
14681     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14682     if (CallExpr->isInvalid()) {
14683       *CallExpr = ExprError();
14684       return FRS_DiagnosticIssued;
14685     }
14686   } else {
14687     UnresolvedSet<0> FoundNames;
14688     UnresolvedLookupExpr *Fn =
14689       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14690                                    NestedNameSpecifierLoc(), NameInfo,
14691                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14692                                    FoundNames.begin(), FoundNames.end());
14693 
14694     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14695                                                     CandidateSet, CallExpr);
14696     if (CandidateSet->empty() || CandidateSetError) {
14697       *CallExpr = ExprError();
14698       return FRS_NoViableFunction;
14699     }
14700     OverloadCandidateSet::iterator Best;
14701     OverloadingResult OverloadResult =
14702         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14703 
14704     if (OverloadResult == OR_No_Viable_Function) {
14705       *CallExpr = ExprError();
14706       return FRS_NoViableFunction;
14707     }
14708     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14709                                          Loc, nullptr, CandidateSet, &Best,
14710                                          OverloadResult,
14711                                          /*AllowTypoCorrection=*/false);
14712     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14713       *CallExpr = ExprError();
14714       return FRS_DiagnosticIssued;
14715     }
14716   }
14717   return FRS_Success;
14718 }
14719 
14720 
14721 /// FixOverloadedFunctionReference - E is an expression that refers to
14722 /// a C++ overloaded function (possibly with some parentheses and
14723 /// perhaps a '&' around it). We have resolved the overloaded function
14724 /// to the function declaration Fn, so patch up the expression E to
14725 /// refer (possibly indirectly) to Fn. Returns the new expr.
14726 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14727                                            FunctionDecl *Fn) {
14728   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14729     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14730                                                    Found, Fn);
14731     if (SubExpr == PE->getSubExpr())
14732       return PE;
14733 
14734     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14735   }
14736 
14737   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14738     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14739                                                    Found, Fn);
14740     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14741                                SubExpr->getType()) &&
14742            "Implicit cast type cannot be determined from overload");
14743     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14744     if (SubExpr == ICE->getSubExpr())
14745       return ICE;
14746 
14747     return ImplicitCastExpr::Create(Context, ICE->getType(),
14748                                     ICE->getCastKind(),
14749                                     SubExpr, nullptr,
14750                                     ICE->getValueKind());
14751   }
14752 
14753   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14754     if (!GSE->isResultDependent()) {
14755       Expr *SubExpr =
14756           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14757       if (SubExpr == GSE->getResultExpr())
14758         return GSE;
14759 
14760       // Replace the resulting type information before rebuilding the generic
14761       // selection expression.
14762       ArrayRef<Expr *> A = GSE->getAssocExprs();
14763       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14764       unsigned ResultIdx = GSE->getResultIndex();
14765       AssocExprs[ResultIdx] = SubExpr;
14766 
14767       return GenericSelectionExpr::Create(
14768           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14769           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14770           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14771           ResultIdx);
14772     }
14773     // Rather than fall through to the unreachable, return the original generic
14774     // selection expression.
14775     return GSE;
14776   }
14777 
14778   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14779     assert(UnOp->getOpcode() == UO_AddrOf &&
14780            "Can only take the address of an overloaded function");
14781     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14782       if (Method->isStatic()) {
14783         // Do nothing: static member functions aren't any different
14784         // from non-member functions.
14785       } else {
14786         // Fix the subexpression, which really has to be an
14787         // UnresolvedLookupExpr holding an overloaded member function
14788         // or template.
14789         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14790                                                        Found, Fn);
14791         if (SubExpr == UnOp->getSubExpr())
14792           return UnOp;
14793 
14794         assert(isa<DeclRefExpr>(SubExpr)
14795                && "fixed to something other than a decl ref");
14796         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14797                && "fixed to a member ref with no nested name qualifier");
14798 
14799         // We have taken the address of a pointer to member
14800         // function. Perform the computation here so that we get the
14801         // appropriate pointer to member type.
14802         QualType ClassType
14803           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14804         QualType MemPtrType
14805           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14806         // Under the MS ABI, lock down the inheritance model now.
14807         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14808           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14809 
14810         return UnaryOperator::Create(
14811             Context, SubExpr, UO_AddrOf, MemPtrType, VK_RValue, OK_Ordinary,
14812             UnOp->getOperatorLoc(), false, CurFPFeatures);
14813       }
14814     }
14815     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14816                                                    Found, Fn);
14817     if (SubExpr == UnOp->getSubExpr())
14818       return UnOp;
14819 
14820     return UnaryOperator::Create(
14821         Context, SubExpr, UO_AddrOf, Context.getPointerType(SubExpr->getType()),
14822         VK_RValue, OK_Ordinary, UnOp->getOperatorLoc(), false, CurFPFeatures);
14823   }
14824 
14825   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14826     // FIXME: avoid copy.
14827     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14828     if (ULE->hasExplicitTemplateArgs()) {
14829       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14830       TemplateArgs = &TemplateArgsBuffer;
14831     }
14832 
14833     DeclRefExpr *DRE =
14834         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14835                          ULE->getQualifierLoc(), Found.getDecl(),
14836                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14837     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14838     return DRE;
14839   }
14840 
14841   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14842     // FIXME: avoid copy.
14843     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14844     if (MemExpr->hasExplicitTemplateArgs()) {
14845       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14846       TemplateArgs = &TemplateArgsBuffer;
14847     }
14848 
14849     Expr *Base;
14850 
14851     // If we're filling in a static method where we used to have an
14852     // implicit member access, rewrite to a simple decl ref.
14853     if (MemExpr->isImplicitAccess()) {
14854       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14855         DeclRefExpr *DRE = BuildDeclRefExpr(
14856             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14857             MemExpr->getQualifierLoc(), Found.getDecl(),
14858             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14859         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14860         return DRE;
14861       } else {
14862         SourceLocation Loc = MemExpr->getMemberLoc();
14863         if (MemExpr->getQualifier())
14864           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14865         Base =
14866             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14867       }
14868     } else
14869       Base = MemExpr->getBase();
14870 
14871     ExprValueKind valueKind;
14872     QualType type;
14873     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14874       valueKind = VK_LValue;
14875       type = Fn->getType();
14876     } else {
14877       valueKind = VK_RValue;
14878       type = Context.BoundMemberTy;
14879     }
14880 
14881     return BuildMemberExpr(
14882         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14883         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14884         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14885         type, valueKind, OK_Ordinary, TemplateArgs);
14886   }
14887 
14888   llvm_unreachable("Invalid reference to overloaded function");
14889 }
14890 
14891 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14892                                                 DeclAccessPair Found,
14893                                                 FunctionDecl *Fn) {
14894   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14895 }
14896