1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include <algorithm>
36 #include <cstdlib>
37 
38 using namespace clang;
39 using namespace sema;
40 
41 using AllowedExplicit = Sema::AllowedExplicit;
42 
43 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
44   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
45     return P->hasAttr<PassObjectSizeAttr>();
46   });
47 }
48 
49 /// A convenience routine for creating a decayed reference to a function.
50 static ExprResult
51 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
52                       const Expr *Base, bool HadMultipleCandidates,
53                       SourceLocation Loc = SourceLocation(),
54                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
55   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
56     return ExprError();
57   // If FoundDecl is different from Fn (such as if one is a template
58   // and the other a specialization), make sure DiagnoseUseOfDecl is
59   // called on both.
60   // FIXME: This would be more comprehensively addressed by modifying
61   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
62   // being used.
63   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
64     return ExprError();
65   DeclRefExpr *DRE = new (S.Context)
66       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67   if (HadMultipleCandidates)
68     DRE->setHadMultipleCandidates(true);
69 
70   S.MarkDeclRefReferenced(DRE, Base);
71   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
72     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
73       S.ResolveExceptionSpec(Loc, FPT);
74       DRE->setType(Fn->getType());
75     }
76   }
77   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
78                              CK_FunctionToPointerDecay);
79 }
80 
81 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
82                                  bool InOverloadResolution,
83                                  StandardConversionSequence &SCS,
84                                  bool CStyle,
85                                  bool AllowObjCWritebackConversion);
86 
87 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
88                                                  QualType &ToType,
89                                                  bool InOverloadResolution,
90                                                  StandardConversionSequence &SCS,
91                                                  bool CStyle);
92 static OverloadingResult
93 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
94                         UserDefinedConversionSequence& User,
95                         OverloadCandidateSet& Conversions,
96                         AllowedExplicit AllowExplicit,
97                         bool AllowObjCConversionOnExplicit);
98 
99 static ImplicitConversionSequence::CompareKind
100 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
101                                    const StandardConversionSequence& SCS1,
102                                    const StandardConversionSequence& SCS2);
103 
104 static ImplicitConversionSequence::CompareKind
105 CompareQualificationConversions(Sema &S,
106                                 const StandardConversionSequence& SCS1,
107                                 const StandardConversionSequence& SCS2);
108 
109 static ImplicitConversionSequence::CompareKind
110 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
111                                 const StandardConversionSequence& SCS1,
112                                 const StandardConversionSequence& SCS2);
113 
114 /// GetConversionRank - Retrieve the implicit conversion rank
115 /// corresponding to the given implicit conversion kind.
116 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
117   static const ImplicitConversionRank
118     Rank[(int)ICK_Num_Conversion_Kinds] = {
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Exact_Match,
125     ICR_Promotion,
126     ICR_Promotion,
127     ICR_Promotion,
128     ICR_Conversion,
129     ICR_Conversion,
130     ICR_Conversion,
131     ICR_Conversion,
132     ICR_Conversion,
133     ICR_Conversion,
134     ICR_Conversion,
135     ICR_Conversion,
136     ICR_Conversion,
137     ICR_Conversion,
138     ICR_OCL_Scalar_Widening,
139     ICR_Complex_Real_Conversion,
140     ICR_Conversion,
141     ICR_Conversion,
142     ICR_Writeback_Conversion,
143     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
144                      // it was omitted by the patch that added
145                      // ICK_Zero_Event_Conversion
146     ICR_C_Conversion,
147     ICR_C_Conversion_Extension
148   };
149   return Rank[(int)Kind];
150 }
151 
152 /// GetImplicitConversionName - Return the name of this kind of
153 /// implicit conversion.
154 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
155   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
156     "No conversion",
157     "Lvalue-to-rvalue",
158     "Array-to-pointer",
159     "Function-to-pointer",
160     "Function pointer conversion",
161     "Qualification",
162     "Integral promotion",
163     "Floating point promotion",
164     "Complex promotion",
165     "Integral conversion",
166     "Floating conversion",
167     "Complex conversion",
168     "Floating-integral conversion",
169     "Pointer conversion",
170     "Pointer-to-member conversion",
171     "Boolean conversion",
172     "Compatible-types conversion",
173     "Derived-to-base conversion",
174     "Vector conversion",
175     "Vector splat",
176     "Complex-real conversion",
177     "Block Pointer conversion",
178     "Transparent Union Conversion",
179     "Writeback conversion",
180     "OpenCL Zero Event Conversion",
181     "C specific type conversion",
182     "Incompatible pointer conversion"
183   };
184   return Name[Kind];
185 }
186 
187 /// StandardConversionSequence - Set the standard conversion
188 /// sequence to the identity conversion.
189 void StandardConversionSequence::setAsIdentityConversion() {
190   First = ICK_Identity;
191   Second = ICK_Identity;
192   Third = ICK_Identity;
193   DeprecatedStringLiteralToCharPtr = false;
194   QualificationIncludesObjCLifetime = false;
195   ReferenceBinding = false;
196   DirectBinding = false;
197   IsLvalueReference = true;
198   BindsToFunctionLvalue = false;
199   BindsToRvalue = false;
200   BindsImplicitObjectArgumentWithoutRefQualifier = false;
201   ObjCLifetimeConversionBinding = false;
202   CopyConstructor = nullptr;
203 }
204 
205 /// getRank - Retrieve the rank of this standard conversion sequence
206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
207 /// implicit conversions.
208 ImplicitConversionRank StandardConversionSequence::getRank() const {
209   ImplicitConversionRank Rank = ICR_Exact_Match;
210   if  (GetConversionRank(First) > Rank)
211     Rank = GetConversionRank(First);
212   if  (GetConversionRank(Second) > Rank)
213     Rank = GetConversionRank(Second);
214   if  (GetConversionRank(Third) > Rank)
215     Rank = GetConversionRank(Third);
216   return Rank;
217 }
218 
219 /// isPointerConversionToBool - Determines whether this conversion is
220 /// a conversion of a pointer or pointer-to-member to bool. This is
221 /// used as part of the ranking of standard conversion sequences
222 /// (C++ 13.3.3.2p4).
223 bool StandardConversionSequence::isPointerConversionToBool() const {
224   // Note that FromType has not necessarily been transformed by the
225   // array-to-pointer or function-to-pointer implicit conversions, so
226   // check for their presence as well as checking whether FromType is
227   // a pointer.
228   if (getToType(1)->isBooleanType() &&
229       (getFromType()->isPointerType() ||
230        getFromType()->isMemberPointerType() ||
231        getFromType()->isObjCObjectPointerType() ||
232        getFromType()->isBlockPointerType() ||
233        getFromType()->isNullPtrType() ||
234        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235     return true;
236 
237   return false;
238 }
239 
240 /// isPointerConversionToVoidPointer - Determines whether this
241 /// conversion is a conversion of a pointer to a void pointer. This is
242 /// used as part of the ranking of standard conversion sequences (C++
243 /// 13.3.3.2p4).
244 bool
245 StandardConversionSequence::
246 isPointerConversionToVoidPointer(ASTContext& Context) const {
247   QualType FromType = getFromType();
248   QualType ToType = getToType(1);
249 
250   // Note that FromType has not necessarily been transformed by the
251   // array-to-pointer implicit conversion, so check for its presence
252   // and redo the conversion to get a pointer.
253   if (First == ICK_Array_To_Pointer)
254     FromType = Context.getArrayDecayedType(FromType);
255 
256   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
257     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
258       return ToPtrType->getPointeeType()->isVoidType();
259 
260   return false;
261 }
262 
263 /// Skip any implicit casts which could be either part of a narrowing conversion
264 /// or after one in an implicit conversion.
265 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
266                                              const Expr *Converted) {
267   // We can have cleanups wrapping the converted expression; these need to be
268   // preserved so that destructors run if necessary.
269   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
270     Expr *Inner =
271         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
272     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
273                                     EWC->getObjects());
274   }
275 
276   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
277     switch (ICE->getCastKind()) {
278     case CK_NoOp:
279     case CK_IntegralCast:
280     case CK_IntegralToBoolean:
281     case CK_IntegralToFloating:
282     case CK_BooleanToSignedIntegral:
283     case CK_FloatingToIntegral:
284     case CK_FloatingToBoolean:
285     case CK_FloatingCast:
286       Converted = ICE->getSubExpr();
287       continue;
288 
289     default:
290       return Converted;
291     }
292   }
293 
294   return Converted;
295 }
296 
297 /// Check if this standard conversion sequence represents a narrowing
298 /// conversion, according to C++11 [dcl.init.list]p7.
299 ///
300 /// \param Ctx  The AST context.
301 /// \param Converted  The result of applying this standard conversion sequence.
302 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
303 ///        value of the expression prior to the narrowing conversion.
304 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
305 ///        type of the expression prior to the narrowing conversion.
306 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
307 ///        from floating point types to integral types should be ignored.
308 NarrowingKind StandardConversionSequence::getNarrowingKind(
309     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
310     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
311   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
312 
313   // C++11 [dcl.init.list]p7:
314   //   A narrowing conversion is an implicit conversion ...
315   QualType FromType = getToType(0);
316   QualType ToType = getToType(1);
317 
318   // A conversion to an enumeration type is narrowing if the conversion to
319   // the underlying type is narrowing. This only arises for expressions of
320   // the form 'Enum{init}'.
321   if (auto *ET = ToType->getAs<EnumType>())
322     ToType = ET->getDecl()->getIntegerType();
323 
324   switch (Second) {
325   // 'bool' is an integral type; dispatch to the right place to handle it.
326   case ICK_Boolean_Conversion:
327     if (FromType->isRealFloatingType())
328       goto FloatingIntegralConversion;
329     if (FromType->isIntegralOrUnscopedEnumerationType())
330       goto IntegralConversion;
331     // Boolean conversions can be from pointers and pointers to members
332     // [conv.bool], and those aren't considered narrowing conversions.
333     return NK_Not_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               FromType->isNullPtrType())) {
1853     // Boolean conversions (C++ 4.12).
1854     SCS.Second = ICK_Boolean_Conversion;
1855     FromType = S.Context.BoolTy;
1856   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1857              ToType->isIntegralType(S.Context)) {
1858     // Integral conversions (C++ 4.7).
1859     SCS.Second = ICK_Integral_Conversion;
1860     FromType = ToType.getUnqualifiedType();
1861   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1862     // Complex conversions (C99 6.3.1.6)
1863     SCS.Second = ICK_Complex_Conversion;
1864     FromType = ToType.getUnqualifiedType();
1865   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1866              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1867     // Complex-real conversions (C99 6.3.1.7)
1868     SCS.Second = ICK_Complex_Real;
1869     FromType = ToType.getUnqualifiedType();
1870   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1871     // FIXME: disable conversions between long double and __float128 if
1872     // their representation is different until there is back end support
1873     // We of course allow this conversion if long double is really double.
1874     if (&S.Context.getFloatTypeSemantics(FromType) !=
1875         &S.Context.getFloatTypeSemantics(ToType)) {
1876       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1877                                     ToType == S.Context.LongDoubleTy) ||
1878                                    (FromType == S.Context.LongDoubleTy &&
1879                                     ToType == S.Context.Float128Ty));
1880       if (Float128AndLongDouble &&
1881           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1882            &llvm::APFloat::PPCDoubleDouble()))
1883         return false;
1884     }
1885     // Floating point conversions (C++ 4.8).
1886     SCS.Second = ICK_Floating_Conversion;
1887     FromType = ToType.getUnqualifiedType();
1888   } else if ((FromType->isRealFloatingType() &&
1889               ToType->isIntegralType(S.Context)) ||
1890              (FromType->isIntegralOrUnscopedEnumerationType() &&
1891               ToType->isRealFloatingType())) {
1892     // Floating-integral conversions (C++ 4.9).
1893     SCS.Second = ICK_Floating_Integral;
1894     FromType = ToType.getUnqualifiedType();
1895   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1896     SCS.Second = ICK_Block_Pointer_Conversion;
1897   } else if (AllowObjCWritebackConversion &&
1898              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1899     SCS.Second = ICK_Writeback_Conversion;
1900   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1901                                    FromType, IncompatibleObjC)) {
1902     // Pointer conversions (C++ 4.10).
1903     SCS.Second = ICK_Pointer_Conversion;
1904     SCS.IncompatibleObjC = IncompatibleObjC;
1905     FromType = FromType.getUnqualifiedType();
1906   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1907                                          InOverloadResolution, FromType)) {
1908     // Pointer to member conversions (4.11).
1909     SCS.Second = ICK_Pointer_Member;
1910   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1911     SCS.Second = SecondICK;
1912     FromType = ToType.getUnqualifiedType();
1913   } else if (!S.getLangOpts().CPlusPlus &&
1914              S.Context.typesAreCompatible(ToType, FromType)) {
1915     // Compatible conversions (Clang extension for C function overloading)
1916     SCS.Second = ICK_Compatible_Conversion;
1917     FromType = ToType.getUnqualifiedType();
1918   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1919                                              InOverloadResolution,
1920                                              SCS, CStyle)) {
1921     SCS.Second = ICK_TransparentUnionConversion;
1922     FromType = ToType;
1923   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1924                                  CStyle)) {
1925     // tryAtomicConversion has updated the standard conversion sequence
1926     // appropriately.
1927     return true;
1928   } else if (ToType->isEventT() &&
1929              From->isIntegerConstantExpr(S.getASTContext()) &&
1930              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1931     SCS.Second = ICK_Zero_Event_Conversion;
1932     FromType = ToType;
1933   } else if (ToType->isQueueT() &&
1934              From->isIntegerConstantExpr(S.getASTContext()) &&
1935              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1936     SCS.Second = ICK_Zero_Queue_Conversion;
1937     FromType = ToType;
1938   } else if (ToType->isSamplerT() &&
1939              From->isIntegerConstantExpr(S.getASTContext())) {
1940     SCS.Second = ICK_Compatible_Conversion;
1941     FromType = ToType;
1942   } else {
1943     // No second conversion required.
1944     SCS.Second = ICK_Identity;
1945   }
1946   SCS.setToType(1, FromType);
1947 
1948   // The third conversion can be a function pointer conversion or a
1949   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1950   bool ObjCLifetimeConversion;
1951   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1952     // Function pointer conversions (removing 'noexcept') including removal of
1953     // 'noreturn' (Clang extension).
1954     SCS.Third = ICK_Function_Conversion;
1955   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1956                                          ObjCLifetimeConversion)) {
1957     SCS.Third = ICK_Qualification;
1958     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1959     FromType = ToType;
1960   } else {
1961     // No conversion required
1962     SCS.Third = ICK_Identity;
1963   }
1964 
1965   // C++ [over.best.ics]p6:
1966   //   [...] Any difference in top-level cv-qualification is
1967   //   subsumed by the initialization itself and does not constitute
1968   //   a conversion. [...]
1969   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1970   QualType CanonTo = S.Context.getCanonicalType(ToType);
1971   if (CanonFrom.getLocalUnqualifiedType()
1972                                      == CanonTo.getLocalUnqualifiedType() &&
1973       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1974     FromType = ToType;
1975     CanonFrom = CanonTo;
1976   }
1977 
1978   SCS.setToType(2, FromType);
1979 
1980   if (CanonFrom == CanonTo)
1981     return true;
1982 
1983   // If we have not converted the argument type to the parameter type,
1984   // this is a bad conversion sequence, unless we're resolving an overload in C.
1985   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1986     return false;
1987 
1988   ExprResult ER = ExprResult{From};
1989   Sema::AssignConvertType Conv =
1990       S.CheckSingleAssignmentConstraints(ToType, ER,
1991                                          /*Diagnose=*/false,
1992                                          /*DiagnoseCFAudited=*/false,
1993                                          /*ConvertRHS=*/false);
1994   ImplicitConversionKind SecondConv;
1995   switch (Conv) {
1996   case Sema::Compatible:
1997     SecondConv = ICK_C_Only_Conversion;
1998     break;
1999   // For our purposes, discarding qualifiers is just as bad as using an
2000   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2001   // qualifiers, as well.
2002   case Sema::CompatiblePointerDiscardsQualifiers:
2003   case Sema::IncompatiblePointer:
2004   case Sema::IncompatiblePointerSign:
2005     SecondConv = ICK_Incompatible_Pointer_Conversion;
2006     break;
2007   default:
2008     return false;
2009   }
2010 
2011   // First can only be an lvalue conversion, so we pretend that this was the
2012   // second conversion. First should already be valid from earlier in the
2013   // function.
2014   SCS.Second = SecondConv;
2015   SCS.setToType(1, ToType);
2016 
2017   // Third is Identity, because Second should rank us worse than any other
2018   // conversion. This could also be ICK_Qualification, but it's simpler to just
2019   // lump everything in with the second conversion, and we don't gain anything
2020   // from making this ICK_Qualification.
2021   SCS.Third = ICK_Identity;
2022   SCS.setToType(2, ToType);
2023   return true;
2024 }
2025 
2026 static bool
2027 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2028                                      QualType &ToType,
2029                                      bool InOverloadResolution,
2030                                      StandardConversionSequence &SCS,
2031                                      bool CStyle) {
2032 
2033   const RecordType *UT = ToType->getAsUnionType();
2034   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2035     return false;
2036   // The field to initialize within the transparent union.
2037   RecordDecl *UD = UT->getDecl();
2038   // It's compatible if the expression matches any of the fields.
2039   for (const auto *it : UD->fields()) {
2040     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2041                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2042       ToType = it->getType();
2043       return true;
2044     }
2045   }
2046   return false;
2047 }
2048 
2049 /// IsIntegralPromotion - Determines whether the conversion from the
2050 /// expression From (whose potentially-adjusted type is FromType) to
2051 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2052 /// sets PromotedType to the promoted type.
2053 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2054   const BuiltinType *To = ToType->getAs<BuiltinType>();
2055   // All integers are built-in.
2056   if (!To) {
2057     return false;
2058   }
2059 
2060   // An rvalue of type char, signed char, unsigned char, short int, or
2061   // unsigned short int can be converted to an rvalue of type int if
2062   // int can represent all the values of the source type; otherwise,
2063   // the source rvalue can be converted to an rvalue of type unsigned
2064   // int (C++ 4.5p1).
2065   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2066       !FromType->isEnumeralType()) {
2067     if (// We can promote any signed, promotable integer type to an int
2068         (FromType->isSignedIntegerType() ||
2069          // We can promote any unsigned integer type whose size is
2070          // less than int to an int.
2071          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2072       return To->getKind() == BuiltinType::Int;
2073     }
2074 
2075     return To->getKind() == BuiltinType::UInt;
2076   }
2077 
2078   // C++11 [conv.prom]p3:
2079   //   A prvalue of an unscoped enumeration type whose underlying type is not
2080   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2081   //   following types that can represent all the values of the enumeration
2082   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2083   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2084   //   long long int. If none of the types in that list can represent all the
2085   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2086   //   type can be converted to an rvalue a prvalue of the extended integer type
2087   //   with lowest integer conversion rank (4.13) greater than the rank of long
2088   //   long in which all the values of the enumeration can be represented. If
2089   //   there are two such extended types, the signed one is chosen.
2090   // C++11 [conv.prom]p4:
2091   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2092   //   can be converted to a prvalue of its underlying type. Moreover, if
2093   //   integral promotion can be applied to its underlying type, a prvalue of an
2094   //   unscoped enumeration type whose underlying type is fixed can also be
2095   //   converted to a prvalue of the promoted underlying type.
2096   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2097     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2098     // provided for a scoped enumeration.
2099     if (FromEnumType->getDecl()->isScoped())
2100       return false;
2101 
2102     // We can perform an integral promotion to the underlying type of the enum,
2103     // even if that's not the promoted type. Note that the check for promoting
2104     // the underlying type is based on the type alone, and does not consider
2105     // the bitfield-ness of the actual source expression.
2106     if (FromEnumType->getDecl()->isFixed()) {
2107       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2108       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2109              IsIntegralPromotion(nullptr, Underlying, ToType);
2110     }
2111 
2112     // We have already pre-calculated the promotion type, so this is trivial.
2113     if (ToType->isIntegerType() &&
2114         isCompleteType(From->getBeginLoc(), FromType))
2115       return Context.hasSameUnqualifiedType(
2116           ToType, FromEnumType->getDecl()->getPromotionType());
2117 
2118     // C++ [conv.prom]p5:
2119     //   If the bit-field has an enumerated type, it is treated as any other
2120     //   value of that type for promotion purposes.
2121     //
2122     // ... so do not fall through into the bit-field checks below in C++.
2123     if (getLangOpts().CPlusPlus)
2124       return false;
2125   }
2126 
2127   // C++0x [conv.prom]p2:
2128   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2129   //   to an rvalue a prvalue of the first of the following types that can
2130   //   represent all the values of its underlying type: int, unsigned int,
2131   //   long int, unsigned long int, long long int, or unsigned long long int.
2132   //   If none of the types in that list can represent all the values of its
2133   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2134   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2135   //   type.
2136   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2137       ToType->isIntegerType()) {
2138     // Determine whether the type we're converting from is signed or
2139     // unsigned.
2140     bool FromIsSigned = FromType->isSignedIntegerType();
2141     uint64_t FromSize = Context.getTypeSize(FromType);
2142 
2143     // The types we'll try to promote to, in the appropriate
2144     // order. Try each of these types.
2145     QualType PromoteTypes[6] = {
2146       Context.IntTy, Context.UnsignedIntTy,
2147       Context.LongTy, Context.UnsignedLongTy ,
2148       Context.LongLongTy, Context.UnsignedLongLongTy
2149     };
2150     for (int Idx = 0; Idx < 6; ++Idx) {
2151       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2152       if (FromSize < ToSize ||
2153           (FromSize == ToSize &&
2154            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2155         // We found the type that we can promote to. If this is the
2156         // type we wanted, we have a promotion. Otherwise, no
2157         // promotion.
2158         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2159       }
2160     }
2161   }
2162 
2163   // An rvalue for an integral bit-field (9.6) can be converted to an
2164   // rvalue of type int if int can represent all the values of the
2165   // bit-field; otherwise, it can be converted to unsigned int if
2166   // unsigned int can represent all the values of the bit-field. If
2167   // the bit-field is larger yet, no integral promotion applies to
2168   // it. If the bit-field has an enumerated type, it is treated as any
2169   // other value of that type for promotion purposes (C++ 4.5p3).
2170   // FIXME: We should delay checking of bit-fields until we actually perform the
2171   // conversion.
2172   //
2173   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2174   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2175   // bit-fields and those whose underlying type is larger than int) for GCC
2176   // compatibility.
2177   if (From) {
2178     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2179       llvm::APSInt BitWidth;
2180       if (FromType->isIntegralType(Context) &&
2181           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2182         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2183         ToSize = Context.getTypeSize(ToType);
2184 
2185         // Are we promoting to an int from a bitfield that fits in an int?
2186         if (BitWidth < ToSize ||
2187             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2188           return To->getKind() == BuiltinType::Int;
2189         }
2190 
2191         // Are we promoting to an unsigned int from an unsigned bitfield
2192         // that fits into an unsigned int?
2193         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2194           return To->getKind() == BuiltinType::UInt;
2195         }
2196 
2197         return false;
2198       }
2199     }
2200   }
2201 
2202   // An rvalue of type bool can be converted to an rvalue of type int,
2203   // with false becoming zero and true becoming one (C++ 4.5p4).
2204   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2205     return true;
2206   }
2207 
2208   return false;
2209 }
2210 
2211 /// IsFloatingPointPromotion - Determines whether the conversion from
2212 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2213 /// returns true and sets PromotedType to the promoted type.
2214 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2215   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2216     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2217       /// An rvalue of type float can be converted to an rvalue of type
2218       /// double. (C++ 4.6p1).
2219       if (FromBuiltin->getKind() == BuiltinType::Float &&
2220           ToBuiltin->getKind() == BuiltinType::Double)
2221         return true;
2222 
2223       // C99 6.3.1.5p1:
2224       //   When a float is promoted to double or long double, or a
2225       //   double is promoted to long double [...].
2226       if (!getLangOpts().CPlusPlus &&
2227           (FromBuiltin->getKind() == BuiltinType::Float ||
2228            FromBuiltin->getKind() == BuiltinType::Double) &&
2229           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2230            ToBuiltin->getKind() == BuiltinType::Float128))
2231         return true;
2232 
2233       // Half can be promoted to float.
2234       if (!getLangOpts().NativeHalfType &&
2235            FromBuiltin->getKind() == BuiltinType::Half &&
2236           ToBuiltin->getKind() == BuiltinType::Float)
2237         return true;
2238     }
2239 
2240   return false;
2241 }
2242 
2243 /// Determine if a conversion is a complex promotion.
2244 ///
2245 /// A complex promotion is defined as a complex -> complex conversion
2246 /// where the conversion between the underlying real types is a
2247 /// floating-point or integral promotion.
2248 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2249   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2250   if (!FromComplex)
2251     return false;
2252 
2253   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2254   if (!ToComplex)
2255     return false;
2256 
2257   return IsFloatingPointPromotion(FromComplex->getElementType(),
2258                                   ToComplex->getElementType()) ||
2259     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2260                         ToComplex->getElementType());
2261 }
2262 
2263 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2264 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2265 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2266 /// if non-empty, will be a pointer to ToType that may or may not have
2267 /// the right set of qualifiers on its pointee.
2268 ///
2269 static QualType
2270 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2271                                    QualType ToPointee, QualType ToType,
2272                                    ASTContext &Context,
2273                                    bool StripObjCLifetime = false) {
2274   assert((FromPtr->getTypeClass() == Type::Pointer ||
2275           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2276          "Invalid similarly-qualified pointer type");
2277 
2278   /// Conversions to 'id' subsume cv-qualifier conversions.
2279   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2280     return ToType.getUnqualifiedType();
2281 
2282   QualType CanonFromPointee
2283     = Context.getCanonicalType(FromPtr->getPointeeType());
2284   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2285   Qualifiers Quals = CanonFromPointee.getQualifiers();
2286 
2287   if (StripObjCLifetime)
2288     Quals.removeObjCLifetime();
2289 
2290   // Exact qualifier match -> return the pointer type we're converting to.
2291   if (CanonToPointee.getLocalQualifiers() == Quals) {
2292     // ToType is exactly what we need. Return it.
2293     if (!ToType.isNull())
2294       return ToType.getUnqualifiedType();
2295 
2296     // Build a pointer to ToPointee. It has the right qualifiers
2297     // already.
2298     if (isa<ObjCObjectPointerType>(ToType))
2299       return Context.getObjCObjectPointerType(ToPointee);
2300     return Context.getPointerType(ToPointee);
2301   }
2302 
2303   // Just build a canonical type that has the right qualifiers.
2304   QualType QualifiedCanonToPointee
2305     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2306 
2307   if (isa<ObjCObjectPointerType>(ToType))
2308     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2309   return Context.getPointerType(QualifiedCanonToPointee);
2310 }
2311 
2312 static bool isNullPointerConstantForConversion(Expr *Expr,
2313                                                bool InOverloadResolution,
2314                                                ASTContext &Context) {
2315   // Handle value-dependent integral null pointer constants correctly.
2316   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2317   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2318       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2319     return !InOverloadResolution;
2320 
2321   return Expr->isNullPointerConstant(Context,
2322                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2323                                         : Expr::NPC_ValueDependentIsNull);
2324 }
2325 
2326 /// IsPointerConversion - Determines whether the conversion of the
2327 /// expression From, which has the (possibly adjusted) type FromType,
2328 /// can be converted to the type ToType via a pointer conversion (C++
2329 /// 4.10). If so, returns true and places the converted type (that
2330 /// might differ from ToType in its cv-qualifiers at some level) into
2331 /// ConvertedType.
2332 ///
2333 /// This routine also supports conversions to and from block pointers
2334 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2335 /// pointers to interfaces. FIXME: Once we've determined the
2336 /// appropriate overloading rules for Objective-C, we may want to
2337 /// split the Objective-C checks into a different routine; however,
2338 /// GCC seems to consider all of these conversions to be pointer
2339 /// conversions, so for now they live here. IncompatibleObjC will be
2340 /// set if the conversion is an allowed Objective-C conversion that
2341 /// should result in a warning.
2342 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2343                                bool InOverloadResolution,
2344                                QualType& ConvertedType,
2345                                bool &IncompatibleObjC) {
2346   IncompatibleObjC = false;
2347   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2348                               IncompatibleObjC))
2349     return true;
2350 
2351   // Conversion from a null pointer constant to any Objective-C pointer type.
2352   if (ToType->isObjCObjectPointerType() &&
2353       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2354     ConvertedType = ToType;
2355     return true;
2356   }
2357 
2358   // Blocks: Block pointers can be converted to void*.
2359   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2360       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2361     ConvertedType = ToType;
2362     return true;
2363   }
2364   // Blocks: A null pointer constant can be converted to a block
2365   // pointer type.
2366   if (ToType->isBlockPointerType() &&
2367       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2368     ConvertedType = ToType;
2369     return true;
2370   }
2371 
2372   // If the left-hand-side is nullptr_t, the right side can be a null
2373   // pointer constant.
2374   if (ToType->isNullPtrType() &&
2375       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2376     ConvertedType = ToType;
2377     return true;
2378   }
2379 
2380   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2381   if (!ToTypePtr)
2382     return false;
2383 
2384   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2385   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2386     ConvertedType = ToType;
2387     return true;
2388   }
2389 
2390   // Beyond this point, both types need to be pointers
2391   // , including objective-c pointers.
2392   QualType ToPointeeType = ToTypePtr->getPointeeType();
2393   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2394       !getLangOpts().ObjCAutoRefCount) {
2395     ConvertedType = BuildSimilarlyQualifiedPointerType(
2396                                       FromType->getAs<ObjCObjectPointerType>(),
2397                                                        ToPointeeType,
2398                                                        ToType, Context);
2399     return true;
2400   }
2401   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2402   if (!FromTypePtr)
2403     return false;
2404 
2405   QualType FromPointeeType = FromTypePtr->getPointeeType();
2406 
2407   // If the unqualified pointee types are the same, this can't be a
2408   // pointer conversion, so don't do all of the work below.
2409   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2410     return false;
2411 
2412   // An rvalue of type "pointer to cv T," where T is an object type,
2413   // can be converted to an rvalue of type "pointer to cv void" (C++
2414   // 4.10p2).
2415   if (FromPointeeType->isIncompleteOrObjectType() &&
2416       ToPointeeType->isVoidType()) {
2417     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2418                                                        ToPointeeType,
2419                                                        ToType, Context,
2420                                                    /*StripObjCLifetime=*/true);
2421     return true;
2422   }
2423 
2424   // MSVC allows implicit function to void* type conversion.
2425   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2426       ToPointeeType->isVoidType()) {
2427     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2428                                                        ToPointeeType,
2429                                                        ToType, Context);
2430     return true;
2431   }
2432 
2433   // When we're overloading in C, we allow a special kind of pointer
2434   // conversion for compatible-but-not-identical pointee types.
2435   if (!getLangOpts().CPlusPlus &&
2436       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2437     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2438                                                        ToPointeeType,
2439                                                        ToType, Context);
2440     return true;
2441   }
2442 
2443   // C++ [conv.ptr]p3:
2444   //
2445   //   An rvalue of type "pointer to cv D," where D is a class type,
2446   //   can be converted to an rvalue of type "pointer to cv B," where
2447   //   B is a base class (clause 10) of D. If B is an inaccessible
2448   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2449   //   necessitates this conversion is ill-formed. The result of the
2450   //   conversion is a pointer to the base class sub-object of the
2451   //   derived class object. The null pointer value is converted to
2452   //   the null pointer value of the destination type.
2453   //
2454   // Note that we do not check for ambiguity or inaccessibility
2455   // here. That is handled by CheckPointerConversion.
2456   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2457       ToPointeeType->isRecordType() &&
2458       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2459       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2460     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2461                                                        ToPointeeType,
2462                                                        ToType, Context);
2463     return true;
2464   }
2465 
2466   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2467       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2468     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2469                                                        ToPointeeType,
2470                                                        ToType, Context);
2471     return true;
2472   }
2473 
2474   return false;
2475 }
2476 
2477 /// Adopt the given qualifiers for the given type.
2478 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2479   Qualifiers TQs = T.getQualifiers();
2480 
2481   // Check whether qualifiers already match.
2482   if (TQs == Qs)
2483     return T;
2484 
2485   if (Qs.compatiblyIncludes(TQs))
2486     return Context.getQualifiedType(T, Qs);
2487 
2488   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2489 }
2490 
2491 /// isObjCPointerConversion - Determines whether this is an
2492 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2493 /// with the same arguments and return values.
2494 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2495                                    QualType& ConvertedType,
2496                                    bool &IncompatibleObjC) {
2497   if (!getLangOpts().ObjC)
2498     return false;
2499 
2500   // The set of qualifiers on the type we're converting from.
2501   Qualifiers FromQualifiers = FromType.getQualifiers();
2502 
2503   // First, we handle all conversions on ObjC object pointer types.
2504   const ObjCObjectPointerType* ToObjCPtr =
2505     ToType->getAs<ObjCObjectPointerType>();
2506   const ObjCObjectPointerType *FromObjCPtr =
2507     FromType->getAs<ObjCObjectPointerType>();
2508 
2509   if (ToObjCPtr && FromObjCPtr) {
2510     // If the pointee types are the same (ignoring qualifications),
2511     // then this is not a pointer conversion.
2512     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2513                                        FromObjCPtr->getPointeeType()))
2514       return false;
2515 
2516     // Conversion between Objective-C pointers.
2517     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2518       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2519       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2520       if (getLangOpts().CPlusPlus && LHS && RHS &&
2521           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2522                                                 FromObjCPtr->getPointeeType()))
2523         return false;
2524       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2525                                                    ToObjCPtr->getPointeeType(),
2526                                                          ToType, Context);
2527       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2528       return true;
2529     }
2530 
2531     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2532       // Okay: this is some kind of implicit downcast of Objective-C
2533       // interfaces, which is permitted. However, we're going to
2534       // complain about it.
2535       IncompatibleObjC = true;
2536       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2537                                                    ToObjCPtr->getPointeeType(),
2538                                                          ToType, Context);
2539       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2540       return true;
2541     }
2542   }
2543   // Beyond this point, both types need to be C pointers or block pointers.
2544   QualType ToPointeeType;
2545   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2546     ToPointeeType = ToCPtr->getPointeeType();
2547   else if (const BlockPointerType *ToBlockPtr =
2548             ToType->getAs<BlockPointerType>()) {
2549     // Objective C++: We're able to convert from a pointer to any object
2550     // to a block pointer type.
2551     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2552       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2553       return true;
2554     }
2555     ToPointeeType = ToBlockPtr->getPointeeType();
2556   }
2557   else if (FromType->getAs<BlockPointerType>() &&
2558            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2559     // Objective C++: We're able to convert from a block pointer type to a
2560     // pointer to any object.
2561     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2562     return true;
2563   }
2564   else
2565     return false;
2566 
2567   QualType FromPointeeType;
2568   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2569     FromPointeeType = FromCPtr->getPointeeType();
2570   else if (const BlockPointerType *FromBlockPtr =
2571            FromType->getAs<BlockPointerType>())
2572     FromPointeeType = FromBlockPtr->getPointeeType();
2573   else
2574     return false;
2575 
2576   // If we have pointers to pointers, recursively check whether this
2577   // is an Objective-C conversion.
2578   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2579       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2580                               IncompatibleObjC)) {
2581     // We always complain about this conversion.
2582     IncompatibleObjC = true;
2583     ConvertedType = Context.getPointerType(ConvertedType);
2584     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2585     return true;
2586   }
2587   // Allow conversion of pointee being objective-c pointer to another one;
2588   // as in I* to id.
2589   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2590       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2591       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2592                               IncompatibleObjC)) {
2593 
2594     ConvertedType = Context.getPointerType(ConvertedType);
2595     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2596     return true;
2597   }
2598 
2599   // If we have pointers to functions or blocks, check whether the only
2600   // differences in the argument and result types are in Objective-C
2601   // pointer conversions. If so, we permit the conversion (but
2602   // complain about it).
2603   const FunctionProtoType *FromFunctionType
2604     = FromPointeeType->getAs<FunctionProtoType>();
2605   const FunctionProtoType *ToFunctionType
2606     = ToPointeeType->getAs<FunctionProtoType>();
2607   if (FromFunctionType && ToFunctionType) {
2608     // If the function types are exactly the same, this isn't an
2609     // Objective-C pointer conversion.
2610     if (Context.getCanonicalType(FromPointeeType)
2611           == Context.getCanonicalType(ToPointeeType))
2612       return false;
2613 
2614     // Perform the quick checks that will tell us whether these
2615     // function types are obviously different.
2616     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2617         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2618         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2619       return false;
2620 
2621     bool HasObjCConversion = false;
2622     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2623         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2624       // Okay, the types match exactly. Nothing to do.
2625     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2626                                        ToFunctionType->getReturnType(),
2627                                        ConvertedType, IncompatibleObjC)) {
2628       // Okay, we have an Objective-C pointer conversion.
2629       HasObjCConversion = true;
2630     } else {
2631       // Function types are too different. Abort.
2632       return false;
2633     }
2634 
2635     // Check argument types.
2636     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2637          ArgIdx != NumArgs; ++ArgIdx) {
2638       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2639       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2640       if (Context.getCanonicalType(FromArgType)
2641             == Context.getCanonicalType(ToArgType)) {
2642         // Okay, the types match exactly. Nothing to do.
2643       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2644                                          ConvertedType, IncompatibleObjC)) {
2645         // Okay, we have an Objective-C pointer conversion.
2646         HasObjCConversion = true;
2647       } else {
2648         // Argument types are too different. Abort.
2649         return false;
2650       }
2651     }
2652 
2653     if (HasObjCConversion) {
2654       // We had an Objective-C conversion. Allow this pointer
2655       // conversion, but complain about it.
2656       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2657       IncompatibleObjC = true;
2658       return true;
2659     }
2660   }
2661 
2662   return false;
2663 }
2664 
2665 /// Determine whether this is an Objective-C writeback conversion,
2666 /// used for parameter passing when performing automatic reference counting.
2667 ///
2668 /// \param FromType The type we're converting form.
2669 ///
2670 /// \param ToType The type we're converting to.
2671 ///
2672 /// \param ConvertedType The type that will be produced after applying
2673 /// this conversion.
2674 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2675                                      QualType &ConvertedType) {
2676   if (!getLangOpts().ObjCAutoRefCount ||
2677       Context.hasSameUnqualifiedType(FromType, ToType))
2678     return false;
2679 
2680   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2681   QualType ToPointee;
2682   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2683     ToPointee = ToPointer->getPointeeType();
2684   else
2685     return false;
2686 
2687   Qualifiers ToQuals = ToPointee.getQualifiers();
2688   if (!ToPointee->isObjCLifetimeType() ||
2689       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2690       !ToQuals.withoutObjCLifetime().empty())
2691     return false;
2692 
2693   // Argument must be a pointer to __strong to __weak.
2694   QualType FromPointee;
2695   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2696     FromPointee = FromPointer->getPointeeType();
2697   else
2698     return false;
2699 
2700   Qualifiers FromQuals = FromPointee.getQualifiers();
2701   if (!FromPointee->isObjCLifetimeType() ||
2702       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2703        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2704     return false;
2705 
2706   // Make sure that we have compatible qualifiers.
2707   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2708   if (!ToQuals.compatiblyIncludes(FromQuals))
2709     return false;
2710 
2711   // Remove qualifiers from the pointee type we're converting from; they
2712   // aren't used in the compatibility check belong, and we'll be adding back
2713   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2714   FromPointee = FromPointee.getUnqualifiedType();
2715 
2716   // The unqualified form of the pointee types must be compatible.
2717   ToPointee = ToPointee.getUnqualifiedType();
2718   bool IncompatibleObjC;
2719   if (Context.typesAreCompatible(FromPointee, ToPointee))
2720     FromPointee = ToPointee;
2721   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2722                                     IncompatibleObjC))
2723     return false;
2724 
2725   /// Construct the type we're converting to, which is a pointer to
2726   /// __autoreleasing pointee.
2727   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2728   ConvertedType = Context.getPointerType(FromPointee);
2729   return true;
2730 }
2731 
2732 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2733                                     QualType& ConvertedType) {
2734   QualType ToPointeeType;
2735   if (const BlockPointerType *ToBlockPtr =
2736         ToType->getAs<BlockPointerType>())
2737     ToPointeeType = ToBlockPtr->getPointeeType();
2738   else
2739     return false;
2740 
2741   QualType FromPointeeType;
2742   if (const BlockPointerType *FromBlockPtr =
2743       FromType->getAs<BlockPointerType>())
2744     FromPointeeType = FromBlockPtr->getPointeeType();
2745   else
2746     return false;
2747   // We have pointer to blocks, check whether the only
2748   // differences in the argument and result types are in Objective-C
2749   // pointer conversions. If so, we permit the conversion.
2750 
2751   const FunctionProtoType *FromFunctionType
2752     = FromPointeeType->getAs<FunctionProtoType>();
2753   const FunctionProtoType *ToFunctionType
2754     = ToPointeeType->getAs<FunctionProtoType>();
2755 
2756   if (!FromFunctionType || !ToFunctionType)
2757     return false;
2758 
2759   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2760     return true;
2761 
2762   // Perform the quick checks that will tell us whether these
2763   // function types are obviously different.
2764   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2765       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2766     return false;
2767 
2768   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2769   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2770   if (FromEInfo != ToEInfo)
2771     return false;
2772 
2773   bool IncompatibleObjC = false;
2774   if (Context.hasSameType(FromFunctionType->getReturnType(),
2775                           ToFunctionType->getReturnType())) {
2776     // Okay, the types match exactly. Nothing to do.
2777   } else {
2778     QualType RHS = FromFunctionType->getReturnType();
2779     QualType LHS = ToFunctionType->getReturnType();
2780     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2781         !RHS.hasQualifiers() && LHS.hasQualifiers())
2782        LHS = LHS.getUnqualifiedType();
2783 
2784      if (Context.hasSameType(RHS,LHS)) {
2785        // OK exact match.
2786      } else if (isObjCPointerConversion(RHS, LHS,
2787                                         ConvertedType, IncompatibleObjC)) {
2788      if (IncompatibleObjC)
2789        return false;
2790      // Okay, we have an Objective-C pointer conversion.
2791      }
2792      else
2793        return false;
2794    }
2795 
2796    // Check argument types.
2797    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2798         ArgIdx != NumArgs; ++ArgIdx) {
2799      IncompatibleObjC = false;
2800      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2801      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2802      if (Context.hasSameType(FromArgType, ToArgType)) {
2803        // Okay, the types match exactly. Nothing to do.
2804      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2805                                         ConvertedType, IncompatibleObjC)) {
2806        if (IncompatibleObjC)
2807          return false;
2808        // Okay, we have an Objective-C pointer conversion.
2809      } else
2810        // Argument types are too different. Abort.
2811        return false;
2812    }
2813 
2814    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2815    bool CanUseToFPT, CanUseFromFPT;
2816    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2817                                       CanUseToFPT, CanUseFromFPT,
2818                                       NewParamInfos))
2819      return false;
2820 
2821    ConvertedType = ToType;
2822    return true;
2823 }
2824 
2825 enum {
2826   ft_default,
2827   ft_different_class,
2828   ft_parameter_arity,
2829   ft_parameter_mismatch,
2830   ft_return_type,
2831   ft_qualifer_mismatch,
2832   ft_noexcept
2833 };
2834 
2835 /// Attempts to get the FunctionProtoType from a Type. Handles
2836 /// MemberFunctionPointers properly.
2837 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2838   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2839     return FPT;
2840 
2841   if (auto *MPT = FromType->getAs<MemberPointerType>())
2842     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2843 
2844   return nullptr;
2845 }
2846 
2847 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2848 /// function types.  Catches different number of parameter, mismatch in
2849 /// parameter types, and different return types.
2850 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2851                                       QualType FromType, QualType ToType) {
2852   // If either type is not valid, include no extra info.
2853   if (FromType.isNull() || ToType.isNull()) {
2854     PDiag << ft_default;
2855     return;
2856   }
2857 
2858   // Get the function type from the pointers.
2859   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2860     const auto *FromMember = FromType->castAs<MemberPointerType>(),
2861                *ToMember = ToType->castAs<MemberPointerType>();
2862     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2863       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2864             << QualType(FromMember->getClass(), 0);
2865       return;
2866     }
2867     FromType = FromMember->getPointeeType();
2868     ToType = ToMember->getPointeeType();
2869   }
2870 
2871   if (FromType->isPointerType())
2872     FromType = FromType->getPointeeType();
2873   if (ToType->isPointerType())
2874     ToType = ToType->getPointeeType();
2875 
2876   // Remove references.
2877   FromType = FromType.getNonReferenceType();
2878   ToType = ToType.getNonReferenceType();
2879 
2880   // Don't print extra info for non-specialized template functions.
2881   if (FromType->isInstantiationDependentType() &&
2882       !FromType->getAs<TemplateSpecializationType>()) {
2883     PDiag << ft_default;
2884     return;
2885   }
2886 
2887   // No extra info for same types.
2888   if (Context.hasSameType(FromType, ToType)) {
2889     PDiag << ft_default;
2890     return;
2891   }
2892 
2893   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2894                           *ToFunction = tryGetFunctionProtoType(ToType);
2895 
2896   // Both types need to be function types.
2897   if (!FromFunction || !ToFunction) {
2898     PDiag << ft_default;
2899     return;
2900   }
2901 
2902   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2903     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2904           << FromFunction->getNumParams();
2905     return;
2906   }
2907 
2908   // Handle different parameter types.
2909   unsigned ArgPos;
2910   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2911     PDiag << ft_parameter_mismatch << ArgPos + 1
2912           << ToFunction->getParamType(ArgPos)
2913           << FromFunction->getParamType(ArgPos);
2914     return;
2915   }
2916 
2917   // Handle different return type.
2918   if (!Context.hasSameType(FromFunction->getReturnType(),
2919                            ToFunction->getReturnType())) {
2920     PDiag << ft_return_type << ToFunction->getReturnType()
2921           << FromFunction->getReturnType();
2922     return;
2923   }
2924 
2925   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2926     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2927           << FromFunction->getMethodQuals();
2928     return;
2929   }
2930 
2931   // Handle exception specification differences on canonical type (in C++17
2932   // onwards).
2933   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2934           ->isNothrow() !=
2935       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2936           ->isNothrow()) {
2937     PDiag << ft_noexcept;
2938     return;
2939   }
2940 
2941   // Unable to find a difference, so add no extra info.
2942   PDiag << ft_default;
2943 }
2944 
2945 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2946 /// for equality of their argument types. Caller has already checked that
2947 /// they have same number of arguments.  If the parameters are different,
2948 /// ArgPos will have the parameter index of the first different parameter.
2949 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2950                                       const FunctionProtoType *NewType,
2951                                       unsigned *ArgPos) {
2952   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2953                                               N = NewType->param_type_begin(),
2954                                               E = OldType->param_type_end();
2955        O && (O != E); ++O, ++N) {
2956     // Ignore address spaces in pointee type. This is to disallow overloading
2957     // on __ptr32/__ptr64 address spaces.
2958     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2959     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2960 
2961     if (!Context.hasSameType(Old, New)) {
2962       if (ArgPos)
2963         *ArgPos = O - OldType->param_type_begin();
2964       return false;
2965     }
2966   }
2967   return true;
2968 }
2969 
2970 /// CheckPointerConversion - Check the pointer conversion from the
2971 /// expression From to the type ToType. This routine checks for
2972 /// ambiguous or inaccessible derived-to-base pointer
2973 /// conversions for which IsPointerConversion has already returned
2974 /// true. It returns true and produces a diagnostic if there was an
2975 /// error, or returns false otherwise.
2976 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2977                                   CastKind &Kind,
2978                                   CXXCastPath& BasePath,
2979                                   bool IgnoreBaseAccess,
2980                                   bool Diagnose) {
2981   QualType FromType = From->getType();
2982   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2983 
2984   Kind = CK_BitCast;
2985 
2986   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2987       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2988           Expr::NPCK_ZeroExpression) {
2989     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2990       DiagRuntimeBehavior(From->getExprLoc(), From,
2991                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2992                             << ToType << From->getSourceRange());
2993     else if (!isUnevaluatedContext())
2994       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2995         << ToType << From->getSourceRange();
2996   }
2997   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2998     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2999       QualType FromPointeeType = FromPtrType->getPointeeType(),
3000                ToPointeeType   = ToPtrType->getPointeeType();
3001 
3002       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3003           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3004         // We must have a derived-to-base conversion. Check an
3005         // ambiguous or inaccessible conversion.
3006         unsigned InaccessibleID = 0;
3007         unsigned AmbigiousID = 0;
3008         if (Diagnose) {
3009           InaccessibleID = diag::err_upcast_to_inaccessible_base;
3010           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3011         }
3012         if (CheckDerivedToBaseConversion(
3013                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3014                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3015                 &BasePath, IgnoreBaseAccess))
3016           return true;
3017 
3018         // The conversion was successful.
3019         Kind = CK_DerivedToBase;
3020       }
3021 
3022       if (Diagnose && !IsCStyleOrFunctionalCast &&
3023           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3024         assert(getLangOpts().MSVCCompat &&
3025                "this should only be possible with MSVCCompat!");
3026         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3027             << From->getSourceRange();
3028       }
3029     }
3030   } else if (const ObjCObjectPointerType *ToPtrType =
3031                ToType->getAs<ObjCObjectPointerType>()) {
3032     if (const ObjCObjectPointerType *FromPtrType =
3033           FromType->getAs<ObjCObjectPointerType>()) {
3034       // Objective-C++ conversions are always okay.
3035       // FIXME: We should have a different class of conversions for the
3036       // Objective-C++ implicit conversions.
3037       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3038         return false;
3039     } else if (FromType->isBlockPointerType()) {
3040       Kind = CK_BlockPointerToObjCPointerCast;
3041     } else {
3042       Kind = CK_CPointerToObjCPointerCast;
3043     }
3044   } else if (ToType->isBlockPointerType()) {
3045     if (!FromType->isBlockPointerType())
3046       Kind = CK_AnyPointerToBlockPointerCast;
3047   }
3048 
3049   // We shouldn't fall into this case unless it's valid for other
3050   // reasons.
3051   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3052     Kind = CK_NullToPointer;
3053 
3054   return false;
3055 }
3056 
3057 /// IsMemberPointerConversion - Determines whether the conversion of the
3058 /// expression From, which has the (possibly adjusted) type FromType, can be
3059 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3060 /// If so, returns true and places the converted type (that might differ from
3061 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3062 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3063                                      QualType ToType,
3064                                      bool InOverloadResolution,
3065                                      QualType &ConvertedType) {
3066   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3067   if (!ToTypePtr)
3068     return false;
3069 
3070   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3071   if (From->isNullPointerConstant(Context,
3072                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3073                                         : Expr::NPC_ValueDependentIsNull)) {
3074     ConvertedType = ToType;
3075     return true;
3076   }
3077 
3078   // Otherwise, both types have to be member pointers.
3079   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3080   if (!FromTypePtr)
3081     return false;
3082 
3083   // A pointer to member of B can be converted to a pointer to member of D,
3084   // where D is derived from B (C++ 4.11p2).
3085   QualType FromClass(FromTypePtr->getClass(), 0);
3086   QualType ToClass(ToTypePtr->getClass(), 0);
3087 
3088   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3089       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3090     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3091                                                  ToClass.getTypePtr());
3092     return true;
3093   }
3094 
3095   return false;
3096 }
3097 
3098 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3099 /// expression From to the type ToType. This routine checks for ambiguous or
3100 /// virtual or inaccessible base-to-derived member pointer conversions
3101 /// for which IsMemberPointerConversion has already returned true. It returns
3102 /// true and produces a diagnostic if there was an error, or returns false
3103 /// otherwise.
3104 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3105                                         CastKind &Kind,
3106                                         CXXCastPath &BasePath,
3107                                         bool IgnoreBaseAccess) {
3108   QualType FromType = From->getType();
3109   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3110   if (!FromPtrType) {
3111     // This must be a null pointer to member pointer conversion
3112     assert(From->isNullPointerConstant(Context,
3113                                        Expr::NPC_ValueDependentIsNull) &&
3114            "Expr must be null pointer constant!");
3115     Kind = CK_NullToMemberPointer;
3116     return false;
3117   }
3118 
3119   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3120   assert(ToPtrType && "No member pointer cast has a target type "
3121                       "that is not a member pointer.");
3122 
3123   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3124   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3125 
3126   // FIXME: What about dependent types?
3127   assert(FromClass->isRecordType() && "Pointer into non-class.");
3128   assert(ToClass->isRecordType() && "Pointer into non-class.");
3129 
3130   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131                      /*DetectVirtual=*/true);
3132   bool DerivationOkay =
3133       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3134   assert(DerivationOkay &&
3135          "Should not have been called if derivation isn't OK.");
3136   (void)DerivationOkay;
3137 
3138   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3139                                   getUnqualifiedType())) {
3140     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3141     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3142       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3143     return true;
3144   }
3145 
3146   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3147     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3148       << FromClass << ToClass << QualType(VBase, 0)
3149       << From->getSourceRange();
3150     return true;
3151   }
3152 
3153   if (!IgnoreBaseAccess)
3154     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3155                          Paths.front(),
3156                          diag::err_downcast_from_inaccessible_base);
3157 
3158   // Must be a base to derived member conversion.
3159   BuildBasePathArray(Paths, BasePath);
3160   Kind = CK_BaseToDerivedMemberPointer;
3161   return false;
3162 }
3163 
3164 /// Determine whether the lifetime conversion between the two given
3165 /// qualifiers sets is nontrivial.
3166 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3167                                                Qualifiers ToQuals) {
3168   // Converting anything to const __unsafe_unretained is trivial.
3169   if (ToQuals.hasConst() &&
3170       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3171     return false;
3172 
3173   return true;
3174 }
3175 
3176 /// Perform a single iteration of the loop for checking if a qualification
3177 /// conversion is valid.
3178 ///
3179 /// Specifically, check whether any change between the qualifiers of \p
3180 /// FromType and \p ToType is permissible, given knowledge about whether every
3181 /// outer layer is const-qualified.
3182 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3183                                           bool CStyle, bool IsTopLevel,
3184                                           bool &PreviousToQualsIncludeConst,
3185                                           bool &ObjCLifetimeConversion) {
3186   Qualifiers FromQuals = FromType.getQualifiers();
3187   Qualifiers ToQuals = ToType.getQualifiers();
3188 
3189   // Ignore __unaligned qualifier if this type is void.
3190   if (ToType.getUnqualifiedType()->isVoidType())
3191     FromQuals.removeUnaligned();
3192 
3193   // Objective-C ARC:
3194   //   Check Objective-C lifetime conversions.
3195   if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3196     if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3197       if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3198         ObjCLifetimeConversion = true;
3199       FromQuals.removeObjCLifetime();
3200       ToQuals.removeObjCLifetime();
3201     } else {
3202       // Qualification conversions cannot cast between different
3203       // Objective-C lifetime qualifiers.
3204       return false;
3205     }
3206   }
3207 
3208   // Allow addition/removal of GC attributes but not changing GC attributes.
3209   if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3210       (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3211     FromQuals.removeObjCGCAttr();
3212     ToQuals.removeObjCGCAttr();
3213   }
3214 
3215   //   -- for every j > 0, if const is in cv 1,j then const is in cv
3216   //      2,j, and similarly for volatile.
3217   if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3218     return false;
3219 
3220   // If address spaces mismatch:
3221   //  - in top level it is only valid to convert to addr space that is a
3222   //    superset in all cases apart from C-style casts where we allow
3223   //    conversions between overlapping address spaces.
3224   //  - in non-top levels it is not a valid conversion.
3225   if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3226       (!IsTopLevel ||
3227        !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3228          (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3229     return false;
3230 
3231   //   -- if the cv 1,j and cv 2,j are different, then const is in
3232   //      every cv for 0 < k < j.
3233   if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3234       !PreviousToQualsIncludeConst)
3235     return false;
3236 
3237   // Keep track of whether all prior cv-qualifiers in the "to" type
3238   // include const.
3239   PreviousToQualsIncludeConst =
3240       PreviousToQualsIncludeConst && ToQuals.hasConst();
3241   return true;
3242 }
3243 
3244 /// IsQualificationConversion - Determines whether the conversion from
3245 /// an rvalue of type FromType to ToType is a qualification conversion
3246 /// (C++ 4.4).
3247 ///
3248 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3249 /// when the qualification conversion involves a change in the Objective-C
3250 /// object lifetime.
3251 bool
3252 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3253                                 bool CStyle, bool &ObjCLifetimeConversion) {
3254   FromType = Context.getCanonicalType(FromType);
3255   ToType = Context.getCanonicalType(ToType);
3256   ObjCLifetimeConversion = false;
3257 
3258   // If FromType and ToType are the same type, this is not a
3259   // qualification conversion.
3260   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3261     return false;
3262 
3263   // (C++ 4.4p4):
3264   //   A conversion can add cv-qualifiers at levels other than the first
3265   //   in multi-level pointers, subject to the following rules: [...]
3266   bool PreviousToQualsIncludeConst = true;
3267   bool UnwrappedAnyPointer = false;
3268   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3269     if (!isQualificationConversionStep(
3270             FromType, ToType, CStyle, !UnwrappedAnyPointer,
3271             PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3272       return false;
3273     UnwrappedAnyPointer = true;
3274   }
3275 
3276   // We are left with FromType and ToType being the pointee types
3277   // after unwrapping the original FromType and ToType the same number
3278   // of times. If we unwrapped any pointers, and if FromType and
3279   // ToType have the same unqualified type (since we checked
3280   // qualifiers above), then this is a qualification conversion.
3281   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3282 }
3283 
3284 /// - Determine whether this is a conversion from a scalar type to an
3285 /// atomic type.
3286 ///
3287 /// If successful, updates \c SCS's second and third steps in the conversion
3288 /// sequence to finish the conversion.
3289 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3290                                 bool InOverloadResolution,
3291                                 StandardConversionSequence &SCS,
3292                                 bool CStyle) {
3293   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3294   if (!ToAtomic)
3295     return false;
3296 
3297   StandardConversionSequence InnerSCS;
3298   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3299                             InOverloadResolution, InnerSCS,
3300                             CStyle, /*AllowObjCWritebackConversion=*/false))
3301     return false;
3302 
3303   SCS.Second = InnerSCS.Second;
3304   SCS.setToType(1, InnerSCS.getToType(1));
3305   SCS.Third = InnerSCS.Third;
3306   SCS.QualificationIncludesObjCLifetime
3307     = InnerSCS.QualificationIncludesObjCLifetime;
3308   SCS.setToType(2, InnerSCS.getToType(2));
3309   return true;
3310 }
3311 
3312 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3313                                               CXXConstructorDecl *Constructor,
3314                                               QualType Type) {
3315   const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3316   if (CtorType->getNumParams() > 0) {
3317     QualType FirstArg = CtorType->getParamType(0);
3318     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3319       return true;
3320   }
3321   return false;
3322 }
3323 
3324 static OverloadingResult
3325 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3326                                        CXXRecordDecl *To,
3327                                        UserDefinedConversionSequence &User,
3328                                        OverloadCandidateSet &CandidateSet,
3329                                        bool AllowExplicit) {
3330   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3331   for (auto *D : S.LookupConstructors(To)) {
3332     auto Info = getConstructorInfo(D);
3333     if (!Info)
3334       continue;
3335 
3336     bool Usable = !Info.Constructor->isInvalidDecl() &&
3337                   S.isInitListConstructor(Info.Constructor);
3338     if (Usable) {
3339       // If the first argument is (a reference to) the target type,
3340       // suppress conversions.
3341       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3342           S.Context, Info.Constructor, ToType);
3343       if (Info.ConstructorTmpl)
3344         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3345                                        /*ExplicitArgs*/ nullptr, From,
3346                                        CandidateSet, SuppressUserConversions,
3347                                        /*PartialOverloading*/ false,
3348                                        AllowExplicit);
3349       else
3350         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3351                                CandidateSet, SuppressUserConversions,
3352                                /*PartialOverloading*/ false, AllowExplicit);
3353     }
3354   }
3355 
3356   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3357 
3358   OverloadCandidateSet::iterator Best;
3359   switch (auto Result =
3360               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3361   case OR_Deleted:
3362   case OR_Success: {
3363     // Record the standard conversion we used and the conversion function.
3364     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3365     QualType ThisType = Constructor->getThisType();
3366     // Initializer lists don't have conversions as such.
3367     User.Before.setAsIdentityConversion();
3368     User.HadMultipleCandidates = HadMultipleCandidates;
3369     User.ConversionFunction = Constructor;
3370     User.FoundConversionFunction = Best->FoundDecl;
3371     User.After.setAsIdentityConversion();
3372     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3373     User.After.setAllToTypes(ToType);
3374     return Result;
3375   }
3376 
3377   case OR_No_Viable_Function:
3378     return OR_No_Viable_Function;
3379   case OR_Ambiguous:
3380     return OR_Ambiguous;
3381   }
3382 
3383   llvm_unreachable("Invalid OverloadResult!");
3384 }
3385 
3386 /// Determines whether there is a user-defined conversion sequence
3387 /// (C++ [over.ics.user]) that converts expression From to the type
3388 /// ToType. If such a conversion exists, User will contain the
3389 /// user-defined conversion sequence that performs such a conversion
3390 /// and this routine will return true. Otherwise, this routine returns
3391 /// false and User is unspecified.
3392 ///
3393 /// \param AllowExplicit  true if the conversion should consider C++0x
3394 /// "explicit" conversion functions as well as non-explicit conversion
3395 /// functions (C++0x [class.conv.fct]p2).
3396 ///
3397 /// \param AllowObjCConversionOnExplicit true if the conversion should
3398 /// allow an extra Objective-C pointer conversion on uses of explicit
3399 /// constructors. Requires \c AllowExplicit to also be set.
3400 static OverloadingResult
3401 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3402                         UserDefinedConversionSequence &User,
3403                         OverloadCandidateSet &CandidateSet,
3404                         AllowedExplicit AllowExplicit,
3405                         bool AllowObjCConversionOnExplicit) {
3406   assert(AllowExplicit != AllowedExplicit::None ||
3407          !AllowObjCConversionOnExplicit);
3408   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3409 
3410   // Whether we will only visit constructors.
3411   bool ConstructorsOnly = false;
3412 
3413   // If the type we are conversion to is a class type, enumerate its
3414   // constructors.
3415   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3416     // C++ [over.match.ctor]p1:
3417     //   When objects of class type are direct-initialized (8.5), or
3418     //   copy-initialized from an expression of the same or a
3419     //   derived class type (8.5), overload resolution selects the
3420     //   constructor. [...] For copy-initialization, the candidate
3421     //   functions are all the converting constructors (12.3.1) of
3422     //   that class. The argument list is the expression-list within
3423     //   the parentheses of the initializer.
3424     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3425         (From->getType()->getAs<RecordType>() &&
3426          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3427       ConstructorsOnly = true;
3428 
3429     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3430       // We're not going to find any constructors.
3431     } else if (CXXRecordDecl *ToRecordDecl
3432                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3433 
3434       Expr **Args = &From;
3435       unsigned NumArgs = 1;
3436       bool ListInitializing = false;
3437       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3438         // But first, see if there is an init-list-constructor that will work.
3439         OverloadingResult Result = IsInitializerListConstructorConversion(
3440             S, From, ToType, ToRecordDecl, User, CandidateSet,
3441             AllowExplicit == AllowedExplicit::All);
3442         if (Result != OR_No_Viable_Function)
3443           return Result;
3444         // Never mind.
3445         CandidateSet.clear(
3446             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3447 
3448         // If we're list-initializing, we pass the individual elements as
3449         // arguments, not the entire list.
3450         Args = InitList->getInits();
3451         NumArgs = InitList->getNumInits();
3452         ListInitializing = true;
3453       }
3454 
3455       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3456         auto Info = getConstructorInfo(D);
3457         if (!Info)
3458           continue;
3459 
3460         bool Usable = !Info.Constructor->isInvalidDecl();
3461         if (!ListInitializing)
3462           Usable = Usable && Info.Constructor->isConvertingConstructor(
3463                                  /*AllowExplicit*/ true);
3464         if (Usable) {
3465           bool SuppressUserConversions = !ConstructorsOnly;
3466           if (SuppressUserConversions && ListInitializing) {
3467             SuppressUserConversions = false;
3468             if (NumArgs == 1) {
3469               // If the first argument is (a reference to) the target type,
3470               // suppress conversions.
3471               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3472                   S.Context, Info.Constructor, ToType);
3473             }
3474           }
3475           if (Info.ConstructorTmpl)
3476             S.AddTemplateOverloadCandidate(
3477                 Info.ConstructorTmpl, Info.FoundDecl,
3478                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3479                 CandidateSet, SuppressUserConversions,
3480                 /*PartialOverloading*/ false,
3481                 AllowExplicit == AllowedExplicit::All);
3482           else
3483             // Allow one user-defined conversion when user specifies a
3484             // From->ToType conversion via an static cast (c-style, etc).
3485             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3486                                    llvm::makeArrayRef(Args, NumArgs),
3487                                    CandidateSet, SuppressUserConversions,
3488                                    /*PartialOverloading*/ false,
3489                                    AllowExplicit == AllowedExplicit::All);
3490         }
3491       }
3492     }
3493   }
3494 
3495   // Enumerate conversion functions, if we're allowed to.
3496   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3497   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3498     // No conversion functions from incomplete types.
3499   } else if (const RecordType *FromRecordType =
3500                  From->getType()->getAs<RecordType>()) {
3501     if (CXXRecordDecl *FromRecordDecl
3502          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3503       // Add all of the conversion functions as candidates.
3504       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3505       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3506         DeclAccessPair FoundDecl = I.getPair();
3507         NamedDecl *D = FoundDecl.getDecl();
3508         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3509         if (isa<UsingShadowDecl>(D))
3510           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3511 
3512         CXXConversionDecl *Conv;
3513         FunctionTemplateDecl *ConvTemplate;
3514         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3515           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3516         else
3517           Conv = cast<CXXConversionDecl>(D);
3518 
3519         if (ConvTemplate)
3520           S.AddTemplateConversionCandidate(
3521               ConvTemplate, FoundDecl, ActingContext, From, ToType,
3522               CandidateSet, AllowObjCConversionOnExplicit,
3523               AllowExplicit != AllowedExplicit::None);
3524         else
3525           S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3526                                    CandidateSet, AllowObjCConversionOnExplicit,
3527                                    AllowExplicit != AllowedExplicit::None);
3528       }
3529     }
3530   }
3531 
3532   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3533 
3534   OverloadCandidateSet::iterator Best;
3535   switch (auto Result =
3536               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3537   case OR_Success:
3538   case OR_Deleted:
3539     // Record the standard conversion we used and the conversion function.
3540     if (CXXConstructorDecl *Constructor
3541           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3542       // C++ [over.ics.user]p1:
3543       //   If the user-defined conversion is specified by a
3544       //   constructor (12.3.1), the initial standard conversion
3545       //   sequence converts the source type to the type required by
3546       //   the argument of the constructor.
3547       //
3548       QualType ThisType = Constructor->getThisType();
3549       if (isa<InitListExpr>(From)) {
3550         // Initializer lists don't have conversions as such.
3551         User.Before.setAsIdentityConversion();
3552       } else {
3553         if (Best->Conversions[0].isEllipsis())
3554           User.EllipsisConversion = true;
3555         else {
3556           User.Before = Best->Conversions[0].Standard;
3557           User.EllipsisConversion = false;
3558         }
3559       }
3560       User.HadMultipleCandidates = HadMultipleCandidates;
3561       User.ConversionFunction = Constructor;
3562       User.FoundConversionFunction = Best->FoundDecl;
3563       User.After.setAsIdentityConversion();
3564       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3565       User.After.setAllToTypes(ToType);
3566       return Result;
3567     }
3568     if (CXXConversionDecl *Conversion
3569                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3570       // C++ [over.ics.user]p1:
3571       //
3572       //   [...] If the user-defined conversion is specified by a
3573       //   conversion function (12.3.2), the initial standard
3574       //   conversion sequence converts the source type to the
3575       //   implicit object parameter of the conversion function.
3576       User.Before = Best->Conversions[0].Standard;
3577       User.HadMultipleCandidates = HadMultipleCandidates;
3578       User.ConversionFunction = Conversion;
3579       User.FoundConversionFunction = Best->FoundDecl;
3580       User.EllipsisConversion = false;
3581 
3582       // C++ [over.ics.user]p2:
3583       //   The second standard conversion sequence converts the
3584       //   result of the user-defined conversion to the target type
3585       //   for the sequence. Since an implicit conversion sequence
3586       //   is an initialization, the special rules for
3587       //   initialization by user-defined conversion apply when
3588       //   selecting the best user-defined conversion for a
3589       //   user-defined conversion sequence (see 13.3.3 and
3590       //   13.3.3.1).
3591       User.After = Best->FinalConversion;
3592       return Result;
3593     }
3594     llvm_unreachable("Not a constructor or conversion function?");
3595 
3596   case OR_No_Viable_Function:
3597     return OR_No_Viable_Function;
3598 
3599   case OR_Ambiguous:
3600     return OR_Ambiguous;
3601   }
3602 
3603   llvm_unreachable("Invalid OverloadResult!");
3604 }
3605 
3606 bool
3607 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3608   ImplicitConversionSequence ICS;
3609   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3610                                     OverloadCandidateSet::CSK_Normal);
3611   OverloadingResult OvResult =
3612     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3613                             CandidateSet, AllowedExplicit::None, false);
3614 
3615   if (!(OvResult == OR_Ambiguous ||
3616         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3617     return false;
3618 
3619   auto Cands = CandidateSet.CompleteCandidates(
3620       *this,
3621       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3622       From);
3623   if (OvResult == OR_Ambiguous)
3624     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3625         << From->getType() << ToType << From->getSourceRange();
3626   else { // OR_No_Viable_Function && !CandidateSet.empty()
3627     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3628                              diag::err_typecheck_nonviable_condition_incomplete,
3629                              From->getType(), From->getSourceRange()))
3630       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3631           << false << From->getType() << From->getSourceRange() << ToType;
3632   }
3633 
3634   CandidateSet.NoteCandidates(
3635                               *this, From, Cands);
3636   return true;
3637 }
3638 
3639 /// Compare the user-defined conversion functions or constructors
3640 /// of two user-defined conversion sequences to determine whether any ordering
3641 /// is possible.
3642 static ImplicitConversionSequence::CompareKind
3643 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3644                            FunctionDecl *Function2) {
3645   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3646     return ImplicitConversionSequence::Indistinguishable;
3647 
3648   // Objective-C++:
3649   //   If both conversion functions are implicitly-declared conversions from
3650   //   a lambda closure type to a function pointer and a block pointer,
3651   //   respectively, always prefer the conversion to a function pointer,
3652   //   because the function pointer is more lightweight and is more likely
3653   //   to keep code working.
3654   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3655   if (!Conv1)
3656     return ImplicitConversionSequence::Indistinguishable;
3657 
3658   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3659   if (!Conv2)
3660     return ImplicitConversionSequence::Indistinguishable;
3661 
3662   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3663     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3664     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3665     if (Block1 != Block2)
3666       return Block1 ? ImplicitConversionSequence::Worse
3667                     : ImplicitConversionSequence::Better;
3668   }
3669 
3670   return ImplicitConversionSequence::Indistinguishable;
3671 }
3672 
3673 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3674     const ImplicitConversionSequence &ICS) {
3675   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3676          (ICS.isUserDefined() &&
3677           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3678 }
3679 
3680 /// CompareImplicitConversionSequences - Compare two implicit
3681 /// conversion sequences to determine whether one is better than the
3682 /// other or if they are indistinguishable (C++ 13.3.3.2).
3683 static ImplicitConversionSequence::CompareKind
3684 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3685                                    const ImplicitConversionSequence& ICS1,
3686                                    const ImplicitConversionSequence& ICS2)
3687 {
3688   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3689   // conversion sequences (as defined in 13.3.3.1)
3690   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3691   //      conversion sequence than a user-defined conversion sequence or
3692   //      an ellipsis conversion sequence, and
3693   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3694   //      conversion sequence than an ellipsis conversion sequence
3695   //      (13.3.3.1.3).
3696   //
3697   // C++0x [over.best.ics]p10:
3698   //   For the purpose of ranking implicit conversion sequences as
3699   //   described in 13.3.3.2, the ambiguous conversion sequence is
3700   //   treated as a user-defined sequence that is indistinguishable
3701   //   from any other user-defined conversion sequence.
3702 
3703   // String literal to 'char *' conversion has been deprecated in C++03. It has
3704   // been removed from C++11. We still accept this conversion, if it happens at
3705   // the best viable function. Otherwise, this conversion is considered worse
3706   // than ellipsis conversion. Consider this as an extension; this is not in the
3707   // standard. For example:
3708   //
3709   // int &f(...);    // #1
3710   // void f(char*);  // #2
3711   // void g() { int &r = f("foo"); }
3712   //
3713   // In C++03, we pick #2 as the best viable function.
3714   // In C++11, we pick #1 as the best viable function, because ellipsis
3715   // conversion is better than string-literal to char* conversion (since there
3716   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3717   // convert arguments, #2 would be the best viable function in C++11.
3718   // If the best viable function has this conversion, a warning will be issued
3719   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3720 
3721   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3722       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3723       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3724     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3725                ? ImplicitConversionSequence::Worse
3726                : ImplicitConversionSequence::Better;
3727 
3728   if (ICS1.getKindRank() < ICS2.getKindRank())
3729     return ImplicitConversionSequence::Better;
3730   if (ICS2.getKindRank() < ICS1.getKindRank())
3731     return ImplicitConversionSequence::Worse;
3732 
3733   // The following checks require both conversion sequences to be of
3734   // the same kind.
3735   if (ICS1.getKind() != ICS2.getKind())
3736     return ImplicitConversionSequence::Indistinguishable;
3737 
3738   ImplicitConversionSequence::CompareKind Result =
3739       ImplicitConversionSequence::Indistinguishable;
3740 
3741   // Two implicit conversion sequences of the same form are
3742   // indistinguishable conversion sequences unless one of the
3743   // following rules apply: (C++ 13.3.3.2p3):
3744 
3745   // List-initialization sequence L1 is a better conversion sequence than
3746   // list-initialization sequence L2 if:
3747   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3748   //   if not that,
3749   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3750   //   and N1 is smaller than N2.,
3751   // even if one of the other rules in this paragraph would otherwise apply.
3752   if (!ICS1.isBad()) {
3753     if (ICS1.isStdInitializerListElement() &&
3754         !ICS2.isStdInitializerListElement())
3755       return ImplicitConversionSequence::Better;
3756     if (!ICS1.isStdInitializerListElement() &&
3757         ICS2.isStdInitializerListElement())
3758       return ImplicitConversionSequence::Worse;
3759   }
3760 
3761   if (ICS1.isStandard())
3762     // Standard conversion sequence S1 is a better conversion sequence than
3763     // standard conversion sequence S2 if [...]
3764     Result = CompareStandardConversionSequences(S, Loc,
3765                                                 ICS1.Standard, ICS2.Standard);
3766   else if (ICS1.isUserDefined()) {
3767     // User-defined conversion sequence U1 is a better conversion
3768     // sequence than another user-defined conversion sequence U2 if
3769     // they contain the same user-defined conversion function or
3770     // constructor and if the second standard conversion sequence of
3771     // U1 is better than the second standard conversion sequence of
3772     // U2 (C++ 13.3.3.2p3).
3773     if (ICS1.UserDefined.ConversionFunction ==
3774           ICS2.UserDefined.ConversionFunction)
3775       Result = CompareStandardConversionSequences(S, Loc,
3776                                                   ICS1.UserDefined.After,
3777                                                   ICS2.UserDefined.After);
3778     else
3779       Result = compareConversionFunctions(S,
3780                                           ICS1.UserDefined.ConversionFunction,
3781                                           ICS2.UserDefined.ConversionFunction);
3782   }
3783 
3784   return Result;
3785 }
3786 
3787 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3788 // determine if one is a proper subset of the other.
3789 static ImplicitConversionSequence::CompareKind
3790 compareStandardConversionSubsets(ASTContext &Context,
3791                                  const StandardConversionSequence& SCS1,
3792                                  const StandardConversionSequence& SCS2) {
3793   ImplicitConversionSequence::CompareKind Result
3794     = ImplicitConversionSequence::Indistinguishable;
3795 
3796   // the identity conversion sequence is considered to be a subsequence of
3797   // any non-identity conversion sequence
3798   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3799     return ImplicitConversionSequence::Better;
3800   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3801     return ImplicitConversionSequence::Worse;
3802 
3803   if (SCS1.Second != SCS2.Second) {
3804     if (SCS1.Second == ICK_Identity)
3805       Result = ImplicitConversionSequence::Better;
3806     else if (SCS2.Second == ICK_Identity)
3807       Result = ImplicitConversionSequence::Worse;
3808     else
3809       return ImplicitConversionSequence::Indistinguishable;
3810   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3811     return ImplicitConversionSequence::Indistinguishable;
3812 
3813   if (SCS1.Third == SCS2.Third) {
3814     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3815                              : ImplicitConversionSequence::Indistinguishable;
3816   }
3817 
3818   if (SCS1.Third == ICK_Identity)
3819     return Result == ImplicitConversionSequence::Worse
3820              ? ImplicitConversionSequence::Indistinguishable
3821              : ImplicitConversionSequence::Better;
3822 
3823   if (SCS2.Third == ICK_Identity)
3824     return Result == ImplicitConversionSequence::Better
3825              ? ImplicitConversionSequence::Indistinguishable
3826              : ImplicitConversionSequence::Worse;
3827 
3828   return ImplicitConversionSequence::Indistinguishable;
3829 }
3830 
3831 /// Determine whether one of the given reference bindings is better
3832 /// than the other based on what kind of bindings they are.
3833 static bool
3834 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3835                              const StandardConversionSequence &SCS2) {
3836   // C++0x [over.ics.rank]p3b4:
3837   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3838   //      implicit object parameter of a non-static member function declared
3839   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3840   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3841   //      lvalue reference to a function lvalue and S2 binds an rvalue
3842   //      reference*.
3843   //
3844   // FIXME: Rvalue references. We're going rogue with the above edits,
3845   // because the semantics in the current C++0x working paper (N3225 at the
3846   // time of this writing) break the standard definition of std::forward
3847   // and std::reference_wrapper when dealing with references to functions.
3848   // Proposed wording changes submitted to CWG for consideration.
3849   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3850       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3851     return false;
3852 
3853   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3854           SCS2.IsLvalueReference) ||
3855          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3856           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3857 }
3858 
3859 enum class FixedEnumPromotion {
3860   None,
3861   ToUnderlyingType,
3862   ToPromotedUnderlyingType
3863 };
3864 
3865 /// Returns kind of fixed enum promotion the \a SCS uses.
3866 static FixedEnumPromotion
3867 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3868 
3869   if (SCS.Second != ICK_Integral_Promotion)
3870     return FixedEnumPromotion::None;
3871 
3872   QualType FromType = SCS.getFromType();
3873   if (!FromType->isEnumeralType())
3874     return FixedEnumPromotion::None;
3875 
3876   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3877   if (!Enum->isFixed())
3878     return FixedEnumPromotion::None;
3879 
3880   QualType UnderlyingType = Enum->getIntegerType();
3881   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3882     return FixedEnumPromotion::ToUnderlyingType;
3883 
3884   return FixedEnumPromotion::ToPromotedUnderlyingType;
3885 }
3886 
3887 /// CompareStandardConversionSequences - Compare two standard
3888 /// conversion sequences to determine whether one is better than the
3889 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3890 static ImplicitConversionSequence::CompareKind
3891 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3892                                    const StandardConversionSequence& SCS1,
3893                                    const StandardConversionSequence& SCS2)
3894 {
3895   // Standard conversion sequence S1 is a better conversion sequence
3896   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3897 
3898   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3899   //     sequences in the canonical form defined by 13.3.3.1.1,
3900   //     excluding any Lvalue Transformation; the identity conversion
3901   //     sequence is considered to be a subsequence of any
3902   //     non-identity conversion sequence) or, if not that,
3903   if (ImplicitConversionSequence::CompareKind CK
3904         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3905     return CK;
3906 
3907   //  -- the rank of S1 is better than the rank of S2 (by the rules
3908   //     defined below), or, if not that,
3909   ImplicitConversionRank Rank1 = SCS1.getRank();
3910   ImplicitConversionRank Rank2 = SCS2.getRank();
3911   if (Rank1 < Rank2)
3912     return ImplicitConversionSequence::Better;
3913   else if (Rank2 < Rank1)
3914     return ImplicitConversionSequence::Worse;
3915 
3916   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3917   // are indistinguishable unless one of the following rules
3918   // applies:
3919 
3920   //   A conversion that is not a conversion of a pointer, or
3921   //   pointer to member, to bool is better than another conversion
3922   //   that is such a conversion.
3923   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3924     return SCS2.isPointerConversionToBool()
3925              ? ImplicitConversionSequence::Better
3926              : ImplicitConversionSequence::Worse;
3927 
3928   // C++14 [over.ics.rank]p4b2:
3929   // This is retroactively applied to C++11 by CWG 1601.
3930   //
3931   //   A conversion that promotes an enumeration whose underlying type is fixed
3932   //   to its underlying type is better than one that promotes to the promoted
3933   //   underlying type, if the two are different.
3934   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3935   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3936   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3937       FEP1 != FEP2)
3938     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3939                ? ImplicitConversionSequence::Better
3940                : ImplicitConversionSequence::Worse;
3941 
3942   // C++ [over.ics.rank]p4b2:
3943   //
3944   //   If class B is derived directly or indirectly from class A,
3945   //   conversion of B* to A* is better than conversion of B* to
3946   //   void*, and conversion of A* to void* is better than conversion
3947   //   of B* to void*.
3948   bool SCS1ConvertsToVoid
3949     = SCS1.isPointerConversionToVoidPointer(S.Context);
3950   bool SCS2ConvertsToVoid
3951     = SCS2.isPointerConversionToVoidPointer(S.Context);
3952   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3953     // Exactly one of the conversion sequences is a conversion to
3954     // a void pointer; it's the worse conversion.
3955     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3956                               : ImplicitConversionSequence::Worse;
3957   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3958     // Neither conversion sequence converts to a void pointer; compare
3959     // their derived-to-base conversions.
3960     if (ImplicitConversionSequence::CompareKind DerivedCK
3961           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3962       return DerivedCK;
3963   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3964              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3965     // Both conversion sequences are conversions to void
3966     // pointers. Compare the source types to determine if there's an
3967     // inheritance relationship in their sources.
3968     QualType FromType1 = SCS1.getFromType();
3969     QualType FromType2 = SCS2.getFromType();
3970 
3971     // Adjust the types we're converting from via the array-to-pointer
3972     // conversion, if we need to.
3973     if (SCS1.First == ICK_Array_To_Pointer)
3974       FromType1 = S.Context.getArrayDecayedType(FromType1);
3975     if (SCS2.First == ICK_Array_To_Pointer)
3976       FromType2 = S.Context.getArrayDecayedType(FromType2);
3977 
3978     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3979     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3980 
3981     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3982       return ImplicitConversionSequence::Better;
3983     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3984       return ImplicitConversionSequence::Worse;
3985 
3986     // Objective-C++: If one interface is more specific than the
3987     // other, it is the better one.
3988     const ObjCObjectPointerType* FromObjCPtr1
3989       = FromType1->getAs<ObjCObjectPointerType>();
3990     const ObjCObjectPointerType* FromObjCPtr2
3991       = FromType2->getAs<ObjCObjectPointerType>();
3992     if (FromObjCPtr1 && FromObjCPtr2) {
3993       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3994                                                           FromObjCPtr2);
3995       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3996                                                            FromObjCPtr1);
3997       if (AssignLeft != AssignRight) {
3998         return AssignLeft? ImplicitConversionSequence::Better
3999                          : ImplicitConversionSequence::Worse;
4000       }
4001     }
4002   }
4003 
4004   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4005     // Check for a better reference binding based on the kind of bindings.
4006     if (isBetterReferenceBindingKind(SCS1, SCS2))
4007       return ImplicitConversionSequence::Better;
4008     else if (isBetterReferenceBindingKind(SCS2, SCS1))
4009       return ImplicitConversionSequence::Worse;
4010   }
4011 
4012   // Compare based on qualification conversions (C++ 13.3.3.2p3,
4013   // bullet 3).
4014   if (ImplicitConversionSequence::CompareKind QualCK
4015         = CompareQualificationConversions(S, SCS1, SCS2))
4016     return QualCK;
4017 
4018   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4019     // C++ [over.ics.rank]p3b4:
4020     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
4021     //      which the references refer are the same type except for
4022     //      top-level cv-qualifiers, and the type to which the reference
4023     //      initialized by S2 refers is more cv-qualified than the type
4024     //      to which the reference initialized by S1 refers.
4025     QualType T1 = SCS1.getToType(2);
4026     QualType T2 = SCS2.getToType(2);
4027     T1 = S.Context.getCanonicalType(T1);
4028     T2 = S.Context.getCanonicalType(T2);
4029     Qualifiers T1Quals, T2Quals;
4030     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4031     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4032     if (UnqualT1 == UnqualT2) {
4033       // Objective-C++ ARC: If the references refer to objects with different
4034       // lifetimes, prefer bindings that don't change lifetime.
4035       if (SCS1.ObjCLifetimeConversionBinding !=
4036                                           SCS2.ObjCLifetimeConversionBinding) {
4037         return SCS1.ObjCLifetimeConversionBinding
4038                                            ? ImplicitConversionSequence::Worse
4039                                            : ImplicitConversionSequence::Better;
4040       }
4041 
4042       // If the type is an array type, promote the element qualifiers to the
4043       // type for comparison.
4044       if (isa<ArrayType>(T1) && T1Quals)
4045         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4046       if (isa<ArrayType>(T2) && T2Quals)
4047         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4048       if (T2.isMoreQualifiedThan(T1))
4049         return ImplicitConversionSequence::Better;
4050       if (T1.isMoreQualifiedThan(T2))
4051         return ImplicitConversionSequence::Worse;
4052     }
4053   }
4054 
4055   // In Microsoft mode, prefer an integral conversion to a
4056   // floating-to-integral conversion if the integral conversion
4057   // is between types of the same size.
4058   // For example:
4059   // void f(float);
4060   // void f(int);
4061   // int main {
4062   //    long a;
4063   //    f(a);
4064   // }
4065   // Here, MSVC will call f(int) instead of generating a compile error
4066   // as clang will do in standard mode.
4067   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4068       SCS2.Second == ICK_Floating_Integral &&
4069       S.Context.getTypeSize(SCS1.getFromType()) ==
4070           S.Context.getTypeSize(SCS1.getToType(2)))
4071     return ImplicitConversionSequence::Better;
4072 
4073   // Prefer a compatible vector conversion over a lax vector conversion
4074   // For example:
4075   //
4076   // typedef float __v4sf __attribute__((__vector_size__(16)));
4077   // void f(vector float);
4078   // void f(vector signed int);
4079   // int main() {
4080   //   __v4sf a;
4081   //   f(a);
4082   // }
4083   // Here, we'd like to choose f(vector float) and not
4084   // report an ambiguous call error
4085   if (SCS1.Second == ICK_Vector_Conversion &&
4086       SCS2.Second == ICK_Vector_Conversion) {
4087     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4088         SCS1.getFromType(), SCS1.getToType(2));
4089     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4090         SCS2.getFromType(), SCS2.getToType(2));
4091 
4092     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4093       return SCS1IsCompatibleVectorConversion
4094                  ? ImplicitConversionSequence::Better
4095                  : ImplicitConversionSequence::Worse;
4096   }
4097 
4098   return ImplicitConversionSequence::Indistinguishable;
4099 }
4100 
4101 /// CompareQualificationConversions - Compares two standard conversion
4102 /// sequences to determine whether they can be ranked based on their
4103 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4104 static ImplicitConversionSequence::CompareKind
4105 CompareQualificationConversions(Sema &S,
4106                                 const StandardConversionSequence& SCS1,
4107                                 const StandardConversionSequence& SCS2) {
4108   // C++ 13.3.3.2p3:
4109   //  -- S1 and S2 differ only in their qualification conversion and
4110   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4111   //     cv-qualification signature of type T1 is a proper subset of
4112   //     the cv-qualification signature of type T2, and S1 is not the
4113   //     deprecated string literal array-to-pointer conversion (4.2).
4114   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4115       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4116     return ImplicitConversionSequence::Indistinguishable;
4117 
4118   // FIXME: the example in the standard doesn't use a qualification
4119   // conversion (!)
4120   QualType T1 = SCS1.getToType(2);
4121   QualType T2 = SCS2.getToType(2);
4122   T1 = S.Context.getCanonicalType(T1);
4123   T2 = S.Context.getCanonicalType(T2);
4124   assert(!T1->isReferenceType() && !T2->isReferenceType());
4125   Qualifiers T1Quals, T2Quals;
4126   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4127   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4128 
4129   // If the types are the same, we won't learn anything by unwrapping
4130   // them.
4131   if (UnqualT1 == UnqualT2)
4132     return ImplicitConversionSequence::Indistinguishable;
4133 
4134   ImplicitConversionSequence::CompareKind Result
4135     = ImplicitConversionSequence::Indistinguishable;
4136 
4137   // Objective-C++ ARC:
4138   //   Prefer qualification conversions not involving a change in lifetime
4139   //   to qualification conversions that do not change lifetime.
4140   if (SCS1.QualificationIncludesObjCLifetime !=
4141                                       SCS2.QualificationIncludesObjCLifetime) {
4142     Result = SCS1.QualificationIncludesObjCLifetime
4143                ? ImplicitConversionSequence::Worse
4144                : ImplicitConversionSequence::Better;
4145   }
4146 
4147   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4148     // Within each iteration of the loop, we check the qualifiers to
4149     // determine if this still looks like a qualification
4150     // conversion. Then, if all is well, we unwrap one more level of
4151     // pointers or pointers-to-members and do it all again
4152     // until there are no more pointers or pointers-to-members left
4153     // to unwrap. This essentially mimics what
4154     // IsQualificationConversion does, but here we're checking for a
4155     // strict subset of qualifiers.
4156     if (T1.getQualifiers().withoutObjCLifetime() ==
4157         T2.getQualifiers().withoutObjCLifetime())
4158       // The qualifiers are the same, so this doesn't tell us anything
4159       // about how the sequences rank.
4160       // ObjC ownership quals are omitted above as they interfere with
4161       // the ARC overload rule.
4162       ;
4163     else if (T2.isMoreQualifiedThan(T1)) {
4164       // T1 has fewer qualifiers, so it could be the better sequence.
4165       if (Result == ImplicitConversionSequence::Worse)
4166         // Neither has qualifiers that are a subset of the other's
4167         // qualifiers.
4168         return ImplicitConversionSequence::Indistinguishable;
4169 
4170       Result = ImplicitConversionSequence::Better;
4171     } else if (T1.isMoreQualifiedThan(T2)) {
4172       // T2 has fewer qualifiers, so it could be the better sequence.
4173       if (Result == ImplicitConversionSequence::Better)
4174         // Neither has qualifiers that are a subset of the other's
4175         // qualifiers.
4176         return ImplicitConversionSequence::Indistinguishable;
4177 
4178       Result = ImplicitConversionSequence::Worse;
4179     } else {
4180       // Qualifiers are disjoint.
4181       return ImplicitConversionSequence::Indistinguishable;
4182     }
4183 
4184     // If the types after this point are equivalent, we're done.
4185     if (S.Context.hasSameUnqualifiedType(T1, T2))
4186       break;
4187   }
4188 
4189   // Check that the winning standard conversion sequence isn't using
4190   // the deprecated string literal array to pointer conversion.
4191   switch (Result) {
4192   case ImplicitConversionSequence::Better:
4193     if (SCS1.DeprecatedStringLiteralToCharPtr)
4194       Result = ImplicitConversionSequence::Indistinguishable;
4195     break;
4196 
4197   case ImplicitConversionSequence::Indistinguishable:
4198     break;
4199 
4200   case ImplicitConversionSequence::Worse:
4201     if (SCS2.DeprecatedStringLiteralToCharPtr)
4202       Result = ImplicitConversionSequence::Indistinguishable;
4203     break;
4204   }
4205 
4206   return Result;
4207 }
4208 
4209 /// CompareDerivedToBaseConversions - Compares two standard conversion
4210 /// sequences to determine whether they can be ranked based on their
4211 /// various kinds of derived-to-base conversions (C++
4212 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4213 /// conversions between Objective-C interface types.
4214 static ImplicitConversionSequence::CompareKind
4215 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4216                                 const StandardConversionSequence& SCS1,
4217                                 const StandardConversionSequence& SCS2) {
4218   QualType FromType1 = SCS1.getFromType();
4219   QualType ToType1 = SCS1.getToType(1);
4220   QualType FromType2 = SCS2.getFromType();
4221   QualType ToType2 = SCS2.getToType(1);
4222 
4223   // Adjust the types we're converting from via the array-to-pointer
4224   // conversion, if we need to.
4225   if (SCS1.First == ICK_Array_To_Pointer)
4226     FromType1 = S.Context.getArrayDecayedType(FromType1);
4227   if (SCS2.First == ICK_Array_To_Pointer)
4228     FromType2 = S.Context.getArrayDecayedType(FromType2);
4229 
4230   // Canonicalize all of the types.
4231   FromType1 = S.Context.getCanonicalType(FromType1);
4232   ToType1 = S.Context.getCanonicalType(ToType1);
4233   FromType2 = S.Context.getCanonicalType(FromType2);
4234   ToType2 = S.Context.getCanonicalType(ToType2);
4235 
4236   // C++ [over.ics.rank]p4b3:
4237   //
4238   //   If class B is derived directly or indirectly from class A and
4239   //   class C is derived directly or indirectly from B,
4240   //
4241   // Compare based on pointer conversions.
4242   if (SCS1.Second == ICK_Pointer_Conversion &&
4243       SCS2.Second == ICK_Pointer_Conversion &&
4244       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4245       FromType1->isPointerType() && FromType2->isPointerType() &&
4246       ToType1->isPointerType() && ToType2->isPointerType()) {
4247     QualType FromPointee1 =
4248         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4249     QualType ToPointee1 =
4250         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4251     QualType FromPointee2 =
4252         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4253     QualType ToPointee2 =
4254         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4255 
4256     //   -- conversion of C* to B* is better than conversion of C* to A*,
4257     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4258       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4259         return ImplicitConversionSequence::Better;
4260       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4261         return ImplicitConversionSequence::Worse;
4262     }
4263 
4264     //   -- conversion of B* to A* is better than conversion of C* to A*,
4265     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4266       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4267         return ImplicitConversionSequence::Better;
4268       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4269         return ImplicitConversionSequence::Worse;
4270     }
4271   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4272              SCS2.Second == ICK_Pointer_Conversion) {
4273     const ObjCObjectPointerType *FromPtr1
4274       = FromType1->getAs<ObjCObjectPointerType>();
4275     const ObjCObjectPointerType *FromPtr2
4276       = FromType2->getAs<ObjCObjectPointerType>();
4277     const ObjCObjectPointerType *ToPtr1
4278       = ToType1->getAs<ObjCObjectPointerType>();
4279     const ObjCObjectPointerType *ToPtr2
4280       = ToType2->getAs<ObjCObjectPointerType>();
4281 
4282     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4283       // Apply the same conversion ranking rules for Objective-C pointer types
4284       // that we do for C++ pointers to class types. However, we employ the
4285       // Objective-C pseudo-subtyping relationship used for assignment of
4286       // Objective-C pointer types.
4287       bool FromAssignLeft
4288         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4289       bool FromAssignRight
4290         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4291       bool ToAssignLeft
4292         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4293       bool ToAssignRight
4294         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4295 
4296       // A conversion to an a non-id object pointer type or qualified 'id'
4297       // type is better than a conversion to 'id'.
4298       if (ToPtr1->isObjCIdType() &&
4299           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4300         return ImplicitConversionSequence::Worse;
4301       if (ToPtr2->isObjCIdType() &&
4302           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4303         return ImplicitConversionSequence::Better;
4304 
4305       // A conversion to a non-id object pointer type is better than a
4306       // conversion to a qualified 'id' type
4307       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4308         return ImplicitConversionSequence::Worse;
4309       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4310         return ImplicitConversionSequence::Better;
4311 
4312       // A conversion to an a non-Class object pointer type or qualified 'Class'
4313       // type is better than a conversion to 'Class'.
4314       if (ToPtr1->isObjCClassType() &&
4315           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4316         return ImplicitConversionSequence::Worse;
4317       if (ToPtr2->isObjCClassType() &&
4318           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4319         return ImplicitConversionSequence::Better;
4320 
4321       // A conversion to a non-Class object pointer type is better than a
4322       // conversion to a qualified 'Class' type.
4323       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4324         return ImplicitConversionSequence::Worse;
4325       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4326         return ImplicitConversionSequence::Better;
4327 
4328       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4329       if (S.Context.hasSameType(FromType1, FromType2) &&
4330           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4331           (ToAssignLeft != ToAssignRight)) {
4332         if (FromPtr1->isSpecialized()) {
4333           // "conversion of B<A> * to B * is better than conversion of B * to
4334           // C *.
4335           bool IsFirstSame =
4336               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4337           bool IsSecondSame =
4338               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4339           if (IsFirstSame) {
4340             if (!IsSecondSame)
4341               return ImplicitConversionSequence::Better;
4342           } else if (IsSecondSame)
4343             return ImplicitConversionSequence::Worse;
4344         }
4345         return ToAssignLeft? ImplicitConversionSequence::Worse
4346                            : ImplicitConversionSequence::Better;
4347       }
4348 
4349       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4350       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4351           (FromAssignLeft != FromAssignRight))
4352         return FromAssignLeft? ImplicitConversionSequence::Better
4353         : ImplicitConversionSequence::Worse;
4354     }
4355   }
4356 
4357   // Ranking of member-pointer types.
4358   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4359       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4360       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4361     const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4362     const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4363     const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4364     const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4365     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4366     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4367     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4368     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4369     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4370     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4371     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4372     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4373     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4374     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4375       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4376         return ImplicitConversionSequence::Worse;
4377       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4378         return ImplicitConversionSequence::Better;
4379     }
4380     // conversion of B::* to C::* is better than conversion of A::* to C::*
4381     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4382       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4383         return ImplicitConversionSequence::Better;
4384       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4385         return ImplicitConversionSequence::Worse;
4386     }
4387   }
4388 
4389   if (SCS1.Second == ICK_Derived_To_Base) {
4390     //   -- conversion of C to B is better than conversion of C to A,
4391     //   -- binding of an expression of type C to a reference of type
4392     //      B& is better than binding an expression of type C to a
4393     //      reference of type A&,
4394     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4395         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4396       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4397         return ImplicitConversionSequence::Better;
4398       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4399         return ImplicitConversionSequence::Worse;
4400     }
4401 
4402     //   -- conversion of B to A is better than conversion of C to A.
4403     //   -- binding of an expression of type B to a reference of type
4404     //      A& is better than binding an expression of type C to a
4405     //      reference of type A&,
4406     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4407         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4408       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4409         return ImplicitConversionSequence::Better;
4410       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4411         return ImplicitConversionSequence::Worse;
4412     }
4413   }
4414 
4415   return ImplicitConversionSequence::Indistinguishable;
4416 }
4417 
4418 /// Determine whether the given type is valid, e.g., it is not an invalid
4419 /// C++ class.
4420 static bool isTypeValid(QualType T) {
4421   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4422     return !Record->isInvalidDecl();
4423 
4424   return true;
4425 }
4426 
4427 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4428   if (!T.getQualifiers().hasUnaligned())
4429     return T;
4430 
4431   Qualifiers Q;
4432   T = Ctx.getUnqualifiedArrayType(T, Q);
4433   Q.removeUnaligned();
4434   return Ctx.getQualifiedType(T, Q);
4435 }
4436 
4437 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4438 /// determine whether they are reference-compatible,
4439 /// reference-related, or incompatible, for use in C++ initialization by
4440 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4441 /// type, and the first type (T1) is the pointee type of the reference
4442 /// type being initialized.
4443 Sema::ReferenceCompareResult
4444 Sema::CompareReferenceRelationship(SourceLocation Loc,
4445                                    QualType OrigT1, QualType OrigT2,
4446                                    ReferenceConversions *ConvOut) {
4447   assert(!OrigT1->isReferenceType() &&
4448     "T1 must be the pointee type of the reference type");
4449   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4450 
4451   QualType T1 = Context.getCanonicalType(OrigT1);
4452   QualType T2 = Context.getCanonicalType(OrigT2);
4453   Qualifiers T1Quals, T2Quals;
4454   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4455   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4456 
4457   ReferenceConversions ConvTmp;
4458   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4459   Conv = ReferenceConversions();
4460 
4461   // C++2a [dcl.init.ref]p4:
4462   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4463   //   reference-related to "cv2 T2" if T1 is similar to T2, or
4464   //   T1 is a base class of T2.
4465   //   "cv1 T1" is reference-compatible with "cv2 T2" if
4466   //   a prvalue of type "pointer to cv2 T2" can be converted to the type
4467   //   "pointer to cv1 T1" via a standard conversion sequence.
4468 
4469   // Check for standard conversions we can apply to pointers: derived-to-base
4470   // conversions, ObjC pointer conversions, and function pointer conversions.
4471   // (Qualification conversions are checked last.)
4472   QualType ConvertedT2;
4473   if (UnqualT1 == UnqualT2) {
4474     // Nothing to do.
4475   } else if (isCompleteType(Loc, OrigT2) &&
4476              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4477              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4478     Conv |= ReferenceConversions::DerivedToBase;
4479   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4480            UnqualT2->isObjCObjectOrInterfaceType() &&
4481            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4482     Conv |= ReferenceConversions::ObjC;
4483   else if (UnqualT2->isFunctionType() &&
4484            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4485     Conv |= ReferenceConversions::Function;
4486     // No need to check qualifiers; function types don't have them.
4487     return Ref_Compatible;
4488   }
4489   bool ConvertedReferent = Conv != 0;
4490 
4491   // We can have a qualification conversion. Compute whether the types are
4492   // similar at the same time.
4493   bool PreviousToQualsIncludeConst = true;
4494   bool TopLevel = true;
4495   do {
4496     if (T1 == T2)
4497       break;
4498 
4499     // We will need a qualification conversion.
4500     Conv |= ReferenceConversions::Qualification;
4501 
4502     // Track whether we performed a qualification conversion anywhere other
4503     // than the top level. This matters for ranking reference bindings in
4504     // overload resolution.
4505     if (!TopLevel)
4506       Conv |= ReferenceConversions::NestedQualification;
4507 
4508     // MS compiler ignores __unaligned qualifier for references; do the same.
4509     T1 = withoutUnaligned(Context, T1);
4510     T2 = withoutUnaligned(Context, T2);
4511 
4512     // If we find a qualifier mismatch, the types are not reference-compatible,
4513     // but are still be reference-related if they're similar.
4514     bool ObjCLifetimeConversion = false;
4515     if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4516                                        PreviousToQualsIncludeConst,
4517                                        ObjCLifetimeConversion))
4518       return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4519                  ? Ref_Related
4520                  : Ref_Incompatible;
4521 
4522     // FIXME: Should we track this for any level other than the first?
4523     if (ObjCLifetimeConversion)
4524       Conv |= ReferenceConversions::ObjCLifetime;
4525 
4526     TopLevel = false;
4527   } while (Context.UnwrapSimilarTypes(T1, T2));
4528 
4529   // At this point, if the types are reference-related, we must either have the
4530   // same inner type (ignoring qualifiers), or must have already worked out how
4531   // to convert the referent.
4532   return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4533              ? Ref_Compatible
4534              : Ref_Incompatible;
4535 }
4536 
4537 /// Look for a user-defined conversion to a value reference-compatible
4538 ///        with DeclType. Return true if something definite is found.
4539 static bool
4540 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4541                          QualType DeclType, SourceLocation DeclLoc,
4542                          Expr *Init, QualType T2, bool AllowRvalues,
4543                          bool AllowExplicit) {
4544   assert(T2->isRecordType() && "Can only find conversions of record types.");
4545   auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4546 
4547   OverloadCandidateSet CandidateSet(
4548       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4549   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4550   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4551     NamedDecl *D = *I;
4552     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4553     if (isa<UsingShadowDecl>(D))
4554       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4555 
4556     FunctionTemplateDecl *ConvTemplate
4557       = dyn_cast<FunctionTemplateDecl>(D);
4558     CXXConversionDecl *Conv;
4559     if (ConvTemplate)
4560       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4561     else
4562       Conv = cast<CXXConversionDecl>(D);
4563 
4564     if (AllowRvalues) {
4565       // If we are initializing an rvalue reference, don't permit conversion
4566       // functions that return lvalues.
4567       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4568         const ReferenceType *RefType
4569           = Conv->getConversionType()->getAs<LValueReferenceType>();
4570         if (RefType && !RefType->getPointeeType()->isFunctionType())
4571           continue;
4572       }
4573 
4574       if (!ConvTemplate &&
4575           S.CompareReferenceRelationship(
4576               DeclLoc,
4577               Conv->getConversionType()
4578                   .getNonReferenceType()
4579                   .getUnqualifiedType(),
4580               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4581               Sema::Ref_Incompatible)
4582         continue;
4583     } else {
4584       // If the conversion function doesn't return a reference type,
4585       // it can't be considered for this conversion. An rvalue reference
4586       // is only acceptable if its referencee is a function type.
4587 
4588       const ReferenceType *RefType =
4589         Conv->getConversionType()->getAs<ReferenceType>();
4590       if (!RefType ||
4591           (!RefType->isLValueReferenceType() &&
4592            !RefType->getPointeeType()->isFunctionType()))
4593         continue;
4594     }
4595 
4596     if (ConvTemplate)
4597       S.AddTemplateConversionCandidate(
4598           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4599           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4600     else
4601       S.AddConversionCandidate(
4602           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4603           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4604   }
4605 
4606   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4607 
4608   OverloadCandidateSet::iterator Best;
4609   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4610   case OR_Success:
4611     // C++ [over.ics.ref]p1:
4612     //
4613     //   [...] If the parameter binds directly to the result of
4614     //   applying a conversion function to the argument
4615     //   expression, the implicit conversion sequence is a
4616     //   user-defined conversion sequence (13.3.3.1.2), with the
4617     //   second standard conversion sequence either an identity
4618     //   conversion or, if the conversion function returns an
4619     //   entity of a type that is a derived class of the parameter
4620     //   type, a derived-to-base Conversion.
4621     if (!Best->FinalConversion.DirectBinding)
4622       return false;
4623 
4624     ICS.setUserDefined();
4625     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4626     ICS.UserDefined.After = Best->FinalConversion;
4627     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4628     ICS.UserDefined.ConversionFunction = Best->Function;
4629     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4630     ICS.UserDefined.EllipsisConversion = false;
4631     assert(ICS.UserDefined.After.ReferenceBinding &&
4632            ICS.UserDefined.After.DirectBinding &&
4633            "Expected a direct reference binding!");
4634     return true;
4635 
4636   case OR_Ambiguous:
4637     ICS.setAmbiguous();
4638     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4639          Cand != CandidateSet.end(); ++Cand)
4640       if (Cand->Best)
4641         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4642     return true;
4643 
4644   case OR_No_Viable_Function:
4645   case OR_Deleted:
4646     // There was no suitable conversion, or we found a deleted
4647     // conversion; continue with other checks.
4648     return false;
4649   }
4650 
4651   llvm_unreachable("Invalid OverloadResult!");
4652 }
4653 
4654 /// Compute an implicit conversion sequence for reference
4655 /// initialization.
4656 static ImplicitConversionSequence
4657 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4658                  SourceLocation DeclLoc,
4659                  bool SuppressUserConversions,
4660                  bool AllowExplicit) {
4661   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4662 
4663   // Most paths end in a failed conversion.
4664   ImplicitConversionSequence ICS;
4665   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4666 
4667   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4668   QualType T2 = Init->getType();
4669 
4670   // If the initializer is the address of an overloaded function, try
4671   // to resolve the overloaded function. If all goes well, T2 is the
4672   // type of the resulting function.
4673   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4674     DeclAccessPair Found;
4675     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4676                                                                 false, Found))
4677       T2 = Fn->getType();
4678   }
4679 
4680   // Compute some basic properties of the types and the initializer.
4681   bool isRValRef = DeclType->isRValueReferenceType();
4682   Expr::Classification InitCategory = Init->Classify(S.Context);
4683 
4684   Sema::ReferenceConversions RefConv;
4685   Sema::ReferenceCompareResult RefRelationship =
4686       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4687 
4688   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4689     ICS.setStandard();
4690     ICS.Standard.First = ICK_Identity;
4691     // FIXME: A reference binding can be a function conversion too. We should
4692     // consider that when ordering reference-to-function bindings.
4693     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4694                               ? ICK_Derived_To_Base
4695                               : (RefConv & Sema::ReferenceConversions::ObjC)
4696                                     ? ICK_Compatible_Conversion
4697                                     : ICK_Identity;
4698     // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4699     // a reference binding that performs a non-top-level qualification
4700     // conversion as a qualification conversion, not as an identity conversion.
4701     ICS.Standard.Third = (RefConv &
4702                               Sema::ReferenceConversions::NestedQualification)
4703                              ? ICK_Qualification
4704                              : ICK_Identity;
4705     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4706     ICS.Standard.setToType(0, T2);
4707     ICS.Standard.setToType(1, T1);
4708     ICS.Standard.setToType(2, T1);
4709     ICS.Standard.ReferenceBinding = true;
4710     ICS.Standard.DirectBinding = BindsDirectly;
4711     ICS.Standard.IsLvalueReference = !isRValRef;
4712     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4713     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4714     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4715     ICS.Standard.ObjCLifetimeConversionBinding =
4716         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4717     ICS.Standard.CopyConstructor = nullptr;
4718     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4719   };
4720 
4721   // C++0x [dcl.init.ref]p5:
4722   //   A reference to type "cv1 T1" is initialized by an expression
4723   //   of type "cv2 T2" as follows:
4724 
4725   //     -- If reference is an lvalue reference and the initializer expression
4726   if (!isRValRef) {
4727     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4728     //        reference-compatible with "cv2 T2," or
4729     //
4730     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4731     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4732       // C++ [over.ics.ref]p1:
4733       //   When a parameter of reference type binds directly (8.5.3)
4734       //   to an argument expression, the implicit conversion sequence
4735       //   is the identity conversion, unless the argument expression
4736       //   has a type that is a derived class of the parameter type,
4737       //   in which case the implicit conversion sequence is a
4738       //   derived-to-base Conversion (13.3.3.1).
4739       SetAsReferenceBinding(/*BindsDirectly=*/true);
4740 
4741       // Nothing more to do: the inaccessibility/ambiguity check for
4742       // derived-to-base conversions is suppressed when we're
4743       // computing the implicit conversion sequence (C++
4744       // [over.best.ics]p2).
4745       return ICS;
4746     }
4747 
4748     //       -- has a class type (i.e., T2 is a class type), where T1 is
4749     //          not reference-related to T2, and can be implicitly
4750     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4751     //          is reference-compatible with "cv3 T3" 92) (this
4752     //          conversion is selected by enumerating the applicable
4753     //          conversion functions (13.3.1.6) and choosing the best
4754     //          one through overload resolution (13.3)),
4755     if (!SuppressUserConversions && T2->isRecordType() &&
4756         S.isCompleteType(DeclLoc, T2) &&
4757         RefRelationship == Sema::Ref_Incompatible) {
4758       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4759                                    Init, T2, /*AllowRvalues=*/false,
4760                                    AllowExplicit))
4761         return ICS;
4762     }
4763   }
4764 
4765   //     -- Otherwise, the reference shall be an lvalue reference to a
4766   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4767   //        shall be an rvalue reference.
4768   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4769     return ICS;
4770 
4771   //       -- If the initializer expression
4772   //
4773   //            -- is an xvalue, class prvalue, array prvalue or function
4774   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4775   if (RefRelationship == Sema::Ref_Compatible &&
4776       (InitCategory.isXValue() ||
4777        (InitCategory.isPRValue() &&
4778           (T2->isRecordType() || T2->isArrayType())) ||
4779        (InitCategory.isLValue() && T2->isFunctionType()))) {
4780     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4781     // binding unless we're binding to a class prvalue.
4782     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4783     // allow the use of rvalue references in C++98/03 for the benefit of
4784     // standard library implementors; therefore, we need the xvalue check here.
4785     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4786                           !(InitCategory.isPRValue() || T2->isRecordType()));
4787     return ICS;
4788   }
4789 
4790   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4791   //               reference-related to T2, and can be implicitly converted to
4792   //               an xvalue, class prvalue, or function lvalue of type
4793   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4794   //               "cv3 T3",
4795   //
4796   //          then the reference is bound to the value of the initializer
4797   //          expression in the first case and to the result of the conversion
4798   //          in the second case (or, in either case, to an appropriate base
4799   //          class subobject).
4800   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4801       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4802       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4803                                Init, T2, /*AllowRvalues=*/true,
4804                                AllowExplicit)) {
4805     // In the second case, if the reference is an rvalue reference
4806     // and the second standard conversion sequence of the
4807     // user-defined conversion sequence includes an lvalue-to-rvalue
4808     // conversion, the program is ill-formed.
4809     if (ICS.isUserDefined() && isRValRef &&
4810         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4811       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4812 
4813     return ICS;
4814   }
4815 
4816   // A temporary of function type cannot be created; don't even try.
4817   if (T1->isFunctionType())
4818     return ICS;
4819 
4820   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4821   //          initialized from the initializer expression using the
4822   //          rules for a non-reference copy initialization (8.5). The
4823   //          reference is then bound to the temporary. If T1 is
4824   //          reference-related to T2, cv1 must be the same
4825   //          cv-qualification as, or greater cv-qualification than,
4826   //          cv2; otherwise, the program is ill-formed.
4827   if (RefRelationship == Sema::Ref_Related) {
4828     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4829     // we would be reference-compatible or reference-compatible with
4830     // added qualification. But that wasn't the case, so the reference
4831     // initialization fails.
4832     //
4833     // Note that we only want to check address spaces and cvr-qualifiers here.
4834     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4835     Qualifiers T1Quals = T1.getQualifiers();
4836     Qualifiers T2Quals = T2.getQualifiers();
4837     T1Quals.removeObjCGCAttr();
4838     T1Quals.removeObjCLifetime();
4839     T2Quals.removeObjCGCAttr();
4840     T2Quals.removeObjCLifetime();
4841     // MS compiler ignores __unaligned qualifier for references; do the same.
4842     T1Quals.removeUnaligned();
4843     T2Quals.removeUnaligned();
4844     if (!T1Quals.compatiblyIncludes(T2Quals))
4845       return ICS;
4846   }
4847 
4848   // If at least one of the types is a class type, the types are not
4849   // related, and we aren't allowed any user conversions, the
4850   // reference binding fails. This case is important for breaking
4851   // recursion, since TryImplicitConversion below will attempt to
4852   // create a temporary through the use of a copy constructor.
4853   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4854       (T1->isRecordType() || T2->isRecordType()))
4855     return ICS;
4856 
4857   // If T1 is reference-related to T2 and the reference is an rvalue
4858   // reference, the initializer expression shall not be an lvalue.
4859   if (RefRelationship >= Sema::Ref_Related &&
4860       isRValRef && Init->Classify(S.Context).isLValue())
4861     return ICS;
4862 
4863   // C++ [over.ics.ref]p2:
4864   //   When a parameter of reference type is not bound directly to
4865   //   an argument expression, the conversion sequence is the one
4866   //   required to convert the argument expression to the
4867   //   underlying type of the reference according to
4868   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4869   //   to copy-initializing a temporary of the underlying type with
4870   //   the argument expression. Any difference in top-level
4871   //   cv-qualification is subsumed by the initialization itself
4872   //   and does not constitute a conversion.
4873   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4874                               AllowedExplicit::None,
4875                               /*InOverloadResolution=*/false,
4876                               /*CStyle=*/false,
4877                               /*AllowObjCWritebackConversion=*/false,
4878                               /*AllowObjCConversionOnExplicit=*/false);
4879 
4880   // Of course, that's still a reference binding.
4881   if (ICS.isStandard()) {
4882     ICS.Standard.ReferenceBinding = true;
4883     ICS.Standard.IsLvalueReference = !isRValRef;
4884     ICS.Standard.BindsToFunctionLvalue = false;
4885     ICS.Standard.BindsToRvalue = true;
4886     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4887     ICS.Standard.ObjCLifetimeConversionBinding = false;
4888   } else if (ICS.isUserDefined()) {
4889     const ReferenceType *LValRefType =
4890         ICS.UserDefined.ConversionFunction->getReturnType()
4891             ->getAs<LValueReferenceType>();
4892 
4893     // C++ [over.ics.ref]p3:
4894     //   Except for an implicit object parameter, for which see 13.3.1, a
4895     //   standard conversion sequence cannot be formed if it requires [...]
4896     //   binding an rvalue reference to an lvalue other than a function
4897     //   lvalue.
4898     // Note that the function case is not possible here.
4899     if (DeclType->isRValueReferenceType() && LValRefType) {
4900       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4901       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4902       // reference to an rvalue!
4903       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4904       return ICS;
4905     }
4906 
4907     ICS.UserDefined.After.ReferenceBinding = true;
4908     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4909     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4910     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4911     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4912     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4913   }
4914 
4915   return ICS;
4916 }
4917 
4918 static ImplicitConversionSequence
4919 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4920                       bool SuppressUserConversions,
4921                       bool InOverloadResolution,
4922                       bool AllowObjCWritebackConversion,
4923                       bool AllowExplicit = false);
4924 
4925 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4926 /// initializer list From.
4927 static ImplicitConversionSequence
4928 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4929                   bool SuppressUserConversions,
4930                   bool InOverloadResolution,
4931                   bool AllowObjCWritebackConversion) {
4932   // C++11 [over.ics.list]p1:
4933   //   When an argument is an initializer list, it is not an expression and
4934   //   special rules apply for converting it to a parameter type.
4935 
4936   ImplicitConversionSequence Result;
4937   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4938 
4939   // We need a complete type for what follows. Incomplete types can never be
4940   // initialized from init lists.
4941   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4942     return Result;
4943 
4944   // Per DR1467:
4945   //   If the parameter type is a class X and the initializer list has a single
4946   //   element of type cv U, where U is X or a class derived from X, the
4947   //   implicit conversion sequence is the one required to convert the element
4948   //   to the parameter type.
4949   //
4950   //   Otherwise, if the parameter type is a character array [... ]
4951   //   and the initializer list has a single element that is an
4952   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4953   //   implicit conversion sequence is the identity conversion.
4954   if (From->getNumInits() == 1) {
4955     if (ToType->isRecordType()) {
4956       QualType InitType = From->getInit(0)->getType();
4957       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4958           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4959         return TryCopyInitialization(S, From->getInit(0), ToType,
4960                                      SuppressUserConversions,
4961                                      InOverloadResolution,
4962                                      AllowObjCWritebackConversion);
4963     }
4964     // FIXME: Check the other conditions here: array of character type,
4965     // initializer is a string literal.
4966     if (ToType->isArrayType()) {
4967       InitializedEntity Entity =
4968         InitializedEntity::InitializeParameter(S.Context, ToType,
4969                                                /*Consumed=*/false);
4970       if (S.CanPerformCopyInitialization(Entity, From)) {
4971         Result.setStandard();
4972         Result.Standard.setAsIdentityConversion();
4973         Result.Standard.setFromType(ToType);
4974         Result.Standard.setAllToTypes(ToType);
4975         return Result;
4976       }
4977     }
4978   }
4979 
4980   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4981   // C++11 [over.ics.list]p2:
4982   //   If the parameter type is std::initializer_list<X> or "array of X" and
4983   //   all the elements can be implicitly converted to X, the implicit
4984   //   conversion sequence is the worst conversion necessary to convert an
4985   //   element of the list to X.
4986   //
4987   // C++14 [over.ics.list]p3:
4988   //   Otherwise, if the parameter type is "array of N X", if the initializer
4989   //   list has exactly N elements or if it has fewer than N elements and X is
4990   //   default-constructible, and if all the elements of the initializer list
4991   //   can be implicitly converted to X, the implicit conversion sequence is
4992   //   the worst conversion necessary to convert an element of the list to X.
4993   //
4994   // FIXME: We're missing a lot of these checks.
4995   bool toStdInitializerList = false;
4996   QualType X;
4997   if (ToType->isArrayType())
4998     X = S.Context.getAsArrayType(ToType)->getElementType();
4999   else
5000     toStdInitializerList = S.isStdInitializerList(ToType, &X);
5001   if (!X.isNull()) {
5002     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
5003       Expr *Init = From->getInit(i);
5004       ImplicitConversionSequence ICS =
5005           TryCopyInitialization(S, Init, X, SuppressUserConversions,
5006                                 InOverloadResolution,
5007                                 AllowObjCWritebackConversion);
5008       // If a single element isn't convertible, fail.
5009       if (ICS.isBad()) {
5010         Result = ICS;
5011         break;
5012       }
5013       // Otherwise, look for the worst conversion.
5014       if (Result.isBad() || CompareImplicitConversionSequences(
5015                                 S, From->getBeginLoc(), ICS, Result) ==
5016                                 ImplicitConversionSequence::Worse)
5017         Result = ICS;
5018     }
5019 
5020     // For an empty list, we won't have computed any conversion sequence.
5021     // Introduce the identity conversion sequence.
5022     if (From->getNumInits() == 0) {
5023       Result.setStandard();
5024       Result.Standard.setAsIdentityConversion();
5025       Result.Standard.setFromType(ToType);
5026       Result.Standard.setAllToTypes(ToType);
5027     }
5028 
5029     Result.setStdInitializerListElement(toStdInitializerList);
5030     return Result;
5031   }
5032 
5033   // C++14 [over.ics.list]p4:
5034   // C++11 [over.ics.list]p3:
5035   //   Otherwise, if the parameter is a non-aggregate class X and overload
5036   //   resolution chooses a single best constructor [...] the implicit
5037   //   conversion sequence is a user-defined conversion sequence. If multiple
5038   //   constructors are viable but none is better than the others, the
5039   //   implicit conversion sequence is a user-defined conversion sequence.
5040   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5041     // This function can deal with initializer lists.
5042     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5043                                     AllowedExplicit::None,
5044                                     InOverloadResolution, /*CStyle=*/false,
5045                                     AllowObjCWritebackConversion,
5046                                     /*AllowObjCConversionOnExplicit=*/false);
5047   }
5048 
5049   // C++14 [over.ics.list]p5:
5050   // C++11 [over.ics.list]p4:
5051   //   Otherwise, if the parameter has an aggregate type which can be
5052   //   initialized from the initializer list [...] the implicit conversion
5053   //   sequence is a user-defined conversion sequence.
5054   if (ToType->isAggregateType()) {
5055     // Type is an aggregate, argument is an init list. At this point it comes
5056     // down to checking whether the initialization works.
5057     // FIXME: Find out whether this parameter is consumed or not.
5058     InitializedEntity Entity =
5059         InitializedEntity::InitializeParameter(S.Context, ToType,
5060                                                /*Consumed=*/false);
5061     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5062                                                                  From)) {
5063       Result.setUserDefined();
5064       Result.UserDefined.Before.setAsIdentityConversion();
5065       // Initializer lists don't have a type.
5066       Result.UserDefined.Before.setFromType(QualType());
5067       Result.UserDefined.Before.setAllToTypes(QualType());
5068 
5069       Result.UserDefined.After.setAsIdentityConversion();
5070       Result.UserDefined.After.setFromType(ToType);
5071       Result.UserDefined.After.setAllToTypes(ToType);
5072       Result.UserDefined.ConversionFunction = nullptr;
5073     }
5074     return Result;
5075   }
5076 
5077   // C++14 [over.ics.list]p6:
5078   // C++11 [over.ics.list]p5:
5079   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5080   if (ToType->isReferenceType()) {
5081     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5082     // mention initializer lists in any way. So we go by what list-
5083     // initialization would do and try to extrapolate from that.
5084 
5085     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5086 
5087     // If the initializer list has a single element that is reference-related
5088     // to the parameter type, we initialize the reference from that.
5089     if (From->getNumInits() == 1) {
5090       Expr *Init = From->getInit(0);
5091 
5092       QualType T2 = Init->getType();
5093 
5094       // If the initializer is the address of an overloaded function, try
5095       // to resolve the overloaded function. If all goes well, T2 is the
5096       // type of the resulting function.
5097       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5098         DeclAccessPair Found;
5099         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5100                                    Init, ToType, false, Found))
5101           T2 = Fn->getType();
5102       }
5103 
5104       // Compute some basic properties of the types and the initializer.
5105       Sema::ReferenceCompareResult RefRelationship =
5106           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5107 
5108       if (RefRelationship >= Sema::Ref_Related) {
5109         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5110                                 SuppressUserConversions,
5111                                 /*AllowExplicit=*/false);
5112       }
5113     }
5114 
5115     // Otherwise, we bind the reference to a temporary created from the
5116     // initializer list.
5117     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5118                                InOverloadResolution,
5119                                AllowObjCWritebackConversion);
5120     if (Result.isFailure())
5121       return Result;
5122     assert(!Result.isEllipsis() &&
5123            "Sub-initialization cannot result in ellipsis conversion.");
5124 
5125     // Can we even bind to a temporary?
5126     if (ToType->isRValueReferenceType() ||
5127         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5128       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5129                                             Result.UserDefined.After;
5130       SCS.ReferenceBinding = true;
5131       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5132       SCS.BindsToRvalue = true;
5133       SCS.BindsToFunctionLvalue = false;
5134       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5135       SCS.ObjCLifetimeConversionBinding = false;
5136     } else
5137       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5138                     From, ToType);
5139     return Result;
5140   }
5141 
5142   // C++14 [over.ics.list]p7:
5143   // C++11 [over.ics.list]p6:
5144   //   Otherwise, if the parameter type is not a class:
5145   if (!ToType->isRecordType()) {
5146     //    - if the initializer list has one element that is not itself an
5147     //      initializer list, the implicit conversion sequence is the one
5148     //      required to convert the element to the parameter type.
5149     unsigned NumInits = From->getNumInits();
5150     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5151       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5152                                      SuppressUserConversions,
5153                                      InOverloadResolution,
5154                                      AllowObjCWritebackConversion);
5155     //    - if the initializer list has no elements, the implicit conversion
5156     //      sequence is the identity conversion.
5157     else if (NumInits == 0) {
5158       Result.setStandard();
5159       Result.Standard.setAsIdentityConversion();
5160       Result.Standard.setFromType(ToType);
5161       Result.Standard.setAllToTypes(ToType);
5162     }
5163     return Result;
5164   }
5165 
5166   // C++14 [over.ics.list]p8:
5167   // C++11 [over.ics.list]p7:
5168   //   In all cases other than those enumerated above, no conversion is possible
5169   return Result;
5170 }
5171 
5172 /// TryCopyInitialization - Try to copy-initialize a value of type
5173 /// ToType from the expression From. Return the implicit conversion
5174 /// sequence required to pass this argument, which may be a bad
5175 /// conversion sequence (meaning that the argument cannot be passed to
5176 /// a parameter of this type). If @p SuppressUserConversions, then we
5177 /// do not permit any user-defined conversion sequences.
5178 static ImplicitConversionSequence
5179 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5180                       bool SuppressUserConversions,
5181                       bool InOverloadResolution,
5182                       bool AllowObjCWritebackConversion,
5183                       bool AllowExplicit) {
5184   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5185     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5186                              InOverloadResolution,AllowObjCWritebackConversion);
5187 
5188   if (ToType->isReferenceType())
5189     return TryReferenceInit(S, From, ToType,
5190                             /*FIXME:*/ From->getBeginLoc(),
5191                             SuppressUserConversions, AllowExplicit);
5192 
5193   return TryImplicitConversion(S, From, ToType,
5194                                SuppressUserConversions,
5195                                AllowedExplicit::None,
5196                                InOverloadResolution,
5197                                /*CStyle=*/false,
5198                                AllowObjCWritebackConversion,
5199                                /*AllowObjCConversionOnExplicit=*/false);
5200 }
5201 
5202 static bool TryCopyInitialization(const CanQualType FromQTy,
5203                                   const CanQualType ToQTy,
5204                                   Sema &S,
5205                                   SourceLocation Loc,
5206                                   ExprValueKind FromVK) {
5207   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5208   ImplicitConversionSequence ICS =
5209     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5210 
5211   return !ICS.isBad();
5212 }
5213 
5214 /// TryObjectArgumentInitialization - Try to initialize the object
5215 /// parameter of the given member function (@c Method) from the
5216 /// expression @p From.
5217 static ImplicitConversionSequence
5218 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5219                                 Expr::Classification FromClassification,
5220                                 CXXMethodDecl *Method,
5221                                 CXXRecordDecl *ActingContext) {
5222   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5223   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5224   //                 const volatile object.
5225   Qualifiers Quals = Method->getMethodQualifiers();
5226   if (isa<CXXDestructorDecl>(Method)) {
5227     Quals.addConst();
5228     Quals.addVolatile();
5229   }
5230 
5231   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5232 
5233   // Set up the conversion sequence as a "bad" conversion, to allow us
5234   // to exit early.
5235   ImplicitConversionSequence ICS;
5236 
5237   // We need to have an object of class type.
5238   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5239     FromType = PT->getPointeeType();
5240 
5241     // When we had a pointer, it's implicitly dereferenced, so we
5242     // better have an lvalue.
5243     assert(FromClassification.isLValue());
5244   }
5245 
5246   assert(FromType->isRecordType());
5247 
5248   // C++0x [over.match.funcs]p4:
5249   //   For non-static member functions, the type of the implicit object
5250   //   parameter is
5251   //
5252   //     - "lvalue reference to cv X" for functions declared without a
5253   //        ref-qualifier or with the & ref-qualifier
5254   //     - "rvalue reference to cv X" for functions declared with the &&
5255   //        ref-qualifier
5256   //
5257   // where X is the class of which the function is a member and cv is the
5258   // cv-qualification on the member function declaration.
5259   //
5260   // However, when finding an implicit conversion sequence for the argument, we
5261   // are not allowed to perform user-defined conversions
5262   // (C++ [over.match.funcs]p5). We perform a simplified version of
5263   // reference binding here, that allows class rvalues to bind to
5264   // non-constant references.
5265 
5266   // First check the qualifiers.
5267   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5268   if (ImplicitParamType.getCVRQualifiers()
5269                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5270       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5271     ICS.setBad(BadConversionSequence::bad_qualifiers,
5272                FromType, ImplicitParamType);
5273     return ICS;
5274   }
5275 
5276   if (FromTypeCanon.hasAddressSpace()) {
5277     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5278     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5279     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5280       ICS.setBad(BadConversionSequence::bad_qualifiers,
5281                  FromType, ImplicitParamType);
5282       return ICS;
5283     }
5284   }
5285 
5286   // Check that we have either the same type or a derived type. It
5287   // affects the conversion rank.
5288   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5289   ImplicitConversionKind SecondKind;
5290   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5291     SecondKind = ICK_Identity;
5292   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5293     SecondKind = ICK_Derived_To_Base;
5294   else {
5295     ICS.setBad(BadConversionSequence::unrelated_class,
5296                FromType, ImplicitParamType);
5297     return ICS;
5298   }
5299 
5300   // Check the ref-qualifier.
5301   switch (Method->getRefQualifier()) {
5302   case RQ_None:
5303     // Do nothing; we don't care about lvalueness or rvalueness.
5304     break;
5305 
5306   case RQ_LValue:
5307     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5308       // non-const lvalue reference cannot bind to an rvalue
5309       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5310                  ImplicitParamType);
5311       return ICS;
5312     }
5313     break;
5314 
5315   case RQ_RValue:
5316     if (!FromClassification.isRValue()) {
5317       // rvalue reference cannot bind to an lvalue
5318       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5319                  ImplicitParamType);
5320       return ICS;
5321     }
5322     break;
5323   }
5324 
5325   // Success. Mark this as a reference binding.
5326   ICS.setStandard();
5327   ICS.Standard.setAsIdentityConversion();
5328   ICS.Standard.Second = SecondKind;
5329   ICS.Standard.setFromType(FromType);
5330   ICS.Standard.setAllToTypes(ImplicitParamType);
5331   ICS.Standard.ReferenceBinding = true;
5332   ICS.Standard.DirectBinding = true;
5333   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5334   ICS.Standard.BindsToFunctionLvalue = false;
5335   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5336   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5337     = (Method->getRefQualifier() == RQ_None);
5338   return ICS;
5339 }
5340 
5341 /// PerformObjectArgumentInitialization - Perform initialization of
5342 /// the implicit object parameter for the given Method with the given
5343 /// expression.
5344 ExprResult
5345 Sema::PerformObjectArgumentInitialization(Expr *From,
5346                                           NestedNameSpecifier *Qualifier,
5347                                           NamedDecl *FoundDecl,
5348                                           CXXMethodDecl *Method) {
5349   QualType FromRecordType, DestType;
5350   QualType ImplicitParamRecordType  =
5351     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5352 
5353   Expr::Classification FromClassification;
5354   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5355     FromRecordType = PT->getPointeeType();
5356     DestType = Method->getThisType();
5357     FromClassification = Expr::Classification::makeSimpleLValue();
5358   } else {
5359     FromRecordType = From->getType();
5360     DestType = ImplicitParamRecordType;
5361     FromClassification = From->Classify(Context);
5362 
5363     // When performing member access on an rvalue, materialize a temporary.
5364     if (From->isRValue()) {
5365       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5366                                             Method->getRefQualifier() !=
5367                                                 RefQualifierKind::RQ_RValue);
5368     }
5369   }
5370 
5371   // Note that we always use the true parent context when performing
5372   // the actual argument initialization.
5373   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5374       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5375       Method->getParent());
5376   if (ICS.isBad()) {
5377     switch (ICS.Bad.Kind) {
5378     case BadConversionSequence::bad_qualifiers: {
5379       Qualifiers FromQs = FromRecordType.getQualifiers();
5380       Qualifiers ToQs = DestType.getQualifiers();
5381       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5382       if (CVR) {
5383         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5384             << Method->getDeclName() << FromRecordType << (CVR - 1)
5385             << From->getSourceRange();
5386         Diag(Method->getLocation(), diag::note_previous_decl)
5387           << Method->getDeclName();
5388         return ExprError();
5389       }
5390       break;
5391     }
5392 
5393     case BadConversionSequence::lvalue_ref_to_rvalue:
5394     case BadConversionSequence::rvalue_ref_to_lvalue: {
5395       bool IsRValueQualified =
5396         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5397       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5398           << Method->getDeclName() << FromClassification.isRValue()
5399           << IsRValueQualified;
5400       Diag(Method->getLocation(), diag::note_previous_decl)
5401         << Method->getDeclName();
5402       return ExprError();
5403     }
5404 
5405     case BadConversionSequence::no_conversion:
5406     case BadConversionSequence::unrelated_class:
5407       break;
5408     }
5409 
5410     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5411            << ImplicitParamRecordType << FromRecordType
5412            << From->getSourceRange();
5413   }
5414 
5415   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5416     ExprResult FromRes =
5417       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5418     if (FromRes.isInvalid())
5419       return ExprError();
5420     From = FromRes.get();
5421   }
5422 
5423   if (!Context.hasSameType(From->getType(), DestType)) {
5424     CastKind CK;
5425     QualType PteeTy = DestType->getPointeeType();
5426     LangAS DestAS =
5427         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5428     if (FromRecordType.getAddressSpace() != DestAS)
5429       CK = CK_AddressSpaceConversion;
5430     else
5431       CK = CK_NoOp;
5432     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5433   }
5434   return From;
5435 }
5436 
5437 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5438 /// expression From to bool (C++0x [conv]p3).
5439 static ImplicitConversionSequence
5440 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5441   return TryImplicitConversion(S, From, S.Context.BoolTy,
5442                                /*SuppressUserConversions=*/false,
5443                                AllowedExplicit::Conversions,
5444                                /*InOverloadResolution=*/false,
5445                                /*CStyle=*/false,
5446                                /*AllowObjCWritebackConversion=*/false,
5447                                /*AllowObjCConversionOnExplicit=*/false);
5448 }
5449 
5450 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5451 /// of the expression From to bool (C++0x [conv]p3).
5452 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5453   if (checkPlaceholderForOverload(*this, From))
5454     return ExprError();
5455 
5456   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5457   if (!ICS.isBad())
5458     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5459 
5460   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5461     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5462            << From->getType() << From->getSourceRange();
5463   return ExprError();
5464 }
5465 
5466 /// Check that the specified conversion is permitted in a converted constant
5467 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5468 /// is acceptable.
5469 static bool CheckConvertedConstantConversions(Sema &S,
5470                                               StandardConversionSequence &SCS) {
5471   // Since we know that the target type is an integral or unscoped enumeration
5472   // type, most conversion kinds are impossible. All possible First and Third
5473   // conversions are fine.
5474   switch (SCS.Second) {
5475   case ICK_Identity:
5476   case ICK_Function_Conversion:
5477   case ICK_Integral_Promotion:
5478   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5479   case ICK_Zero_Queue_Conversion:
5480     return true;
5481 
5482   case ICK_Boolean_Conversion:
5483     // Conversion from an integral or unscoped enumeration type to bool is
5484     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5485     // conversion, so we allow it in a converted constant expression.
5486     //
5487     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5488     // a lot of popular code. We should at least add a warning for this
5489     // (non-conforming) extension.
5490     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5491            SCS.getToType(2)->isBooleanType();
5492 
5493   case ICK_Pointer_Conversion:
5494   case ICK_Pointer_Member:
5495     // C++1z: null pointer conversions and null member pointer conversions are
5496     // only permitted if the source type is std::nullptr_t.
5497     return SCS.getFromType()->isNullPtrType();
5498 
5499   case ICK_Floating_Promotion:
5500   case ICK_Complex_Promotion:
5501   case ICK_Floating_Conversion:
5502   case ICK_Complex_Conversion:
5503   case ICK_Floating_Integral:
5504   case ICK_Compatible_Conversion:
5505   case ICK_Derived_To_Base:
5506   case ICK_Vector_Conversion:
5507   case ICK_Vector_Splat:
5508   case ICK_Complex_Real:
5509   case ICK_Block_Pointer_Conversion:
5510   case ICK_TransparentUnionConversion:
5511   case ICK_Writeback_Conversion:
5512   case ICK_Zero_Event_Conversion:
5513   case ICK_C_Only_Conversion:
5514   case ICK_Incompatible_Pointer_Conversion:
5515     return false;
5516 
5517   case ICK_Lvalue_To_Rvalue:
5518   case ICK_Array_To_Pointer:
5519   case ICK_Function_To_Pointer:
5520     llvm_unreachable("found a first conversion kind in Second");
5521 
5522   case ICK_Qualification:
5523     llvm_unreachable("found a third conversion kind in Second");
5524 
5525   case ICK_Num_Conversion_Kinds:
5526     break;
5527   }
5528 
5529   llvm_unreachable("unknown conversion kind");
5530 }
5531 
5532 /// CheckConvertedConstantExpression - Check that the expression From is a
5533 /// converted constant expression of type T, perform the conversion and produce
5534 /// the converted expression, per C++11 [expr.const]p3.
5535 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5536                                                    QualType T, APValue &Value,
5537                                                    Sema::CCEKind CCE,
5538                                                    bool RequireInt) {
5539   assert(S.getLangOpts().CPlusPlus11 &&
5540          "converted constant expression outside C++11");
5541 
5542   if (checkPlaceholderForOverload(S, From))
5543     return ExprError();
5544 
5545   // C++1z [expr.const]p3:
5546   //  A converted constant expression of type T is an expression,
5547   //  implicitly converted to type T, where the converted
5548   //  expression is a constant expression and the implicit conversion
5549   //  sequence contains only [... list of conversions ...].
5550   // C++1z [stmt.if]p2:
5551   //  If the if statement is of the form if constexpr, the value of the
5552   //  condition shall be a contextually converted constant expression of type
5553   //  bool.
5554   ImplicitConversionSequence ICS =
5555       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5556           ? TryContextuallyConvertToBool(S, From)
5557           : TryCopyInitialization(S, From, T,
5558                                   /*SuppressUserConversions=*/false,
5559                                   /*InOverloadResolution=*/false,
5560                                   /*AllowObjCWritebackConversion=*/false,
5561                                   /*AllowExplicit=*/false);
5562   StandardConversionSequence *SCS = nullptr;
5563   switch (ICS.getKind()) {
5564   case ImplicitConversionSequence::StandardConversion:
5565     SCS = &ICS.Standard;
5566     break;
5567   case ImplicitConversionSequence::UserDefinedConversion:
5568     // We are converting to a non-class type, so the Before sequence
5569     // must be trivial.
5570     SCS = &ICS.UserDefined.After;
5571     break;
5572   case ImplicitConversionSequence::AmbiguousConversion:
5573   case ImplicitConversionSequence::BadConversion:
5574     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5575       return S.Diag(From->getBeginLoc(),
5576                     diag::err_typecheck_converted_constant_expression)
5577              << From->getType() << From->getSourceRange() << T;
5578     return ExprError();
5579 
5580   case ImplicitConversionSequence::EllipsisConversion:
5581     llvm_unreachable("ellipsis conversion in converted constant expression");
5582   }
5583 
5584   // Check that we would only use permitted conversions.
5585   if (!CheckConvertedConstantConversions(S, *SCS)) {
5586     return S.Diag(From->getBeginLoc(),
5587                   diag::err_typecheck_converted_constant_expression_disallowed)
5588            << From->getType() << From->getSourceRange() << T;
5589   }
5590   // [...] and where the reference binding (if any) binds directly.
5591   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5592     return S.Diag(From->getBeginLoc(),
5593                   diag::err_typecheck_converted_constant_expression_indirect)
5594            << From->getType() << From->getSourceRange() << T;
5595   }
5596 
5597   ExprResult Result =
5598       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5599   if (Result.isInvalid())
5600     return Result;
5601 
5602   // C++2a [intro.execution]p5:
5603   //   A full-expression is [...] a constant-expression [...]
5604   Result =
5605       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5606                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5607   if (Result.isInvalid())
5608     return Result;
5609 
5610   // Check for a narrowing implicit conversion.
5611   APValue PreNarrowingValue;
5612   QualType PreNarrowingType;
5613   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5614                                 PreNarrowingType)) {
5615   case NK_Dependent_Narrowing:
5616     // Implicit conversion to a narrower type, but the expression is
5617     // value-dependent so we can't tell whether it's actually narrowing.
5618   case NK_Variable_Narrowing:
5619     // Implicit conversion to a narrower type, and the value is not a constant
5620     // expression. We'll diagnose this in a moment.
5621   case NK_Not_Narrowing:
5622     break;
5623 
5624   case NK_Constant_Narrowing:
5625     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5626         << CCE << /*Constant*/ 1
5627         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5628     break;
5629 
5630   case NK_Type_Narrowing:
5631     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5632         << CCE << /*Constant*/ 0 << From->getType() << T;
5633     break;
5634   }
5635 
5636   if (Result.get()->isValueDependent()) {
5637     Value = APValue();
5638     return Result;
5639   }
5640 
5641   // Check the expression is a constant expression.
5642   SmallVector<PartialDiagnosticAt, 8> Notes;
5643   Expr::EvalResult Eval;
5644   Eval.Diag = &Notes;
5645   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5646                                    ? Expr::EvaluateForMangling
5647                                    : Expr::EvaluateForCodeGen;
5648 
5649   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5650       (RequireInt && !Eval.Val.isInt())) {
5651     // The expression can't be folded, so we can't keep it at this position in
5652     // the AST.
5653     Result = ExprError();
5654   } else {
5655     Value = Eval.Val;
5656 
5657     if (Notes.empty()) {
5658       // It's a constant expression.
5659       return ConstantExpr::Create(S.Context, Result.get(), Value);
5660     }
5661   }
5662 
5663   // It's not a constant expression. Produce an appropriate diagnostic.
5664   if (Notes.size() == 1 &&
5665       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5666     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5667   else {
5668     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5669         << CCE << From->getSourceRange();
5670     for (unsigned I = 0; I < Notes.size(); ++I)
5671       S.Diag(Notes[I].first, Notes[I].second);
5672   }
5673   return ExprError();
5674 }
5675 
5676 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5677                                                   APValue &Value, CCEKind CCE) {
5678   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5679 }
5680 
5681 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5682                                                   llvm::APSInt &Value,
5683                                                   CCEKind CCE) {
5684   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5685 
5686   APValue V;
5687   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5688   if (!R.isInvalid() && !R.get()->isValueDependent())
5689     Value = V.getInt();
5690   return R;
5691 }
5692 
5693 
5694 /// dropPointerConversions - If the given standard conversion sequence
5695 /// involves any pointer conversions, remove them.  This may change
5696 /// the result type of the conversion sequence.
5697 static void dropPointerConversion(StandardConversionSequence &SCS) {
5698   if (SCS.Second == ICK_Pointer_Conversion) {
5699     SCS.Second = ICK_Identity;
5700     SCS.Third = ICK_Identity;
5701     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5702   }
5703 }
5704 
5705 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5706 /// convert the expression From to an Objective-C pointer type.
5707 static ImplicitConversionSequence
5708 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5709   // Do an implicit conversion to 'id'.
5710   QualType Ty = S.Context.getObjCIdType();
5711   ImplicitConversionSequence ICS
5712     = TryImplicitConversion(S, From, Ty,
5713                             // FIXME: Are these flags correct?
5714                             /*SuppressUserConversions=*/false,
5715                             AllowedExplicit::Conversions,
5716                             /*InOverloadResolution=*/false,
5717                             /*CStyle=*/false,
5718                             /*AllowObjCWritebackConversion=*/false,
5719                             /*AllowObjCConversionOnExplicit=*/true);
5720 
5721   // Strip off any final conversions to 'id'.
5722   switch (ICS.getKind()) {
5723   case ImplicitConversionSequence::BadConversion:
5724   case ImplicitConversionSequence::AmbiguousConversion:
5725   case ImplicitConversionSequence::EllipsisConversion:
5726     break;
5727 
5728   case ImplicitConversionSequence::UserDefinedConversion:
5729     dropPointerConversion(ICS.UserDefined.After);
5730     break;
5731 
5732   case ImplicitConversionSequence::StandardConversion:
5733     dropPointerConversion(ICS.Standard);
5734     break;
5735   }
5736 
5737   return ICS;
5738 }
5739 
5740 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5741 /// conversion of the expression From to an Objective-C pointer type.
5742 /// Returns a valid but null ExprResult if no conversion sequence exists.
5743 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5744   if (checkPlaceholderForOverload(*this, From))
5745     return ExprError();
5746 
5747   QualType Ty = Context.getObjCIdType();
5748   ImplicitConversionSequence ICS =
5749     TryContextuallyConvertToObjCPointer(*this, From);
5750   if (!ICS.isBad())
5751     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5752   return ExprResult();
5753 }
5754 
5755 /// Determine whether the provided type is an integral type, or an enumeration
5756 /// type of a permitted flavor.
5757 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5758   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5759                                  : T->isIntegralOrUnscopedEnumerationType();
5760 }
5761 
5762 static ExprResult
5763 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5764                             Sema::ContextualImplicitConverter &Converter,
5765                             QualType T, UnresolvedSetImpl &ViableConversions) {
5766 
5767   if (Converter.Suppress)
5768     return ExprError();
5769 
5770   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5771   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5772     CXXConversionDecl *Conv =
5773         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5774     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5775     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5776   }
5777   return From;
5778 }
5779 
5780 static bool
5781 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5782                            Sema::ContextualImplicitConverter &Converter,
5783                            QualType T, bool HadMultipleCandidates,
5784                            UnresolvedSetImpl &ExplicitConversions) {
5785   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5786     DeclAccessPair Found = ExplicitConversions[0];
5787     CXXConversionDecl *Conversion =
5788         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5789 
5790     // The user probably meant to invoke the given explicit
5791     // conversion; use it.
5792     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5793     std::string TypeStr;
5794     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5795 
5796     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5797         << FixItHint::CreateInsertion(From->getBeginLoc(),
5798                                       "static_cast<" + TypeStr + ">(")
5799         << FixItHint::CreateInsertion(
5800                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5801     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5802 
5803     // If we aren't in a SFINAE context, build a call to the
5804     // explicit conversion function.
5805     if (SemaRef.isSFINAEContext())
5806       return true;
5807 
5808     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5809     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5810                                                        HadMultipleCandidates);
5811     if (Result.isInvalid())
5812       return true;
5813     // Record usage of conversion in an implicit cast.
5814     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5815                                     CK_UserDefinedConversion, Result.get(),
5816                                     nullptr, Result.get()->getValueKind());
5817   }
5818   return false;
5819 }
5820 
5821 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5822                              Sema::ContextualImplicitConverter &Converter,
5823                              QualType T, bool HadMultipleCandidates,
5824                              DeclAccessPair &Found) {
5825   CXXConversionDecl *Conversion =
5826       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5827   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5828 
5829   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5830   if (!Converter.SuppressConversion) {
5831     if (SemaRef.isSFINAEContext())
5832       return true;
5833 
5834     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5835         << From->getSourceRange();
5836   }
5837 
5838   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5839                                                      HadMultipleCandidates);
5840   if (Result.isInvalid())
5841     return true;
5842   // Record usage of conversion in an implicit cast.
5843   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5844                                   CK_UserDefinedConversion, Result.get(),
5845                                   nullptr, Result.get()->getValueKind());
5846   return false;
5847 }
5848 
5849 static ExprResult finishContextualImplicitConversion(
5850     Sema &SemaRef, SourceLocation Loc, Expr *From,
5851     Sema::ContextualImplicitConverter &Converter) {
5852   if (!Converter.match(From->getType()) && !Converter.Suppress)
5853     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5854         << From->getSourceRange();
5855 
5856   return SemaRef.DefaultLvalueConversion(From);
5857 }
5858 
5859 static void
5860 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5861                                   UnresolvedSetImpl &ViableConversions,
5862                                   OverloadCandidateSet &CandidateSet) {
5863   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5864     DeclAccessPair FoundDecl = ViableConversions[I];
5865     NamedDecl *D = FoundDecl.getDecl();
5866     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5867     if (isa<UsingShadowDecl>(D))
5868       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5869 
5870     CXXConversionDecl *Conv;
5871     FunctionTemplateDecl *ConvTemplate;
5872     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5873       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5874     else
5875       Conv = cast<CXXConversionDecl>(D);
5876 
5877     if (ConvTemplate)
5878       SemaRef.AddTemplateConversionCandidate(
5879           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5880           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5881     else
5882       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5883                                      ToType, CandidateSet,
5884                                      /*AllowObjCConversionOnExplicit=*/false,
5885                                      /*AllowExplicit*/ true);
5886   }
5887 }
5888 
5889 /// Attempt to convert the given expression to a type which is accepted
5890 /// by the given converter.
5891 ///
5892 /// This routine will attempt to convert an expression of class type to a
5893 /// type accepted by the specified converter. In C++11 and before, the class
5894 /// must have a single non-explicit conversion function converting to a matching
5895 /// type. In C++1y, there can be multiple such conversion functions, but only
5896 /// one target type.
5897 ///
5898 /// \param Loc The source location of the construct that requires the
5899 /// conversion.
5900 ///
5901 /// \param From The expression we're converting from.
5902 ///
5903 /// \param Converter Used to control and diagnose the conversion process.
5904 ///
5905 /// \returns The expression, converted to an integral or enumeration type if
5906 /// successful.
5907 ExprResult Sema::PerformContextualImplicitConversion(
5908     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5909   // We can't perform any more checking for type-dependent expressions.
5910   if (From->isTypeDependent())
5911     return From;
5912 
5913   // Process placeholders immediately.
5914   if (From->hasPlaceholderType()) {
5915     ExprResult result = CheckPlaceholderExpr(From);
5916     if (result.isInvalid())
5917       return result;
5918     From = result.get();
5919   }
5920 
5921   // If the expression already has a matching type, we're golden.
5922   QualType T = From->getType();
5923   if (Converter.match(T))
5924     return DefaultLvalueConversion(From);
5925 
5926   // FIXME: Check for missing '()' if T is a function type?
5927 
5928   // We can only perform contextual implicit conversions on objects of class
5929   // type.
5930   const RecordType *RecordTy = T->getAs<RecordType>();
5931   if (!RecordTy || !getLangOpts().CPlusPlus) {
5932     if (!Converter.Suppress)
5933       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5934     return From;
5935   }
5936 
5937   // We must have a complete class type.
5938   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5939     ContextualImplicitConverter &Converter;
5940     Expr *From;
5941 
5942     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5943         : Converter(Converter), From(From) {}
5944 
5945     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5946       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5947     }
5948   } IncompleteDiagnoser(Converter, From);
5949 
5950   if (Converter.Suppress ? !isCompleteType(Loc, T)
5951                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5952     return From;
5953 
5954   // Look for a conversion to an integral or enumeration type.
5955   UnresolvedSet<4>
5956       ViableConversions; // These are *potentially* viable in C++1y.
5957   UnresolvedSet<4> ExplicitConversions;
5958   const auto &Conversions =
5959       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5960 
5961   bool HadMultipleCandidates =
5962       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5963 
5964   // To check that there is only one target type, in C++1y:
5965   QualType ToType;
5966   bool HasUniqueTargetType = true;
5967 
5968   // Collect explicit or viable (potentially in C++1y) conversions.
5969   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5970     NamedDecl *D = (*I)->getUnderlyingDecl();
5971     CXXConversionDecl *Conversion;
5972     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5973     if (ConvTemplate) {
5974       if (getLangOpts().CPlusPlus14)
5975         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5976       else
5977         continue; // C++11 does not consider conversion operator templates(?).
5978     } else
5979       Conversion = cast<CXXConversionDecl>(D);
5980 
5981     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5982            "Conversion operator templates are considered potentially "
5983            "viable in C++1y");
5984 
5985     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5986     if (Converter.match(CurToType) || ConvTemplate) {
5987 
5988       if (Conversion->isExplicit()) {
5989         // FIXME: For C++1y, do we need this restriction?
5990         // cf. diagnoseNoViableConversion()
5991         if (!ConvTemplate)
5992           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5993       } else {
5994         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5995           if (ToType.isNull())
5996             ToType = CurToType.getUnqualifiedType();
5997           else if (HasUniqueTargetType &&
5998                    (CurToType.getUnqualifiedType() != ToType))
5999             HasUniqueTargetType = false;
6000         }
6001         ViableConversions.addDecl(I.getDecl(), I.getAccess());
6002       }
6003     }
6004   }
6005 
6006   if (getLangOpts().CPlusPlus14) {
6007     // C++1y [conv]p6:
6008     // ... An expression e of class type E appearing in such a context
6009     // is said to be contextually implicitly converted to a specified
6010     // type T and is well-formed if and only if e can be implicitly
6011     // converted to a type T that is determined as follows: E is searched
6012     // for conversion functions whose return type is cv T or reference to
6013     // cv T such that T is allowed by the context. There shall be
6014     // exactly one such T.
6015 
6016     // If no unique T is found:
6017     if (ToType.isNull()) {
6018       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6019                                      HadMultipleCandidates,
6020                                      ExplicitConversions))
6021         return ExprError();
6022       return finishContextualImplicitConversion(*this, Loc, From, Converter);
6023     }
6024 
6025     // If more than one unique Ts are found:
6026     if (!HasUniqueTargetType)
6027       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6028                                          ViableConversions);
6029 
6030     // If one unique T is found:
6031     // First, build a candidate set from the previously recorded
6032     // potentially viable conversions.
6033     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6034     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6035                                       CandidateSet);
6036 
6037     // Then, perform overload resolution over the candidate set.
6038     OverloadCandidateSet::iterator Best;
6039     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6040     case OR_Success: {
6041       // Apply this conversion.
6042       DeclAccessPair Found =
6043           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6044       if (recordConversion(*this, Loc, From, Converter, T,
6045                            HadMultipleCandidates, Found))
6046         return ExprError();
6047       break;
6048     }
6049     case OR_Ambiguous:
6050       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6051                                          ViableConversions);
6052     case OR_No_Viable_Function:
6053       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6054                                      HadMultipleCandidates,
6055                                      ExplicitConversions))
6056         return ExprError();
6057       LLVM_FALLTHROUGH;
6058     case OR_Deleted:
6059       // We'll complain below about a non-integral condition type.
6060       break;
6061     }
6062   } else {
6063     switch (ViableConversions.size()) {
6064     case 0: {
6065       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6066                                      HadMultipleCandidates,
6067                                      ExplicitConversions))
6068         return ExprError();
6069 
6070       // We'll complain below about a non-integral condition type.
6071       break;
6072     }
6073     case 1: {
6074       // Apply this conversion.
6075       DeclAccessPair Found = ViableConversions[0];
6076       if (recordConversion(*this, Loc, From, Converter, T,
6077                            HadMultipleCandidates, Found))
6078         return ExprError();
6079       break;
6080     }
6081     default:
6082       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6083                                          ViableConversions);
6084     }
6085   }
6086 
6087   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6088 }
6089 
6090 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6091 /// an acceptable non-member overloaded operator for a call whose
6092 /// arguments have types T1 (and, if non-empty, T2). This routine
6093 /// implements the check in C++ [over.match.oper]p3b2 concerning
6094 /// enumeration types.
6095 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6096                                                    FunctionDecl *Fn,
6097                                                    ArrayRef<Expr *> Args) {
6098   QualType T1 = Args[0]->getType();
6099   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6100 
6101   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6102     return true;
6103 
6104   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6105     return true;
6106 
6107   const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6108   if (Proto->getNumParams() < 1)
6109     return false;
6110 
6111   if (T1->isEnumeralType()) {
6112     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6113     if (Context.hasSameUnqualifiedType(T1, ArgType))
6114       return true;
6115   }
6116 
6117   if (Proto->getNumParams() < 2)
6118     return false;
6119 
6120   if (!T2.isNull() && T2->isEnumeralType()) {
6121     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6122     if (Context.hasSameUnqualifiedType(T2, ArgType))
6123       return true;
6124   }
6125 
6126   return false;
6127 }
6128 
6129 /// AddOverloadCandidate - Adds the given function to the set of
6130 /// candidate functions, using the given function call arguments.  If
6131 /// @p SuppressUserConversions, then don't allow user-defined
6132 /// conversions via constructors or conversion operators.
6133 ///
6134 /// \param PartialOverloading true if we are performing "partial" overloading
6135 /// based on an incomplete set of function arguments. This feature is used by
6136 /// code completion.
6137 void Sema::AddOverloadCandidate(
6138     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6139     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6140     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6141     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6142     OverloadCandidateParamOrder PO) {
6143   const FunctionProtoType *Proto
6144     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6145   assert(Proto && "Functions without a prototype cannot be overloaded");
6146   assert(!Function->getDescribedFunctionTemplate() &&
6147          "Use AddTemplateOverloadCandidate for function templates");
6148 
6149   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6150     if (!isa<CXXConstructorDecl>(Method)) {
6151       // If we get here, it's because we're calling a member function
6152       // that is named without a member access expression (e.g.,
6153       // "this->f") that was either written explicitly or created
6154       // implicitly. This can happen with a qualified call to a member
6155       // function, e.g., X::f(). We use an empty type for the implied
6156       // object argument (C++ [over.call.func]p3), and the acting context
6157       // is irrelevant.
6158       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6159                          Expr::Classification::makeSimpleLValue(), Args,
6160                          CandidateSet, SuppressUserConversions,
6161                          PartialOverloading, EarlyConversions, PO);
6162       return;
6163     }
6164     // We treat a constructor like a non-member function, since its object
6165     // argument doesn't participate in overload resolution.
6166   }
6167 
6168   if (!CandidateSet.isNewCandidate(Function, PO))
6169     return;
6170 
6171   // C++11 [class.copy]p11: [DR1402]
6172   //   A defaulted move constructor that is defined as deleted is ignored by
6173   //   overload resolution.
6174   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6175   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6176       Constructor->isMoveConstructor())
6177     return;
6178 
6179   // Overload resolution is always an unevaluated context.
6180   EnterExpressionEvaluationContext Unevaluated(
6181       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6182 
6183   // C++ [over.match.oper]p3:
6184   //   if no operand has a class type, only those non-member functions in the
6185   //   lookup set that have a first parameter of type T1 or "reference to
6186   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6187   //   is a right operand) a second parameter of type T2 or "reference to
6188   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6189   //   candidate functions.
6190   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6191       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6192     return;
6193 
6194   // Add this candidate
6195   OverloadCandidate &Candidate =
6196       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6197   Candidate.FoundDecl = FoundDecl;
6198   Candidate.Function = Function;
6199   Candidate.Viable = true;
6200   Candidate.RewriteKind =
6201       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6202   Candidate.IsSurrogate = false;
6203   Candidate.IsADLCandidate = IsADLCandidate;
6204   Candidate.IgnoreObjectArgument = false;
6205   Candidate.ExplicitCallArguments = Args.size();
6206 
6207   // Explicit functions are not actually candidates at all if we're not
6208   // allowing them in this context, but keep them around so we can point
6209   // to them in diagnostics.
6210   if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6211     Candidate.Viable = false;
6212     Candidate.FailureKind = ovl_fail_explicit;
6213     return;
6214   }
6215 
6216   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6217       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6218     Candidate.Viable = false;
6219     Candidate.FailureKind = ovl_non_default_multiversion_function;
6220     return;
6221   }
6222 
6223   if (Constructor) {
6224     // C++ [class.copy]p3:
6225     //   A member function template is never instantiated to perform the copy
6226     //   of a class object to an object of its class type.
6227     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6228     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6229         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6230          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6231                        ClassType))) {
6232       Candidate.Viable = false;
6233       Candidate.FailureKind = ovl_fail_illegal_constructor;
6234       return;
6235     }
6236 
6237     // C++ [over.match.funcs]p8: (proposed DR resolution)
6238     //   A constructor inherited from class type C that has a first parameter
6239     //   of type "reference to P" (including such a constructor instantiated
6240     //   from a template) is excluded from the set of candidate functions when
6241     //   constructing an object of type cv D if the argument list has exactly
6242     //   one argument and D is reference-related to P and P is reference-related
6243     //   to C.
6244     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6245     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6246         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6247       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6248       QualType C = Context.getRecordType(Constructor->getParent());
6249       QualType D = Context.getRecordType(Shadow->getParent());
6250       SourceLocation Loc = Args.front()->getExprLoc();
6251       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6252           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6253         Candidate.Viable = false;
6254         Candidate.FailureKind = ovl_fail_inhctor_slice;
6255         return;
6256       }
6257     }
6258 
6259     // Check that the constructor is capable of constructing an object in the
6260     // destination address space.
6261     if (!Qualifiers::isAddressSpaceSupersetOf(
6262             Constructor->getMethodQualifiers().getAddressSpace(),
6263             CandidateSet.getDestAS())) {
6264       Candidate.Viable = false;
6265       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6266     }
6267   }
6268 
6269   unsigned NumParams = Proto->getNumParams();
6270 
6271   // (C++ 13.3.2p2): A candidate function having fewer than m
6272   // parameters is viable only if it has an ellipsis in its parameter
6273   // list (8.3.5).
6274   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6275       !Proto->isVariadic()) {
6276     Candidate.Viable = false;
6277     Candidate.FailureKind = ovl_fail_too_many_arguments;
6278     return;
6279   }
6280 
6281   // (C++ 13.3.2p2): A candidate function having more than m parameters
6282   // is viable only if the (m+1)st parameter has a default argument
6283   // (8.3.6). For the purposes of overload resolution, the
6284   // parameter list is truncated on the right, so that there are
6285   // exactly m parameters.
6286   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6287   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6288     // Not enough arguments.
6289     Candidate.Viable = false;
6290     Candidate.FailureKind = ovl_fail_too_few_arguments;
6291     return;
6292   }
6293 
6294   // (CUDA B.1): Check for invalid calls between targets.
6295   if (getLangOpts().CUDA)
6296     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6297       // Skip the check for callers that are implicit members, because in this
6298       // case we may not yet know what the member's target is; the target is
6299       // inferred for the member automatically, based on the bases and fields of
6300       // the class.
6301       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6302         Candidate.Viable = false;
6303         Candidate.FailureKind = ovl_fail_bad_target;
6304         return;
6305       }
6306 
6307   if (Function->getTrailingRequiresClause()) {
6308     ConstraintSatisfaction Satisfaction;
6309     if (CheckFunctionConstraints(Function, Satisfaction) ||
6310         !Satisfaction.IsSatisfied) {
6311       Candidate.Viable = false;
6312       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6313       return;
6314     }
6315   }
6316 
6317   // Determine the implicit conversion sequences for each of the
6318   // arguments.
6319   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6320     unsigned ConvIdx =
6321         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6322     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6323       // We already formed a conversion sequence for this parameter during
6324       // template argument deduction.
6325     } else if (ArgIdx < NumParams) {
6326       // (C++ 13.3.2p3): for F to be a viable function, there shall
6327       // exist for each argument an implicit conversion sequence
6328       // (13.3.3.1) that converts that argument to the corresponding
6329       // parameter of F.
6330       QualType ParamType = Proto->getParamType(ArgIdx);
6331       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6332           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6333           /*InOverloadResolution=*/true,
6334           /*AllowObjCWritebackConversion=*/
6335           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6336       if (Candidate.Conversions[ConvIdx].isBad()) {
6337         Candidate.Viable = false;
6338         Candidate.FailureKind = ovl_fail_bad_conversion;
6339         return;
6340       }
6341     } else {
6342       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6343       // argument for which there is no corresponding parameter is
6344       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6345       Candidate.Conversions[ConvIdx].setEllipsis();
6346     }
6347   }
6348 
6349   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6350     Candidate.Viable = false;
6351     Candidate.FailureKind = ovl_fail_enable_if;
6352     Candidate.DeductionFailure.Data = FailedAttr;
6353     return;
6354   }
6355 
6356   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6357     Candidate.Viable = false;
6358     Candidate.FailureKind = ovl_fail_ext_disabled;
6359     return;
6360   }
6361 }
6362 
6363 ObjCMethodDecl *
6364 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6365                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6366   if (Methods.size() <= 1)
6367     return nullptr;
6368 
6369   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6370     bool Match = true;
6371     ObjCMethodDecl *Method = Methods[b];
6372     unsigned NumNamedArgs = Sel.getNumArgs();
6373     // Method might have more arguments than selector indicates. This is due
6374     // to addition of c-style arguments in method.
6375     if (Method->param_size() > NumNamedArgs)
6376       NumNamedArgs = Method->param_size();
6377     if (Args.size() < NumNamedArgs)
6378       continue;
6379 
6380     for (unsigned i = 0; i < NumNamedArgs; i++) {
6381       // We can't do any type-checking on a type-dependent argument.
6382       if (Args[i]->isTypeDependent()) {
6383         Match = false;
6384         break;
6385       }
6386 
6387       ParmVarDecl *param = Method->parameters()[i];
6388       Expr *argExpr = Args[i];
6389       assert(argExpr && "SelectBestMethod(): missing expression");
6390 
6391       // Strip the unbridged-cast placeholder expression off unless it's
6392       // a consumed argument.
6393       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6394           !param->hasAttr<CFConsumedAttr>())
6395         argExpr = stripARCUnbridgedCast(argExpr);
6396 
6397       // If the parameter is __unknown_anytype, move on to the next method.
6398       if (param->getType() == Context.UnknownAnyTy) {
6399         Match = false;
6400         break;
6401       }
6402 
6403       ImplicitConversionSequence ConversionState
6404         = TryCopyInitialization(*this, argExpr, param->getType(),
6405                                 /*SuppressUserConversions*/false,
6406                                 /*InOverloadResolution=*/true,
6407                                 /*AllowObjCWritebackConversion=*/
6408                                 getLangOpts().ObjCAutoRefCount,
6409                                 /*AllowExplicit*/false);
6410       // This function looks for a reasonably-exact match, so we consider
6411       // incompatible pointer conversions to be a failure here.
6412       if (ConversionState.isBad() ||
6413           (ConversionState.isStandard() &&
6414            ConversionState.Standard.Second ==
6415                ICK_Incompatible_Pointer_Conversion)) {
6416         Match = false;
6417         break;
6418       }
6419     }
6420     // Promote additional arguments to variadic methods.
6421     if (Match && Method->isVariadic()) {
6422       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6423         if (Args[i]->isTypeDependent()) {
6424           Match = false;
6425           break;
6426         }
6427         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6428                                                           nullptr);
6429         if (Arg.isInvalid()) {
6430           Match = false;
6431           break;
6432         }
6433       }
6434     } else {
6435       // Check for extra arguments to non-variadic methods.
6436       if (Args.size() != NumNamedArgs)
6437         Match = false;
6438       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6439         // Special case when selectors have no argument. In this case, select
6440         // one with the most general result type of 'id'.
6441         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6442           QualType ReturnT = Methods[b]->getReturnType();
6443           if (ReturnT->isObjCIdType())
6444             return Methods[b];
6445         }
6446       }
6447     }
6448 
6449     if (Match)
6450       return Method;
6451   }
6452   return nullptr;
6453 }
6454 
6455 static bool
6456 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6457                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6458                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6459                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6460   if (ThisArg) {
6461     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6462     assert(!isa<CXXConstructorDecl>(Method) &&
6463            "Shouldn't have `this` for ctors!");
6464     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6465     ExprResult R = S.PerformObjectArgumentInitialization(
6466         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6467     if (R.isInvalid())
6468       return false;
6469     ConvertedThis = R.get();
6470   } else {
6471     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6472       (void)MD;
6473       assert((MissingImplicitThis || MD->isStatic() ||
6474               isa<CXXConstructorDecl>(MD)) &&
6475              "Expected `this` for non-ctor instance methods");
6476     }
6477     ConvertedThis = nullptr;
6478   }
6479 
6480   // Ignore any variadic arguments. Converting them is pointless, since the
6481   // user can't refer to them in the function condition.
6482   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6483 
6484   // Convert the arguments.
6485   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6486     ExprResult R;
6487     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6488                                         S.Context, Function->getParamDecl(I)),
6489                                     SourceLocation(), Args[I]);
6490 
6491     if (R.isInvalid())
6492       return false;
6493 
6494     ConvertedArgs.push_back(R.get());
6495   }
6496 
6497   if (Trap.hasErrorOccurred())
6498     return false;
6499 
6500   // Push default arguments if needed.
6501   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6502     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6503       ParmVarDecl *P = Function->getParamDecl(i);
6504       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6505                          ? P->getUninstantiatedDefaultArg()
6506                          : P->getDefaultArg();
6507       // This can only happen in code completion, i.e. when PartialOverloading
6508       // is true.
6509       if (!DefArg)
6510         return false;
6511       ExprResult R =
6512           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6513                                           S.Context, Function->getParamDecl(i)),
6514                                       SourceLocation(), DefArg);
6515       if (R.isInvalid())
6516         return false;
6517       ConvertedArgs.push_back(R.get());
6518     }
6519 
6520     if (Trap.hasErrorOccurred())
6521       return false;
6522   }
6523   return true;
6524 }
6525 
6526 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6527                                   bool MissingImplicitThis) {
6528   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6529   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6530     return nullptr;
6531 
6532   SFINAETrap Trap(*this);
6533   SmallVector<Expr *, 16> ConvertedArgs;
6534   // FIXME: We should look into making enable_if late-parsed.
6535   Expr *DiscardedThis;
6536   if (!convertArgsForAvailabilityChecks(
6537           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6538           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6539     return *EnableIfAttrs.begin();
6540 
6541   for (auto *EIA : EnableIfAttrs) {
6542     APValue Result;
6543     // FIXME: This doesn't consider value-dependent cases, because doing so is
6544     // very difficult. Ideally, we should handle them more gracefully.
6545     if (EIA->getCond()->isValueDependent() ||
6546         !EIA->getCond()->EvaluateWithSubstitution(
6547             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6548       return EIA;
6549 
6550     if (!Result.isInt() || !Result.getInt().getBoolValue())
6551       return EIA;
6552   }
6553   return nullptr;
6554 }
6555 
6556 template <typename CheckFn>
6557 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6558                                         bool ArgDependent, SourceLocation Loc,
6559                                         CheckFn &&IsSuccessful) {
6560   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6561   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6562     if (ArgDependent == DIA->getArgDependent())
6563       Attrs.push_back(DIA);
6564   }
6565 
6566   // Common case: No diagnose_if attributes, so we can quit early.
6567   if (Attrs.empty())
6568     return false;
6569 
6570   auto WarningBegin = std::stable_partition(
6571       Attrs.begin(), Attrs.end(),
6572       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6573 
6574   // Note that diagnose_if attributes are late-parsed, so they appear in the
6575   // correct order (unlike enable_if attributes).
6576   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6577                                IsSuccessful);
6578   if (ErrAttr != WarningBegin) {
6579     const DiagnoseIfAttr *DIA = *ErrAttr;
6580     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6581     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6582         << DIA->getParent() << DIA->getCond()->getSourceRange();
6583     return true;
6584   }
6585 
6586   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6587     if (IsSuccessful(DIA)) {
6588       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6589       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6590           << DIA->getParent() << DIA->getCond()->getSourceRange();
6591     }
6592 
6593   return false;
6594 }
6595 
6596 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6597                                                const Expr *ThisArg,
6598                                                ArrayRef<const Expr *> Args,
6599                                                SourceLocation Loc) {
6600   return diagnoseDiagnoseIfAttrsWith(
6601       *this, Function, /*ArgDependent=*/true, Loc,
6602       [&](const DiagnoseIfAttr *DIA) {
6603         APValue Result;
6604         // It's sane to use the same Args for any redecl of this function, since
6605         // EvaluateWithSubstitution only cares about the position of each
6606         // argument in the arg list, not the ParmVarDecl* it maps to.
6607         if (!DIA->getCond()->EvaluateWithSubstitution(
6608                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6609           return false;
6610         return Result.isInt() && Result.getInt().getBoolValue();
6611       });
6612 }
6613 
6614 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6615                                                  SourceLocation Loc) {
6616   return diagnoseDiagnoseIfAttrsWith(
6617       *this, ND, /*ArgDependent=*/false, Loc,
6618       [&](const DiagnoseIfAttr *DIA) {
6619         bool Result;
6620         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6621                Result;
6622       });
6623 }
6624 
6625 /// Add all of the function declarations in the given function set to
6626 /// the overload candidate set.
6627 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6628                                  ArrayRef<Expr *> Args,
6629                                  OverloadCandidateSet &CandidateSet,
6630                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6631                                  bool SuppressUserConversions,
6632                                  bool PartialOverloading,
6633                                  bool FirstArgumentIsBase) {
6634   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6635     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6636     ArrayRef<Expr *> FunctionArgs = Args;
6637 
6638     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6639     FunctionDecl *FD =
6640         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6641 
6642     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6643       QualType ObjectType;
6644       Expr::Classification ObjectClassification;
6645       if (Args.size() > 0) {
6646         if (Expr *E = Args[0]) {
6647           // Use the explicit base to restrict the lookup:
6648           ObjectType = E->getType();
6649           // Pointers in the object arguments are implicitly dereferenced, so we
6650           // always classify them as l-values.
6651           if (!ObjectType.isNull() && ObjectType->isPointerType())
6652             ObjectClassification = Expr::Classification::makeSimpleLValue();
6653           else
6654             ObjectClassification = E->Classify(Context);
6655         } // .. else there is an implicit base.
6656         FunctionArgs = Args.slice(1);
6657       }
6658       if (FunTmpl) {
6659         AddMethodTemplateCandidate(
6660             FunTmpl, F.getPair(),
6661             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6662             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6663             FunctionArgs, CandidateSet, SuppressUserConversions,
6664             PartialOverloading);
6665       } else {
6666         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6667                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6668                            ObjectClassification, FunctionArgs, CandidateSet,
6669                            SuppressUserConversions, PartialOverloading);
6670       }
6671     } else {
6672       // This branch handles both standalone functions and static methods.
6673 
6674       // Slice the first argument (which is the base) when we access
6675       // static method as non-static.
6676       if (Args.size() > 0 &&
6677           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6678                         !isa<CXXConstructorDecl>(FD)))) {
6679         assert(cast<CXXMethodDecl>(FD)->isStatic());
6680         FunctionArgs = Args.slice(1);
6681       }
6682       if (FunTmpl) {
6683         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6684                                      ExplicitTemplateArgs, FunctionArgs,
6685                                      CandidateSet, SuppressUserConversions,
6686                                      PartialOverloading);
6687       } else {
6688         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6689                              SuppressUserConversions, PartialOverloading);
6690       }
6691     }
6692   }
6693 }
6694 
6695 /// AddMethodCandidate - Adds a named decl (which is some kind of
6696 /// method) as a method candidate to the given overload set.
6697 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6698                               Expr::Classification ObjectClassification,
6699                               ArrayRef<Expr *> Args,
6700                               OverloadCandidateSet &CandidateSet,
6701                               bool SuppressUserConversions,
6702                               OverloadCandidateParamOrder PO) {
6703   NamedDecl *Decl = FoundDecl.getDecl();
6704   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6705 
6706   if (isa<UsingShadowDecl>(Decl))
6707     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6708 
6709   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6710     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6711            "Expected a member function template");
6712     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6713                                /*ExplicitArgs*/ nullptr, ObjectType,
6714                                ObjectClassification, Args, CandidateSet,
6715                                SuppressUserConversions, false, PO);
6716   } else {
6717     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6718                        ObjectType, ObjectClassification, Args, CandidateSet,
6719                        SuppressUserConversions, false, None, PO);
6720   }
6721 }
6722 
6723 /// AddMethodCandidate - Adds the given C++ member function to the set
6724 /// of candidate functions, using the given function call arguments
6725 /// and the object argument (@c Object). For example, in a call
6726 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6727 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6728 /// allow user-defined conversions via constructors or conversion
6729 /// operators.
6730 void
6731 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6732                          CXXRecordDecl *ActingContext, QualType ObjectType,
6733                          Expr::Classification ObjectClassification,
6734                          ArrayRef<Expr *> Args,
6735                          OverloadCandidateSet &CandidateSet,
6736                          bool SuppressUserConversions,
6737                          bool PartialOverloading,
6738                          ConversionSequenceList EarlyConversions,
6739                          OverloadCandidateParamOrder PO) {
6740   const FunctionProtoType *Proto
6741     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6742   assert(Proto && "Methods without a prototype cannot be overloaded");
6743   assert(!isa<CXXConstructorDecl>(Method) &&
6744          "Use AddOverloadCandidate for constructors");
6745 
6746   if (!CandidateSet.isNewCandidate(Method, PO))
6747     return;
6748 
6749   // C++11 [class.copy]p23: [DR1402]
6750   //   A defaulted move assignment operator that is defined as deleted is
6751   //   ignored by overload resolution.
6752   if (Method->isDefaulted() && Method->isDeleted() &&
6753       Method->isMoveAssignmentOperator())
6754     return;
6755 
6756   // Overload resolution is always an unevaluated context.
6757   EnterExpressionEvaluationContext Unevaluated(
6758       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6759 
6760   // Add this candidate
6761   OverloadCandidate &Candidate =
6762       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6763   Candidate.FoundDecl = FoundDecl;
6764   Candidate.Function = Method;
6765   Candidate.RewriteKind =
6766       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6767   Candidate.IsSurrogate = false;
6768   Candidate.IgnoreObjectArgument = false;
6769   Candidate.ExplicitCallArguments = Args.size();
6770 
6771   unsigned NumParams = Proto->getNumParams();
6772 
6773   // (C++ 13.3.2p2): A candidate function having fewer than m
6774   // parameters is viable only if it has an ellipsis in its parameter
6775   // list (8.3.5).
6776   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6777       !Proto->isVariadic()) {
6778     Candidate.Viable = false;
6779     Candidate.FailureKind = ovl_fail_too_many_arguments;
6780     return;
6781   }
6782 
6783   // (C++ 13.3.2p2): A candidate function having more than m parameters
6784   // is viable only if the (m+1)st parameter has a default argument
6785   // (8.3.6). For the purposes of overload resolution, the
6786   // parameter list is truncated on the right, so that there are
6787   // exactly m parameters.
6788   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6789   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6790     // Not enough arguments.
6791     Candidate.Viable = false;
6792     Candidate.FailureKind = ovl_fail_too_few_arguments;
6793     return;
6794   }
6795 
6796   Candidate.Viable = true;
6797 
6798   if (Method->isStatic() || ObjectType.isNull())
6799     // The implicit object argument is ignored.
6800     Candidate.IgnoreObjectArgument = true;
6801   else {
6802     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6803     // Determine the implicit conversion sequence for the object
6804     // parameter.
6805     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6806         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6807         Method, ActingContext);
6808     if (Candidate.Conversions[ConvIdx].isBad()) {
6809       Candidate.Viable = false;
6810       Candidate.FailureKind = ovl_fail_bad_conversion;
6811       return;
6812     }
6813   }
6814 
6815   // (CUDA B.1): Check for invalid calls between targets.
6816   if (getLangOpts().CUDA)
6817     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6818       if (!IsAllowedCUDACall(Caller, Method)) {
6819         Candidate.Viable = false;
6820         Candidate.FailureKind = ovl_fail_bad_target;
6821         return;
6822       }
6823 
6824   if (Method->getTrailingRequiresClause()) {
6825     ConstraintSatisfaction Satisfaction;
6826     if (CheckFunctionConstraints(Method, Satisfaction) ||
6827         !Satisfaction.IsSatisfied) {
6828       Candidate.Viable = false;
6829       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6830       return;
6831     }
6832   }
6833 
6834   // Determine the implicit conversion sequences for each of the
6835   // arguments.
6836   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6837     unsigned ConvIdx =
6838         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6839     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6840       // We already formed a conversion sequence for this parameter during
6841       // template argument deduction.
6842     } else if (ArgIdx < NumParams) {
6843       // (C++ 13.3.2p3): for F to be a viable function, there shall
6844       // exist for each argument an implicit conversion sequence
6845       // (13.3.3.1) that converts that argument to the corresponding
6846       // parameter of F.
6847       QualType ParamType = Proto->getParamType(ArgIdx);
6848       Candidate.Conversions[ConvIdx]
6849         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6850                                 SuppressUserConversions,
6851                                 /*InOverloadResolution=*/true,
6852                                 /*AllowObjCWritebackConversion=*/
6853                                   getLangOpts().ObjCAutoRefCount);
6854       if (Candidate.Conversions[ConvIdx].isBad()) {
6855         Candidate.Viable = false;
6856         Candidate.FailureKind = ovl_fail_bad_conversion;
6857         return;
6858       }
6859     } else {
6860       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6861       // argument for which there is no corresponding parameter is
6862       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6863       Candidate.Conversions[ConvIdx].setEllipsis();
6864     }
6865   }
6866 
6867   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6868     Candidate.Viable = false;
6869     Candidate.FailureKind = ovl_fail_enable_if;
6870     Candidate.DeductionFailure.Data = FailedAttr;
6871     return;
6872   }
6873 
6874   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6875       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6876     Candidate.Viable = false;
6877     Candidate.FailureKind = ovl_non_default_multiversion_function;
6878   }
6879 }
6880 
6881 /// Add a C++ member function template as a candidate to the candidate
6882 /// set, using template argument deduction to produce an appropriate member
6883 /// function template specialization.
6884 void Sema::AddMethodTemplateCandidate(
6885     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6886     CXXRecordDecl *ActingContext,
6887     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6888     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6889     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6890     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6891   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6892     return;
6893 
6894   // C++ [over.match.funcs]p7:
6895   //   In each case where a candidate is a function template, candidate
6896   //   function template specializations are generated using template argument
6897   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6898   //   candidate functions in the usual way.113) A given name can refer to one
6899   //   or more function templates and also to a set of overloaded non-template
6900   //   functions. In such a case, the candidate functions generated from each
6901   //   function template are combined with the set of non-template candidate
6902   //   functions.
6903   TemplateDeductionInfo Info(CandidateSet.getLocation());
6904   FunctionDecl *Specialization = nullptr;
6905   ConversionSequenceList Conversions;
6906   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6907           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6908           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6909             return CheckNonDependentConversions(
6910                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6911                 SuppressUserConversions, ActingContext, ObjectType,
6912                 ObjectClassification, PO);
6913           })) {
6914     OverloadCandidate &Candidate =
6915         CandidateSet.addCandidate(Conversions.size(), Conversions);
6916     Candidate.FoundDecl = FoundDecl;
6917     Candidate.Function = MethodTmpl->getTemplatedDecl();
6918     Candidate.Viable = false;
6919     Candidate.RewriteKind =
6920       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6921     Candidate.IsSurrogate = false;
6922     Candidate.IgnoreObjectArgument =
6923         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6924         ObjectType.isNull();
6925     Candidate.ExplicitCallArguments = Args.size();
6926     if (Result == TDK_NonDependentConversionFailure)
6927       Candidate.FailureKind = ovl_fail_bad_conversion;
6928     else {
6929       Candidate.FailureKind = ovl_fail_bad_deduction;
6930       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6931                                                             Info);
6932     }
6933     return;
6934   }
6935 
6936   // Add the function template specialization produced by template argument
6937   // deduction as a candidate.
6938   assert(Specialization && "Missing member function template specialization?");
6939   assert(isa<CXXMethodDecl>(Specialization) &&
6940          "Specialization is not a member function?");
6941   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6942                      ActingContext, ObjectType, ObjectClassification, Args,
6943                      CandidateSet, SuppressUserConversions, PartialOverloading,
6944                      Conversions, PO);
6945 }
6946 
6947 /// Determine whether a given function template has a simple explicit specifier
6948 /// or a non-value-dependent explicit-specification that evaluates to true.
6949 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6950   return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6951 }
6952 
6953 /// Add a C++ function template specialization as a candidate
6954 /// in the candidate set, using template argument deduction to produce
6955 /// an appropriate function template specialization.
6956 void Sema::AddTemplateOverloadCandidate(
6957     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6958     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6959     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6960     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6961     OverloadCandidateParamOrder PO) {
6962   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6963     return;
6964 
6965   // If the function template has a non-dependent explicit specification,
6966   // exclude it now if appropriate; we are not permitted to perform deduction
6967   // and substitution in this case.
6968   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6969     OverloadCandidate &Candidate = CandidateSet.addCandidate();
6970     Candidate.FoundDecl = FoundDecl;
6971     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6972     Candidate.Viable = false;
6973     Candidate.FailureKind = ovl_fail_explicit;
6974     return;
6975   }
6976 
6977   // C++ [over.match.funcs]p7:
6978   //   In each case where a candidate is a function template, candidate
6979   //   function template specializations are generated using template argument
6980   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6981   //   candidate functions in the usual way.113) A given name can refer to one
6982   //   or more function templates and also to a set of overloaded non-template
6983   //   functions. In such a case, the candidate functions generated from each
6984   //   function template are combined with the set of non-template candidate
6985   //   functions.
6986   TemplateDeductionInfo Info(CandidateSet.getLocation());
6987   FunctionDecl *Specialization = nullptr;
6988   ConversionSequenceList Conversions;
6989   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6990           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6991           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6992             return CheckNonDependentConversions(
6993                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6994                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6995           })) {
6996     OverloadCandidate &Candidate =
6997         CandidateSet.addCandidate(Conversions.size(), Conversions);
6998     Candidate.FoundDecl = FoundDecl;
6999     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7000     Candidate.Viable = false;
7001     Candidate.RewriteKind =
7002       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7003     Candidate.IsSurrogate = false;
7004     Candidate.IsADLCandidate = IsADLCandidate;
7005     // Ignore the object argument if there is one, since we don't have an object
7006     // type.
7007     Candidate.IgnoreObjectArgument =
7008         isa<CXXMethodDecl>(Candidate.Function) &&
7009         !isa<CXXConstructorDecl>(Candidate.Function);
7010     Candidate.ExplicitCallArguments = Args.size();
7011     if (Result == TDK_NonDependentConversionFailure)
7012       Candidate.FailureKind = ovl_fail_bad_conversion;
7013     else {
7014       Candidate.FailureKind = ovl_fail_bad_deduction;
7015       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7016                                                             Info);
7017     }
7018     return;
7019   }
7020 
7021   // Add the function template specialization produced by template argument
7022   // deduction as a candidate.
7023   assert(Specialization && "Missing function template specialization?");
7024   AddOverloadCandidate(
7025       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7026       PartialOverloading, AllowExplicit,
7027       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7028 }
7029 
7030 /// Check that implicit conversion sequences can be formed for each argument
7031 /// whose corresponding parameter has a non-dependent type, per DR1391's
7032 /// [temp.deduct.call]p10.
7033 bool Sema::CheckNonDependentConversions(
7034     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7035     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7036     ConversionSequenceList &Conversions, bool SuppressUserConversions,
7037     CXXRecordDecl *ActingContext, QualType ObjectType,
7038     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7039   // FIXME: The cases in which we allow explicit conversions for constructor
7040   // arguments never consider calling a constructor template. It's not clear
7041   // that is correct.
7042   const bool AllowExplicit = false;
7043 
7044   auto *FD = FunctionTemplate->getTemplatedDecl();
7045   auto *Method = dyn_cast<CXXMethodDecl>(FD);
7046   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7047   unsigned ThisConversions = HasThisConversion ? 1 : 0;
7048 
7049   Conversions =
7050       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7051 
7052   // Overload resolution is always an unevaluated context.
7053   EnterExpressionEvaluationContext Unevaluated(
7054       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7055 
7056   // For a method call, check the 'this' conversion here too. DR1391 doesn't
7057   // require that, but this check should never result in a hard error, and
7058   // overload resolution is permitted to sidestep instantiations.
7059   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7060       !ObjectType.isNull()) {
7061     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7062     Conversions[ConvIdx] = TryObjectArgumentInitialization(
7063         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7064         Method, ActingContext);
7065     if (Conversions[ConvIdx].isBad())
7066       return true;
7067   }
7068 
7069   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7070        ++I) {
7071     QualType ParamType = ParamTypes[I];
7072     if (!ParamType->isDependentType()) {
7073       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7074                              ? 0
7075                              : (ThisConversions + I);
7076       Conversions[ConvIdx]
7077         = TryCopyInitialization(*this, Args[I], ParamType,
7078                                 SuppressUserConversions,
7079                                 /*InOverloadResolution=*/true,
7080                                 /*AllowObjCWritebackConversion=*/
7081                                   getLangOpts().ObjCAutoRefCount,
7082                                 AllowExplicit);
7083       if (Conversions[ConvIdx].isBad())
7084         return true;
7085     }
7086   }
7087 
7088   return false;
7089 }
7090 
7091 /// Determine whether this is an allowable conversion from the result
7092 /// of an explicit conversion operator to the expected type, per C++
7093 /// [over.match.conv]p1 and [over.match.ref]p1.
7094 ///
7095 /// \param ConvType The return type of the conversion function.
7096 ///
7097 /// \param ToType The type we are converting to.
7098 ///
7099 /// \param AllowObjCPointerConversion Allow a conversion from one
7100 /// Objective-C pointer to another.
7101 ///
7102 /// \returns true if the conversion is allowable, false otherwise.
7103 static bool isAllowableExplicitConversion(Sema &S,
7104                                           QualType ConvType, QualType ToType,
7105                                           bool AllowObjCPointerConversion) {
7106   QualType ToNonRefType = ToType.getNonReferenceType();
7107 
7108   // Easy case: the types are the same.
7109   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7110     return true;
7111 
7112   // Allow qualification conversions.
7113   bool ObjCLifetimeConversion;
7114   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7115                                   ObjCLifetimeConversion))
7116     return true;
7117 
7118   // If we're not allowed to consider Objective-C pointer conversions,
7119   // we're done.
7120   if (!AllowObjCPointerConversion)
7121     return false;
7122 
7123   // Is this an Objective-C pointer conversion?
7124   bool IncompatibleObjC = false;
7125   QualType ConvertedType;
7126   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7127                                    IncompatibleObjC);
7128 }
7129 
7130 /// AddConversionCandidate - Add a C++ conversion function as a
7131 /// candidate in the candidate set (C++ [over.match.conv],
7132 /// C++ [over.match.copy]). From is the expression we're converting from,
7133 /// and ToType is the type that we're eventually trying to convert to
7134 /// (which may or may not be the same type as the type that the
7135 /// conversion function produces).
7136 void Sema::AddConversionCandidate(
7137     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7138     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7139     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7140     bool AllowExplicit, bool AllowResultConversion) {
7141   assert(!Conversion->getDescribedFunctionTemplate() &&
7142          "Conversion function templates use AddTemplateConversionCandidate");
7143   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7144   if (!CandidateSet.isNewCandidate(Conversion))
7145     return;
7146 
7147   // If the conversion function has an undeduced return type, trigger its
7148   // deduction now.
7149   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7150     if (DeduceReturnType(Conversion, From->getExprLoc()))
7151       return;
7152     ConvType = Conversion->getConversionType().getNonReferenceType();
7153   }
7154 
7155   // If we don't allow any conversion of the result type, ignore conversion
7156   // functions that don't convert to exactly (possibly cv-qualified) T.
7157   if (!AllowResultConversion &&
7158       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7159     return;
7160 
7161   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7162   // operator is only a candidate if its return type is the target type or
7163   // can be converted to the target type with a qualification conversion.
7164   //
7165   // FIXME: Include such functions in the candidate list and explain why we
7166   // can't select them.
7167   if (Conversion->isExplicit() &&
7168       !isAllowableExplicitConversion(*this, ConvType, ToType,
7169                                      AllowObjCConversionOnExplicit))
7170     return;
7171 
7172   // Overload resolution is always an unevaluated context.
7173   EnterExpressionEvaluationContext Unevaluated(
7174       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7175 
7176   // Add this candidate
7177   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7178   Candidate.FoundDecl = FoundDecl;
7179   Candidate.Function = Conversion;
7180   Candidate.IsSurrogate = false;
7181   Candidate.IgnoreObjectArgument = false;
7182   Candidate.FinalConversion.setAsIdentityConversion();
7183   Candidate.FinalConversion.setFromType(ConvType);
7184   Candidate.FinalConversion.setAllToTypes(ToType);
7185   Candidate.Viable = true;
7186   Candidate.ExplicitCallArguments = 1;
7187 
7188   // Explicit functions are not actually candidates at all if we're not
7189   // allowing them in this context, but keep them around so we can point
7190   // to them in diagnostics.
7191   if (!AllowExplicit && Conversion->isExplicit()) {
7192     Candidate.Viable = false;
7193     Candidate.FailureKind = ovl_fail_explicit;
7194     return;
7195   }
7196 
7197   // C++ [over.match.funcs]p4:
7198   //   For conversion functions, the function is considered to be a member of
7199   //   the class of the implicit implied object argument for the purpose of
7200   //   defining the type of the implicit object parameter.
7201   //
7202   // Determine the implicit conversion sequence for the implicit
7203   // object parameter.
7204   QualType ImplicitParamType = From->getType();
7205   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7206     ImplicitParamType = FromPtrType->getPointeeType();
7207   CXXRecordDecl *ConversionContext
7208     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7209 
7210   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7211       *this, CandidateSet.getLocation(), From->getType(),
7212       From->Classify(Context), Conversion, ConversionContext);
7213 
7214   if (Candidate.Conversions[0].isBad()) {
7215     Candidate.Viable = false;
7216     Candidate.FailureKind = ovl_fail_bad_conversion;
7217     return;
7218   }
7219 
7220   if (Conversion->getTrailingRequiresClause()) {
7221     ConstraintSatisfaction Satisfaction;
7222     if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7223         !Satisfaction.IsSatisfied) {
7224       Candidate.Viable = false;
7225       Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7226       return;
7227     }
7228   }
7229 
7230   // We won't go through a user-defined type conversion function to convert a
7231   // derived to base as such conversions are given Conversion Rank. They only
7232   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7233   QualType FromCanon
7234     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7235   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7236   if (FromCanon == ToCanon ||
7237       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7238     Candidate.Viable = false;
7239     Candidate.FailureKind = ovl_fail_trivial_conversion;
7240     return;
7241   }
7242 
7243   // To determine what the conversion from the result of calling the
7244   // conversion function to the type we're eventually trying to
7245   // convert to (ToType), we need to synthesize a call to the
7246   // conversion function and attempt copy initialization from it. This
7247   // makes sure that we get the right semantics with respect to
7248   // lvalues/rvalues and the type. Fortunately, we can allocate this
7249   // call on the stack and we don't need its arguments to be
7250   // well-formed.
7251   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7252                             VK_LValue, From->getBeginLoc());
7253   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7254                                 Context.getPointerType(Conversion->getType()),
7255                                 CK_FunctionToPointerDecay,
7256                                 &ConversionRef, VK_RValue);
7257 
7258   QualType ConversionType = Conversion->getConversionType();
7259   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7260     Candidate.Viable = false;
7261     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7262     return;
7263   }
7264 
7265   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7266 
7267   // Note that it is safe to allocate CallExpr on the stack here because
7268   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7269   // allocator).
7270   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7271 
7272   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7273   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7274       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7275 
7276   ImplicitConversionSequence ICS =
7277       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7278                             /*SuppressUserConversions=*/true,
7279                             /*InOverloadResolution=*/false,
7280                             /*AllowObjCWritebackConversion=*/false);
7281 
7282   switch (ICS.getKind()) {
7283   case ImplicitConversionSequence::StandardConversion:
7284     Candidate.FinalConversion = ICS.Standard;
7285 
7286     // C++ [over.ics.user]p3:
7287     //   If the user-defined conversion is specified by a specialization of a
7288     //   conversion function template, the second standard conversion sequence
7289     //   shall have exact match rank.
7290     if (Conversion->getPrimaryTemplate() &&
7291         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7292       Candidate.Viable = false;
7293       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7294       return;
7295     }
7296 
7297     // C++0x [dcl.init.ref]p5:
7298     //    In the second case, if the reference is an rvalue reference and
7299     //    the second standard conversion sequence of the user-defined
7300     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7301     //    program is ill-formed.
7302     if (ToType->isRValueReferenceType() &&
7303         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7304       Candidate.Viable = false;
7305       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7306       return;
7307     }
7308     break;
7309 
7310   case ImplicitConversionSequence::BadConversion:
7311     Candidate.Viable = false;
7312     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7313     return;
7314 
7315   default:
7316     llvm_unreachable(
7317            "Can only end up with a standard conversion sequence or failure");
7318   }
7319 
7320   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7321     Candidate.Viable = false;
7322     Candidate.FailureKind = ovl_fail_enable_if;
7323     Candidate.DeductionFailure.Data = FailedAttr;
7324     return;
7325   }
7326 
7327   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7328       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7329     Candidate.Viable = false;
7330     Candidate.FailureKind = ovl_non_default_multiversion_function;
7331   }
7332 }
7333 
7334 /// Adds a conversion function template specialization
7335 /// candidate to the overload set, using template argument deduction
7336 /// to deduce the template arguments of the conversion function
7337 /// template from the type that we are converting to (C++
7338 /// [temp.deduct.conv]).
7339 void Sema::AddTemplateConversionCandidate(
7340     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7341     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7342     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7343     bool AllowExplicit, bool AllowResultConversion) {
7344   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7345          "Only conversion function templates permitted here");
7346 
7347   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7348     return;
7349 
7350   // If the function template has a non-dependent explicit specification,
7351   // exclude it now if appropriate; we are not permitted to perform deduction
7352   // and substitution in this case.
7353   if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7354     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7355     Candidate.FoundDecl = FoundDecl;
7356     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7357     Candidate.Viable = false;
7358     Candidate.FailureKind = ovl_fail_explicit;
7359     return;
7360   }
7361 
7362   TemplateDeductionInfo Info(CandidateSet.getLocation());
7363   CXXConversionDecl *Specialization = nullptr;
7364   if (TemplateDeductionResult Result
7365         = DeduceTemplateArguments(FunctionTemplate, ToType,
7366                                   Specialization, Info)) {
7367     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7368     Candidate.FoundDecl = FoundDecl;
7369     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7370     Candidate.Viable = false;
7371     Candidate.FailureKind = ovl_fail_bad_deduction;
7372     Candidate.IsSurrogate = false;
7373     Candidate.IgnoreObjectArgument = false;
7374     Candidate.ExplicitCallArguments = 1;
7375     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7376                                                           Info);
7377     return;
7378   }
7379 
7380   // Add the conversion function template specialization produced by
7381   // template argument deduction as a candidate.
7382   assert(Specialization && "Missing function template specialization?");
7383   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7384                          CandidateSet, AllowObjCConversionOnExplicit,
7385                          AllowExplicit, AllowResultConversion);
7386 }
7387 
7388 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7389 /// converts the given @c Object to a function pointer via the
7390 /// conversion function @c Conversion, and then attempts to call it
7391 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7392 /// the type of function that we'll eventually be calling.
7393 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7394                                  DeclAccessPair FoundDecl,
7395                                  CXXRecordDecl *ActingContext,
7396                                  const FunctionProtoType *Proto,
7397                                  Expr *Object,
7398                                  ArrayRef<Expr *> Args,
7399                                  OverloadCandidateSet& CandidateSet) {
7400   if (!CandidateSet.isNewCandidate(Conversion))
7401     return;
7402 
7403   // Overload resolution is always an unevaluated context.
7404   EnterExpressionEvaluationContext Unevaluated(
7405       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7406 
7407   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7408   Candidate.FoundDecl = FoundDecl;
7409   Candidate.Function = nullptr;
7410   Candidate.Surrogate = Conversion;
7411   Candidate.Viable = true;
7412   Candidate.IsSurrogate = true;
7413   Candidate.IgnoreObjectArgument = false;
7414   Candidate.ExplicitCallArguments = Args.size();
7415 
7416   // Determine the implicit conversion sequence for the implicit
7417   // object parameter.
7418   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7419       *this, CandidateSet.getLocation(), Object->getType(),
7420       Object->Classify(Context), Conversion, ActingContext);
7421   if (ObjectInit.isBad()) {
7422     Candidate.Viable = false;
7423     Candidate.FailureKind = ovl_fail_bad_conversion;
7424     Candidate.Conversions[0] = ObjectInit;
7425     return;
7426   }
7427 
7428   // The first conversion is actually a user-defined conversion whose
7429   // first conversion is ObjectInit's standard conversion (which is
7430   // effectively a reference binding). Record it as such.
7431   Candidate.Conversions[0].setUserDefined();
7432   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7433   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7434   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7435   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7436   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7437   Candidate.Conversions[0].UserDefined.After
7438     = Candidate.Conversions[0].UserDefined.Before;
7439   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7440 
7441   // Find the
7442   unsigned NumParams = Proto->getNumParams();
7443 
7444   // (C++ 13.3.2p2): A candidate function having fewer than m
7445   // parameters is viable only if it has an ellipsis in its parameter
7446   // list (8.3.5).
7447   if (Args.size() > NumParams && !Proto->isVariadic()) {
7448     Candidate.Viable = false;
7449     Candidate.FailureKind = ovl_fail_too_many_arguments;
7450     return;
7451   }
7452 
7453   // Function types don't have any default arguments, so just check if
7454   // we have enough arguments.
7455   if (Args.size() < NumParams) {
7456     // Not enough arguments.
7457     Candidate.Viable = false;
7458     Candidate.FailureKind = ovl_fail_too_few_arguments;
7459     return;
7460   }
7461 
7462   // Determine the implicit conversion sequences for each of the
7463   // arguments.
7464   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7465     if (ArgIdx < NumParams) {
7466       // (C++ 13.3.2p3): for F to be a viable function, there shall
7467       // exist for each argument an implicit conversion sequence
7468       // (13.3.3.1) that converts that argument to the corresponding
7469       // parameter of F.
7470       QualType ParamType = Proto->getParamType(ArgIdx);
7471       Candidate.Conversions[ArgIdx + 1]
7472         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7473                                 /*SuppressUserConversions=*/false,
7474                                 /*InOverloadResolution=*/false,
7475                                 /*AllowObjCWritebackConversion=*/
7476                                   getLangOpts().ObjCAutoRefCount);
7477       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7478         Candidate.Viable = false;
7479         Candidate.FailureKind = ovl_fail_bad_conversion;
7480         return;
7481       }
7482     } else {
7483       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7484       // argument for which there is no corresponding parameter is
7485       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7486       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7487     }
7488   }
7489 
7490   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7491     Candidate.Viable = false;
7492     Candidate.FailureKind = ovl_fail_enable_if;
7493     Candidate.DeductionFailure.Data = FailedAttr;
7494     return;
7495   }
7496 }
7497 
7498 /// Add all of the non-member operator function declarations in the given
7499 /// function set to the overload candidate set.
7500 void Sema::AddNonMemberOperatorCandidates(
7501     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7502     OverloadCandidateSet &CandidateSet,
7503     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7504   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7505     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7506     ArrayRef<Expr *> FunctionArgs = Args;
7507 
7508     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7509     FunctionDecl *FD =
7510         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7511 
7512     // Don't consider rewritten functions if we're not rewriting.
7513     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7514       continue;
7515 
7516     assert(!isa<CXXMethodDecl>(FD) &&
7517            "unqualified operator lookup found a member function");
7518 
7519     if (FunTmpl) {
7520       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7521                                    FunctionArgs, CandidateSet);
7522       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7523         AddTemplateOverloadCandidate(
7524             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7525             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7526             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7527     } else {
7528       if (ExplicitTemplateArgs)
7529         continue;
7530       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7531       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7532         AddOverloadCandidate(FD, F.getPair(),
7533                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7534                              false, false, true, false, ADLCallKind::NotADL,
7535                              None, OverloadCandidateParamOrder::Reversed);
7536     }
7537   }
7538 }
7539 
7540 /// Add overload candidates for overloaded operators that are
7541 /// member functions.
7542 ///
7543 /// Add the overloaded operator candidates that are member functions
7544 /// for the operator Op that was used in an operator expression such
7545 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7546 /// CandidateSet will store the added overload candidates. (C++
7547 /// [over.match.oper]).
7548 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7549                                        SourceLocation OpLoc,
7550                                        ArrayRef<Expr *> Args,
7551                                        OverloadCandidateSet &CandidateSet,
7552                                        OverloadCandidateParamOrder PO) {
7553   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7554 
7555   // C++ [over.match.oper]p3:
7556   //   For a unary operator @ with an operand of a type whose
7557   //   cv-unqualified version is T1, and for a binary operator @ with
7558   //   a left operand of a type whose cv-unqualified version is T1 and
7559   //   a right operand of a type whose cv-unqualified version is T2,
7560   //   three sets of candidate functions, designated member
7561   //   candidates, non-member candidates and built-in candidates, are
7562   //   constructed as follows:
7563   QualType T1 = Args[0]->getType();
7564 
7565   //     -- If T1 is a complete class type or a class currently being
7566   //        defined, the set of member candidates is the result of the
7567   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7568   //        the set of member candidates is empty.
7569   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7570     // Complete the type if it can be completed.
7571     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7572       return;
7573     // If the type is neither complete nor being defined, bail out now.
7574     if (!T1Rec->getDecl()->getDefinition())
7575       return;
7576 
7577     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7578     LookupQualifiedName(Operators, T1Rec->getDecl());
7579     Operators.suppressDiagnostics();
7580 
7581     for (LookupResult::iterator Oper = Operators.begin(),
7582                              OperEnd = Operators.end();
7583          Oper != OperEnd;
7584          ++Oper)
7585       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7586                          Args[0]->Classify(Context), Args.slice(1),
7587                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7588   }
7589 }
7590 
7591 /// AddBuiltinCandidate - Add a candidate for a built-in
7592 /// operator. ResultTy and ParamTys are the result and parameter types
7593 /// of the built-in candidate, respectively. Args and NumArgs are the
7594 /// arguments being passed to the candidate. IsAssignmentOperator
7595 /// should be true when this built-in candidate is an assignment
7596 /// operator. NumContextualBoolArguments is the number of arguments
7597 /// (at the beginning of the argument list) that will be contextually
7598 /// converted to bool.
7599 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7600                                OverloadCandidateSet& CandidateSet,
7601                                bool IsAssignmentOperator,
7602                                unsigned NumContextualBoolArguments) {
7603   // Overload resolution is always an unevaluated context.
7604   EnterExpressionEvaluationContext Unevaluated(
7605       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7606 
7607   // Add this candidate
7608   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7609   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7610   Candidate.Function = nullptr;
7611   Candidate.IsSurrogate = false;
7612   Candidate.IgnoreObjectArgument = false;
7613   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7614 
7615   // Determine the implicit conversion sequences for each of the
7616   // arguments.
7617   Candidate.Viable = true;
7618   Candidate.ExplicitCallArguments = Args.size();
7619   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7620     // C++ [over.match.oper]p4:
7621     //   For the built-in assignment operators, conversions of the
7622     //   left operand are restricted as follows:
7623     //     -- no temporaries are introduced to hold the left operand, and
7624     //     -- no user-defined conversions are applied to the left
7625     //        operand to achieve a type match with the left-most
7626     //        parameter of a built-in candidate.
7627     //
7628     // We block these conversions by turning off user-defined
7629     // conversions, since that is the only way that initialization of
7630     // a reference to a non-class type can occur from something that
7631     // is not of the same type.
7632     if (ArgIdx < NumContextualBoolArguments) {
7633       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7634              "Contextual conversion to bool requires bool type");
7635       Candidate.Conversions[ArgIdx]
7636         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7637     } else {
7638       Candidate.Conversions[ArgIdx]
7639         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7640                                 ArgIdx == 0 && IsAssignmentOperator,
7641                                 /*InOverloadResolution=*/false,
7642                                 /*AllowObjCWritebackConversion=*/
7643                                   getLangOpts().ObjCAutoRefCount);
7644     }
7645     if (Candidate.Conversions[ArgIdx].isBad()) {
7646       Candidate.Viable = false;
7647       Candidate.FailureKind = ovl_fail_bad_conversion;
7648       break;
7649     }
7650   }
7651 }
7652 
7653 namespace {
7654 
7655 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7656 /// candidate operator functions for built-in operators (C++
7657 /// [over.built]). The types are separated into pointer types and
7658 /// enumeration types.
7659 class BuiltinCandidateTypeSet  {
7660   /// TypeSet - A set of types.
7661   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7662                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7663 
7664   /// PointerTypes - The set of pointer types that will be used in the
7665   /// built-in candidates.
7666   TypeSet PointerTypes;
7667 
7668   /// MemberPointerTypes - The set of member pointer types that will be
7669   /// used in the built-in candidates.
7670   TypeSet MemberPointerTypes;
7671 
7672   /// EnumerationTypes - The set of enumeration types that will be
7673   /// used in the built-in candidates.
7674   TypeSet EnumerationTypes;
7675 
7676   /// The set of vector types that will be used in the built-in
7677   /// candidates.
7678   TypeSet VectorTypes;
7679 
7680   /// A flag indicating non-record types are viable candidates
7681   bool HasNonRecordTypes;
7682 
7683   /// A flag indicating whether either arithmetic or enumeration types
7684   /// were present in the candidate set.
7685   bool HasArithmeticOrEnumeralTypes;
7686 
7687   /// A flag indicating whether the nullptr type was present in the
7688   /// candidate set.
7689   bool HasNullPtrType;
7690 
7691   /// Sema - The semantic analysis instance where we are building the
7692   /// candidate type set.
7693   Sema &SemaRef;
7694 
7695   /// Context - The AST context in which we will build the type sets.
7696   ASTContext &Context;
7697 
7698   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7699                                                const Qualifiers &VisibleQuals);
7700   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7701 
7702 public:
7703   /// iterator - Iterates through the types that are part of the set.
7704   typedef TypeSet::iterator iterator;
7705 
7706   BuiltinCandidateTypeSet(Sema &SemaRef)
7707     : HasNonRecordTypes(false),
7708       HasArithmeticOrEnumeralTypes(false),
7709       HasNullPtrType(false),
7710       SemaRef(SemaRef),
7711       Context(SemaRef.Context) { }
7712 
7713   void AddTypesConvertedFrom(QualType Ty,
7714                              SourceLocation Loc,
7715                              bool AllowUserConversions,
7716                              bool AllowExplicitConversions,
7717                              const Qualifiers &VisibleTypeConversionsQuals);
7718 
7719   /// pointer_begin - First pointer type found;
7720   iterator pointer_begin() { return PointerTypes.begin(); }
7721 
7722   /// pointer_end - Past the last pointer type found;
7723   iterator pointer_end() { return PointerTypes.end(); }
7724 
7725   /// member_pointer_begin - First member pointer type found;
7726   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7727 
7728   /// member_pointer_end - Past the last member pointer type found;
7729   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7730 
7731   /// enumeration_begin - First enumeration type found;
7732   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7733 
7734   /// enumeration_end - Past the last enumeration type found;
7735   iterator enumeration_end() { return EnumerationTypes.end(); }
7736 
7737   iterator vector_begin() { return VectorTypes.begin(); }
7738   iterator vector_end() { return VectorTypes.end(); }
7739 
7740   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7741   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7742   bool hasNullPtrType() const { return HasNullPtrType; }
7743 };
7744 
7745 } // end anonymous namespace
7746 
7747 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7748 /// the set of pointer types along with any more-qualified variants of
7749 /// that type. For example, if @p Ty is "int const *", this routine
7750 /// will add "int const *", "int const volatile *", "int const
7751 /// restrict *", and "int const volatile restrict *" to the set of
7752 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7753 /// false otherwise.
7754 ///
7755 /// FIXME: what to do about extended qualifiers?
7756 bool
7757 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7758                                              const Qualifiers &VisibleQuals) {
7759 
7760   // Insert this type.
7761   if (!PointerTypes.insert(Ty))
7762     return false;
7763 
7764   QualType PointeeTy;
7765   const PointerType *PointerTy = Ty->getAs<PointerType>();
7766   bool buildObjCPtr = false;
7767   if (!PointerTy) {
7768     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7769     PointeeTy = PTy->getPointeeType();
7770     buildObjCPtr = true;
7771   } else {
7772     PointeeTy = PointerTy->getPointeeType();
7773   }
7774 
7775   // Don't add qualified variants of arrays. For one, they're not allowed
7776   // (the qualifier would sink to the element type), and for another, the
7777   // only overload situation where it matters is subscript or pointer +- int,
7778   // and those shouldn't have qualifier variants anyway.
7779   if (PointeeTy->isArrayType())
7780     return true;
7781 
7782   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7783   bool hasVolatile = VisibleQuals.hasVolatile();
7784   bool hasRestrict = VisibleQuals.hasRestrict();
7785 
7786   // Iterate through all strict supersets of BaseCVR.
7787   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7788     if ((CVR | BaseCVR) != CVR) continue;
7789     // Skip over volatile if no volatile found anywhere in the types.
7790     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7791 
7792     // Skip over restrict if no restrict found anywhere in the types, or if
7793     // the type cannot be restrict-qualified.
7794     if ((CVR & Qualifiers::Restrict) &&
7795         (!hasRestrict ||
7796          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7797       continue;
7798 
7799     // Build qualified pointee type.
7800     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7801 
7802     // Build qualified pointer type.
7803     QualType QPointerTy;
7804     if (!buildObjCPtr)
7805       QPointerTy = Context.getPointerType(QPointeeTy);
7806     else
7807       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7808 
7809     // Insert qualified pointer type.
7810     PointerTypes.insert(QPointerTy);
7811   }
7812 
7813   return true;
7814 }
7815 
7816 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7817 /// to the set of pointer types along with any more-qualified variants of
7818 /// that type. For example, if @p Ty is "int const *", this routine
7819 /// will add "int const *", "int const volatile *", "int const
7820 /// restrict *", and "int const volatile restrict *" to the set of
7821 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7822 /// false otherwise.
7823 ///
7824 /// FIXME: what to do about extended qualifiers?
7825 bool
7826 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7827     QualType Ty) {
7828   // Insert this type.
7829   if (!MemberPointerTypes.insert(Ty))
7830     return false;
7831 
7832   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7833   assert(PointerTy && "type was not a member pointer type!");
7834 
7835   QualType PointeeTy = PointerTy->getPointeeType();
7836   // Don't add qualified variants of arrays. For one, they're not allowed
7837   // (the qualifier would sink to the element type), and for another, the
7838   // only overload situation where it matters is subscript or pointer +- int,
7839   // and those shouldn't have qualifier variants anyway.
7840   if (PointeeTy->isArrayType())
7841     return true;
7842   const Type *ClassTy = PointerTy->getClass();
7843 
7844   // Iterate through all strict supersets of the pointee type's CVR
7845   // qualifiers.
7846   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7847   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7848     if ((CVR | BaseCVR) != CVR) continue;
7849 
7850     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7851     MemberPointerTypes.insert(
7852       Context.getMemberPointerType(QPointeeTy, ClassTy));
7853   }
7854 
7855   return true;
7856 }
7857 
7858 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7859 /// Ty can be implicit converted to the given set of @p Types. We're
7860 /// primarily interested in pointer types and enumeration types. We also
7861 /// take member pointer types, for the conditional operator.
7862 /// AllowUserConversions is true if we should look at the conversion
7863 /// functions of a class type, and AllowExplicitConversions if we
7864 /// should also include the explicit conversion functions of a class
7865 /// type.
7866 void
7867 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7868                                                SourceLocation Loc,
7869                                                bool AllowUserConversions,
7870                                                bool AllowExplicitConversions,
7871                                                const Qualifiers &VisibleQuals) {
7872   // Only deal with canonical types.
7873   Ty = Context.getCanonicalType(Ty);
7874 
7875   // Look through reference types; they aren't part of the type of an
7876   // expression for the purposes of conversions.
7877   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7878     Ty = RefTy->getPointeeType();
7879 
7880   // If we're dealing with an array type, decay to the pointer.
7881   if (Ty->isArrayType())
7882     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7883 
7884   // Otherwise, we don't care about qualifiers on the type.
7885   Ty = Ty.getLocalUnqualifiedType();
7886 
7887   // Flag if we ever add a non-record type.
7888   const RecordType *TyRec = Ty->getAs<RecordType>();
7889   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7890 
7891   // Flag if we encounter an arithmetic type.
7892   HasArithmeticOrEnumeralTypes =
7893     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7894 
7895   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7896     PointerTypes.insert(Ty);
7897   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7898     // Insert our type, and its more-qualified variants, into the set
7899     // of types.
7900     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7901       return;
7902   } else if (Ty->isMemberPointerType()) {
7903     // Member pointers are far easier, since the pointee can't be converted.
7904     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7905       return;
7906   } else if (Ty->isEnumeralType()) {
7907     HasArithmeticOrEnumeralTypes = true;
7908     EnumerationTypes.insert(Ty);
7909   } else if (Ty->isVectorType()) {
7910     // We treat vector types as arithmetic types in many contexts as an
7911     // extension.
7912     HasArithmeticOrEnumeralTypes = true;
7913     VectorTypes.insert(Ty);
7914   } else if (Ty->isNullPtrType()) {
7915     HasNullPtrType = true;
7916   } else if (AllowUserConversions && TyRec) {
7917     // No conversion functions in incomplete types.
7918     if (!SemaRef.isCompleteType(Loc, Ty))
7919       return;
7920 
7921     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7922     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7923       if (isa<UsingShadowDecl>(D))
7924         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7925 
7926       // Skip conversion function templates; they don't tell us anything
7927       // about which builtin types we can convert to.
7928       if (isa<FunctionTemplateDecl>(D))
7929         continue;
7930 
7931       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7932       if (AllowExplicitConversions || !Conv->isExplicit()) {
7933         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7934                               VisibleQuals);
7935       }
7936     }
7937   }
7938 }
7939 /// Helper function for adjusting address spaces for the pointer or reference
7940 /// operands of builtin operators depending on the argument.
7941 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7942                                                         Expr *Arg) {
7943   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7944 }
7945 
7946 /// Helper function for AddBuiltinOperatorCandidates() that adds
7947 /// the volatile- and non-volatile-qualified assignment operators for the
7948 /// given type to the candidate set.
7949 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7950                                                    QualType T,
7951                                                    ArrayRef<Expr *> Args,
7952                                     OverloadCandidateSet &CandidateSet) {
7953   QualType ParamTypes[2];
7954 
7955   // T& operator=(T&, T)
7956   ParamTypes[0] = S.Context.getLValueReferenceType(
7957       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7958   ParamTypes[1] = T;
7959   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7960                         /*IsAssignmentOperator=*/true);
7961 
7962   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7963     // volatile T& operator=(volatile T&, T)
7964     ParamTypes[0] = S.Context.getLValueReferenceType(
7965         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7966                                                 Args[0]));
7967     ParamTypes[1] = T;
7968     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7969                           /*IsAssignmentOperator=*/true);
7970   }
7971 }
7972 
7973 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7974 /// if any, found in visible type conversion functions found in ArgExpr's type.
7975 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7976     Qualifiers VRQuals;
7977     const RecordType *TyRec;
7978     if (const MemberPointerType *RHSMPType =
7979         ArgExpr->getType()->getAs<MemberPointerType>())
7980       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7981     else
7982       TyRec = ArgExpr->getType()->getAs<RecordType>();
7983     if (!TyRec) {
7984       // Just to be safe, assume the worst case.
7985       VRQuals.addVolatile();
7986       VRQuals.addRestrict();
7987       return VRQuals;
7988     }
7989 
7990     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7991     if (!ClassDecl->hasDefinition())
7992       return VRQuals;
7993 
7994     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7995       if (isa<UsingShadowDecl>(D))
7996         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7997       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7998         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7999         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8000           CanTy = ResTypeRef->getPointeeType();
8001         // Need to go down the pointer/mempointer chain and add qualifiers
8002         // as see them.
8003         bool done = false;
8004         while (!done) {
8005           if (CanTy.isRestrictQualified())
8006             VRQuals.addRestrict();
8007           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8008             CanTy = ResTypePtr->getPointeeType();
8009           else if (const MemberPointerType *ResTypeMPtr =
8010                 CanTy->getAs<MemberPointerType>())
8011             CanTy = ResTypeMPtr->getPointeeType();
8012           else
8013             done = true;
8014           if (CanTy.isVolatileQualified())
8015             VRQuals.addVolatile();
8016           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8017             return VRQuals;
8018         }
8019       }
8020     }
8021     return VRQuals;
8022 }
8023 
8024 namespace {
8025 
8026 /// Helper class to manage the addition of builtin operator overload
8027 /// candidates. It provides shared state and utility methods used throughout
8028 /// the process, as well as a helper method to add each group of builtin
8029 /// operator overloads from the standard to a candidate set.
8030 class BuiltinOperatorOverloadBuilder {
8031   // Common instance state available to all overload candidate addition methods.
8032   Sema &S;
8033   ArrayRef<Expr *> Args;
8034   Qualifiers VisibleTypeConversionsQuals;
8035   bool HasArithmeticOrEnumeralCandidateType;
8036   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8037   OverloadCandidateSet &CandidateSet;
8038 
8039   static constexpr int ArithmeticTypesCap = 24;
8040   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8041 
8042   // Define some indices used to iterate over the arithmetic types in
8043   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
8044   // types are that preserved by promotion (C++ [over.built]p2).
8045   unsigned FirstIntegralType,
8046            LastIntegralType;
8047   unsigned FirstPromotedIntegralType,
8048            LastPromotedIntegralType;
8049   unsigned FirstPromotedArithmeticType,
8050            LastPromotedArithmeticType;
8051   unsigned NumArithmeticTypes;
8052 
8053   void InitArithmeticTypes() {
8054     // Start of promoted types.
8055     FirstPromotedArithmeticType = 0;
8056     ArithmeticTypes.push_back(S.Context.FloatTy);
8057     ArithmeticTypes.push_back(S.Context.DoubleTy);
8058     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8059     if (S.Context.getTargetInfo().hasFloat128Type())
8060       ArithmeticTypes.push_back(S.Context.Float128Ty);
8061 
8062     // Start of integral types.
8063     FirstIntegralType = ArithmeticTypes.size();
8064     FirstPromotedIntegralType = ArithmeticTypes.size();
8065     ArithmeticTypes.push_back(S.Context.IntTy);
8066     ArithmeticTypes.push_back(S.Context.LongTy);
8067     ArithmeticTypes.push_back(S.Context.LongLongTy);
8068     if (S.Context.getTargetInfo().hasInt128Type())
8069       ArithmeticTypes.push_back(S.Context.Int128Ty);
8070     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8071     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8072     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8073     if (S.Context.getTargetInfo().hasInt128Type())
8074       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8075     LastPromotedIntegralType = ArithmeticTypes.size();
8076     LastPromotedArithmeticType = ArithmeticTypes.size();
8077     // End of promoted types.
8078 
8079     ArithmeticTypes.push_back(S.Context.BoolTy);
8080     ArithmeticTypes.push_back(S.Context.CharTy);
8081     ArithmeticTypes.push_back(S.Context.WCharTy);
8082     if (S.Context.getLangOpts().Char8)
8083       ArithmeticTypes.push_back(S.Context.Char8Ty);
8084     ArithmeticTypes.push_back(S.Context.Char16Ty);
8085     ArithmeticTypes.push_back(S.Context.Char32Ty);
8086     ArithmeticTypes.push_back(S.Context.SignedCharTy);
8087     ArithmeticTypes.push_back(S.Context.ShortTy);
8088     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8089     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8090     LastIntegralType = ArithmeticTypes.size();
8091     NumArithmeticTypes = ArithmeticTypes.size();
8092     // End of integral types.
8093     // FIXME: What about complex? What about half?
8094 
8095     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8096            "Enough inline storage for all arithmetic types.");
8097   }
8098 
8099   /// Helper method to factor out the common pattern of adding overloads
8100   /// for '++' and '--' builtin operators.
8101   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8102                                            bool HasVolatile,
8103                                            bool HasRestrict) {
8104     QualType ParamTypes[2] = {
8105       S.Context.getLValueReferenceType(CandidateTy),
8106       S.Context.IntTy
8107     };
8108 
8109     // Non-volatile version.
8110     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8111 
8112     // Use a heuristic to reduce number of builtin candidates in the set:
8113     // add volatile version only if there are conversions to a volatile type.
8114     if (HasVolatile) {
8115       ParamTypes[0] =
8116         S.Context.getLValueReferenceType(
8117           S.Context.getVolatileType(CandidateTy));
8118       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8119     }
8120 
8121     // Add restrict version only if there are conversions to a restrict type
8122     // and our candidate type is a non-restrict-qualified pointer.
8123     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8124         !CandidateTy.isRestrictQualified()) {
8125       ParamTypes[0]
8126         = S.Context.getLValueReferenceType(
8127             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8128       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8129 
8130       if (HasVolatile) {
8131         ParamTypes[0]
8132           = S.Context.getLValueReferenceType(
8133               S.Context.getCVRQualifiedType(CandidateTy,
8134                                             (Qualifiers::Volatile |
8135                                              Qualifiers::Restrict)));
8136         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8137       }
8138     }
8139 
8140   }
8141 
8142 public:
8143   BuiltinOperatorOverloadBuilder(
8144     Sema &S, ArrayRef<Expr *> Args,
8145     Qualifiers VisibleTypeConversionsQuals,
8146     bool HasArithmeticOrEnumeralCandidateType,
8147     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8148     OverloadCandidateSet &CandidateSet)
8149     : S(S), Args(Args),
8150       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8151       HasArithmeticOrEnumeralCandidateType(
8152         HasArithmeticOrEnumeralCandidateType),
8153       CandidateTypes(CandidateTypes),
8154       CandidateSet(CandidateSet) {
8155 
8156     InitArithmeticTypes();
8157   }
8158 
8159   // Increment is deprecated for bool since C++17.
8160   //
8161   // C++ [over.built]p3:
8162   //
8163   //   For every pair (T, VQ), where T is an arithmetic type other
8164   //   than bool, and VQ is either volatile or empty, there exist
8165   //   candidate operator functions of the form
8166   //
8167   //       VQ T&      operator++(VQ T&);
8168   //       T          operator++(VQ T&, int);
8169   //
8170   // C++ [over.built]p4:
8171   //
8172   //   For every pair (T, VQ), where T is an arithmetic type other
8173   //   than bool, and VQ is either volatile or empty, there exist
8174   //   candidate operator functions of the form
8175   //
8176   //       VQ T&      operator--(VQ T&);
8177   //       T          operator--(VQ T&, int);
8178   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8179     if (!HasArithmeticOrEnumeralCandidateType)
8180       return;
8181 
8182     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8183       const auto TypeOfT = ArithmeticTypes[Arith];
8184       if (TypeOfT == S.Context.BoolTy) {
8185         if (Op == OO_MinusMinus)
8186           continue;
8187         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8188           continue;
8189       }
8190       addPlusPlusMinusMinusStyleOverloads(
8191         TypeOfT,
8192         VisibleTypeConversionsQuals.hasVolatile(),
8193         VisibleTypeConversionsQuals.hasRestrict());
8194     }
8195   }
8196 
8197   // C++ [over.built]p5:
8198   //
8199   //   For every pair (T, VQ), where T is a cv-qualified or
8200   //   cv-unqualified object type, and VQ is either volatile or
8201   //   empty, there exist candidate operator functions of the form
8202   //
8203   //       T*VQ&      operator++(T*VQ&);
8204   //       T*VQ&      operator--(T*VQ&);
8205   //       T*         operator++(T*VQ&, int);
8206   //       T*         operator--(T*VQ&, int);
8207   void addPlusPlusMinusMinusPointerOverloads() {
8208     for (BuiltinCandidateTypeSet::iterator
8209               Ptr = CandidateTypes[0].pointer_begin(),
8210            PtrEnd = CandidateTypes[0].pointer_end();
8211          Ptr != PtrEnd; ++Ptr) {
8212       // Skip pointer types that aren't pointers to object types.
8213       if (!(*Ptr)->getPointeeType()->isObjectType())
8214         continue;
8215 
8216       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8217         (!(*Ptr).isVolatileQualified() &&
8218          VisibleTypeConversionsQuals.hasVolatile()),
8219         (!(*Ptr).isRestrictQualified() &&
8220          VisibleTypeConversionsQuals.hasRestrict()));
8221     }
8222   }
8223 
8224   // C++ [over.built]p6:
8225   //   For every cv-qualified or cv-unqualified object type T, there
8226   //   exist candidate operator functions of the form
8227   //
8228   //       T&         operator*(T*);
8229   //
8230   // C++ [over.built]p7:
8231   //   For every function type T that does not have cv-qualifiers or a
8232   //   ref-qualifier, there exist candidate operator functions of the form
8233   //       T&         operator*(T*);
8234   void addUnaryStarPointerOverloads() {
8235     for (BuiltinCandidateTypeSet::iterator
8236               Ptr = CandidateTypes[0].pointer_begin(),
8237            PtrEnd = CandidateTypes[0].pointer_end();
8238          Ptr != PtrEnd; ++Ptr) {
8239       QualType ParamTy = *Ptr;
8240       QualType PointeeTy = ParamTy->getPointeeType();
8241       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8242         continue;
8243 
8244       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8245         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8246           continue;
8247 
8248       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8249     }
8250   }
8251 
8252   // C++ [over.built]p9:
8253   //  For every promoted arithmetic type T, there exist candidate
8254   //  operator functions of the form
8255   //
8256   //       T         operator+(T);
8257   //       T         operator-(T);
8258   void addUnaryPlusOrMinusArithmeticOverloads() {
8259     if (!HasArithmeticOrEnumeralCandidateType)
8260       return;
8261 
8262     for (unsigned Arith = FirstPromotedArithmeticType;
8263          Arith < LastPromotedArithmeticType; ++Arith) {
8264       QualType ArithTy = ArithmeticTypes[Arith];
8265       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8266     }
8267 
8268     // Extension: We also add these operators for vector types.
8269     for (BuiltinCandidateTypeSet::iterator
8270               Vec = CandidateTypes[0].vector_begin(),
8271            VecEnd = CandidateTypes[0].vector_end();
8272          Vec != VecEnd; ++Vec) {
8273       QualType VecTy = *Vec;
8274       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8275     }
8276   }
8277 
8278   // C++ [over.built]p8:
8279   //   For every type T, there exist candidate operator functions of
8280   //   the form
8281   //
8282   //       T*         operator+(T*);
8283   void addUnaryPlusPointerOverloads() {
8284     for (BuiltinCandidateTypeSet::iterator
8285               Ptr = CandidateTypes[0].pointer_begin(),
8286            PtrEnd = CandidateTypes[0].pointer_end();
8287          Ptr != PtrEnd; ++Ptr) {
8288       QualType ParamTy = *Ptr;
8289       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8290     }
8291   }
8292 
8293   // C++ [over.built]p10:
8294   //   For every promoted integral type T, there exist candidate
8295   //   operator functions of the form
8296   //
8297   //        T         operator~(T);
8298   void addUnaryTildePromotedIntegralOverloads() {
8299     if (!HasArithmeticOrEnumeralCandidateType)
8300       return;
8301 
8302     for (unsigned Int = FirstPromotedIntegralType;
8303          Int < LastPromotedIntegralType; ++Int) {
8304       QualType IntTy = ArithmeticTypes[Int];
8305       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8306     }
8307 
8308     // Extension: We also add this operator for vector types.
8309     for (BuiltinCandidateTypeSet::iterator
8310               Vec = CandidateTypes[0].vector_begin(),
8311            VecEnd = CandidateTypes[0].vector_end();
8312          Vec != VecEnd; ++Vec) {
8313       QualType VecTy = *Vec;
8314       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8315     }
8316   }
8317 
8318   // C++ [over.match.oper]p16:
8319   //   For every pointer to member type T or type std::nullptr_t, there
8320   //   exist candidate operator functions of the form
8321   //
8322   //        bool operator==(T,T);
8323   //        bool operator!=(T,T);
8324   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8325     /// Set of (canonical) types that we've already handled.
8326     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8327 
8328     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8329       for (BuiltinCandidateTypeSet::iterator
8330                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8331              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8332            MemPtr != MemPtrEnd;
8333            ++MemPtr) {
8334         // Don't add the same builtin candidate twice.
8335         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8336           continue;
8337 
8338         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8339         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8340       }
8341 
8342       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8343         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8344         if (AddedTypes.insert(NullPtrTy).second) {
8345           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8346           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8347         }
8348       }
8349     }
8350   }
8351 
8352   // C++ [over.built]p15:
8353   //
8354   //   For every T, where T is an enumeration type or a pointer type,
8355   //   there exist candidate operator functions of the form
8356   //
8357   //        bool       operator<(T, T);
8358   //        bool       operator>(T, T);
8359   //        bool       operator<=(T, T);
8360   //        bool       operator>=(T, T);
8361   //        bool       operator==(T, T);
8362   //        bool       operator!=(T, T);
8363   //           R       operator<=>(T, T)
8364   void addGenericBinaryPointerOrEnumeralOverloads() {
8365     // C++ [over.match.oper]p3:
8366     //   [...]the built-in candidates include all of the candidate operator
8367     //   functions defined in 13.6 that, compared to the given operator, [...]
8368     //   do not have the same parameter-type-list as any non-template non-member
8369     //   candidate.
8370     //
8371     // Note that in practice, this only affects enumeration types because there
8372     // aren't any built-in candidates of record type, and a user-defined operator
8373     // must have an operand of record or enumeration type. Also, the only other
8374     // overloaded operator with enumeration arguments, operator=,
8375     // cannot be overloaded for enumeration types, so this is the only place
8376     // where we must suppress candidates like this.
8377     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8378       UserDefinedBinaryOperators;
8379 
8380     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8381       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8382           CandidateTypes[ArgIdx].enumeration_end()) {
8383         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8384                                          CEnd = CandidateSet.end();
8385              C != CEnd; ++C) {
8386           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8387             continue;
8388 
8389           if (C->Function->isFunctionTemplateSpecialization())
8390             continue;
8391 
8392           // We interpret "same parameter-type-list" as applying to the
8393           // "synthesized candidate, with the order of the two parameters
8394           // reversed", not to the original function.
8395           bool Reversed = C->RewriteKind & CRK_Reversed;
8396           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8397                                         ->getType()
8398                                         .getUnqualifiedType();
8399           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8400                                          ->getType()
8401                                          .getUnqualifiedType();
8402 
8403           // Skip if either parameter isn't of enumeral type.
8404           if (!FirstParamType->isEnumeralType() ||
8405               !SecondParamType->isEnumeralType())
8406             continue;
8407 
8408           // Add this operator to the set of known user-defined operators.
8409           UserDefinedBinaryOperators.insert(
8410             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8411                            S.Context.getCanonicalType(SecondParamType)));
8412         }
8413       }
8414     }
8415 
8416     /// Set of (canonical) types that we've already handled.
8417     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8418 
8419     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8420       for (BuiltinCandidateTypeSet::iterator
8421                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8422              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8423            Ptr != PtrEnd; ++Ptr) {
8424         // Don't add the same builtin candidate twice.
8425         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8426           continue;
8427 
8428         QualType ParamTypes[2] = { *Ptr, *Ptr };
8429         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8430       }
8431       for (BuiltinCandidateTypeSet::iterator
8432                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8433              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8434            Enum != EnumEnd; ++Enum) {
8435         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8436 
8437         // Don't add the same builtin candidate twice, or if a user defined
8438         // candidate exists.
8439         if (!AddedTypes.insert(CanonType).second ||
8440             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8441                                                             CanonType)))
8442           continue;
8443         QualType ParamTypes[2] = { *Enum, *Enum };
8444         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8445       }
8446     }
8447   }
8448 
8449   // C++ [over.built]p13:
8450   //
8451   //   For every cv-qualified or cv-unqualified object type T
8452   //   there exist candidate operator functions of the form
8453   //
8454   //      T*         operator+(T*, ptrdiff_t);
8455   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8456   //      T*         operator-(T*, ptrdiff_t);
8457   //      T*         operator+(ptrdiff_t, T*);
8458   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8459   //
8460   // C++ [over.built]p14:
8461   //
8462   //   For every T, where T is a pointer to object type, there
8463   //   exist candidate operator functions of the form
8464   //
8465   //      ptrdiff_t  operator-(T, T);
8466   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8467     /// Set of (canonical) types that we've already handled.
8468     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8469 
8470     for (int Arg = 0; Arg < 2; ++Arg) {
8471       QualType AsymmetricParamTypes[2] = {
8472         S.Context.getPointerDiffType(),
8473         S.Context.getPointerDiffType(),
8474       };
8475       for (BuiltinCandidateTypeSet::iterator
8476                 Ptr = CandidateTypes[Arg].pointer_begin(),
8477              PtrEnd = CandidateTypes[Arg].pointer_end();
8478            Ptr != PtrEnd; ++Ptr) {
8479         QualType PointeeTy = (*Ptr)->getPointeeType();
8480         if (!PointeeTy->isObjectType())
8481           continue;
8482 
8483         AsymmetricParamTypes[Arg] = *Ptr;
8484         if (Arg == 0 || Op == OO_Plus) {
8485           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8486           // T* operator+(ptrdiff_t, T*);
8487           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8488         }
8489         if (Op == OO_Minus) {
8490           // ptrdiff_t operator-(T, T);
8491           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8492             continue;
8493 
8494           QualType ParamTypes[2] = { *Ptr, *Ptr };
8495           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8496         }
8497       }
8498     }
8499   }
8500 
8501   // C++ [over.built]p12:
8502   //
8503   //   For every pair of promoted arithmetic types L and R, there
8504   //   exist candidate operator functions of the form
8505   //
8506   //        LR         operator*(L, R);
8507   //        LR         operator/(L, R);
8508   //        LR         operator+(L, R);
8509   //        LR         operator-(L, R);
8510   //        bool       operator<(L, R);
8511   //        bool       operator>(L, R);
8512   //        bool       operator<=(L, R);
8513   //        bool       operator>=(L, R);
8514   //        bool       operator==(L, R);
8515   //        bool       operator!=(L, R);
8516   //
8517   //   where LR is the result of the usual arithmetic conversions
8518   //   between types L and R.
8519   //
8520   // C++ [over.built]p24:
8521   //
8522   //   For every pair of promoted arithmetic types L and R, there exist
8523   //   candidate operator functions of the form
8524   //
8525   //        LR       operator?(bool, L, R);
8526   //
8527   //   where LR is the result of the usual arithmetic conversions
8528   //   between types L and R.
8529   // Our candidates ignore the first parameter.
8530   void addGenericBinaryArithmeticOverloads() {
8531     if (!HasArithmeticOrEnumeralCandidateType)
8532       return;
8533 
8534     for (unsigned Left = FirstPromotedArithmeticType;
8535          Left < LastPromotedArithmeticType; ++Left) {
8536       for (unsigned Right = FirstPromotedArithmeticType;
8537            Right < LastPromotedArithmeticType; ++Right) {
8538         QualType LandR[2] = { ArithmeticTypes[Left],
8539                               ArithmeticTypes[Right] };
8540         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8541       }
8542     }
8543 
8544     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8545     // conditional operator for vector types.
8546     for (BuiltinCandidateTypeSet::iterator
8547               Vec1 = CandidateTypes[0].vector_begin(),
8548            Vec1End = CandidateTypes[0].vector_end();
8549          Vec1 != Vec1End; ++Vec1) {
8550       for (BuiltinCandidateTypeSet::iterator
8551                 Vec2 = CandidateTypes[1].vector_begin(),
8552              Vec2End = CandidateTypes[1].vector_end();
8553            Vec2 != Vec2End; ++Vec2) {
8554         QualType LandR[2] = { *Vec1, *Vec2 };
8555         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8556       }
8557     }
8558   }
8559 
8560   // C++2a [over.built]p14:
8561   //
8562   //   For every integral type T there exists a candidate operator function
8563   //   of the form
8564   //
8565   //        std::strong_ordering operator<=>(T, T)
8566   //
8567   // C++2a [over.built]p15:
8568   //
8569   //   For every pair of floating-point types L and R, there exists a candidate
8570   //   operator function of the form
8571   //
8572   //       std::partial_ordering operator<=>(L, R);
8573   //
8574   // FIXME: The current specification for integral types doesn't play nice with
8575   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8576   // comparisons. Under the current spec this can lead to ambiguity during
8577   // overload resolution. For example:
8578   //
8579   //   enum A : int {a};
8580   //   auto x = (a <=> (long)42);
8581   //
8582   //   error: call is ambiguous for arguments 'A' and 'long'.
8583   //   note: candidate operator<=>(int, int)
8584   //   note: candidate operator<=>(long, long)
8585   //
8586   // To avoid this error, this function deviates from the specification and adds
8587   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8588   // arithmetic types (the same as the generic relational overloads).
8589   //
8590   // For now this function acts as a placeholder.
8591   void addThreeWayArithmeticOverloads() {
8592     addGenericBinaryArithmeticOverloads();
8593   }
8594 
8595   // C++ [over.built]p17:
8596   //
8597   //   For every pair of promoted integral types L and R, there
8598   //   exist candidate operator functions of the form
8599   //
8600   //      LR         operator%(L, R);
8601   //      LR         operator&(L, R);
8602   //      LR         operator^(L, R);
8603   //      LR         operator|(L, R);
8604   //      L          operator<<(L, R);
8605   //      L          operator>>(L, R);
8606   //
8607   //   where LR is the result of the usual arithmetic conversions
8608   //   between types L and R.
8609   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8610     if (!HasArithmeticOrEnumeralCandidateType)
8611       return;
8612 
8613     for (unsigned Left = FirstPromotedIntegralType;
8614          Left < LastPromotedIntegralType; ++Left) {
8615       for (unsigned Right = FirstPromotedIntegralType;
8616            Right < LastPromotedIntegralType; ++Right) {
8617         QualType LandR[2] = { ArithmeticTypes[Left],
8618                               ArithmeticTypes[Right] };
8619         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8620       }
8621     }
8622   }
8623 
8624   // C++ [over.built]p20:
8625   //
8626   //   For every pair (T, VQ), where T is an enumeration or
8627   //   pointer to member type and VQ is either volatile or
8628   //   empty, there exist candidate operator functions of the form
8629   //
8630   //        VQ T&      operator=(VQ T&, T);
8631   void addAssignmentMemberPointerOrEnumeralOverloads() {
8632     /// Set of (canonical) types that we've already handled.
8633     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8634 
8635     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8636       for (BuiltinCandidateTypeSet::iterator
8637                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8638              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8639            Enum != EnumEnd; ++Enum) {
8640         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8641           continue;
8642 
8643         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8644       }
8645 
8646       for (BuiltinCandidateTypeSet::iterator
8647                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8648              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8649            MemPtr != MemPtrEnd; ++MemPtr) {
8650         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8651           continue;
8652 
8653         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8654       }
8655     }
8656   }
8657 
8658   // C++ [over.built]p19:
8659   //
8660   //   For every pair (T, VQ), where T is any type and VQ is either
8661   //   volatile or empty, there exist candidate operator functions
8662   //   of the form
8663   //
8664   //        T*VQ&      operator=(T*VQ&, T*);
8665   //
8666   // C++ [over.built]p21:
8667   //
8668   //   For every pair (T, VQ), where T is a cv-qualified or
8669   //   cv-unqualified object type and VQ is either volatile or
8670   //   empty, there exist candidate operator functions of the form
8671   //
8672   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8673   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8674   void addAssignmentPointerOverloads(bool isEqualOp) {
8675     /// Set of (canonical) types that we've already handled.
8676     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8677 
8678     for (BuiltinCandidateTypeSet::iterator
8679               Ptr = CandidateTypes[0].pointer_begin(),
8680            PtrEnd = CandidateTypes[0].pointer_end();
8681          Ptr != PtrEnd; ++Ptr) {
8682       // If this is operator=, keep track of the builtin candidates we added.
8683       if (isEqualOp)
8684         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8685       else if (!(*Ptr)->getPointeeType()->isObjectType())
8686         continue;
8687 
8688       // non-volatile version
8689       QualType ParamTypes[2] = {
8690         S.Context.getLValueReferenceType(*Ptr),
8691         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8692       };
8693       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8694                             /*IsAssignmentOperator=*/ isEqualOp);
8695 
8696       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8697                           VisibleTypeConversionsQuals.hasVolatile();
8698       if (NeedVolatile) {
8699         // volatile version
8700         ParamTypes[0] =
8701           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8702         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8703                               /*IsAssignmentOperator=*/isEqualOp);
8704       }
8705 
8706       if (!(*Ptr).isRestrictQualified() &&
8707           VisibleTypeConversionsQuals.hasRestrict()) {
8708         // restrict version
8709         ParamTypes[0]
8710           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8711         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8712                               /*IsAssignmentOperator=*/isEqualOp);
8713 
8714         if (NeedVolatile) {
8715           // volatile restrict version
8716           ParamTypes[0]
8717             = S.Context.getLValueReferenceType(
8718                 S.Context.getCVRQualifiedType(*Ptr,
8719                                               (Qualifiers::Volatile |
8720                                                Qualifiers::Restrict)));
8721           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8722                                 /*IsAssignmentOperator=*/isEqualOp);
8723         }
8724       }
8725     }
8726 
8727     if (isEqualOp) {
8728       for (BuiltinCandidateTypeSet::iterator
8729                 Ptr = CandidateTypes[1].pointer_begin(),
8730              PtrEnd = CandidateTypes[1].pointer_end();
8731            Ptr != PtrEnd; ++Ptr) {
8732         // Make sure we don't add the same candidate twice.
8733         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8734           continue;
8735 
8736         QualType ParamTypes[2] = {
8737           S.Context.getLValueReferenceType(*Ptr),
8738           *Ptr,
8739         };
8740 
8741         // non-volatile version
8742         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8743                               /*IsAssignmentOperator=*/true);
8744 
8745         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8746                            VisibleTypeConversionsQuals.hasVolatile();
8747         if (NeedVolatile) {
8748           // volatile version
8749           ParamTypes[0] =
8750             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8751           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8752                                 /*IsAssignmentOperator=*/true);
8753         }
8754 
8755         if (!(*Ptr).isRestrictQualified() &&
8756             VisibleTypeConversionsQuals.hasRestrict()) {
8757           // restrict version
8758           ParamTypes[0]
8759             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8760           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8761                                 /*IsAssignmentOperator=*/true);
8762 
8763           if (NeedVolatile) {
8764             // volatile restrict version
8765             ParamTypes[0]
8766               = S.Context.getLValueReferenceType(
8767                   S.Context.getCVRQualifiedType(*Ptr,
8768                                                 (Qualifiers::Volatile |
8769                                                  Qualifiers::Restrict)));
8770             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8771                                   /*IsAssignmentOperator=*/true);
8772           }
8773         }
8774       }
8775     }
8776   }
8777 
8778   // C++ [over.built]p18:
8779   //
8780   //   For every triple (L, VQ, R), where L is an arithmetic type,
8781   //   VQ is either volatile or empty, and R is a promoted
8782   //   arithmetic type, there exist candidate operator functions of
8783   //   the form
8784   //
8785   //        VQ L&      operator=(VQ L&, R);
8786   //        VQ L&      operator*=(VQ L&, R);
8787   //        VQ L&      operator/=(VQ L&, R);
8788   //        VQ L&      operator+=(VQ L&, R);
8789   //        VQ L&      operator-=(VQ L&, R);
8790   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8791     if (!HasArithmeticOrEnumeralCandidateType)
8792       return;
8793 
8794     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8795       for (unsigned Right = FirstPromotedArithmeticType;
8796            Right < LastPromotedArithmeticType; ++Right) {
8797         QualType ParamTypes[2];
8798         ParamTypes[1] = ArithmeticTypes[Right];
8799         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8800             S, ArithmeticTypes[Left], Args[0]);
8801         // Add this built-in operator as a candidate (VQ is empty).
8802         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8803         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8804                               /*IsAssignmentOperator=*/isEqualOp);
8805 
8806         // Add this built-in operator as a candidate (VQ is 'volatile').
8807         if (VisibleTypeConversionsQuals.hasVolatile()) {
8808           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8809           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8810           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8811                                 /*IsAssignmentOperator=*/isEqualOp);
8812         }
8813       }
8814     }
8815 
8816     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8817     for (BuiltinCandidateTypeSet::iterator
8818               Vec1 = CandidateTypes[0].vector_begin(),
8819            Vec1End = CandidateTypes[0].vector_end();
8820          Vec1 != Vec1End; ++Vec1) {
8821       for (BuiltinCandidateTypeSet::iterator
8822                 Vec2 = CandidateTypes[1].vector_begin(),
8823              Vec2End = CandidateTypes[1].vector_end();
8824            Vec2 != Vec2End; ++Vec2) {
8825         QualType ParamTypes[2];
8826         ParamTypes[1] = *Vec2;
8827         // Add this built-in operator as a candidate (VQ is empty).
8828         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8829         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8830                               /*IsAssignmentOperator=*/isEqualOp);
8831 
8832         // Add this built-in operator as a candidate (VQ is 'volatile').
8833         if (VisibleTypeConversionsQuals.hasVolatile()) {
8834           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8835           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8836           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8837                                 /*IsAssignmentOperator=*/isEqualOp);
8838         }
8839       }
8840     }
8841   }
8842 
8843   // C++ [over.built]p22:
8844   //
8845   //   For every triple (L, VQ, R), where L is an integral type, VQ
8846   //   is either volatile or empty, and R is a promoted integral
8847   //   type, there exist candidate operator functions of the form
8848   //
8849   //        VQ L&       operator%=(VQ L&, R);
8850   //        VQ L&       operator<<=(VQ L&, R);
8851   //        VQ L&       operator>>=(VQ L&, R);
8852   //        VQ L&       operator&=(VQ L&, R);
8853   //        VQ L&       operator^=(VQ L&, R);
8854   //        VQ L&       operator|=(VQ L&, R);
8855   void addAssignmentIntegralOverloads() {
8856     if (!HasArithmeticOrEnumeralCandidateType)
8857       return;
8858 
8859     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8860       for (unsigned Right = FirstPromotedIntegralType;
8861            Right < LastPromotedIntegralType; ++Right) {
8862         QualType ParamTypes[2];
8863         ParamTypes[1] = ArithmeticTypes[Right];
8864         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8865             S, ArithmeticTypes[Left], Args[0]);
8866         // Add this built-in operator as a candidate (VQ is empty).
8867         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8868         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8869         if (VisibleTypeConversionsQuals.hasVolatile()) {
8870           // Add this built-in operator as a candidate (VQ is 'volatile').
8871           ParamTypes[0] = LeftBaseTy;
8872           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8873           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8874           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8875         }
8876       }
8877     }
8878   }
8879 
8880   // C++ [over.operator]p23:
8881   //
8882   //   There also exist candidate operator functions of the form
8883   //
8884   //        bool        operator!(bool);
8885   //        bool        operator&&(bool, bool);
8886   //        bool        operator||(bool, bool);
8887   void addExclaimOverload() {
8888     QualType ParamTy = S.Context.BoolTy;
8889     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8890                           /*IsAssignmentOperator=*/false,
8891                           /*NumContextualBoolArguments=*/1);
8892   }
8893   void addAmpAmpOrPipePipeOverload() {
8894     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8895     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8896                           /*IsAssignmentOperator=*/false,
8897                           /*NumContextualBoolArguments=*/2);
8898   }
8899 
8900   // C++ [over.built]p13:
8901   //
8902   //   For every cv-qualified or cv-unqualified object type T there
8903   //   exist candidate operator functions of the form
8904   //
8905   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8906   //        T&         operator[](T*, ptrdiff_t);
8907   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8908   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8909   //        T&         operator[](ptrdiff_t, T*);
8910   void addSubscriptOverloads() {
8911     for (BuiltinCandidateTypeSet::iterator
8912               Ptr = CandidateTypes[0].pointer_begin(),
8913            PtrEnd = CandidateTypes[0].pointer_end();
8914          Ptr != PtrEnd; ++Ptr) {
8915       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8916       QualType PointeeType = (*Ptr)->getPointeeType();
8917       if (!PointeeType->isObjectType())
8918         continue;
8919 
8920       // T& operator[](T*, ptrdiff_t)
8921       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8922     }
8923 
8924     for (BuiltinCandidateTypeSet::iterator
8925               Ptr = CandidateTypes[1].pointer_begin(),
8926            PtrEnd = CandidateTypes[1].pointer_end();
8927          Ptr != PtrEnd; ++Ptr) {
8928       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8929       QualType PointeeType = (*Ptr)->getPointeeType();
8930       if (!PointeeType->isObjectType())
8931         continue;
8932 
8933       // T& operator[](ptrdiff_t, T*)
8934       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8935     }
8936   }
8937 
8938   // C++ [over.built]p11:
8939   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8940   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8941   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8942   //    there exist candidate operator functions of the form
8943   //
8944   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8945   //
8946   //    where CV12 is the union of CV1 and CV2.
8947   void addArrowStarOverloads() {
8948     for (BuiltinCandidateTypeSet::iterator
8949              Ptr = CandidateTypes[0].pointer_begin(),
8950            PtrEnd = CandidateTypes[0].pointer_end();
8951          Ptr != PtrEnd; ++Ptr) {
8952       QualType C1Ty = (*Ptr);
8953       QualType C1;
8954       QualifierCollector Q1;
8955       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8956       if (!isa<RecordType>(C1))
8957         continue;
8958       // heuristic to reduce number of builtin candidates in the set.
8959       // Add volatile/restrict version only if there are conversions to a
8960       // volatile/restrict type.
8961       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8962         continue;
8963       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8964         continue;
8965       for (BuiltinCandidateTypeSet::iterator
8966                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8967              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8968            MemPtr != MemPtrEnd; ++MemPtr) {
8969         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8970         QualType C2 = QualType(mptr->getClass(), 0);
8971         C2 = C2.getUnqualifiedType();
8972         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8973           break;
8974         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8975         // build CV12 T&
8976         QualType T = mptr->getPointeeType();
8977         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8978             T.isVolatileQualified())
8979           continue;
8980         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8981             T.isRestrictQualified())
8982           continue;
8983         T = Q1.apply(S.Context, T);
8984         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8985       }
8986     }
8987   }
8988 
8989   // Note that we don't consider the first argument, since it has been
8990   // contextually converted to bool long ago. The candidates below are
8991   // therefore added as binary.
8992   //
8993   // C++ [over.built]p25:
8994   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8995   //   enumeration type, there exist candidate operator functions of the form
8996   //
8997   //        T        operator?(bool, T, T);
8998   //
8999   void addConditionalOperatorOverloads() {
9000     /// Set of (canonical) types that we've already handled.
9001     llvm::SmallPtrSet<QualType, 8> AddedTypes;
9002 
9003     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9004       for (BuiltinCandidateTypeSet::iterator
9005                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
9006              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
9007            Ptr != PtrEnd; ++Ptr) {
9008         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9009           continue;
9010 
9011         QualType ParamTypes[2] = { *Ptr, *Ptr };
9012         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9013       }
9014 
9015       for (BuiltinCandidateTypeSet::iterator
9016                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9017              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9018            MemPtr != MemPtrEnd; ++MemPtr) {
9019         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9020           continue;
9021 
9022         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9023         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9024       }
9025 
9026       if (S.getLangOpts().CPlusPlus11) {
9027         for (BuiltinCandidateTypeSet::iterator
9028                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9029                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9030              Enum != EnumEnd; ++Enum) {
9031           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9032             continue;
9033 
9034           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9035             continue;
9036 
9037           QualType ParamTypes[2] = { *Enum, *Enum };
9038           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9039         }
9040       }
9041     }
9042   }
9043 };
9044 
9045 } // end anonymous namespace
9046 
9047 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9048 /// operator overloads to the candidate set (C++ [over.built]), based
9049 /// on the operator @p Op and the arguments given. For example, if the
9050 /// operator is a binary '+', this routine might add "int
9051 /// operator+(int, int)" to cover integer addition.
9052 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9053                                         SourceLocation OpLoc,
9054                                         ArrayRef<Expr *> Args,
9055                                         OverloadCandidateSet &CandidateSet) {
9056   // Find all of the types that the arguments can convert to, but only
9057   // if the operator we're looking at has built-in operator candidates
9058   // that make use of these types. Also record whether we encounter non-record
9059   // candidate types or either arithmetic or enumeral candidate types.
9060   Qualifiers VisibleTypeConversionsQuals;
9061   VisibleTypeConversionsQuals.addConst();
9062   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9063     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9064 
9065   bool HasNonRecordCandidateType = false;
9066   bool HasArithmeticOrEnumeralCandidateType = false;
9067   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9068   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9069     CandidateTypes.emplace_back(*this);
9070     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9071                                                  OpLoc,
9072                                                  true,
9073                                                  (Op == OO_Exclaim ||
9074                                                   Op == OO_AmpAmp ||
9075                                                   Op == OO_PipePipe),
9076                                                  VisibleTypeConversionsQuals);
9077     HasNonRecordCandidateType = HasNonRecordCandidateType ||
9078         CandidateTypes[ArgIdx].hasNonRecordTypes();
9079     HasArithmeticOrEnumeralCandidateType =
9080         HasArithmeticOrEnumeralCandidateType ||
9081         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9082   }
9083 
9084   // Exit early when no non-record types have been added to the candidate set
9085   // for any of the arguments to the operator.
9086   //
9087   // We can't exit early for !, ||, or &&, since there we have always have
9088   // 'bool' overloads.
9089   if (!HasNonRecordCandidateType &&
9090       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9091     return;
9092 
9093   // Setup an object to manage the common state for building overloads.
9094   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9095                                            VisibleTypeConversionsQuals,
9096                                            HasArithmeticOrEnumeralCandidateType,
9097                                            CandidateTypes, CandidateSet);
9098 
9099   // Dispatch over the operation to add in only those overloads which apply.
9100   switch (Op) {
9101   case OO_None:
9102   case NUM_OVERLOADED_OPERATORS:
9103     llvm_unreachable("Expected an overloaded operator");
9104 
9105   case OO_New:
9106   case OO_Delete:
9107   case OO_Array_New:
9108   case OO_Array_Delete:
9109   case OO_Call:
9110     llvm_unreachable(
9111                     "Special operators don't use AddBuiltinOperatorCandidates");
9112 
9113   case OO_Comma:
9114   case OO_Arrow:
9115   case OO_Coawait:
9116     // C++ [over.match.oper]p3:
9117     //   -- For the operator ',', the unary operator '&', the
9118     //      operator '->', or the operator 'co_await', the
9119     //      built-in candidates set is empty.
9120     break;
9121 
9122   case OO_Plus: // '+' is either unary or binary
9123     if (Args.size() == 1)
9124       OpBuilder.addUnaryPlusPointerOverloads();
9125     LLVM_FALLTHROUGH;
9126 
9127   case OO_Minus: // '-' is either unary or binary
9128     if (Args.size() == 1) {
9129       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9130     } else {
9131       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9132       OpBuilder.addGenericBinaryArithmeticOverloads();
9133     }
9134     break;
9135 
9136   case OO_Star: // '*' is either unary or binary
9137     if (Args.size() == 1)
9138       OpBuilder.addUnaryStarPointerOverloads();
9139     else
9140       OpBuilder.addGenericBinaryArithmeticOverloads();
9141     break;
9142 
9143   case OO_Slash:
9144     OpBuilder.addGenericBinaryArithmeticOverloads();
9145     break;
9146 
9147   case OO_PlusPlus:
9148   case OO_MinusMinus:
9149     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9150     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9151     break;
9152 
9153   case OO_EqualEqual:
9154   case OO_ExclaimEqual:
9155     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9156     LLVM_FALLTHROUGH;
9157 
9158   case OO_Less:
9159   case OO_Greater:
9160   case OO_LessEqual:
9161   case OO_GreaterEqual:
9162     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9163     OpBuilder.addGenericBinaryArithmeticOverloads();
9164     break;
9165 
9166   case OO_Spaceship:
9167     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9168     OpBuilder.addThreeWayArithmeticOverloads();
9169     break;
9170 
9171   case OO_Percent:
9172   case OO_Caret:
9173   case OO_Pipe:
9174   case OO_LessLess:
9175   case OO_GreaterGreater:
9176     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9177     break;
9178 
9179   case OO_Amp: // '&' is either unary or binary
9180     if (Args.size() == 1)
9181       // C++ [over.match.oper]p3:
9182       //   -- For the operator ',', the unary operator '&', or the
9183       //      operator '->', the built-in candidates set is empty.
9184       break;
9185 
9186     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9187     break;
9188 
9189   case OO_Tilde:
9190     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9191     break;
9192 
9193   case OO_Equal:
9194     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9195     LLVM_FALLTHROUGH;
9196 
9197   case OO_PlusEqual:
9198   case OO_MinusEqual:
9199     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9200     LLVM_FALLTHROUGH;
9201 
9202   case OO_StarEqual:
9203   case OO_SlashEqual:
9204     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9205     break;
9206 
9207   case OO_PercentEqual:
9208   case OO_LessLessEqual:
9209   case OO_GreaterGreaterEqual:
9210   case OO_AmpEqual:
9211   case OO_CaretEqual:
9212   case OO_PipeEqual:
9213     OpBuilder.addAssignmentIntegralOverloads();
9214     break;
9215 
9216   case OO_Exclaim:
9217     OpBuilder.addExclaimOverload();
9218     break;
9219 
9220   case OO_AmpAmp:
9221   case OO_PipePipe:
9222     OpBuilder.addAmpAmpOrPipePipeOverload();
9223     break;
9224 
9225   case OO_Subscript:
9226     OpBuilder.addSubscriptOverloads();
9227     break;
9228 
9229   case OO_ArrowStar:
9230     OpBuilder.addArrowStarOverloads();
9231     break;
9232 
9233   case OO_Conditional:
9234     OpBuilder.addConditionalOperatorOverloads();
9235     OpBuilder.addGenericBinaryArithmeticOverloads();
9236     break;
9237   }
9238 }
9239 
9240 /// Add function candidates found via argument-dependent lookup
9241 /// to the set of overloading candidates.
9242 ///
9243 /// This routine performs argument-dependent name lookup based on the
9244 /// given function name (which may also be an operator name) and adds
9245 /// all of the overload candidates found by ADL to the overload
9246 /// candidate set (C++ [basic.lookup.argdep]).
9247 void
9248 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9249                                            SourceLocation Loc,
9250                                            ArrayRef<Expr *> Args,
9251                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9252                                            OverloadCandidateSet& CandidateSet,
9253                                            bool PartialOverloading) {
9254   ADLResult Fns;
9255 
9256   // FIXME: This approach for uniquing ADL results (and removing
9257   // redundant candidates from the set) relies on pointer-equality,
9258   // which means we need to key off the canonical decl.  However,
9259   // always going back to the canonical decl might not get us the
9260   // right set of default arguments.  What default arguments are
9261   // we supposed to consider on ADL candidates, anyway?
9262 
9263   // FIXME: Pass in the explicit template arguments?
9264   ArgumentDependentLookup(Name, Loc, Args, Fns);
9265 
9266   // Erase all of the candidates we already knew about.
9267   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9268                                    CandEnd = CandidateSet.end();
9269        Cand != CandEnd; ++Cand)
9270     if (Cand->Function) {
9271       Fns.erase(Cand->Function);
9272       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9273         Fns.erase(FunTmpl);
9274     }
9275 
9276   // For each of the ADL candidates we found, add it to the overload
9277   // set.
9278   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9279     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9280 
9281     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9282       if (ExplicitTemplateArgs)
9283         continue;
9284 
9285       AddOverloadCandidate(
9286           FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9287           PartialOverloading, /*AllowExplicit=*/true,
9288           /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9289       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9290         AddOverloadCandidate(
9291             FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9292             /*SuppressUserConversions=*/false, PartialOverloading,
9293             /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9294             ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9295       }
9296     } else {
9297       auto *FTD = cast<FunctionTemplateDecl>(*I);
9298       AddTemplateOverloadCandidate(
9299           FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9300           /*SuppressUserConversions=*/false, PartialOverloading,
9301           /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9302       if (CandidateSet.getRewriteInfo().shouldAddReversed(
9303               Context, FTD->getTemplatedDecl())) {
9304         AddTemplateOverloadCandidate(
9305             FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9306             CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9307             /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9308             OverloadCandidateParamOrder::Reversed);
9309       }
9310     }
9311   }
9312 }
9313 
9314 namespace {
9315 enum class Comparison { Equal, Better, Worse };
9316 }
9317 
9318 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9319 /// overload resolution.
9320 ///
9321 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9322 /// Cand1's first N enable_if attributes have precisely the same conditions as
9323 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9324 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9325 ///
9326 /// Note that you can have a pair of candidates such that Cand1's enable_if
9327 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9328 /// worse than Cand1's.
9329 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9330                                        const FunctionDecl *Cand2) {
9331   // Common case: One (or both) decls don't have enable_if attrs.
9332   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9333   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9334   if (!Cand1Attr || !Cand2Attr) {
9335     if (Cand1Attr == Cand2Attr)
9336       return Comparison::Equal;
9337     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9338   }
9339 
9340   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9341   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9342 
9343   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9344   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9345     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9346     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9347 
9348     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9349     // has fewer enable_if attributes than Cand2, and vice versa.
9350     if (!Cand1A)
9351       return Comparison::Worse;
9352     if (!Cand2A)
9353       return Comparison::Better;
9354 
9355     Cand1ID.clear();
9356     Cand2ID.clear();
9357 
9358     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9359     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9360     if (Cand1ID != Cand2ID)
9361       return Comparison::Worse;
9362   }
9363 
9364   return Comparison::Equal;
9365 }
9366 
9367 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9368                                           const OverloadCandidate &Cand2) {
9369   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9370       !Cand2.Function->isMultiVersion())
9371     return false;
9372 
9373   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9374   // is obviously better.
9375   if (Cand1.Function->isInvalidDecl()) return false;
9376   if (Cand2.Function->isInvalidDecl()) return true;
9377 
9378   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9379   // cpu_dispatch, else arbitrarily based on the identifiers.
9380   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9381   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9382   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9383   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9384 
9385   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9386     return false;
9387 
9388   if (Cand1CPUDisp && !Cand2CPUDisp)
9389     return true;
9390   if (Cand2CPUDisp && !Cand1CPUDisp)
9391     return false;
9392 
9393   if (Cand1CPUSpec && Cand2CPUSpec) {
9394     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9395       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9396 
9397     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9398         FirstDiff = std::mismatch(
9399             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9400             Cand2CPUSpec->cpus_begin(),
9401             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9402               return LHS->getName() == RHS->getName();
9403             });
9404 
9405     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9406            "Two different cpu-specific versions should not have the same "
9407            "identifier list, otherwise they'd be the same decl!");
9408     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9409   }
9410   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9411 }
9412 
9413 /// isBetterOverloadCandidate - Determines whether the first overload
9414 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9415 bool clang::isBetterOverloadCandidate(
9416     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9417     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9418   // Define viable functions to be better candidates than non-viable
9419   // functions.
9420   if (!Cand2.Viable)
9421     return Cand1.Viable;
9422   else if (!Cand1.Viable)
9423     return false;
9424 
9425   // C++ [over.match.best]p1:
9426   //
9427   //   -- if F is a static member function, ICS1(F) is defined such
9428   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9429   //      any function G, and, symmetrically, ICS1(G) is neither
9430   //      better nor worse than ICS1(F).
9431   unsigned StartArg = 0;
9432   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9433     StartArg = 1;
9434 
9435   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9436     // We don't allow incompatible pointer conversions in C++.
9437     if (!S.getLangOpts().CPlusPlus)
9438       return ICS.isStandard() &&
9439              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9440 
9441     // The only ill-formed conversion we allow in C++ is the string literal to
9442     // char* conversion, which is only considered ill-formed after C++11.
9443     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9444            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9445   };
9446 
9447   // Define functions that don't require ill-formed conversions for a given
9448   // argument to be better candidates than functions that do.
9449   unsigned NumArgs = Cand1.Conversions.size();
9450   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9451   bool HasBetterConversion = false;
9452   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9453     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9454     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9455     if (Cand1Bad != Cand2Bad) {
9456       if (Cand1Bad)
9457         return false;
9458       HasBetterConversion = true;
9459     }
9460   }
9461 
9462   if (HasBetterConversion)
9463     return true;
9464 
9465   // C++ [over.match.best]p1:
9466   //   A viable function F1 is defined to be a better function than another
9467   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9468   //   conversion sequence than ICSi(F2), and then...
9469   bool HasWorseConversion = false;
9470   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9471     switch (CompareImplicitConversionSequences(S, Loc,
9472                                                Cand1.Conversions[ArgIdx],
9473                                                Cand2.Conversions[ArgIdx])) {
9474     case ImplicitConversionSequence::Better:
9475       // Cand1 has a better conversion sequence.
9476       HasBetterConversion = true;
9477       break;
9478 
9479     case ImplicitConversionSequence::Worse:
9480       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9481           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9482         // Work around large-scale breakage caused by considering reversed
9483         // forms of operator== in C++20:
9484         //
9485         // When comparing a function against its reversed form, if we have a
9486         // better conversion for one argument and a worse conversion for the
9487         // other, we prefer the non-reversed form.
9488         //
9489         // This prevents a conversion function from being considered ambiguous
9490         // with its own reversed form in various where it's only incidentally
9491         // heterogeneous.
9492         //
9493         // We diagnose this as an extension from CreateOverloadedBinOp.
9494         HasWorseConversion = true;
9495         break;
9496       }
9497 
9498       // Cand1 can't be better than Cand2.
9499       return false;
9500 
9501     case ImplicitConversionSequence::Indistinguishable:
9502       // Do nothing.
9503       break;
9504     }
9505   }
9506 
9507   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9508   //       ICSj(F2), or, if not that,
9509   if (HasBetterConversion)
9510     return true;
9511   if (HasWorseConversion)
9512     return false;
9513 
9514   //   -- the context is an initialization by user-defined conversion
9515   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9516   //      from the return type of F1 to the destination type (i.e.,
9517   //      the type of the entity being initialized) is a better
9518   //      conversion sequence than the standard conversion sequence
9519   //      from the return type of F2 to the destination type.
9520   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9521       Cand1.Function && Cand2.Function &&
9522       isa<CXXConversionDecl>(Cand1.Function) &&
9523       isa<CXXConversionDecl>(Cand2.Function)) {
9524     // First check whether we prefer one of the conversion functions over the
9525     // other. This only distinguishes the results in non-standard, extension
9526     // cases such as the conversion from a lambda closure type to a function
9527     // pointer or block.
9528     ImplicitConversionSequence::CompareKind Result =
9529         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9530     if (Result == ImplicitConversionSequence::Indistinguishable)
9531       Result = CompareStandardConversionSequences(S, Loc,
9532                                                   Cand1.FinalConversion,
9533                                                   Cand2.FinalConversion);
9534 
9535     if (Result != ImplicitConversionSequence::Indistinguishable)
9536       return Result == ImplicitConversionSequence::Better;
9537 
9538     // FIXME: Compare kind of reference binding if conversion functions
9539     // convert to a reference type used in direct reference binding, per
9540     // C++14 [over.match.best]p1 section 2 bullet 3.
9541   }
9542 
9543   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9544   // as combined with the resolution to CWG issue 243.
9545   //
9546   // When the context is initialization by constructor ([over.match.ctor] or
9547   // either phase of [over.match.list]), a constructor is preferred over
9548   // a conversion function.
9549   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9550       Cand1.Function && Cand2.Function &&
9551       isa<CXXConstructorDecl>(Cand1.Function) !=
9552           isa<CXXConstructorDecl>(Cand2.Function))
9553     return isa<CXXConstructorDecl>(Cand1.Function);
9554 
9555   //    -- F1 is a non-template function and F2 is a function template
9556   //       specialization, or, if not that,
9557   bool Cand1IsSpecialization = Cand1.Function &&
9558                                Cand1.Function->getPrimaryTemplate();
9559   bool Cand2IsSpecialization = Cand2.Function &&
9560                                Cand2.Function->getPrimaryTemplate();
9561   if (Cand1IsSpecialization != Cand2IsSpecialization)
9562     return Cand2IsSpecialization;
9563 
9564   //   -- F1 and F2 are function template specializations, and the function
9565   //      template for F1 is more specialized than the template for F2
9566   //      according to the partial ordering rules described in 14.5.5.2, or,
9567   //      if not that,
9568   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9569     if (FunctionTemplateDecl *BetterTemplate
9570           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9571                                          Cand2.Function->getPrimaryTemplate(),
9572                                          Loc,
9573                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9574                                                              : TPOC_Call,
9575                                          Cand1.ExplicitCallArguments,
9576                                          Cand2.ExplicitCallArguments))
9577       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9578   }
9579 
9580   //   -— F1 and F2 are non-template functions with the same
9581   //      parameter-type-lists, and F1 is more constrained than F2 [...],
9582   if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9583       !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9584       Cand2.Function->hasPrototype()) {
9585     auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9586     auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9587     if (PT1->getNumParams() == PT2->getNumParams() &&
9588         PT1->isVariadic() == PT2->isVariadic() &&
9589         S.FunctionParamTypesAreEqual(PT1, PT2)) {
9590       Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9591       Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9592       if (RC1 && RC2) {
9593         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9594         if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9595                                      {RC2}, AtLeastAsConstrained1) ||
9596             S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9597                                      {RC1}, AtLeastAsConstrained2))
9598           return false;
9599         if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9600           return AtLeastAsConstrained1;
9601       } else if (RC1 || RC2) {
9602         return RC1 != nullptr;
9603       }
9604     }
9605   }
9606 
9607   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9608   //      class B of D, and for all arguments the corresponding parameters of
9609   //      F1 and F2 have the same type.
9610   // FIXME: Implement the "all parameters have the same type" check.
9611   bool Cand1IsInherited =
9612       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9613   bool Cand2IsInherited =
9614       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9615   if (Cand1IsInherited != Cand2IsInherited)
9616     return Cand2IsInherited;
9617   else if (Cand1IsInherited) {
9618     assert(Cand2IsInherited);
9619     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9620     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9621     if (Cand1Class->isDerivedFrom(Cand2Class))
9622       return true;
9623     if (Cand2Class->isDerivedFrom(Cand1Class))
9624       return false;
9625     // Inherited from sibling base classes: still ambiguous.
9626   }
9627 
9628   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9629   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9630   //      with reversed order of parameters and F1 is not
9631   //
9632   // We rank reversed + different operator as worse than just reversed, but
9633   // that comparison can never happen, because we only consider reversing for
9634   // the maximally-rewritten operator (== or <=>).
9635   if (Cand1.RewriteKind != Cand2.RewriteKind)
9636     return Cand1.RewriteKind < Cand2.RewriteKind;
9637 
9638   // Check C++17 tie-breakers for deduction guides.
9639   {
9640     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9641     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9642     if (Guide1 && Guide2) {
9643       //  -- F1 is generated from a deduction-guide and F2 is not
9644       if (Guide1->isImplicit() != Guide2->isImplicit())
9645         return Guide2->isImplicit();
9646 
9647       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9648       if (Guide1->isCopyDeductionCandidate())
9649         return true;
9650     }
9651   }
9652 
9653   // Check for enable_if value-based overload resolution.
9654   if (Cand1.Function && Cand2.Function) {
9655     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9656     if (Cmp != Comparison::Equal)
9657       return Cmp == Comparison::Better;
9658   }
9659 
9660   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9661     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9662     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9663            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9664   }
9665 
9666   bool HasPS1 = Cand1.Function != nullptr &&
9667                 functionHasPassObjectSizeParams(Cand1.Function);
9668   bool HasPS2 = Cand2.Function != nullptr &&
9669                 functionHasPassObjectSizeParams(Cand2.Function);
9670   if (HasPS1 != HasPS2 && HasPS1)
9671     return true;
9672 
9673   return isBetterMultiversionCandidate(Cand1, Cand2);
9674 }
9675 
9676 /// Determine whether two declarations are "equivalent" for the purposes of
9677 /// name lookup and overload resolution. This applies when the same internal/no
9678 /// linkage entity is defined by two modules (probably by textually including
9679 /// the same header). In such a case, we don't consider the declarations to
9680 /// declare the same entity, but we also don't want lookups with both
9681 /// declarations visible to be ambiguous in some cases (this happens when using
9682 /// a modularized libstdc++).
9683 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9684                                                   const NamedDecl *B) {
9685   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9686   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9687   if (!VA || !VB)
9688     return false;
9689 
9690   // The declarations must be declaring the same name as an internal linkage
9691   // entity in different modules.
9692   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9693           VB->getDeclContext()->getRedeclContext()) ||
9694       getOwningModule(VA) == getOwningModule(VB) ||
9695       VA->isExternallyVisible() || VB->isExternallyVisible())
9696     return false;
9697 
9698   // Check that the declarations appear to be equivalent.
9699   //
9700   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9701   // For constants and functions, we should check the initializer or body is
9702   // the same. For non-constant variables, we shouldn't allow it at all.
9703   if (Context.hasSameType(VA->getType(), VB->getType()))
9704     return true;
9705 
9706   // Enum constants within unnamed enumerations will have different types, but
9707   // may still be similar enough to be interchangeable for our purposes.
9708   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9709     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9710       // Only handle anonymous enums. If the enumerations were named and
9711       // equivalent, they would have been merged to the same type.
9712       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9713       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9714       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9715           !Context.hasSameType(EnumA->getIntegerType(),
9716                                EnumB->getIntegerType()))
9717         return false;
9718       // Allow this only if the value is the same for both enumerators.
9719       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9720     }
9721   }
9722 
9723   // Nothing else is sufficiently similar.
9724   return false;
9725 }
9726 
9727 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9728     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9729   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9730 
9731   Module *M = getOwningModule(D);
9732   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9733       << !M << (M ? M->getFullModuleName() : "");
9734 
9735   for (auto *E : Equiv) {
9736     Module *M = getOwningModule(E);
9737     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9738         << !M << (M ? M->getFullModuleName() : "");
9739   }
9740 }
9741 
9742 /// Computes the best viable function (C++ 13.3.3)
9743 /// within an overload candidate set.
9744 ///
9745 /// \param Loc The location of the function name (or operator symbol) for
9746 /// which overload resolution occurs.
9747 ///
9748 /// \param Best If overload resolution was successful or found a deleted
9749 /// function, \p Best points to the candidate function found.
9750 ///
9751 /// \returns The result of overload resolution.
9752 OverloadingResult
9753 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9754                                          iterator &Best) {
9755   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9756   std::transform(begin(), end(), std::back_inserter(Candidates),
9757                  [](OverloadCandidate &Cand) { return &Cand; });
9758 
9759   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9760   // are accepted by both clang and NVCC. However, during a particular
9761   // compilation mode only one call variant is viable. We need to
9762   // exclude non-viable overload candidates from consideration based
9763   // only on their host/device attributes. Specifically, if one
9764   // candidate call is WrongSide and the other is SameSide, we ignore
9765   // the WrongSide candidate.
9766   if (S.getLangOpts().CUDA) {
9767     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9768     bool ContainsSameSideCandidate =
9769         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9770           // Check viable function only.
9771           return Cand->Viable && Cand->Function &&
9772                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9773                      Sema::CFP_SameSide;
9774         });
9775     if (ContainsSameSideCandidate) {
9776       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9777         // Check viable function only to avoid unnecessary data copying/moving.
9778         return Cand->Viable && Cand->Function &&
9779                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9780                    Sema::CFP_WrongSide;
9781       };
9782       llvm::erase_if(Candidates, IsWrongSideCandidate);
9783     }
9784   }
9785 
9786   // Find the best viable function.
9787   Best = end();
9788   for (auto *Cand : Candidates) {
9789     Cand->Best = false;
9790     if (Cand->Viable)
9791       if (Best == end() ||
9792           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9793         Best = Cand;
9794   }
9795 
9796   // If we didn't find any viable functions, abort.
9797   if (Best == end())
9798     return OR_No_Viable_Function;
9799 
9800   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9801 
9802   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9803   PendingBest.push_back(&*Best);
9804   Best->Best = true;
9805 
9806   // Make sure that this function is better than every other viable
9807   // function. If not, we have an ambiguity.
9808   while (!PendingBest.empty()) {
9809     auto *Curr = PendingBest.pop_back_val();
9810     for (auto *Cand : Candidates) {
9811       if (Cand->Viable && !Cand->Best &&
9812           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9813         PendingBest.push_back(Cand);
9814         Cand->Best = true;
9815 
9816         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9817                                                      Curr->Function))
9818           EquivalentCands.push_back(Cand->Function);
9819         else
9820           Best = end();
9821       }
9822     }
9823   }
9824 
9825   // If we found more than one best candidate, this is ambiguous.
9826   if (Best == end())
9827     return OR_Ambiguous;
9828 
9829   // Best is the best viable function.
9830   if (Best->Function && Best->Function->isDeleted())
9831     return OR_Deleted;
9832 
9833   if (!EquivalentCands.empty())
9834     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9835                                                     EquivalentCands);
9836 
9837   return OR_Success;
9838 }
9839 
9840 namespace {
9841 
9842 enum OverloadCandidateKind {
9843   oc_function,
9844   oc_method,
9845   oc_reversed_binary_operator,
9846   oc_constructor,
9847   oc_implicit_default_constructor,
9848   oc_implicit_copy_constructor,
9849   oc_implicit_move_constructor,
9850   oc_implicit_copy_assignment,
9851   oc_implicit_move_assignment,
9852   oc_implicit_equality_comparison,
9853   oc_inherited_constructor
9854 };
9855 
9856 enum OverloadCandidateSelect {
9857   ocs_non_template,
9858   ocs_template,
9859   ocs_described_template,
9860 };
9861 
9862 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9863 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9864                           OverloadCandidateRewriteKind CRK,
9865                           std::string &Description) {
9866 
9867   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9868   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9869     isTemplate = true;
9870     Description = S.getTemplateArgumentBindingsText(
9871         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9872   }
9873 
9874   OverloadCandidateSelect Select = [&]() {
9875     if (!Description.empty())
9876       return ocs_described_template;
9877     return isTemplate ? ocs_template : ocs_non_template;
9878   }();
9879 
9880   OverloadCandidateKind Kind = [&]() {
9881     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9882       return oc_implicit_equality_comparison;
9883 
9884     if (CRK & CRK_Reversed)
9885       return oc_reversed_binary_operator;
9886 
9887     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9888       if (!Ctor->isImplicit()) {
9889         if (isa<ConstructorUsingShadowDecl>(Found))
9890           return oc_inherited_constructor;
9891         else
9892           return oc_constructor;
9893       }
9894 
9895       if (Ctor->isDefaultConstructor())
9896         return oc_implicit_default_constructor;
9897 
9898       if (Ctor->isMoveConstructor())
9899         return oc_implicit_move_constructor;
9900 
9901       assert(Ctor->isCopyConstructor() &&
9902              "unexpected sort of implicit constructor");
9903       return oc_implicit_copy_constructor;
9904     }
9905 
9906     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9907       // This actually gets spelled 'candidate function' for now, but
9908       // it doesn't hurt to split it out.
9909       if (!Meth->isImplicit())
9910         return oc_method;
9911 
9912       if (Meth->isMoveAssignmentOperator())
9913         return oc_implicit_move_assignment;
9914 
9915       if (Meth->isCopyAssignmentOperator())
9916         return oc_implicit_copy_assignment;
9917 
9918       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9919       return oc_method;
9920     }
9921 
9922     return oc_function;
9923   }();
9924 
9925   return std::make_pair(Kind, Select);
9926 }
9927 
9928 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9929   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9930   // set.
9931   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9932     S.Diag(FoundDecl->getLocation(),
9933            diag::note_ovl_candidate_inherited_constructor)
9934       << Shadow->getNominatedBaseClass();
9935 }
9936 
9937 } // end anonymous namespace
9938 
9939 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9940                                     const FunctionDecl *FD) {
9941   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9942     bool AlwaysTrue;
9943     if (EnableIf->getCond()->isValueDependent() ||
9944         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9945       return false;
9946     if (!AlwaysTrue)
9947       return false;
9948   }
9949   return true;
9950 }
9951 
9952 /// Returns true if we can take the address of the function.
9953 ///
9954 /// \param Complain - If true, we'll emit a diagnostic
9955 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9956 ///   we in overload resolution?
9957 /// \param Loc - The location of the statement we're complaining about. Ignored
9958 ///   if we're not complaining, or if we're in overload resolution.
9959 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9960                                               bool Complain,
9961                                               bool InOverloadResolution,
9962                                               SourceLocation Loc) {
9963   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9964     if (Complain) {
9965       if (InOverloadResolution)
9966         S.Diag(FD->getBeginLoc(),
9967                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9968       else
9969         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9970     }
9971     return false;
9972   }
9973 
9974   if (FD->getTrailingRequiresClause()) {
9975     ConstraintSatisfaction Satisfaction;
9976     if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
9977       return false;
9978     if (!Satisfaction.IsSatisfied) {
9979       if (Complain) {
9980         if (InOverloadResolution)
9981           S.Diag(FD->getBeginLoc(),
9982                  diag::note_ovl_candidate_unsatisfied_constraints);
9983         else
9984           S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9985               << FD;
9986         S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9987       }
9988       return false;
9989     }
9990   }
9991 
9992   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9993     return P->hasAttr<PassObjectSizeAttr>();
9994   });
9995   if (I == FD->param_end())
9996     return true;
9997 
9998   if (Complain) {
9999     // Add one to ParamNo because it's user-facing
10000     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
10001     if (InOverloadResolution)
10002       S.Diag(FD->getLocation(),
10003              diag::note_ovl_candidate_has_pass_object_size_params)
10004           << ParamNo;
10005     else
10006       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10007           << FD << ParamNo;
10008   }
10009   return false;
10010 }
10011 
10012 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10013                                                const FunctionDecl *FD) {
10014   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10015                                            /*InOverloadResolution=*/true,
10016                                            /*Loc=*/SourceLocation());
10017 }
10018 
10019 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10020                                              bool Complain,
10021                                              SourceLocation Loc) {
10022   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10023                                              /*InOverloadResolution=*/false,
10024                                              Loc);
10025 }
10026 
10027 // Notes the location of an overload candidate.
10028 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10029                                  OverloadCandidateRewriteKind RewriteKind,
10030                                  QualType DestType, bool TakingAddress) {
10031   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10032     return;
10033   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10034       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10035     return;
10036 
10037   std::string FnDesc;
10038   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10039       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10040   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10041                          << (unsigned)KSPair.first << (unsigned)KSPair.second
10042                          << Fn << FnDesc;
10043 
10044   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10045   Diag(Fn->getLocation(), PD);
10046   MaybeEmitInheritedConstructorNote(*this, Found);
10047 }
10048 
10049 static void
10050 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10051   // Perhaps the ambiguity was caused by two atomic constraints that are
10052   // 'identical' but not equivalent:
10053   //
10054   // void foo() requires (sizeof(T) > 4) { } // #1
10055   // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10056   //
10057   // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10058   // #2 to subsume #1, but these constraint are not considered equivalent
10059   // according to the subsumption rules because they are not the same
10060   // source-level construct. This behavior is quite confusing and we should try
10061   // to help the user figure out what happened.
10062 
10063   SmallVector<const Expr *, 3> FirstAC, SecondAC;
10064   FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10065   for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10066     if (!I->Function)
10067       continue;
10068     SmallVector<const Expr *, 3> AC;
10069     if (auto *Template = I->Function->getPrimaryTemplate())
10070       Template->getAssociatedConstraints(AC);
10071     else
10072       I->Function->getAssociatedConstraints(AC);
10073     if (AC.empty())
10074       continue;
10075     if (FirstCand == nullptr) {
10076       FirstCand = I->Function;
10077       FirstAC = AC;
10078     } else if (SecondCand == nullptr) {
10079       SecondCand = I->Function;
10080       SecondAC = AC;
10081     } else {
10082       // We have more than one pair of constrained functions - this check is
10083       // expensive and we'd rather not try to diagnose it.
10084       return;
10085     }
10086   }
10087   if (!SecondCand)
10088     return;
10089   // The diagnostic can only happen if there are associated constraints on
10090   // both sides (there needs to be some identical atomic constraint).
10091   if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10092                                                       SecondCand, SecondAC))
10093     // Just show the user one diagnostic, they'll probably figure it out
10094     // from here.
10095     return;
10096 }
10097 
10098 // Notes the location of all overload candidates designated through
10099 // OverloadedExpr
10100 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10101                                      bool TakingAddress) {
10102   assert(OverloadedExpr->getType() == Context.OverloadTy);
10103 
10104   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10105   OverloadExpr *OvlExpr = Ovl.Expression;
10106 
10107   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10108                             IEnd = OvlExpr->decls_end();
10109        I != IEnd; ++I) {
10110     if (FunctionTemplateDecl *FunTmpl =
10111                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10112       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10113                             TakingAddress);
10114     } else if (FunctionDecl *Fun
10115                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10116       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10117     }
10118   }
10119 }
10120 
10121 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
10122 /// "lead" diagnostic; it will be given two arguments, the source and
10123 /// target types of the conversion.
10124 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10125                                  Sema &S,
10126                                  SourceLocation CaretLoc,
10127                                  const PartialDiagnostic &PDiag) const {
10128   S.Diag(CaretLoc, PDiag)
10129     << Ambiguous.getFromType() << Ambiguous.getToType();
10130   // FIXME: The note limiting machinery is borrowed from
10131   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10132   // refactoring here.
10133   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10134   unsigned CandsShown = 0;
10135   AmbiguousConversionSequence::const_iterator I, E;
10136   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10137     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10138       break;
10139     ++CandsShown;
10140     S.NoteOverloadCandidate(I->first, I->second);
10141   }
10142   if (I != E)
10143     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10144 }
10145 
10146 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10147                                   unsigned I, bool TakingCandidateAddress) {
10148   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10149   assert(Conv.isBad());
10150   assert(Cand->Function && "for now, candidate must be a function");
10151   FunctionDecl *Fn = Cand->Function;
10152 
10153   // There's a conversion slot for the object argument if this is a
10154   // non-constructor method.  Note that 'I' corresponds the
10155   // conversion-slot index.
10156   bool isObjectArgument = false;
10157   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10158     if (I == 0)
10159       isObjectArgument = true;
10160     else
10161       I--;
10162   }
10163 
10164   std::string FnDesc;
10165   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10166       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10167                                 FnDesc);
10168 
10169   Expr *FromExpr = Conv.Bad.FromExpr;
10170   QualType FromTy = Conv.Bad.getFromType();
10171   QualType ToTy = Conv.Bad.getToType();
10172 
10173   if (FromTy == S.Context.OverloadTy) {
10174     assert(FromExpr && "overload set argument came from implicit argument?");
10175     Expr *E = FromExpr->IgnoreParens();
10176     if (isa<UnaryOperator>(E))
10177       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10178     DeclarationName Name = cast<OverloadExpr>(E)->getName();
10179 
10180     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10181         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10182         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10183         << Name << I + 1;
10184     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10185     return;
10186   }
10187 
10188   // Do some hand-waving analysis to see if the non-viability is due
10189   // to a qualifier mismatch.
10190   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10191   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10192   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10193     CToTy = RT->getPointeeType();
10194   else {
10195     // TODO: detect and diagnose the full richness of const mismatches.
10196     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10197       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10198         CFromTy = FromPT->getPointeeType();
10199         CToTy = ToPT->getPointeeType();
10200       }
10201   }
10202 
10203   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10204       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10205     Qualifiers FromQs = CFromTy.getQualifiers();
10206     Qualifiers ToQs = CToTy.getQualifiers();
10207 
10208     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10209       if (isObjectArgument)
10210         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10211             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10212             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10213             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10214       else
10215         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10216             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10217             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10218             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10219             << ToTy->isReferenceType() << I + 1;
10220       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10221       return;
10222     }
10223 
10224     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10225       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10226           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10227           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10228           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10229           << (unsigned)isObjectArgument << I + 1;
10230       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10231       return;
10232     }
10233 
10234     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10235       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10236           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10237           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10238           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10239           << (unsigned)isObjectArgument << I + 1;
10240       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10241       return;
10242     }
10243 
10244     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10245       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10246           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10247           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10248           << FromQs.hasUnaligned() << I + 1;
10249       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10250       return;
10251     }
10252 
10253     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10254     assert(CVR && "unexpected qualifiers mismatch");
10255 
10256     if (isObjectArgument) {
10257       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10258           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10259           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10260           << (CVR - 1);
10261     } else {
10262       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10263           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10264           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10265           << (CVR - 1) << I + 1;
10266     }
10267     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10268     return;
10269   }
10270 
10271   // Special diagnostic for failure to convert an initializer list, since
10272   // telling the user that it has type void is not useful.
10273   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10274     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10275         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10276         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10277         << ToTy << (unsigned)isObjectArgument << I + 1;
10278     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10279     return;
10280   }
10281 
10282   // Diagnose references or pointers to incomplete types differently,
10283   // since it's far from impossible that the incompleteness triggered
10284   // the failure.
10285   QualType TempFromTy = FromTy.getNonReferenceType();
10286   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10287     TempFromTy = PTy->getPointeeType();
10288   if (TempFromTy->isIncompleteType()) {
10289     // Emit the generic diagnostic and, optionally, add the hints to it.
10290     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10291         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10292         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10293         << ToTy << (unsigned)isObjectArgument << I + 1
10294         << (unsigned)(Cand->Fix.Kind);
10295 
10296     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10297     return;
10298   }
10299 
10300   // Diagnose base -> derived pointer conversions.
10301   unsigned BaseToDerivedConversion = 0;
10302   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10303     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10304       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10305                                                FromPtrTy->getPointeeType()) &&
10306           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10307           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10308           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10309                           FromPtrTy->getPointeeType()))
10310         BaseToDerivedConversion = 1;
10311     }
10312   } else if (const ObjCObjectPointerType *FromPtrTy
10313                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10314     if (const ObjCObjectPointerType *ToPtrTy
10315                                         = ToTy->getAs<ObjCObjectPointerType>())
10316       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10317         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10318           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10319                                                 FromPtrTy->getPointeeType()) &&
10320               FromIface->isSuperClassOf(ToIface))
10321             BaseToDerivedConversion = 2;
10322   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10323     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10324         !FromTy->isIncompleteType() &&
10325         !ToRefTy->getPointeeType()->isIncompleteType() &&
10326         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10327       BaseToDerivedConversion = 3;
10328     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10329                ToTy.getNonReferenceType().getCanonicalType() ==
10330                FromTy.getNonReferenceType().getCanonicalType()) {
10331       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10332           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10333           << (unsigned)isObjectArgument << I + 1
10334           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10335       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10336       return;
10337     }
10338   }
10339 
10340   if (BaseToDerivedConversion) {
10341     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10342         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10343         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10344         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10345     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10346     return;
10347   }
10348 
10349   if (isa<ObjCObjectPointerType>(CFromTy) &&
10350       isa<PointerType>(CToTy)) {
10351       Qualifiers FromQs = CFromTy.getQualifiers();
10352       Qualifiers ToQs = CToTy.getQualifiers();
10353       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10354         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10355             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10356             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10357             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10358         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10359         return;
10360       }
10361   }
10362 
10363   if (TakingCandidateAddress &&
10364       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10365     return;
10366 
10367   // Emit the generic diagnostic and, optionally, add the hints to it.
10368   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10369   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10370         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10371         << ToTy << (unsigned)isObjectArgument << I + 1
10372         << (unsigned)(Cand->Fix.Kind);
10373 
10374   // If we can fix the conversion, suggest the FixIts.
10375   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10376        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10377     FDiag << *HI;
10378   S.Diag(Fn->getLocation(), FDiag);
10379 
10380   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10381 }
10382 
10383 /// Additional arity mismatch diagnosis specific to a function overload
10384 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10385 /// over a candidate in any candidate set.
10386 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10387                                unsigned NumArgs) {
10388   FunctionDecl *Fn = Cand->Function;
10389   unsigned MinParams = Fn->getMinRequiredArguments();
10390 
10391   // With invalid overloaded operators, it's possible that we think we
10392   // have an arity mismatch when in fact it looks like we have the
10393   // right number of arguments, because only overloaded operators have
10394   // the weird behavior of overloading member and non-member functions.
10395   // Just don't report anything.
10396   if (Fn->isInvalidDecl() &&
10397       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10398     return true;
10399 
10400   if (NumArgs < MinParams) {
10401     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10402            (Cand->FailureKind == ovl_fail_bad_deduction &&
10403             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10404   } else {
10405     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10406            (Cand->FailureKind == ovl_fail_bad_deduction &&
10407             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10408   }
10409 
10410   return false;
10411 }
10412 
10413 /// General arity mismatch diagnosis over a candidate in a candidate set.
10414 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10415                                   unsigned NumFormalArgs) {
10416   assert(isa<FunctionDecl>(D) &&
10417       "The templated declaration should at least be a function"
10418       " when diagnosing bad template argument deduction due to too many"
10419       " or too few arguments");
10420 
10421   FunctionDecl *Fn = cast<FunctionDecl>(D);
10422 
10423   // TODO: treat calls to a missing default constructor as a special case
10424   const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10425   unsigned MinParams = Fn->getMinRequiredArguments();
10426 
10427   // at least / at most / exactly
10428   unsigned mode, modeCount;
10429   if (NumFormalArgs < MinParams) {
10430     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10431         FnTy->isTemplateVariadic())
10432       mode = 0; // "at least"
10433     else
10434       mode = 2; // "exactly"
10435     modeCount = MinParams;
10436   } else {
10437     if (MinParams != FnTy->getNumParams())
10438       mode = 1; // "at most"
10439     else
10440       mode = 2; // "exactly"
10441     modeCount = FnTy->getNumParams();
10442   }
10443 
10444   std::string Description;
10445   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10446       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10447 
10448   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10449     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10450         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10451         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10452   else
10453     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10454         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10455         << Description << mode << modeCount << NumFormalArgs;
10456 
10457   MaybeEmitInheritedConstructorNote(S, Found);
10458 }
10459 
10460 /// Arity mismatch diagnosis specific to a function overload candidate.
10461 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10462                                   unsigned NumFormalArgs) {
10463   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10464     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10465 }
10466 
10467 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10468   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10469     return TD;
10470   llvm_unreachable("Unsupported: Getting the described template declaration"
10471                    " for bad deduction diagnosis");
10472 }
10473 
10474 /// Diagnose a failed template-argument deduction.
10475 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10476                                  DeductionFailureInfo &DeductionFailure,
10477                                  unsigned NumArgs,
10478                                  bool TakingCandidateAddress) {
10479   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10480   NamedDecl *ParamD;
10481   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10482   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10483   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10484   switch (DeductionFailure.Result) {
10485   case Sema::TDK_Success:
10486     llvm_unreachable("TDK_success while diagnosing bad deduction");
10487 
10488   case Sema::TDK_Incomplete: {
10489     assert(ParamD && "no parameter found for incomplete deduction result");
10490     S.Diag(Templated->getLocation(),
10491            diag::note_ovl_candidate_incomplete_deduction)
10492         << ParamD->getDeclName();
10493     MaybeEmitInheritedConstructorNote(S, Found);
10494     return;
10495   }
10496 
10497   case Sema::TDK_IncompletePack: {
10498     assert(ParamD && "no parameter found for incomplete deduction result");
10499     S.Diag(Templated->getLocation(),
10500            diag::note_ovl_candidate_incomplete_deduction_pack)
10501         << ParamD->getDeclName()
10502         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10503         << *DeductionFailure.getFirstArg();
10504     MaybeEmitInheritedConstructorNote(S, Found);
10505     return;
10506   }
10507 
10508   case Sema::TDK_Underqualified: {
10509     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10510     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10511 
10512     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10513 
10514     // Param will have been canonicalized, but it should just be a
10515     // qualified version of ParamD, so move the qualifiers to that.
10516     QualifierCollector Qs;
10517     Qs.strip(Param);
10518     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10519     assert(S.Context.hasSameType(Param, NonCanonParam));
10520 
10521     // Arg has also been canonicalized, but there's nothing we can do
10522     // about that.  It also doesn't matter as much, because it won't
10523     // have any template parameters in it (because deduction isn't
10524     // done on dependent types).
10525     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10526 
10527     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10528         << ParamD->getDeclName() << Arg << NonCanonParam;
10529     MaybeEmitInheritedConstructorNote(S, Found);
10530     return;
10531   }
10532 
10533   case Sema::TDK_Inconsistent: {
10534     assert(ParamD && "no parameter found for inconsistent deduction result");
10535     int which = 0;
10536     if (isa<TemplateTypeParmDecl>(ParamD))
10537       which = 0;
10538     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10539       // Deduction might have failed because we deduced arguments of two
10540       // different types for a non-type template parameter.
10541       // FIXME: Use a different TDK value for this.
10542       QualType T1 =
10543           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10544       QualType T2 =
10545           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10546       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10547         S.Diag(Templated->getLocation(),
10548                diag::note_ovl_candidate_inconsistent_deduction_types)
10549           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10550           << *DeductionFailure.getSecondArg() << T2;
10551         MaybeEmitInheritedConstructorNote(S, Found);
10552         return;
10553       }
10554 
10555       which = 1;
10556     } else {
10557       which = 2;
10558     }
10559 
10560     // Tweak the diagnostic if the problem is that we deduced packs of
10561     // different arities. We'll print the actual packs anyway in case that
10562     // includes additional useful information.
10563     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10564         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10565         DeductionFailure.getFirstArg()->pack_size() !=
10566             DeductionFailure.getSecondArg()->pack_size()) {
10567       which = 3;
10568     }
10569 
10570     S.Diag(Templated->getLocation(),
10571            diag::note_ovl_candidate_inconsistent_deduction)
10572         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10573         << *DeductionFailure.getSecondArg();
10574     MaybeEmitInheritedConstructorNote(S, Found);
10575     return;
10576   }
10577 
10578   case Sema::TDK_InvalidExplicitArguments:
10579     assert(ParamD && "no parameter found for invalid explicit arguments");
10580     if (ParamD->getDeclName())
10581       S.Diag(Templated->getLocation(),
10582              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10583           << ParamD->getDeclName();
10584     else {
10585       int index = 0;
10586       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10587         index = TTP->getIndex();
10588       else if (NonTypeTemplateParmDecl *NTTP
10589                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10590         index = NTTP->getIndex();
10591       else
10592         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10593       S.Diag(Templated->getLocation(),
10594              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10595           << (index + 1);
10596     }
10597     MaybeEmitInheritedConstructorNote(S, Found);
10598     return;
10599 
10600   case Sema::TDK_ConstraintsNotSatisfied: {
10601     // Format the template argument list into the argument string.
10602     SmallString<128> TemplateArgString;
10603     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10604     TemplateArgString = " ";
10605     TemplateArgString += S.getTemplateArgumentBindingsText(
10606         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10607     if (TemplateArgString.size() == 1)
10608       TemplateArgString.clear();
10609     S.Diag(Templated->getLocation(),
10610            diag::note_ovl_candidate_unsatisfied_constraints)
10611         << TemplateArgString;
10612 
10613     S.DiagnoseUnsatisfiedConstraint(
10614         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10615     return;
10616   }
10617   case Sema::TDK_TooManyArguments:
10618   case Sema::TDK_TooFewArguments:
10619     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10620     return;
10621 
10622   case Sema::TDK_InstantiationDepth:
10623     S.Diag(Templated->getLocation(),
10624            diag::note_ovl_candidate_instantiation_depth);
10625     MaybeEmitInheritedConstructorNote(S, Found);
10626     return;
10627 
10628   case Sema::TDK_SubstitutionFailure: {
10629     // Format the template argument list into the argument string.
10630     SmallString<128> TemplateArgString;
10631     if (TemplateArgumentList *Args =
10632             DeductionFailure.getTemplateArgumentList()) {
10633       TemplateArgString = " ";
10634       TemplateArgString += S.getTemplateArgumentBindingsText(
10635           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10636       if (TemplateArgString.size() == 1)
10637         TemplateArgString.clear();
10638     }
10639 
10640     // If this candidate was disabled by enable_if, say so.
10641     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10642     if (PDiag && PDiag->second.getDiagID() ==
10643           diag::err_typename_nested_not_found_enable_if) {
10644       // FIXME: Use the source range of the condition, and the fully-qualified
10645       //        name of the enable_if template. These are both present in PDiag.
10646       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10647         << "'enable_if'" << TemplateArgString;
10648       return;
10649     }
10650 
10651     // We found a specific requirement that disabled the enable_if.
10652     if (PDiag && PDiag->second.getDiagID() ==
10653         diag::err_typename_nested_not_found_requirement) {
10654       S.Diag(Templated->getLocation(),
10655              diag::note_ovl_candidate_disabled_by_requirement)
10656         << PDiag->second.getStringArg(0) << TemplateArgString;
10657       return;
10658     }
10659 
10660     // Format the SFINAE diagnostic into the argument string.
10661     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10662     //        formatted message in another diagnostic.
10663     SmallString<128> SFINAEArgString;
10664     SourceRange R;
10665     if (PDiag) {
10666       SFINAEArgString = ": ";
10667       R = SourceRange(PDiag->first, PDiag->first);
10668       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10669     }
10670 
10671     S.Diag(Templated->getLocation(),
10672            diag::note_ovl_candidate_substitution_failure)
10673         << TemplateArgString << SFINAEArgString << R;
10674     MaybeEmitInheritedConstructorNote(S, Found);
10675     return;
10676   }
10677 
10678   case Sema::TDK_DeducedMismatch:
10679   case Sema::TDK_DeducedMismatchNested: {
10680     // Format the template argument list into the argument string.
10681     SmallString<128> TemplateArgString;
10682     if (TemplateArgumentList *Args =
10683             DeductionFailure.getTemplateArgumentList()) {
10684       TemplateArgString = " ";
10685       TemplateArgString += S.getTemplateArgumentBindingsText(
10686           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10687       if (TemplateArgString.size() == 1)
10688         TemplateArgString.clear();
10689     }
10690 
10691     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10692         << (*DeductionFailure.getCallArgIndex() + 1)
10693         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10694         << TemplateArgString
10695         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10696     break;
10697   }
10698 
10699   case Sema::TDK_NonDeducedMismatch: {
10700     // FIXME: Provide a source location to indicate what we couldn't match.
10701     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10702     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10703     if (FirstTA.getKind() == TemplateArgument::Template &&
10704         SecondTA.getKind() == TemplateArgument::Template) {
10705       TemplateName FirstTN = FirstTA.getAsTemplate();
10706       TemplateName SecondTN = SecondTA.getAsTemplate();
10707       if (FirstTN.getKind() == TemplateName::Template &&
10708           SecondTN.getKind() == TemplateName::Template) {
10709         if (FirstTN.getAsTemplateDecl()->getName() ==
10710             SecondTN.getAsTemplateDecl()->getName()) {
10711           // FIXME: This fixes a bad diagnostic where both templates are named
10712           // the same.  This particular case is a bit difficult since:
10713           // 1) It is passed as a string to the diagnostic printer.
10714           // 2) The diagnostic printer only attempts to find a better
10715           //    name for types, not decls.
10716           // Ideally, this should folded into the diagnostic printer.
10717           S.Diag(Templated->getLocation(),
10718                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10719               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10720           return;
10721         }
10722       }
10723     }
10724 
10725     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10726         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10727       return;
10728 
10729     // FIXME: For generic lambda parameters, check if the function is a lambda
10730     // call operator, and if so, emit a prettier and more informative
10731     // diagnostic that mentions 'auto' and lambda in addition to
10732     // (or instead of?) the canonical template type parameters.
10733     S.Diag(Templated->getLocation(),
10734            diag::note_ovl_candidate_non_deduced_mismatch)
10735         << FirstTA << SecondTA;
10736     return;
10737   }
10738   // TODO: diagnose these individually, then kill off
10739   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10740   case Sema::TDK_MiscellaneousDeductionFailure:
10741     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10742     MaybeEmitInheritedConstructorNote(S, Found);
10743     return;
10744   case Sema::TDK_CUDATargetMismatch:
10745     S.Diag(Templated->getLocation(),
10746            diag::note_cuda_ovl_candidate_target_mismatch);
10747     return;
10748   }
10749 }
10750 
10751 /// Diagnose a failed template-argument deduction, for function calls.
10752 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10753                                  unsigned NumArgs,
10754                                  bool TakingCandidateAddress) {
10755   unsigned TDK = Cand->DeductionFailure.Result;
10756   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10757     if (CheckArityMismatch(S, Cand, NumArgs))
10758       return;
10759   }
10760   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10761                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10762 }
10763 
10764 /// CUDA: diagnose an invalid call across targets.
10765 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10766   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10767   FunctionDecl *Callee = Cand->Function;
10768 
10769   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10770                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10771 
10772   std::string FnDesc;
10773   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10774       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10775                                 Cand->getRewriteKind(), FnDesc);
10776 
10777   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10778       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10779       << FnDesc /* Ignored */
10780       << CalleeTarget << CallerTarget;
10781 
10782   // This could be an implicit constructor for which we could not infer the
10783   // target due to a collsion. Diagnose that case.
10784   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10785   if (Meth != nullptr && Meth->isImplicit()) {
10786     CXXRecordDecl *ParentClass = Meth->getParent();
10787     Sema::CXXSpecialMember CSM;
10788 
10789     switch (FnKindPair.first) {
10790     default:
10791       return;
10792     case oc_implicit_default_constructor:
10793       CSM = Sema::CXXDefaultConstructor;
10794       break;
10795     case oc_implicit_copy_constructor:
10796       CSM = Sema::CXXCopyConstructor;
10797       break;
10798     case oc_implicit_move_constructor:
10799       CSM = Sema::CXXMoveConstructor;
10800       break;
10801     case oc_implicit_copy_assignment:
10802       CSM = Sema::CXXCopyAssignment;
10803       break;
10804     case oc_implicit_move_assignment:
10805       CSM = Sema::CXXMoveAssignment;
10806       break;
10807     };
10808 
10809     bool ConstRHS = false;
10810     if (Meth->getNumParams()) {
10811       if (const ReferenceType *RT =
10812               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10813         ConstRHS = RT->getPointeeType().isConstQualified();
10814       }
10815     }
10816 
10817     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10818                                               /* ConstRHS */ ConstRHS,
10819                                               /* Diagnose */ true);
10820   }
10821 }
10822 
10823 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10824   FunctionDecl *Callee = Cand->Function;
10825   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10826 
10827   S.Diag(Callee->getLocation(),
10828          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10829       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10830 }
10831 
10832 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10833   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10834   assert(ES.isExplicit() && "not an explicit candidate");
10835 
10836   unsigned Kind;
10837   switch (Cand->Function->getDeclKind()) {
10838   case Decl::Kind::CXXConstructor:
10839     Kind = 0;
10840     break;
10841   case Decl::Kind::CXXConversion:
10842     Kind = 1;
10843     break;
10844   case Decl::Kind::CXXDeductionGuide:
10845     Kind = Cand->Function->isImplicit() ? 0 : 2;
10846     break;
10847   default:
10848     llvm_unreachable("invalid Decl");
10849   }
10850 
10851   // Note the location of the first (in-class) declaration; a redeclaration
10852   // (particularly an out-of-class definition) will typically lack the
10853   // 'explicit' specifier.
10854   // FIXME: This is probably a good thing to do for all 'candidate' notes.
10855   FunctionDecl *First = Cand->Function->getFirstDecl();
10856   if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10857     First = Pattern->getFirstDecl();
10858 
10859   S.Diag(First->getLocation(),
10860          diag::note_ovl_candidate_explicit)
10861       << Kind << (ES.getExpr() ? 1 : 0)
10862       << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10863 }
10864 
10865 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10866   FunctionDecl *Callee = Cand->Function;
10867 
10868   S.Diag(Callee->getLocation(),
10869          diag::note_ovl_candidate_disabled_by_extension)
10870     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10871 }
10872 
10873 /// Generates a 'note' diagnostic for an overload candidate.  We've
10874 /// already generated a primary error at the call site.
10875 ///
10876 /// It really does need to be a single diagnostic with its caret
10877 /// pointed at the candidate declaration.  Yes, this creates some
10878 /// major challenges of technical writing.  Yes, this makes pointing
10879 /// out problems with specific arguments quite awkward.  It's still
10880 /// better than generating twenty screens of text for every failed
10881 /// overload.
10882 ///
10883 /// It would be great to be able to express per-candidate problems
10884 /// more richly for those diagnostic clients that cared, but we'd
10885 /// still have to be just as careful with the default diagnostics.
10886 /// \param CtorDestAS Addr space of object being constructed (for ctor
10887 /// candidates only).
10888 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10889                                   unsigned NumArgs,
10890                                   bool TakingCandidateAddress,
10891                                   LangAS CtorDestAS = LangAS::Default) {
10892   FunctionDecl *Fn = Cand->Function;
10893 
10894   // Note deleted candidates, but only if they're viable.
10895   if (Cand->Viable) {
10896     if (Fn->isDeleted()) {
10897       std::string FnDesc;
10898       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10899           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10900                                     Cand->getRewriteKind(), FnDesc);
10901 
10902       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10903           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10904           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10905       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10906       return;
10907     }
10908 
10909     // We don't really have anything else to say about viable candidates.
10910     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10911     return;
10912   }
10913 
10914   switch (Cand->FailureKind) {
10915   case ovl_fail_too_many_arguments:
10916   case ovl_fail_too_few_arguments:
10917     return DiagnoseArityMismatch(S, Cand, NumArgs);
10918 
10919   case ovl_fail_bad_deduction:
10920     return DiagnoseBadDeduction(S, Cand, NumArgs,
10921                                 TakingCandidateAddress);
10922 
10923   case ovl_fail_illegal_constructor: {
10924     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10925       << (Fn->getPrimaryTemplate() ? 1 : 0);
10926     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10927     return;
10928   }
10929 
10930   case ovl_fail_object_addrspace_mismatch: {
10931     Qualifiers QualsForPrinting;
10932     QualsForPrinting.setAddressSpace(CtorDestAS);
10933     S.Diag(Fn->getLocation(),
10934            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10935         << QualsForPrinting;
10936     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10937     return;
10938   }
10939 
10940   case ovl_fail_trivial_conversion:
10941   case ovl_fail_bad_final_conversion:
10942   case ovl_fail_final_conversion_not_exact:
10943     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10944 
10945   case ovl_fail_bad_conversion: {
10946     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10947     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10948       if (Cand->Conversions[I].isBad())
10949         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10950 
10951     // FIXME: this currently happens when we're called from SemaInit
10952     // when user-conversion overload fails.  Figure out how to handle
10953     // those conditions and diagnose them well.
10954     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10955   }
10956 
10957   case ovl_fail_bad_target:
10958     return DiagnoseBadTarget(S, Cand);
10959 
10960   case ovl_fail_enable_if:
10961     return DiagnoseFailedEnableIfAttr(S, Cand);
10962 
10963   case ovl_fail_explicit:
10964     return DiagnoseFailedExplicitSpec(S, Cand);
10965 
10966   case ovl_fail_ext_disabled:
10967     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10968 
10969   case ovl_fail_inhctor_slice:
10970     // It's generally not interesting to note copy/move constructors here.
10971     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10972       return;
10973     S.Diag(Fn->getLocation(),
10974            diag::note_ovl_candidate_inherited_constructor_slice)
10975       << (Fn->getPrimaryTemplate() ? 1 : 0)
10976       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10977     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10978     return;
10979 
10980   case ovl_fail_addr_not_available: {
10981     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10982     (void)Available;
10983     assert(!Available);
10984     break;
10985   }
10986   case ovl_non_default_multiversion_function:
10987     // Do nothing, these should simply be ignored.
10988     break;
10989 
10990   case ovl_fail_constraints_not_satisfied: {
10991     std::string FnDesc;
10992     std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10993         ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10994                                   Cand->getRewriteKind(), FnDesc);
10995 
10996     S.Diag(Fn->getLocation(),
10997            diag::note_ovl_candidate_constraints_not_satisfied)
10998         << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10999         << FnDesc /* Ignored */;
11000     ConstraintSatisfaction Satisfaction;
11001     if (S.CheckFunctionConstraints(Fn, Satisfaction))
11002       break;
11003     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11004   }
11005   }
11006 }
11007 
11008 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11009   // Desugar the type of the surrogate down to a function type,
11010   // retaining as many typedefs as possible while still showing
11011   // the function type (and, therefore, its parameter types).
11012   QualType FnType = Cand->Surrogate->getConversionType();
11013   bool isLValueReference = false;
11014   bool isRValueReference = false;
11015   bool isPointer = false;
11016   if (const LValueReferenceType *FnTypeRef =
11017         FnType->getAs<LValueReferenceType>()) {
11018     FnType = FnTypeRef->getPointeeType();
11019     isLValueReference = true;
11020   } else if (const RValueReferenceType *FnTypeRef =
11021                FnType->getAs<RValueReferenceType>()) {
11022     FnType = FnTypeRef->getPointeeType();
11023     isRValueReference = true;
11024   }
11025   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11026     FnType = FnTypePtr->getPointeeType();
11027     isPointer = true;
11028   }
11029   // Desugar down to a function type.
11030   FnType = QualType(FnType->getAs<FunctionType>(), 0);
11031   // Reconstruct the pointer/reference as appropriate.
11032   if (isPointer) FnType = S.Context.getPointerType(FnType);
11033   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11034   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11035 
11036   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11037     << FnType;
11038 }
11039 
11040 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11041                                          SourceLocation OpLoc,
11042                                          OverloadCandidate *Cand) {
11043   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11044   std::string TypeStr("operator");
11045   TypeStr += Opc;
11046   TypeStr += "(";
11047   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11048   if (Cand->Conversions.size() == 1) {
11049     TypeStr += ")";
11050     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11051   } else {
11052     TypeStr += ", ";
11053     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11054     TypeStr += ")";
11055     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11056   }
11057 }
11058 
11059 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11060                                          OverloadCandidate *Cand) {
11061   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11062     if (ICS.isBad()) break; // all meaningless after first invalid
11063     if (!ICS.isAmbiguous()) continue;
11064 
11065     ICS.DiagnoseAmbiguousConversion(
11066         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11067   }
11068 }
11069 
11070 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11071   if (Cand->Function)
11072     return Cand->Function->getLocation();
11073   if (Cand->IsSurrogate)
11074     return Cand->Surrogate->getLocation();
11075   return SourceLocation();
11076 }
11077 
11078 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11079   switch ((Sema::TemplateDeductionResult)DFI.Result) {
11080   case Sema::TDK_Success:
11081   case Sema::TDK_NonDependentConversionFailure:
11082     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11083 
11084   case Sema::TDK_Invalid:
11085   case Sema::TDK_Incomplete:
11086   case Sema::TDK_IncompletePack:
11087     return 1;
11088 
11089   case Sema::TDK_Underqualified:
11090   case Sema::TDK_Inconsistent:
11091     return 2;
11092 
11093   case Sema::TDK_SubstitutionFailure:
11094   case Sema::TDK_DeducedMismatch:
11095   case Sema::TDK_ConstraintsNotSatisfied:
11096   case Sema::TDK_DeducedMismatchNested:
11097   case Sema::TDK_NonDeducedMismatch:
11098   case Sema::TDK_MiscellaneousDeductionFailure:
11099   case Sema::TDK_CUDATargetMismatch:
11100     return 3;
11101 
11102   case Sema::TDK_InstantiationDepth:
11103     return 4;
11104 
11105   case Sema::TDK_InvalidExplicitArguments:
11106     return 5;
11107 
11108   case Sema::TDK_TooManyArguments:
11109   case Sema::TDK_TooFewArguments:
11110     return 6;
11111   }
11112   llvm_unreachable("Unhandled deduction result");
11113 }
11114 
11115 namespace {
11116 struct CompareOverloadCandidatesForDisplay {
11117   Sema &S;
11118   SourceLocation Loc;
11119   size_t NumArgs;
11120   OverloadCandidateSet::CandidateSetKind CSK;
11121 
11122   CompareOverloadCandidatesForDisplay(
11123       Sema &S, SourceLocation Loc, size_t NArgs,
11124       OverloadCandidateSet::CandidateSetKind CSK)
11125       : S(S), NumArgs(NArgs), CSK(CSK) {}
11126 
11127   OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11128     // If there are too many or too few arguments, that's the high-order bit we
11129     // want to sort by, even if the immediate failure kind was something else.
11130     if (C->FailureKind == ovl_fail_too_many_arguments ||
11131         C->FailureKind == ovl_fail_too_few_arguments)
11132       return static_cast<OverloadFailureKind>(C->FailureKind);
11133 
11134     if (C->Function) {
11135       if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11136         return ovl_fail_too_many_arguments;
11137       if (NumArgs < C->Function->getMinRequiredArguments())
11138         return ovl_fail_too_few_arguments;
11139     }
11140 
11141     return static_cast<OverloadFailureKind>(C->FailureKind);
11142   }
11143 
11144   bool operator()(const OverloadCandidate *L,
11145                   const OverloadCandidate *R) {
11146     // Fast-path this check.
11147     if (L == R) return false;
11148 
11149     // Order first by viability.
11150     if (L->Viable) {
11151       if (!R->Viable) return true;
11152 
11153       // TODO: introduce a tri-valued comparison for overload
11154       // candidates.  Would be more worthwhile if we had a sort
11155       // that could exploit it.
11156       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11157         return true;
11158       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11159         return false;
11160     } else if (R->Viable)
11161       return false;
11162 
11163     assert(L->Viable == R->Viable);
11164 
11165     // Criteria by which we can sort non-viable candidates:
11166     if (!L->Viable) {
11167       OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11168       OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11169 
11170       // 1. Arity mismatches come after other candidates.
11171       if (LFailureKind == ovl_fail_too_many_arguments ||
11172           LFailureKind == ovl_fail_too_few_arguments) {
11173         if (RFailureKind == ovl_fail_too_many_arguments ||
11174             RFailureKind == ovl_fail_too_few_arguments) {
11175           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11176           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11177           if (LDist == RDist) {
11178             if (LFailureKind == RFailureKind)
11179               // Sort non-surrogates before surrogates.
11180               return !L->IsSurrogate && R->IsSurrogate;
11181             // Sort candidates requiring fewer parameters than there were
11182             // arguments given after candidates requiring more parameters
11183             // than there were arguments given.
11184             return LFailureKind == ovl_fail_too_many_arguments;
11185           }
11186           return LDist < RDist;
11187         }
11188         return false;
11189       }
11190       if (RFailureKind == ovl_fail_too_many_arguments ||
11191           RFailureKind == ovl_fail_too_few_arguments)
11192         return true;
11193 
11194       // 2. Bad conversions come first and are ordered by the number
11195       // of bad conversions and quality of good conversions.
11196       if (LFailureKind == ovl_fail_bad_conversion) {
11197         if (RFailureKind != ovl_fail_bad_conversion)
11198           return true;
11199 
11200         // The conversion that can be fixed with a smaller number of changes,
11201         // comes first.
11202         unsigned numLFixes = L->Fix.NumConversionsFixed;
11203         unsigned numRFixes = R->Fix.NumConversionsFixed;
11204         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11205         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11206         if (numLFixes != numRFixes) {
11207           return numLFixes < numRFixes;
11208         }
11209 
11210         // If there's any ordering between the defined conversions...
11211         // FIXME: this might not be transitive.
11212         assert(L->Conversions.size() == R->Conversions.size());
11213 
11214         int leftBetter = 0;
11215         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11216         for (unsigned E = L->Conversions.size(); I != E; ++I) {
11217           switch (CompareImplicitConversionSequences(S, Loc,
11218                                                      L->Conversions[I],
11219                                                      R->Conversions[I])) {
11220           case ImplicitConversionSequence::Better:
11221             leftBetter++;
11222             break;
11223 
11224           case ImplicitConversionSequence::Worse:
11225             leftBetter--;
11226             break;
11227 
11228           case ImplicitConversionSequence::Indistinguishable:
11229             break;
11230           }
11231         }
11232         if (leftBetter > 0) return true;
11233         if (leftBetter < 0) return false;
11234 
11235       } else if (RFailureKind == ovl_fail_bad_conversion)
11236         return false;
11237 
11238       if (LFailureKind == ovl_fail_bad_deduction) {
11239         if (RFailureKind != ovl_fail_bad_deduction)
11240           return true;
11241 
11242         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11243           return RankDeductionFailure(L->DeductionFailure)
11244                < RankDeductionFailure(R->DeductionFailure);
11245       } else if (RFailureKind == ovl_fail_bad_deduction)
11246         return false;
11247 
11248       // TODO: others?
11249     }
11250 
11251     // Sort everything else by location.
11252     SourceLocation LLoc = GetLocationForCandidate(L);
11253     SourceLocation RLoc = GetLocationForCandidate(R);
11254 
11255     // Put candidates without locations (e.g. builtins) at the end.
11256     if (LLoc.isInvalid()) return false;
11257     if (RLoc.isInvalid()) return true;
11258 
11259     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11260   }
11261 };
11262 }
11263 
11264 /// CompleteNonViableCandidate - Normally, overload resolution only
11265 /// computes up to the first bad conversion. Produces the FixIt set if
11266 /// possible.
11267 static void
11268 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11269                            ArrayRef<Expr *> Args,
11270                            OverloadCandidateSet::CandidateSetKind CSK) {
11271   assert(!Cand->Viable);
11272 
11273   // Don't do anything on failures other than bad conversion.
11274   if (Cand->FailureKind != ovl_fail_bad_conversion)
11275     return;
11276 
11277   // We only want the FixIts if all the arguments can be corrected.
11278   bool Unfixable = false;
11279   // Use a implicit copy initialization to check conversion fixes.
11280   Cand->Fix.setConversionChecker(TryCopyInitialization);
11281 
11282   // Attempt to fix the bad conversion.
11283   unsigned ConvCount = Cand->Conversions.size();
11284   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11285        ++ConvIdx) {
11286     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11287     if (Cand->Conversions[ConvIdx].isInitialized() &&
11288         Cand->Conversions[ConvIdx].isBad()) {
11289       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11290       break;
11291     }
11292   }
11293 
11294   // FIXME: this should probably be preserved from the overload
11295   // operation somehow.
11296   bool SuppressUserConversions = false;
11297 
11298   unsigned ConvIdx = 0;
11299   unsigned ArgIdx = 0;
11300   ArrayRef<QualType> ParamTypes;
11301   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11302 
11303   if (Cand->IsSurrogate) {
11304     QualType ConvType
11305       = Cand->Surrogate->getConversionType().getNonReferenceType();
11306     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11307       ConvType = ConvPtrType->getPointeeType();
11308     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11309     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11310     ConvIdx = 1;
11311   } else if (Cand->Function) {
11312     ParamTypes =
11313         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11314     if (isa<CXXMethodDecl>(Cand->Function) &&
11315         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11316       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11317       ConvIdx = 1;
11318       if (CSK == OverloadCandidateSet::CSK_Operator &&
11319           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11320         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11321         ArgIdx = 1;
11322     }
11323   } else {
11324     // Builtin operator.
11325     assert(ConvCount <= 3);
11326     ParamTypes = Cand->BuiltinParamTypes;
11327   }
11328 
11329   // Fill in the rest of the conversions.
11330   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11331        ConvIdx != ConvCount;
11332        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11333     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11334     if (Cand->Conversions[ConvIdx].isInitialized()) {
11335       // We've already checked this conversion.
11336     } else if (ParamIdx < ParamTypes.size()) {
11337       if (ParamTypes[ParamIdx]->isDependentType())
11338         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11339             Args[ArgIdx]->getType());
11340       else {
11341         Cand->Conversions[ConvIdx] =
11342             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11343                                   SuppressUserConversions,
11344                                   /*InOverloadResolution=*/true,
11345                                   /*AllowObjCWritebackConversion=*/
11346                                   S.getLangOpts().ObjCAutoRefCount);
11347         // Store the FixIt in the candidate if it exists.
11348         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11349           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11350       }
11351     } else
11352       Cand->Conversions[ConvIdx].setEllipsis();
11353   }
11354 }
11355 
11356 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11357     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11358     SourceLocation OpLoc,
11359     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11360   // Sort the candidates by viability and position.  Sorting directly would
11361   // be prohibitive, so we make a set of pointers and sort those.
11362   SmallVector<OverloadCandidate*, 32> Cands;
11363   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11364   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11365     if (!Filter(*Cand))
11366       continue;
11367     switch (OCD) {
11368     case OCD_AllCandidates:
11369       if (!Cand->Viable) {
11370         if (!Cand->Function && !Cand->IsSurrogate) {
11371           // This a non-viable builtin candidate.  We do not, in general,
11372           // want to list every possible builtin candidate.
11373           continue;
11374         }
11375         CompleteNonViableCandidate(S, Cand, Args, Kind);
11376       }
11377       break;
11378 
11379     case OCD_ViableCandidates:
11380       if (!Cand->Viable)
11381         continue;
11382       break;
11383 
11384     case OCD_AmbiguousCandidates:
11385       if (!Cand->Best)
11386         continue;
11387       break;
11388     }
11389 
11390     Cands.push_back(Cand);
11391   }
11392 
11393   llvm::stable_sort(
11394       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11395 
11396   return Cands;
11397 }
11398 
11399 /// When overload resolution fails, prints diagnostic messages containing the
11400 /// candidates in the candidate set.
11401 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11402     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11403     StringRef Opc, SourceLocation OpLoc,
11404     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11405 
11406   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11407 
11408   S.Diag(PD.first, PD.second);
11409 
11410   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11411 
11412   if (OCD == OCD_AmbiguousCandidates)
11413     MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11414 }
11415 
11416 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11417                                           ArrayRef<OverloadCandidate *> Cands,
11418                                           StringRef Opc, SourceLocation OpLoc) {
11419   bool ReportedAmbiguousConversions = false;
11420 
11421   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11422   unsigned CandsShown = 0;
11423   auto I = Cands.begin(), E = Cands.end();
11424   for (; I != E; ++I) {
11425     OverloadCandidate *Cand = *I;
11426 
11427     // Set an arbitrary limit on the number of candidate functions we'll spam
11428     // the user with.  FIXME: This limit should depend on details of the
11429     // candidate list.
11430     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11431       break;
11432     }
11433     ++CandsShown;
11434 
11435     if (Cand->Function)
11436       NoteFunctionCandidate(S, Cand, Args.size(),
11437                             /*TakingCandidateAddress=*/false, DestAS);
11438     else if (Cand->IsSurrogate)
11439       NoteSurrogateCandidate(S, Cand);
11440     else {
11441       assert(Cand->Viable &&
11442              "Non-viable built-in candidates are not added to Cands.");
11443       // Generally we only see ambiguities including viable builtin
11444       // operators if overload resolution got screwed up by an
11445       // ambiguous user-defined conversion.
11446       //
11447       // FIXME: It's quite possible for different conversions to see
11448       // different ambiguities, though.
11449       if (!ReportedAmbiguousConversions) {
11450         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11451         ReportedAmbiguousConversions = true;
11452       }
11453 
11454       // If this is a viable builtin, print it.
11455       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11456     }
11457   }
11458 
11459   if (I != E)
11460     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11461 }
11462 
11463 static SourceLocation
11464 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11465   return Cand->Specialization ? Cand->Specialization->getLocation()
11466                               : SourceLocation();
11467 }
11468 
11469 namespace {
11470 struct CompareTemplateSpecCandidatesForDisplay {
11471   Sema &S;
11472   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11473 
11474   bool operator()(const TemplateSpecCandidate *L,
11475                   const TemplateSpecCandidate *R) {
11476     // Fast-path this check.
11477     if (L == R)
11478       return false;
11479 
11480     // Assuming that both candidates are not matches...
11481 
11482     // Sort by the ranking of deduction failures.
11483     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11484       return RankDeductionFailure(L->DeductionFailure) <
11485              RankDeductionFailure(R->DeductionFailure);
11486 
11487     // Sort everything else by location.
11488     SourceLocation LLoc = GetLocationForCandidate(L);
11489     SourceLocation RLoc = GetLocationForCandidate(R);
11490 
11491     // Put candidates without locations (e.g. builtins) at the end.
11492     if (LLoc.isInvalid())
11493       return false;
11494     if (RLoc.isInvalid())
11495       return true;
11496 
11497     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11498   }
11499 };
11500 }
11501 
11502 /// Diagnose a template argument deduction failure.
11503 /// We are treating these failures as overload failures due to bad
11504 /// deductions.
11505 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11506                                                  bool ForTakingAddress) {
11507   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11508                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11509 }
11510 
11511 void TemplateSpecCandidateSet::destroyCandidates() {
11512   for (iterator i = begin(), e = end(); i != e; ++i) {
11513     i->DeductionFailure.Destroy();
11514   }
11515 }
11516 
11517 void TemplateSpecCandidateSet::clear() {
11518   destroyCandidates();
11519   Candidates.clear();
11520 }
11521 
11522 /// NoteCandidates - When no template specialization match is found, prints
11523 /// diagnostic messages containing the non-matching specializations that form
11524 /// the candidate set.
11525 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11526 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11527 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11528   // Sort the candidates by position (assuming no candidate is a match).
11529   // Sorting directly would be prohibitive, so we make a set of pointers
11530   // and sort those.
11531   SmallVector<TemplateSpecCandidate *, 32> Cands;
11532   Cands.reserve(size());
11533   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11534     if (Cand->Specialization)
11535       Cands.push_back(Cand);
11536     // Otherwise, this is a non-matching builtin candidate.  We do not,
11537     // in general, want to list every possible builtin candidate.
11538   }
11539 
11540   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11541 
11542   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11543   // for generalization purposes (?).
11544   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11545 
11546   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11547   unsigned CandsShown = 0;
11548   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11549     TemplateSpecCandidate *Cand = *I;
11550 
11551     // Set an arbitrary limit on the number of candidates we'll spam
11552     // the user with.  FIXME: This limit should depend on details of the
11553     // candidate list.
11554     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11555       break;
11556     ++CandsShown;
11557 
11558     assert(Cand->Specialization &&
11559            "Non-matching built-in candidates are not added to Cands.");
11560     Cand->NoteDeductionFailure(S, ForTakingAddress);
11561   }
11562 
11563   if (I != E)
11564     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11565 }
11566 
11567 // [PossiblyAFunctionType]  -->   [Return]
11568 // NonFunctionType --> NonFunctionType
11569 // R (A) --> R(A)
11570 // R (*)(A) --> R (A)
11571 // R (&)(A) --> R (A)
11572 // R (S::*)(A) --> R (A)
11573 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11574   QualType Ret = PossiblyAFunctionType;
11575   if (const PointerType *ToTypePtr =
11576     PossiblyAFunctionType->getAs<PointerType>())
11577     Ret = ToTypePtr->getPointeeType();
11578   else if (const ReferenceType *ToTypeRef =
11579     PossiblyAFunctionType->getAs<ReferenceType>())
11580     Ret = ToTypeRef->getPointeeType();
11581   else if (const MemberPointerType *MemTypePtr =
11582     PossiblyAFunctionType->getAs<MemberPointerType>())
11583     Ret = MemTypePtr->getPointeeType();
11584   Ret =
11585     Context.getCanonicalType(Ret).getUnqualifiedType();
11586   return Ret;
11587 }
11588 
11589 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11590                                  bool Complain = true) {
11591   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11592       S.DeduceReturnType(FD, Loc, Complain))
11593     return true;
11594 
11595   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11596   if (S.getLangOpts().CPlusPlus17 &&
11597       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11598       !S.ResolveExceptionSpec(Loc, FPT))
11599     return true;
11600 
11601   return false;
11602 }
11603 
11604 namespace {
11605 // A helper class to help with address of function resolution
11606 // - allows us to avoid passing around all those ugly parameters
11607 class AddressOfFunctionResolver {
11608   Sema& S;
11609   Expr* SourceExpr;
11610   const QualType& TargetType;
11611   QualType TargetFunctionType; // Extracted function type from target type
11612 
11613   bool Complain;
11614   //DeclAccessPair& ResultFunctionAccessPair;
11615   ASTContext& Context;
11616 
11617   bool TargetTypeIsNonStaticMemberFunction;
11618   bool FoundNonTemplateFunction;
11619   bool StaticMemberFunctionFromBoundPointer;
11620   bool HasComplained;
11621 
11622   OverloadExpr::FindResult OvlExprInfo;
11623   OverloadExpr *OvlExpr;
11624   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11625   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11626   TemplateSpecCandidateSet FailedCandidates;
11627 
11628 public:
11629   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11630                             const QualType &TargetType, bool Complain)
11631       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11632         Complain(Complain), Context(S.getASTContext()),
11633         TargetTypeIsNonStaticMemberFunction(
11634             !!TargetType->getAs<MemberPointerType>()),
11635         FoundNonTemplateFunction(false),
11636         StaticMemberFunctionFromBoundPointer(false),
11637         HasComplained(false),
11638         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11639         OvlExpr(OvlExprInfo.Expression),
11640         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11641     ExtractUnqualifiedFunctionTypeFromTargetType();
11642 
11643     if (TargetFunctionType->isFunctionType()) {
11644       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11645         if (!UME->isImplicitAccess() &&
11646             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11647           StaticMemberFunctionFromBoundPointer = true;
11648     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11649       DeclAccessPair dap;
11650       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11651               OvlExpr, false, &dap)) {
11652         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11653           if (!Method->isStatic()) {
11654             // If the target type is a non-function type and the function found
11655             // is a non-static member function, pretend as if that was the
11656             // target, it's the only possible type to end up with.
11657             TargetTypeIsNonStaticMemberFunction = true;
11658 
11659             // And skip adding the function if its not in the proper form.
11660             // We'll diagnose this due to an empty set of functions.
11661             if (!OvlExprInfo.HasFormOfMemberPointer)
11662               return;
11663           }
11664 
11665         Matches.push_back(std::make_pair(dap, Fn));
11666       }
11667       return;
11668     }
11669 
11670     if (OvlExpr->hasExplicitTemplateArgs())
11671       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11672 
11673     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11674       // C++ [over.over]p4:
11675       //   If more than one function is selected, [...]
11676       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11677         if (FoundNonTemplateFunction)
11678           EliminateAllTemplateMatches();
11679         else
11680           EliminateAllExceptMostSpecializedTemplate();
11681       }
11682     }
11683 
11684     if (S.getLangOpts().CUDA && Matches.size() > 1)
11685       EliminateSuboptimalCudaMatches();
11686   }
11687 
11688   bool hasComplained() const { return HasComplained; }
11689 
11690 private:
11691   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11692     QualType Discard;
11693     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11694            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11695   }
11696 
11697   /// \return true if A is considered a better overload candidate for the
11698   /// desired type than B.
11699   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11700     // If A doesn't have exactly the correct type, we don't want to classify it
11701     // as "better" than anything else. This way, the user is required to
11702     // disambiguate for us if there are multiple candidates and no exact match.
11703     return candidateHasExactlyCorrectType(A) &&
11704            (!candidateHasExactlyCorrectType(B) ||
11705             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11706   }
11707 
11708   /// \return true if we were able to eliminate all but one overload candidate,
11709   /// false otherwise.
11710   bool eliminiateSuboptimalOverloadCandidates() {
11711     // Same algorithm as overload resolution -- one pass to pick the "best",
11712     // another pass to be sure that nothing is better than the best.
11713     auto Best = Matches.begin();
11714     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11715       if (isBetterCandidate(I->second, Best->second))
11716         Best = I;
11717 
11718     const FunctionDecl *BestFn = Best->second;
11719     auto IsBestOrInferiorToBest = [this, BestFn](
11720         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11721       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11722     };
11723 
11724     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11725     // option, so we can potentially give the user a better error
11726     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11727       return false;
11728     Matches[0] = *Best;
11729     Matches.resize(1);
11730     return true;
11731   }
11732 
11733   bool isTargetTypeAFunction() const {
11734     return TargetFunctionType->isFunctionType();
11735   }
11736 
11737   // [ToType]     [Return]
11738 
11739   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11740   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11741   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11742   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11743     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11744   }
11745 
11746   // return true if any matching specializations were found
11747   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11748                                    const DeclAccessPair& CurAccessFunPair) {
11749     if (CXXMethodDecl *Method
11750               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11751       // Skip non-static function templates when converting to pointer, and
11752       // static when converting to member pointer.
11753       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11754         return false;
11755     }
11756     else if (TargetTypeIsNonStaticMemberFunction)
11757       return false;
11758 
11759     // C++ [over.over]p2:
11760     //   If the name is a function template, template argument deduction is
11761     //   done (14.8.2.2), and if the argument deduction succeeds, the
11762     //   resulting template argument list is used to generate a single
11763     //   function template specialization, which is added to the set of
11764     //   overloaded functions considered.
11765     FunctionDecl *Specialization = nullptr;
11766     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11767     if (Sema::TemplateDeductionResult Result
11768           = S.DeduceTemplateArguments(FunctionTemplate,
11769                                       &OvlExplicitTemplateArgs,
11770                                       TargetFunctionType, Specialization,
11771                                       Info, /*IsAddressOfFunction*/true)) {
11772       // Make a note of the failed deduction for diagnostics.
11773       FailedCandidates.addCandidate()
11774           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11775                MakeDeductionFailureInfo(Context, Result, Info));
11776       return false;
11777     }
11778 
11779     // Template argument deduction ensures that we have an exact match or
11780     // compatible pointer-to-function arguments that would be adjusted by ICS.
11781     // This function template specicalization works.
11782     assert(S.isSameOrCompatibleFunctionType(
11783               Context.getCanonicalType(Specialization->getType()),
11784               Context.getCanonicalType(TargetFunctionType)));
11785 
11786     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11787       return false;
11788 
11789     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11790     return true;
11791   }
11792 
11793   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11794                                       const DeclAccessPair& CurAccessFunPair) {
11795     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11796       // Skip non-static functions when converting to pointer, and static
11797       // when converting to member pointer.
11798       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11799         return false;
11800     }
11801     else if (TargetTypeIsNonStaticMemberFunction)
11802       return false;
11803 
11804     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11805       if (S.getLangOpts().CUDA)
11806         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11807           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11808             return false;
11809       if (FunDecl->isMultiVersion()) {
11810         const auto *TA = FunDecl->getAttr<TargetAttr>();
11811         if (TA && !TA->isDefaultVersion())
11812           return false;
11813       }
11814 
11815       // If any candidate has a placeholder return type, trigger its deduction
11816       // now.
11817       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11818                                Complain)) {
11819         HasComplained |= Complain;
11820         return false;
11821       }
11822 
11823       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11824         return false;
11825 
11826       // If we're in C, we need to support types that aren't exactly identical.
11827       if (!S.getLangOpts().CPlusPlus ||
11828           candidateHasExactlyCorrectType(FunDecl)) {
11829         Matches.push_back(std::make_pair(
11830             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11831         FoundNonTemplateFunction = true;
11832         return true;
11833       }
11834     }
11835 
11836     return false;
11837   }
11838 
11839   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11840     bool Ret = false;
11841 
11842     // If the overload expression doesn't have the form of a pointer to
11843     // member, don't try to convert it to a pointer-to-member type.
11844     if (IsInvalidFormOfPointerToMemberFunction())
11845       return false;
11846 
11847     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11848                                E = OvlExpr->decls_end();
11849          I != E; ++I) {
11850       // Look through any using declarations to find the underlying function.
11851       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11852 
11853       // C++ [over.over]p3:
11854       //   Non-member functions and static member functions match
11855       //   targets of type "pointer-to-function" or "reference-to-function."
11856       //   Nonstatic member functions match targets of
11857       //   type "pointer-to-member-function."
11858       // Note that according to DR 247, the containing class does not matter.
11859       if (FunctionTemplateDecl *FunctionTemplate
11860                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11861         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11862           Ret = true;
11863       }
11864       // If we have explicit template arguments supplied, skip non-templates.
11865       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11866                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11867         Ret = true;
11868     }
11869     assert(Ret || Matches.empty());
11870     return Ret;
11871   }
11872 
11873   void EliminateAllExceptMostSpecializedTemplate() {
11874     //   [...] and any given function template specialization F1 is
11875     //   eliminated if the set contains a second function template
11876     //   specialization whose function template is more specialized
11877     //   than the function template of F1 according to the partial
11878     //   ordering rules of 14.5.5.2.
11879 
11880     // The algorithm specified above is quadratic. We instead use a
11881     // two-pass algorithm (similar to the one used to identify the
11882     // best viable function in an overload set) that identifies the
11883     // best function template (if it exists).
11884 
11885     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11886     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11887       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11888 
11889     // TODO: It looks like FailedCandidates does not serve much purpose
11890     // here, since the no_viable diagnostic has index 0.
11891     UnresolvedSetIterator Result = S.getMostSpecialized(
11892         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11893         SourceExpr->getBeginLoc(), S.PDiag(),
11894         S.PDiag(diag::err_addr_ovl_ambiguous)
11895             << Matches[0].second->getDeclName(),
11896         S.PDiag(diag::note_ovl_candidate)
11897             << (unsigned)oc_function << (unsigned)ocs_described_template,
11898         Complain, TargetFunctionType);
11899 
11900     if (Result != MatchesCopy.end()) {
11901       // Make it the first and only element
11902       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11903       Matches[0].second = cast<FunctionDecl>(*Result);
11904       Matches.resize(1);
11905     } else
11906       HasComplained |= Complain;
11907   }
11908 
11909   void EliminateAllTemplateMatches() {
11910     //   [...] any function template specializations in the set are
11911     //   eliminated if the set also contains a non-template function, [...]
11912     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11913       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11914         ++I;
11915       else {
11916         Matches[I] = Matches[--N];
11917         Matches.resize(N);
11918       }
11919     }
11920   }
11921 
11922   void EliminateSuboptimalCudaMatches() {
11923     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11924   }
11925 
11926 public:
11927   void ComplainNoMatchesFound() const {
11928     assert(Matches.empty());
11929     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11930         << OvlExpr->getName() << TargetFunctionType
11931         << OvlExpr->getSourceRange();
11932     if (FailedCandidates.empty())
11933       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11934                                   /*TakingAddress=*/true);
11935     else {
11936       // We have some deduction failure messages. Use them to diagnose
11937       // the function templates, and diagnose the non-template candidates
11938       // normally.
11939       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11940                                  IEnd = OvlExpr->decls_end();
11941            I != IEnd; ++I)
11942         if (FunctionDecl *Fun =
11943                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11944           if (!functionHasPassObjectSizeParams(Fun))
11945             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11946                                     /*TakingAddress=*/true);
11947       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11948     }
11949   }
11950 
11951   bool IsInvalidFormOfPointerToMemberFunction() const {
11952     return TargetTypeIsNonStaticMemberFunction &&
11953       !OvlExprInfo.HasFormOfMemberPointer;
11954   }
11955 
11956   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11957       // TODO: Should we condition this on whether any functions might
11958       // have matched, or is it more appropriate to do that in callers?
11959       // TODO: a fixit wouldn't hurt.
11960       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11961         << TargetType << OvlExpr->getSourceRange();
11962   }
11963 
11964   bool IsStaticMemberFunctionFromBoundPointer() const {
11965     return StaticMemberFunctionFromBoundPointer;
11966   }
11967 
11968   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11969     S.Diag(OvlExpr->getBeginLoc(),
11970            diag::err_invalid_form_pointer_member_function)
11971         << OvlExpr->getSourceRange();
11972   }
11973 
11974   void ComplainOfInvalidConversion() const {
11975     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11976         << OvlExpr->getName() << TargetType;
11977   }
11978 
11979   void ComplainMultipleMatchesFound() const {
11980     assert(Matches.size() > 1);
11981     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11982         << OvlExpr->getName() << OvlExpr->getSourceRange();
11983     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11984                                 /*TakingAddress=*/true);
11985   }
11986 
11987   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11988 
11989   int getNumMatches() const { return Matches.size(); }
11990 
11991   FunctionDecl* getMatchingFunctionDecl() const {
11992     if (Matches.size() != 1) return nullptr;
11993     return Matches[0].second;
11994   }
11995 
11996   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11997     if (Matches.size() != 1) return nullptr;
11998     return &Matches[0].first;
11999   }
12000 };
12001 }
12002 
12003 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
12004 /// an overloaded function (C++ [over.over]), where @p From is an
12005 /// expression with overloaded function type and @p ToType is the type
12006 /// we're trying to resolve to. For example:
12007 ///
12008 /// @code
12009 /// int f(double);
12010 /// int f(int);
12011 ///
12012 /// int (*pfd)(double) = f; // selects f(double)
12013 /// @endcode
12014 ///
12015 /// This routine returns the resulting FunctionDecl if it could be
12016 /// resolved, and NULL otherwise. When @p Complain is true, this
12017 /// routine will emit diagnostics if there is an error.
12018 FunctionDecl *
12019 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12020                                          QualType TargetType,
12021                                          bool Complain,
12022                                          DeclAccessPair &FoundResult,
12023                                          bool *pHadMultipleCandidates) {
12024   assert(AddressOfExpr->getType() == Context.OverloadTy);
12025 
12026   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12027                                      Complain);
12028   int NumMatches = Resolver.getNumMatches();
12029   FunctionDecl *Fn = nullptr;
12030   bool ShouldComplain = Complain && !Resolver.hasComplained();
12031   if (NumMatches == 0 && ShouldComplain) {
12032     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12033       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12034     else
12035       Resolver.ComplainNoMatchesFound();
12036   }
12037   else if (NumMatches > 1 && ShouldComplain)
12038     Resolver.ComplainMultipleMatchesFound();
12039   else if (NumMatches == 1) {
12040     Fn = Resolver.getMatchingFunctionDecl();
12041     assert(Fn);
12042     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12043       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12044     FoundResult = *Resolver.getMatchingFunctionAccessPair();
12045     if (Complain) {
12046       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12047         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12048       else
12049         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12050     }
12051   }
12052 
12053   if (pHadMultipleCandidates)
12054     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12055   return Fn;
12056 }
12057 
12058 /// Given an expression that refers to an overloaded function, try to
12059 /// resolve that function to a single function that can have its address taken.
12060 /// This will modify `Pair` iff it returns non-null.
12061 ///
12062 /// This routine can only succeed if from all of the candidates in the overload
12063 /// set for SrcExpr that can have their addresses taken, there is one candidate
12064 /// that is more constrained than the rest.
12065 FunctionDecl *
12066 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12067   OverloadExpr::FindResult R = OverloadExpr::find(E);
12068   OverloadExpr *Ovl = R.Expression;
12069   bool IsResultAmbiguous = false;
12070   FunctionDecl *Result = nullptr;
12071   DeclAccessPair DAP;
12072   SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12073 
12074   auto CheckMoreConstrained =
12075       [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12076         SmallVector<const Expr *, 1> AC1, AC2;
12077         FD1->getAssociatedConstraints(AC1);
12078         FD2->getAssociatedConstraints(AC2);
12079         bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12080         if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12081           return None;
12082         if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12083           return None;
12084         if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12085           return None;
12086         return AtLeastAsConstrained1;
12087       };
12088 
12089   // Don't use the AddressOfResolver because we're specifically looking for
12090   // cases where we have one overload candidate that lacks
12091   // enable_if/pass_object_size/...
12092   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12093     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12094     if (!FD)
12095       return nullptr;
12096 
12097     if (!checkAddressOfFunctionIsAvailable(FD))
12098       continue;
12099 
12100     // We have more than one result - see if it is more constrained than the
12101     // previous one.
12102     if (Result) {
12103       Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12104                                                                         Result);
12105       if (!MoreConstrainedThanPrevious) {
12106         IsResultAmbiguous = true;
12107         AmbiguousDecls.push_back(FD);
12108         continue;
12109       }
12110       if (!*MoreConstrainedThanPrevious)
12111         continue;
12112       // FD is more constrained - replace Result with it.
12113     }
12114     IsResultAmbiguous = false;
12115     DAP = I.getPair();
12116     Result = FD;
12117   }
12118 
12119   if (IsResultAmbiguous)
12120     return nullptr;
12121 
12122   if (Result) {
12123     SmallVector<const Expr *, 1> ResultAC;
12124     // We skipped over some ambiguous declarations which might be ambiguous with
12125     // the selected result.
12126     for (FunctionDecl *Skipped : AmbiguousDecls)
12127       if (!CheckMoreConstrained(Skipped, Result).hasValue())
12128         return nullptr;
12129     Pair = DAP;
12130   }
12131   return Result;
12132 }
12133 
12134 /// Given an overloaded function, tries to turn it into a non-overloaded
12135 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12136 /// will perform access checks, diagnose the use of the resultant decl, and, if
12137 /// requested, potentially perform a function-to-pointer decay.
12138 ///
12139 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12140 /// Otherwise, returns true. This may emit diagnostics and return true.
12141 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12142     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12143   Expr *E = SrcExpr.get();
12144   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12145 
12146   DeclAccessPair DAP;
12147   FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12148   if (!Found || Found->isCPUDispatchMultiVersion() ||
12149       Found->isCPUSpecificMultiVersion())
12150     return false;
12151 
12152   // Emitting multiple diagnostics for a function that is both inaccessible and
12153   // unavailable is consistent with our behavior elsewhere. So, always check
12154   // for both.
12155   DiagnoseUseOfDecl(Found, E->getExprLoc());
12156   CheckAddressOfMemberAccess(E, DAP);
12157   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12158   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12159     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12160   else
12161     SrcExpr = Fixed;
12162   return true;
12163 }
12164 
12165 /// Given an expression that refers to an overloaded function, try to
12166 /// resolve that overloaded function expression down to a single function.
12167 ///
12168 /// This routine can only resolve template-ids that refer to a single function
12169 /// template, where that template-id refers to a single template whose template
12170 /// arguments are either provided by the template-id or have defaults,
12171 /// as described in C++0x [temp.arg.explicit]p3.
12172 ///
12173 /// If no template-ids are found, no diagnostics are emitted and NULL is
12174 /// returned.
12175 FunctionDecl *
12176 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12177                                                   bool Complain,
12178                                                   DeclAccessPair *FoundResult) {
12179   // C++ [over.over]p1:
12180   //   [...] [Note: any redundant set of parentheses surrounding the
12181   //   overloaded function name is ignored (5.1). ]
12182   // C++ [over.over]p1:
12183   //   [...] The overloaded function name can be preceded by the &
12184   //   operator.
12185 
12186   // If we didn't actually find any template-ids, we're done.
12187   if (!ovl->hasExplicitTemplateArgs())
12188     return nullptr;
12189 
12190   TemplateArgumentListInfo ExplicitTemplateArgs;
12191   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12192   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12193 
12194   // Look through all of the overloaded functions, searching for one
12195   // whose type matches exactly.
12196   FunctionDecl *Matched = nullptr;
12197   for (UnresolvedSetIterator I = ovl->decls_begin(),
12198          E = ovl->decls_end(); I != E; ++I) {
12199     // C++0x [temp.arg.explicit]p3:
12200     //   [...] In contexts where deduction is done and fails, or in contexts
12201     //   where deduction is not done, if a template argument list is
12202     //   specified and it, along with any default template arguments,
12203     //   identifies a single function template specialization, then the
12204     //   template-id is an lvalue for the function template specialization.
12205     FunctionTemplateDecl *FunctionTemplate
12206       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12207 
12208     // C++ [over.over]p2:
12209     //   If the name is a function template, template argument deduction is
12210     //   done (14.8.2.2), and if the argument deduction succeeds, the
12211     //   resulting template argument list is used to generate a single
12212     //   function template specialization, which is added to the set of
12213     //   overloaded functions considered.
12214     FunctionDecl *Specialization = nullptr;
12215     TemplateDeductionInfo Info(FailedCandidates.getLocation());
12216     if (TemplateDeductionResult Result
12217           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12218                                     Specialization, Info,
12219                                     /*IsAddressOfFunction*/true)) {
12220       // Make a note of the failed deduction for diagnostics.
12221       // TODO: Actually use the failed-deduction info?
12222       FailedCandidates.addCandidate()
12223           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12224                MakeDeductionFailureInfo(Context, Result, Info));
12225       continue;
12226     }
12227 
12228     assert(Specialization && "no specialization and no error?");
12229 
12230     // Multiple matches; we can't resolve to a single declaration.
12231     if (Matched) {
12232       if (Complain) {
12233         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12234           << ovl->getName();
12235         NoteAllOverloadCandidates(ovl);
12236       }
12237       return nullptr;
12238     }
12239 
12240     Matched = Specialization;
12241     if (FoundResult) *FoundResult = I.getPair();
12242   }
12243 
12244   if (Matched &&
12245       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12246     return nullptr;
12247 
12248   return Matched;
12249 }
12250 
12251 // Resolve and fix an overloaded expression that can be resolved
12252 // because it identifies a single function template specialization.
12253 //
12254 // Last three arguments should only be supplied if Complain = true
12255 //
12256 // Return true if it was logically possible to so resolve the
12257 // expression, regardless of whether or not it succeeded.  Always
12258 // returns true if 'complain' is set.
12259 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12260                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
12261                       bool complain, SourceRange OpRangeForComplaining,
12262                                            QualType DestTypeForComplaining,
12263                                             unsigned DiagIDForComplaining) {
12264   assert(SrcExpr.get()->getType() == Context.OverloadTy);
12265 
12266   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12267 
12268   DeclAccessPair found;
12269   ExprResult SingleFunctionExpression;
12270   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12271                            ovl.Expression, /*complain*/ false, &found)) {
12272     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12273       SrcExpr = ExprError();
12274       return true;
12275     }
12276 
12277     // It is only correct to resolve to an instance method if we're
12278     // resolving a form that's permitted to be a pointer to member.
12279     // Otherwise we'll end up making a bound member expression, which
12280     // is illegal in all the contexts we resolve like this.
12281     if (!ovl.HasFormOfMemberPointer &&
12282         isa<CXXMethodDecl>(fn) &&
12283         cast<CXXMethodDecl>(fn)->isInstance()) {
12284       if (!complain) return false;
12285 
12286       Diag(ovl.Expression->getExprLoc(),
12287            diag::err_bound_member_function)
12288         << 0 << ovl.Expression->getSourceRange();
12289 
12290       // TODO: I believe we only end up here if there's a mix of
12291       // static and non-static candidates (otherwise the expression
12292       // would have 'bound member' type, not 'overload' type).
12293       // Ideally we would note which candidate was chosen and why
12294       // the static candidates were rejected.
12295       SrcExpr = ExprError();
12296       return true;
12297     }
12298 
12299     // Fix the expression to refer to 'fn'.
12300     SingleFunctionExpression =
12301         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12302 
12303     // If desired, do function-to-pointer decay.
12304     if (doFunctionPointerConverion) {
12305       SingleFunctionExpression =
12306         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12307       if (SingleFunctionExpression.isInvalid()) {
12308         SrcExpr = ExprError();
12309         return true;
12310       }
12311     }
12312   }
12313 
12314   if (!SingleFunctionExpression.isUsable()) {
12315     if (complain) {
12316       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12317         << ovl.Expression->getName()
12318         << DestTypeForComplaining
12319         << OpRangeForComplaining
12320         << ovl.Expression->getQualifierLoc().getSourceRange();
12321       NoteAllOverloadCandidates(SrcExpr.get());
12322 
12323       SrcExpr = ExprError();
12324       return true;
12325     }
12326 
12327     return false;
12328   }
12329 
12330   SrcExpr = SingleFunctionExpression;
12331   return true;
12332 }
12333 
12334 /// Add a single candidate to the overload set.
12335 static void AddOverloadedCallCandidate(Sema &S,
12336                                        DeclAccessPair FoundDecl,
12337                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12338                                        ArrayRef<Expr *> Args,
12339                                        OverloadCandidateSet &CandidateSet,
12340                                        bool PartialOverloading,
12341                                        bool KnownValid) {
12342   NamedDecl *Callee = FoundDecl.getDecl();
12343   if (isa<UsingShadowDecl>(Callee))
12344     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12345 
12346   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12347     if (ExplicitTemplateArgs) {
12348       assert(!KnownValid && "Explicit template arguments?");
12349       return;
12350     }
12351     // Prevent ill-formed function decls to be added as overload candidates.
12352     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12353       return;
12354 
12355     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12356                            /*SuppressUserConversions=*/false,
12357                            PartialOverloading);
12358     return;
12359   }
12360 
12361   if (FunctionTemplateDecl *FuncTemplate
12362       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12363     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12364                                    ExplicitTemplateArgs, Args, CandidateSet,
12365                                    /*SuppressUserConversions=*/false,
12366                                    PartialOverloading);
12367     return;
12368   }
12369 
12370   assert(!KnownValid && "unhandled case in overloaded call candidate");
12371 }
12372 
12373 /// Add the overload candidates named by callee and/or found by argument
12374 /// dependent lookup to the given overload set.
12375 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12376                                        ArrayRef<Expr *> Args,
12377                                        OverloadCandidateSet &CandidateSet,
12378                                        bool PartialOverloading) {
12379 
12380 #ifndef NDEBUG
12381   // Verify that ArgumentDependentLookup is consistent with the rules
12382   // in C++0x [basic.lookup.argdep]p3:
12383   //
12384   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12385   //   and let Y be the lookup set produced by argument dependent
12386   //   lookup (defined as follows). If X contains
12387   //
12388   //     -- a declaration of a class member, or
12389   //
12390   //     -- a block-scope function declaration that is not a
12391   //        using-declaration, or
12392   //
12393   //     -- a declaration that is neither a function or a function
12394   //        template
12395   //
12396   //   then Y is empty.
12397 
12398   if (ULE->requiresADL()) {
12399     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12400            E = ULE->decls_end(); I != E; ++I) {
12401       assert(!(*I)->getDeclContext()->isRecord());
12402       assert(isa<UsingShadowDecl>(*I) ||
12403              !(*I)->getDeclContext()->isFunctionOrMethod());
12404       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12405     }
12406   }
12407 #endif
12408 
12409   // It would be nice to avoid this copy.
12410   TemplateArgumentListInfo TABuffer;
12411   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12412   if (ULE->hasExplicitTemplateArgs()) {
12413     ULE->copyTemplateArgumentsInto(TABuffer);
12414     ExplicitTemplateArgs = &TABuffer;
12415   }
12416 
12417   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12418          E = ULE->decls_end(); I != E; ++I)
12419     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12420                                CandidateSet, PartialOverloading,
12421                                /*KnownValid*/ true);
12422 
12423   if (ULE->requiresADL())
12424     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12425                                          Args, ExplicitTemplateArgs,
12426                                          CandidateSet, PartialOverloading);
12427 }
12428 
12429 /// Determine whether a declaration with the specified name could be moved into
12430 /// a different namespace.
12431 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12432   switch (Name.getCXXOverloadedOperator()) {
12433   case OO_New: case OO_Array_New:
12434   case OO_Delete: case OO_Array_Delete:
12435     return false;
12436 
12437   default:
12438     return true;
12439   }
12440 }
12441 
12442 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12443 /// template, where the non-dependent name was declared after the template
12444 /// was defined. This is common in code written for a compilers which do not
12445 /// correctly implement two-stage name lookup.
12446 ///
12447 /// Returns true if a viable candidate was found and a diagnostic was issued.
12448 static bool
12449 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12450                        const CXXScopeSpec &SS, LookupResult &R,
12451                        OverloadCandidateSet::CandidateSetKind CSK,
12452                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12453                        ArrayRef<Expr *> Args,
12454                        bool *DoDiagnoseEmptyLookup = nullptr) {
12455   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12456     return false;
12457 
12458   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12459     if (DC->isTransparentContext())
12460       continue;
12461 
12462     SemaRef.LookupQualifiedName(R, DC);
12463 
12464     if (!R.empty()) {
12465       R.suppressDiagnostics();
12466 
12467       if (isa<CXXRecordDecl>(DC)) {
12468         // Don't diagnose names we find in classes; we get much better
12469         // diagnostics for these from DiagnoseEmptyLookup.
12470         R.clear();
12471         if (DoDiagnoseEmptyLookup)
12472           *DoDiagnoseEmptyLookup = true;
12473         return false;
12474       }
12475 
12476       OverloadCandidateSet Candidates(FnLoc, CSK);
12477       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12478         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12479                                    ExplicitTemplateArgs, Args,
12480                                    Candidates, false, /*KnownValid*/ false);
12481 
12482       OverloadCandidateSet::iterator Best;
12483       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12484         // No viable functions. Don't bother the user with notes for functions
12485         // which don't work and shouldn't be found anyway.
12486         R.clear();
12487         return false;
12488       }
12489 
12490       // Find the namespaces where ADL would have looked, and suggest
12491       // declaring the function there instead.
12492       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12493       Sema::AssociatedClassSet AssociatedClasses;
12494       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12495                                                  AssociatedNamespaces,
12496                                                  AssociatedClasses);
12497       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12498       if (canBeDeclaredInNamespace(R.getLookupName())) {
12499         DeclContext *Std = SemaRef.getStdNamespace();
12500         for (Sema::AssociatedNamespaceSet::iterator
12501                it = AssociatedNamespaces.begin(),
12502                end = AssociatedNamespaces.end(); it != end; ++it) {
12503           // Never suggest declaring a function within namespace 'std'.
12504           if (Std && Std->Encloses(*it))
12505             continue;
12506 
12507           // Never suggest declaring a function within a namespace with a
12508           // reserved name, like __gnu_cxx.
12509           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12510           if (NS &&
12511               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12512             continue;
12513 
12514           SuggestedNamespaces.insert(*it);
12515         }
12516       }
12517 
12518       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12519         << R.getLookupName();
12520       if (SuggestedNamespaces.empty()) {
12521         SemaRef.Diag(Best->Function->getLocation(),
12522                      diag::note_not_found_by_two_phase_lookup)
12523           << R.getLookupName() << 0;
12524       } else if (SuggestedNamespaces.size() == 1) {
12525         SemaRef.Diag(Best->Function->getLocation(),
12526                      diag::note_not_found_by_two_phase_lookup)
12527           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12528       } else {
12529         // FIXME: It would be useful to list the associated namespaces here,
12530         // but the diagnostics infrastructure doesn't provide a way to produce
12531         // a localized representation of a list of items.
12532         SemaRef.Diag(Best->Function->getLocation(),
12533                      diag::note_not_found_by_two_phase_lookup)
12534           << R.getLookupName() << 2;
12535       }
12536 
12537       // Try to recover by calling this function.
12538       return true;
12539     }
12540 
12541     R.clear();
12542   }
12543 
12544   return false;
12545 }
12546 
12547 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12548 /// template, where the non-dependent operator was declared after the template
12549 /// was defined.
12550 ///
12551 /// Returns true if a viable candidate was found and a diagnostic was issued.
12552 static bool
12553 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12554                                SourceLocation OpLoc,
12555                                ArrayRef<Expr *> Args) {
12556   DeclarationName OpName =
12557     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12558   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12559   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12560                                 OverloadCandidateSet::CSK_Operator,
12561                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12562 }
12563 
12564 namespace {
12565 class BuildRecoveryCallExprRAII {
12566   Sema &SemaRef;
12567 public:
12568   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12569     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12570     SemaRef.IsBuildingRecoveryCallExpr = true;
12571   }
12572 
12573   ~BuildRecoveryCallExprRAII() {
12574     SemaRef.IsBuildingRecoveryCallExpr = false;
12575   }
12576 };
12577 
12578 }
12579 
12580 /// Attempts to recover from a call where no functions were found.
12581 ///
12582 /// Returns true if new candidates were found.
12583 static ExprResult
12584 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12585                       UnresolvedLookupExpr *ULE,
12586                       SourceLocation LParenLoc,
12587                       MutableArrayRef<Expr *> Args,
12588                       SourceLocation RParenLoc,
12589                       bool EmptyLookup, bool AllowTypoCorrection) {
12590   // Do not try to recover if it is already building a recovery call.
12591   // This stops infinite loops for template instantiations like
12592   //
12593   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12594   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12595   //
12596   if (SemaRef.IsBuildingRecoveryCallExpr)
12597     return ExprError();
12598   BuildRecoveryCallExprRAII RCE(SemaRef);
12599 
12600   CXXScopeSpec SS;
12601   SS.Adopt(ULE->getQualifierLoc());
12602   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12603 
12604   TemplateArgumentListInfo TABuffer;
12605   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12606   if (ULE->hasExplicitTemplateArgs()) {
12607     ULE->copyTemplateArgumentsInto(TABuffer);
12608     ExplicitTemplateArgs = &TABuffer;
12609   }
12610 
12611   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12612                  Sema::LookupOrdinaryName);
12613   bool DoDiagnoseEmptyLookup = EmptyLookup;
12614   if (!DiagnoseTwoPhaseLookup(
12615           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12616           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12617     NoTypoCorrectionCCC NoTypoValidator{};
12618     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12619                                                 ExplicitTemplateArgs != nullptr,
12620                                                 dyn_cast<MemberExpr>(Fn));
12621     CorrectionCandidateCallback &Validator =
12622         AllowTypoCorrection
12623             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12624             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12625     if (!DoDiagnoseEmptyLookup ||
12626         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12627                                     Args))
12628       return ExprError();
12629   }
12630 
12631   assert(!R.empty() && "lookup results empty despite recovery");
12632 
12633   // If recovery created an ambiguity, just bail out.
12634   if (R.isAmbiguous()) {
12635     R.suppressDiagnostics();
12636     return ExprError();
12637   }
12638 
12639   // Build an implicit member call if appropriate.  Just drop the
12640   // casts and such from the call, we don't really care.
12641   ExprResult NewFn = ExprError();
12642   if ((*R.begin())->isCXXClassMember())
12643     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12644                                                     ExplicitTemplateArgs, S);
12645   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12646     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12647                                         ExplicitTemplateArgs);
12648   else
12649     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12650 
12651   if (NewFn.isInvalid())
12652     return ExprError();
12653 
12654   // This shouldn't cause an infinite loop because we're giving it
12655   // an expression with viable lookup results, which should never
12656   // end up here.
12657   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12658                                MultiExprArg(Args.data(), Args.size()),
12659                                RParenLoc);
12660 }
12661 
12662 /// Constructs and populates an OverloadedCandidateSet from
12663 /// the given function.
12664 /// \returns true when an the ExprResult output parameter has been set.
12665 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12666                                   UnresolvedLookupExpr *ULE,
12667                                   MultiExprArg Args,
12668                                   SourceLocation RParenLoc,
12669                                   OverloadCandidateSet *CandidateSet,
12670                                   ExprResult *Result) {
12671 #ifndef NDEBUG
12672   if (ULE->requiresADL()) {
12673     // To do ADL, we must have found an unqualified name.
12674     assert(!ULE->getQualifier() && "qualified name with ADL");
12675 
12676     // We don't perform ADL for implicit declarations of builtins.
12677     // Verify that this was correctly set up.
12678     FunctionDecl *F;
12679     if (ULE->decls_begin() != ULE->decls_end() &&
12680         ULE->decls_begin() + 1 == ULE->decls_end() &&
12681         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12682         F->getBuiltinID() && F->isImplicit())
12683       llvm_unreachable("performing ADL for builtin");
12684 
12685     // We don't perform ADL in C.
12686     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12687   }
12688 #endif
12689 
12690   UnbridgedCastsSet UnbridgedCasts;
12691   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12692     *Result = ExprError();
12693     return true;
12694   }
12695 
12696   // Add the functions denoted by the callee to the set of candidate
12697   // functions, including those from argument-dependent lookup.
12698   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12699 
12700   if (getLangOpts().MSVCCompat &&
12701       CurContext->isDependentContext() && !isSFINAEContext() &&
12702       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12703 
12704     OverloadCandidateSet::iterator Best;
12705     if (CandidateSet->empty() ||
12706         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12707             OR_No_Viable_Function) {
12708       // In Microsoft mode, if we are inside a template class member function
12709       // then create a type dependent CallExpr. The goal is to postpone name
12710       // lookup to instantiation time to be able to search into type dependent
12711       // base classes.
12712       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12713                                       VK_RValue, RParenLoc);
12714       CE->setTypeDependent(true);
12715       CE->setValueDependent(true);
12716       CE->setInstantiationDependent(true);
12717       *Result = CE;
12718       return true;
12719     }
12720   }
12721 
12722   if (CandidateSet->empty())
12723     return false;
12724 
12725   UnbridgedCasts.restore();
12726   return false;
12727 }
12728 
12729 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12730 /// the completed call expression. If overload resolution fails, emits
12731 /// diagnostics and returns ExprError()
12732 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12733                                            UnresolvedLookupExpr *ULE,
12734                                            SourceLocation LParenLoc,
12735                                            MultiExprArg Args,
12736                                            SourceLocation RParenLoc,
12737                                            Expr *ExecConfig,
12738                                            OverloadCandidateSet *CandidateSet,
12739                                            OverloadCandidateSet::iterator *Best,
12740                                            OverloadingResult OverloadResult,
12741                                            bool AllowTypoCorrection) {
12742   if (CandidateSet->empty())
12743     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12744                                  RParenLoc, /*EmptyLookup=*/true,
12745                                  AllowTypoCorrection);
12746 
12747   switch (OverloadResult) {
12748   case OR_Success: {
12749     FunctionDecl *FDecl = (*Best)->Function;
12750     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12751     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12752       return ExprError();
12753     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12754     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12755                                          ExecConfig, /*IsExecConfig=*/false,
12756                                          (*Best)->IsADLCandidate);
12757   }
12758 
12759   case OR_No_Viable_Function: {
12760     // Try to recover by looking for viable functions which the user might
12761     // have meant to call.
12762     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12763                                                 Args, RParenLoc,
12764                                                 /*EmptyLookup=*/false,
12765                                                 AllowTypoCorrection);
12766     if (!Recovery.isInvalid())
12767       return Recovery;
12768 
12769     // If the user passes in a function that we can't take the address of, we
12770     // generally end up emitting really bad error messages. Here, we attempt to
12771     // emit better ones.
12772     for (const Expr *Arg : Args) {
12773       if (!Arg->getType()->isFunctionType())
12774         continue;
12775       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12776         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12777         if (FD &&
12778             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12779                                                        Arg->getExprLoc()))
12780           return ExprError();
12781       }
12782     }
12783 
12784     CandidateSet->NoteCandidates(
12785         PartialDiagnosticAt(
12786             Fn->getBeginLoc(),
12787             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12788                 << ULE->getName() << Fn->getSourceRange()),
12789         SemaRef, OCD_AllCandidates, Args);
12790     break;
12791   }
12792 
12793   case OR_Ambiguous:
12794     CandidateSet->NoteCandidates(
12795         PartialDiagnosticAt(Fn->getBeginLoc(),
12796                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12797                                 << ULE->getName() << Fn->getSourceRange()),
12798         SemaRef, OCD_AmbiguousCandidates, Args);
12799     break;
12800 
12801   case OR_Deleted: {
12802     CandidateSet->NoteCandidates(
12803         PartialDiagnosticAt(Fn->getBeginLoc(),
12804                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12805                                 << ULE->getName() << Fn->getSourceRange()),
12806         SemaRef, OCD_AllCandidates, Args);
12807 
12808     // We emitted an error for the unavailable/deleted function call but keep
12809     // the call in the AST.
12810     FunctionDecl *FDecl = (*Best)->Function;
12811     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12812     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12813                                          ExecConfig, /*IsExecConfig=*/false,
12814                                          (*Best)->IsADLCandidate);
12815   }
12816   }
12817 
12818   // Overload resolution failed.
12819   return ExprError();
12820 }
12821 
12822 static void markUnaddressableCandidatesUnviable(Sema &S,
12823                                                 OverloadCandidateSet &CS) {
12824   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12825     if (I->Viable &&
12826         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12827       I->Viable = false;
12828       I->FailureKind = ovl_fail_addr_not_available;
12829     }
12830   }
12831 }
12832 
12833 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12834 /// (which eventually refers to the declaration Func) and the call
12835 /// arguments Args/NumArgs, attempt to resolve the function call down
12836 /// to a specific function. If overload resolution succeeds, returns
12837 /// the call expression produced by overload resolution.
12838 /// Otherwise, emits diagnostics and returns ExprError.
12839 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12840                                          UnresolvedLookupExpr *ULE,
12841                                          SourceLocation LParenLoc,
12842                                          MultiExprArg Args,
12843                                          SourceLocation RParenLoc,
12844                                          Expr *ExecConfig,
12845                                          bool AllowTypoCorrection,
12846                                          bool CalleesAddressIsTaken) {
12847   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12848                                     OverloadCandidateSet::CSK_Normal);
12849   ExprResult result;
12850 
12851   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12852                              &result))
12853     return result;
12854 
12855   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12856   // functions that aren't addressible are considered unviable.
12857   if (CalleesAddressIsTaken)
12858     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12859 
12860   OverloadCandidateSet::iterator Best;
12861   OverloadingResult OverloadResult =
12862       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12863 
12864   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12865                                   ExecConfig, &CandidateSet, &Best,
12866                                   OverloadResult, AllowTypoCorrection);
12867 }
12868 
12869 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12870   return Functions.size() > 1 ||
12871     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12872 }
12873 
12874 /// Create a unary operation that may resolve to an overloaded
12875 /// operator.
12876 ///
12877 /// \param OpLoc The location of the operator itself (e.g., '*').
12878 ///
12879 /// \param Opc The UnaryOperatorKind that describes this operator.
12880 ///
12881 /// \param Fns The set of non-member functions that will be
12882 /// considered by overload resolution. The caller needs to build this
12883 /// set based on the context using, e.g.,
12884 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12885 /// set should not contain any member functions; those will be added
12886 /// by CreateOverloadedUnaryOp().
12887 ///
12888 /// \param Input The input argument.
12889 ExprResult
12890 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12891                               const UnresolvedSetImpl &Fns,
12892                               Expr *Input, bool PerformADL) {
12893   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12894   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12895   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12896   // TODO: provide better source location info.
12897   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12898 
12899   if (checkPlaceholderForOverload(*this, Input))
12900     return ExprError();
12901 
12902   Expr *Args[2] = { Input, nullptr };
12903   unsigned NumArgs = 1;
12904 
12905   // For post-increment and post-decrement, add the implicit '0' as
12906   // the second argument, so that we know this is a post-increment or
12907   // post-decrement.
12908   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12909     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12910     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12911                                      SourceLocation());
12912     NumArgs = 2;
12913   }
12914 
12915   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12916 
12917   if (Input->isTypeDependent()) {
12918     if (Fns.empty())
12919       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12920                                          VK_RValue, OK_Ordinary, OpLoc, false);
12921 
12922     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12923     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12924         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12925         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12926     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12927                                        Context.DependentTy, VK_RValue, OpLoc,
12928                                        FPOptions());
12929   }
12930 
12931   // Build an empty overload set.
12932   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12933 
12934   // Add the candidates from the given function set.
12935   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12936 
12937   // Add operator candidates that are member functions.
12938   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12939 
12940   // Add candidates from ADL.
12941   if (PerformADL) {
12942     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12943                                          /*ExplicitTemplateArgs*/nullptr,
12944                                          CandidateSet);
12945   }
12946 
12947   // Add builtin operator candidates.
12948   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12949 
12950   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12951 
12952   // Perform overload resolution.
12953   OverloadCandidateSet::iterator Best;
12954   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12955   case OR_Success: {
12956     // We found a built-in operator or an overloaded operator.
12957     FunctionDecl *FnDecl = Best->Function;
12958 
12959     if (FnDecl) {
12960       Expr *Base = nullptr;
12961       // We matched an overloaded operator. Build a call to that
12962       // operator.
12963 
12964       // Convert the arguments.
12965       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12966         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12967 
12968         ExprResult InputRes =
12969           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12970                                               Best->FoundDecl, Method);
12971         if (InputRes.isInvalid())
12972           return ExprError();
12973         Base = Input = InputRes.get();
12974       } else {
12975         // Convert the arguments.
12976         ExprResult InputInit
12977           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12978                                                       Context,
12979                                                       FnDecl->getParamDecl(0)),
12980                                       SourceLocation(),
12981                                       Input);
12982         if (InputInit.isInvalid())
12983           return ExprError();
12984         Input = InputInit.get();
12985       }
12986 
12987       // Build the actual expression node.
12988       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12989                                                 Base, HadMultipleCandidates,
12990                                                 OpLoc);
12991       if (FnExpr.isInvalid())
12992         return ExprError();
12993 
12994       // Determine the result type.
12995       QualType ResultTy = FnDecl->getReturnType();
12996       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12997       ResultTy = ResultTy.getNonLValueExprType(Context);
12998 
12999       Args[0] = Input;
13000       CallExpr *TheCall = CXXOperatorCallExpr::Create(
13001           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
13002           FPOptions(), Best->IsADLCandidate);
13003 
13004       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
13005         return ExprError();
13006 
13007       if (CheckFunctionCall(FnDecl, TheCall,
13008                             FnDecl->getType()->castAs<FunctionProtoType>()))
13009         return ExprError();
13010       return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
13011     } else {
13012       // We matched a built-in operator. Convert the arguments, then
13013       // break out so that we will build the appropriate built-in
13014       // operator node.
13015       ExprResult InputRes = PerformImplicitConversion(
13016           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13017           CCK_ForBuiltinOverloadedOp);
13018       if (InputRes.isInvalid())
13019         return ExprError();
13020       Input = InputRes.get();
13021       break;
13022     }
13023   }
13024 
13025   case OR_No_Viable_Function:
13026     // This is an erroneous use of an operator which can be overloaded by
13027     // a non-member function. Check for non-member operators which were
13028     // defined too late to be candidates.
13029     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13030       // FIXME: Recover by calling the found function.
13031       return ExprError();
13032 
13033     // No viable function; fall through to handling this as a
13034     // built-in operator, which will produce an error message for us.
13035     break;
13036 
13037   case OR_Ambiguous:
13038     CandidateSet.NoteCandidates(
13039         PartialDiagnosticAt(OpLoc,
13040                             PDiag(diag::err_ovl_ambiguous_oper_unary)
13041                                 << UnaryOperator::getOpcodeStr(Opc)
13042                                 << Input->getType() << Input->getSourceRange()),
13043         *this, OCD_AmbiguousCandidates, ArgsArray,
13044         UnaryOperator::getOpcodeStr(Opc), OpLoc);
13045     return ExprError();
13046 
13047   case OR_Deleted:
13048     CandidateSet.NoteCandidates(
13049         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13050                                        << UnaryOperator::getOpcodeStr(Opc)
13051                                        << Input->getSourceRange()),
13052         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13053         OpLoc);
13054     return ExprError();
13055   }
13056 
13057   // Either we found no viable overloaded operator or we matched a
13058   // built-in operator. In either case, fall through to trying to
13059   // build a built-in operation.
13060   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13061 }
13062 
13063 /// Perform lookup for an overloaded binary operator.
13064 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13065                                  OverloadedOperatorKind Op,
13066                                  const UnresolvedSetImpl &Fns,
13067                                  ArrayRef<Expr *> Args, bool PerformADL) {
13068   SourceLocation OpLoc = CandidateSet.getLocation();
13069 
13070   OverloadedOperatorKind ExtraOp =
13071       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13072           ? getRewrittenOverloadedOperator(Op)
13073           : OO_None;
13074 
13075   // Add the candidates from the given function set. This also adds the
13076   // rewritten candidates using these functions if necessary.
13077   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13078 
13079   // Add operator candidates that are member functions.
13080   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13081   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13082     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13083                                 OverloadCandidateParamOrder::Reversed);
13084 
13085   // In C++20, also add any rewritten member candidates.
13086   if (ExtraOp) {
13087     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13088     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13089       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13090                                   CandidateSet,
13091                                   OverloadCandidateParamOrder::Reversed);
13092   }
13093 
13094   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13095   // performed for an assignment operator (nor for operator[] nor operator->,
13096   // which don't get here).
13097   if (Op != OO_Equal && PerformADL) {
13098     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13099     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13100                                          /*ExplicitTemplateArgs*/ nullptr,
13101                                          CandidateSet);
13102     if (ExtraOp) {
13103       DeclarationName ExtraOpName =
13104           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13105       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13106                                            /*ExplicitTemplateArgs*/ nullptr,
13107                                            CandidateSet);
13108     }
13109   }
13110 
13111   // Add builtin operator candidates.
13112   //
13113   // FIXME: We don't add any rewritten candidates here. This is strictly
13114   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13115   // resulting in our selecting a rewritten builtin candidate. For example:
13116   //
13117   //   enum class E { e };
13118   //   bool operator!=(E, E) requires false;
13119   //   bool k = E::e != E::e;
13120   //
13121   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13122   // it seems unreasonable to consider rewritten builtin candidates. A core
13123   // issue has been filed proposing to removed this requirement.
13124   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13125 }
13126 
13127 /// Create a binary operation that may resolve to an overloaded
13128 /// operator.
13129 ///
13130 /// \param OpLoc The location of the operator itself (e.g., '+').
13131 ///
13132 /// \param Opc The BinaryOperatorKind that describes this operator.
13133 ///
13134 /// \param Fns The set of non-member functions that will be
13135 /// considered by overload resolution. The caller needs to build this
13136 /// set based on the context using, e.g.,
13137 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13138 /// set should not contain any member functions; those will be added
13139 /// by CreateOverloadedBinOp().
13140 ///
13141 /// \param LHS Left-hand argument.
13142 /// \param RHS Right-hand argument.
13143 /// \param PerformADL Whether to consider operator candidates found by ADL.
13144 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13145 ///        C++20 operator rewrites.
13146 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13147 ///        the function in question. Such a function is never a candidate in
13148 ///        our overload resolution. This also enables synthesizing a three-way
13149 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
13150 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13151                                        BinaryOperatorKind Opc,
13152                                        const UnresolvedSetImpl &Fns, Expr *LHS,
13153                                        Expr *RHS, bool PerformADL,
13154                                        bool AllowRewrittenCandidates,
13155                                        FunctionDecl *DefaultedFn) {
13156   Expr *Args[2] = { LHS, RHS };
13157   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13158 
13159   if (!getLangOpts().CPlusPlus2a)
13160     AllowRewrittenCandidates = false;
13161 
13162   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13163 
13164   // If either side is type-dependent, create an appropriate dependent
13165   // expression.
13166   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13167     if (Fns.empty()) {
13168       // If there are no functions to store, just build a dependent
13169       // BinaryOperator or CompoundAssignment.
13170       if (Opc <= BO_Assign || Opc > BO_OrAssign)
13171         return new (Context) BinaryOperator(
13172             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13173             OpLoc, FPFeatures);
13174 
13175       return new (Context) CompoundAssignOperator(
13176           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13177           Context.DependentTy, Context.DependentTy, OpLoc,
13178           FPFeatures);
13179     }
13180 
13181     // FIXME: save results of ADL from here?
13182     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13183     // TODO: provide better source location info in DNLoc component.
13184     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13185     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13186     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13187         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13188         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13189     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13190                                        Context.DependentTy, VK_RValue, OpLoc,
13191                                        FPFeatures);
13192   }
13193 
13194   // Always do placeholder-like conversions on the RHS.
13195   if (checkPlaceholderForOverload(*this, Args[1]))
13196     return ExprError();
13197 
13198   // Do placeholder-like conversion on the LHS; note that we should
13199   // not get here with a PseudoObject LHS.
13200   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13201   if (checkPlaceholderForOverload(*this, Args[0]))
13202     return ExprError();
13203 
13204   // If this is the assignment operator, we only perform overload resolution
13205   // if the left-hand side is a class or enumeration type. This is actually
13206   // a hack. The standard requires that we do overload resolution between the
13207   // various built-in candidates, but as DR507 points out, this can lead to
13208   // problems. So we do it this way, which pretty much follows what GCC does.
13209   // Note that we go the traditional code path for compound assignment forms.
13210   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13211     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13212 
13213   // If this is the .* operator, which is not overloadable, just
13214   // create a built-in binary operator.
13215   if (Opc == BO_PtrMemD)
13216     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13217 
13218   // Build the overload set.
13219   OverloadCandidateSet CandidateSet(
13220       OpLoc, OverloadCandidateSet::CSK_Operator,
13221       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13222   if (DefaultedFn)
13223     CandidateSet.exclude(DefaultedFn);
13224   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13225 
13226   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13227 
13228   // Perform overload resolution.
13229   OverloadCandidateSet::iterator Best;
13230   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13231     case OR_Success: {
13232       // We found a built-in operator or an overloaded operator.
13233       FunctionDecl *FnDecl = Best->Function;
13234 
13235       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13236       if (IsReversed)
13237         std::swap(Args[0], Args[1]);
13238 
13239       if (FnDecl) {
13240         Expr *Base = nullptr;
13241         // We matched an overloaded operator. Build a call to that
13242         // operator.
13243 
13244         OverloadedOperatorKind ChosenOp =
13245             FnDecl->getDeclName().getCXXOverloadedOperator();
13246 
13247         // C++2a [over.match.oper]p9:
13248         //   If a rewritten operator== candidate is selected by overload
13249         //   resolution for an operator@, its return type shall be cv bool
13250         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13251             !FnDecl->getReturnType()->isBooleanType()) {
13252           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13253               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13254               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13255           Diag(FnDecl->getLocation(), diag::note_declared_at);
13256           return ExprError();
13257         }
13258 
13259         if (AllowRewrittenCandidates && !IsReversed &&
13260             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13261           // We could have reversed this operator, but didn't. Check if the
13262           // reversed form was a viable candidate, and if so, if it had a
13263           // better conversion for either parameter. If so, this call is
13264           // formally ambiguous, and allowing it is an extension.
13265           for (OverloadCandidate &Cand : CandidateSet) {
13266             if (Cand.Viable && Cand.Function == FnDecl &&
13267                 Cand.RewriteKind & CRK_Reversed) {
13268               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13269                 if (CompareImplicitConversionSequences(
13270                         *this, OpLoc, Cand.Conversions[ArgIdx],
13271                         Best->Conversions[ArgIdx]) ==
13272                     ImplicitConversionSequence::Better) {
13273                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13274                       << BinaryOperator::getOpcodeStr(Opc)
13275                       << Args[0]->getType() << Args[1]->getType()
13276                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13277                   Diag(FnDecl->getLocation(),
13278                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13279                 }
13280               }
13281               break;
13282             }
13283           }
13284         }
13285 
13286         // Convert the arguments.
13287         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13288           // Best->Access is only meaningful for class members.
13289           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13290 
13291           ExprResult Arg1 =
13292             PerformCopyInitialization(
13293               InitializedEntity::InitializeParameter(Context,
13294                                                      FnDecl->getParamDecl(0)),
13295               SourceLocation(), Args[1]);
13296           if (Arg1.isInvalid())
13297             return ExprError();
13298 
13299           ExprResult Arg0 =
13300             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13301                                                 Best->FoundDecl, Method);
13302           if (Arg0.isInvalid())
13303             return ExprError();
13304           Base = Args[0] = Arg0.getAs<Expr>();
13305           Args[1] = RHS = Arg1.getAs<Expr>();
13306         } else {
13307           // Convert the arguments.
13308           ExprResult Arg0 = PerformCopyInitialization(
13309             InitializedEntity::InitializeParameter(Context,
13310                                                    FnDecl->getParamDecl(0)),
13311             SourceLocation(), Args[0]);
13312           if (Arg0.isInvalid())
13313             return ExprError();
13314 
13315           ExprResult Arg1 =
13316             PerformCopyInitialization(
13317               InitializedEntity::InitializeParameter(Context,
13318                                                      FnDecl->getParamDecl(1)),
13319               SourceLocation(), Args[1]);
13320           if (Arg1.isInvalid())
13321             return ExprError();
13322           Args[0] = LHS = Arg0.getAs<Expr>();
13323           Args[1] = RHS = Arg1.getAs<Expr>();
13324         }
13325 
13326         // Build the actual expression node.
13327         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13328                                                   Best->FoundDecl, Base,
13329                                                   HadMultipleCandidates, OpLoc);
13330         if (FnExpr.isInvalid())
13331           return ExprError();
13332 
13333         // Determine the result type.
13334         QualType ResultTy = FnDecl->getReturnType();
13335         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13336         ResultTy = ResultTy.getNonLValueExprType(Context);
13337 
13338         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13339             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13340             FPFeatures, Best->IsADLCandidate);
13341 
13342         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13343                                 FnDecl))
13344           return ExprError();
13345 
13346         ArrayRef<const Expr *> ArgsArray(Args, 2);
13347         const Expr *ImplicitThis = nullptr;
13348         // Cut off the implicit 'this'.
13349         if (isa<CXXMethodDecl>(FnDecl)) {
13350           ImplicitThis = ArgsArray[0];
13351           ArgsArray = ArgsArray.slice(1);
13352         }
13353 
13354         // Check for a self move.
13355         if (Op == OO_Equal)
13356           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13357 
13358         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13359                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13360                   VariadicDoesNotApply);
13361 
13362         ExprResult R = MaybeBindToTemporary(TheCall);
13363         if (R.isInvalid())
13364           return ExprError();
13365 
13366         // For a rewritten candidate, we've already reversed the arguments
13367         // if needed. Perform the rest of the rewrite now.
13368         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13369             (Op == OO_Spaceship && IsReversed)) {
13370           if (Op == OO_ExclaimEqual) {
13371             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13372             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13373           } else {
13374             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13375             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13376             Expr *ZeroLiteral =
13377                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13378 
13379             Sema::CodeSynthesisContext Ctx;
13380             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13381             Ctx.Entity = FnDecl;
13382             pushCodeSynthesisContext(Ctx);
13383 
13384             R = CreateOverloadedBinOp(
13385                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13386                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13387                 /*AllowRewrittenCandidates=*/false);
13388 
13389             popCodeSynthesisContext();
13390           }
13391           if (R.isInvalid())
13392             return ExprError();
13393         } else {
13394           assert(ChosenOp == Op && "unexpected operator name");
13395         }
13396 
13397         // Make a note in the AST if we did any rewriting.
13398         if (Best->RewriteKind != CRK_None)
13399           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13400 
13401         return CheckForImmediateInvocation(R, FnDecl);
13402       } else {
13403         // We matched a built-in operator. Convert the arguments, then
13404         // break out so that we will build the appropriate built-in
13405         // operator node.
13406         ExprResult ArgsRes0 = PerformImplicitConversion(
13407             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13408             AA_Passing, CCK_ForBuiltinOverloadedOp);
13409         if (ArgsRes0.isInvalid())
13410           return ExprError();
13411         Args[0] = ArgsRes0.get();
13412 
13413         ExprResult ArgsRes1 = PerformImplicitConversion(
13414             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13415             AA_Passing, CCK_ForBuiltinOverloadedOp);
13416         if (ArgsRes1.isInvalid())
13417           return ExprError();
13418         Args[1] = ArgsRes1.get();
13419         break;
13420       }
13421     }
13422 
13423     case OR_No_Viable_Function: {
13424       // C++ [over.match.oper]p9:
13425       //   If the operator is the operator , [...] and there are no
13426       //   viable functions, then the operator is assumed to be the
13427       //   built-in operator and interpreted according to clause 5.
13428       if (Opc == BO_Comma)
13429         break;
13430 
13431       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13432       // compare result using '==' and '<'.
13433       if (DefaultedFn && Opc == BO_Cmp) {
13434         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13435                                                           Args[1], DefaultedFn);
13436         if (E.isInvalid() || E.isUsable())
13437           return E;
13438       }
13439 
13440       // For class as left operand for assignment or compound assignment
13441       // operator do not fall through to handling in built-in, but report that
13442       // no overloaded assignment operator found
13443       ExprResult Result = ExprError();
13444       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13445       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13446                                                    Args, OpLoc);
13447       if (Args[0]->getType()->isRecordType() &&
13448           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13449         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13450              << BinaryOperator::getOpcodeStr(Opc)
13451              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13452         if (Args[0]->getType()->isIncompleteType()) {
13453           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13454             << Args[0]->getType()
13455             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13456         }
13457       } else {
13458         // This is an erroneous use of an operator which can be overloaded by
13459         // a non-member function. Check for non-member operators which were
13460         // defined too late to be candidates.
13461         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13462           // FIXME: Recover by calling the found function.
13463           return ExprError();
13464 
13465         // No viable function; try to create a built-in operation, which will
13466         // produce an error. Then, show the non-viable candidates.
13467         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13468       }
13469       assert(Result.isInvalid() &&
13470              "C++ binary operator overloading is missing candidates!");
13471       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13472       return Result;
13473     }
13474 
13475     case OR_Ambiguous:
13476       CandidateSet.NoteCandidates(
13477           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13478                                          << BinaryOperator::getOpcodeStr(Opc)
13479                                          << Args[0]->getType()
13480                                          << Args[1]->getType()
13481                                          << Args[0]->getSourceRange()
13482                                          << Args[1]->getSourceRange()),
13483           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13484           OpLoc);
13485       return ExprError();
13486 
13487     case OR_Deleted:
13488       if (isImplicitlyDeleted(Best->Function)) {
13489         FunctionDecl *DeletedFD = Best->Function;
13490         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13491         if (DFK.isSpecialMember()) {
13492           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13493             << Args[0]->getType() << DFK.asSpecialMember();
13494         } else {
13495           assert(DFK.isComparison());
13496           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13497             << Args[0]->getType() << DeletedFD;
13498         }
13499 
13500         // The user probably meant to call this special member. Just
13501         // explain why it's deleted.
13502         NoteDeletedFunction(DeletedFD);
13503         return ExprError();
13504       }
13505       CandidateSet.NoteCandidates(
13506           PartialDiagnosticAt(
13507               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13508                          << getOperatorSpelling(Best->Function->getDeclName()
13509                                                     .getCXXOverloadedOperator())
13510                          << Args[0]->getSourceRange()
13511                          << Args[1]->getSourceRange()),
13512           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13513           OpLoc);
13514       return ExprError();
13515   }
13516 
13517   // We matched a built-in operator; build it.
13518   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13519 }
13520 
13521 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13522     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13523     FunctionDecl *DefaultedFn) {
13524   const ComparisonCategoryInfo *Info =
13525       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13526   // If we're not producing a known comparison category type, we can't
13527   // synthesize a three-way comparison. Let the caller diagnose this.
13528   if (!Info)
13529     return ExprResult((Expr*)nullptr);
13530 
13531   // If we ever want to perform this synthesis more generally, we will need to
13532   // apply the temporary materialization conversion to the operands.
13533   assert(LHS->isGLValue() && RHS->isGLValue() &&
13534          "cannot use prvalue expressions more than once");
13535   Expr *OrigLHS = LHS;
13536   Expr *OrigRHS = RHS;
13537 
13538   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13539   // each of them multiple times below.
13540   LHS = new (Context)
13541       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13542                       LHS->getObjectKind(), LHS);
13543   RHS = new (Context)
13544       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13545                       RHS->getObjectKind(), RHS);
13546 
13547   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13548                                         DefaultedFn);
13549   if (Eq.isInvalid())
13550     return ExprError();
13551 
13552   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13553                                           true, DefaultedFn);
13554   if (Less.isInvalid())
13555     return ExprError();
13556 
13557   ExprResult Greater;
13558   if (Info->isPartial()) {
13559     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13560                                     DefaultedFn);
13561     if (Greater.isInvalid())
13562       return ExprError();
13563   }
13564 
13565   // Form the list of comparisons we're going to perform.
13566   struct Comparison {
13567     ExprResult Cmp;
13568     ComparisonCategoryResult Result;
13569   } Comparisons[4] =
13570   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13571                           : ComparisonCategoryResult::Equivalent},
13572     {Less, ComparisonCategoryResult::Less},
13573     {Greater, ComparisonCategoryResult::Greater},
13574     {ExprResult(), ComparisonCategoryResult::Unordered},
13575   };
13576 
13577   int I = Info->isPartial() ? 3 : 2;
13578 
13579   // Combine the comparisons with suitable conditional expressions.
13580   ExprResult Result;
13581   for (; I >= 0; --I) {
13582     // Build a reference to the comparison category constant.
13583     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13584     // FIXME: Missing a constant for a comparison category. Diagnose this?
13585     if (!VI)
13586       return ExprResult((Expr*)nullptr);
13587     ExprResult ThisResult =
13588         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13589     if (ThisResult.isInvalid())
13590       return ExprError();
13591 
13592     // Build a conditional unless this is the final case.
13593     if (Result.get()) {
13594       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13595                                   ThisResult.get(), Result.get());
13596       if (Result.isInvalid())
13597         return ExprError();
13598     } else {
13599       Result = ThisResult;
13600     }
13601   }
13602 
13603   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13604   // bind the OpaqueValueExprs before they're (repeatedly) used.
13605   Expr *SyntacticForm = new (Context)
13606       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13607                      Result.get()->getValueKind(),
13608                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13609   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13610   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13611 }
13612 
13613 ExprResult
13614 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13615                                          SourceLocation RLoc,
13616                                          Expr *Base, Expr *Idx) {
13617   Expr *Args[2] = { Base, Idx };
13618   DeclarationName OpName =
13619       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13620 
13621   // If either side is type-dependent, create an appropriate dependent
13622   // expression.
13623   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13624 
13625     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13626     // CHECKME: no 'operator' keyword?
13627     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13628     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13629     UnresolvedLookupExpr *Fn
13630       = UnresolvedLookupExpr::Create(Context, NamingClass,
13631                                      NestedNameSpecifierLoc(), OpNameInfo,
13632                                      /*ADL*/ true, /*Overloaded*/ false,
13633                                      UnresolvedSetIterator(),
13634                                      UnresolvedSetIterator());
13635     // Can't add any actual overloads yet
13636 
13637     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13638                                        Context.DependentTy, VK_RValue, RLoc,
13639                                        FPOptions());
13640   }
13641 
13642   // Handle placeholders on both operands.
13643   if (checkPlaceholderForOverload(*this, Args[0]))
13644     return ExprError();
13645   if (checkPlaceholderForOverload(*this, Args[1]))
13646     return ExprError();
13647 
13648   // Build an empty overload set.
13649   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13650 
13651   // Subscript can only be overloaded as a member function.
13652 
13653   // Add operator candidates that are member functions.
13654   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13655 
13656   // Add builtin operator candidates.
13657   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13658 
13659   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13660 
13661   // Perform overload resolution.
13662   OverloadCandidateSet::iterator Best;
13663   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13664     case OR_Success: {
13665       // We found a built-in operator or an overloaded operator.
13666       FunctionDecl *FnDecl = Best->Function;
13667 
13668       if (FnDecl) {
13669         // We matched an overloaded operator. Build a call to that
13670         // operator.
13671 
13672         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13673 
13674         // Convert the arguments.
13675         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13676         ExprResult Arg0 =
13677           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13678                                               Best->FoundDecl, Method);
13679         if (Arg0.isInvalid())
13680           return ExprError();
13681         Args[0] = Arg0.get();
13682 
13683         // Convert the arguments.
13684         ExprResult InputInit
13685           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13686                                                       Context,
13687                                                       FnDecl->getParamDecl(0)),
13688                                       SourceLocation(),
13689                                       Args[1]);
13690         if (InputInit.isInvalid())
13691           return ExprError();
13692 
13693         Args[1] = InputInit.getAs<Expr>();
13694 
13695         // Build the actual expression node.
13696         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13697         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13698         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13699                                                   Best->FoundDecl,
13700                                                   Base,
13701                                                   HadMultipleCandidates,
13702                                                   OpLocInfo.getLoc(),
13703                                                   OpLocInfo.getInfo());
13704         if (FnExpr.isInvalid())
13705           return ExprError();
13706 
13707         // Determine the result type
13708         QualType ResultTy = FnDecl->getReturnType();
13709         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13710         ResultTy = ResultTy.getNonLValueExprType(Context);
13711 
13712         CXXOperatorCallExpr *TheCall =
13713             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13714                                         Args, ResultTy, VK, RLoc, FPOptions());
13715 
13716         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13717           return ExprError();
13718 
13719         if (CheckFunctionCall(Method, TheCall,
13720                               Method->getType()->castAs<FunctionProtoType>()))
13721           return ExprError();
13722 
13723         return MaybeBindToTemporary(TheCall);
13724       } else {
13725         // We matched a built-in operator. Convert the arguments, then
13726         // break out so that we will build the appropriate built-in
13727         // operator node.
13728         ExprResult ArgsRes0 = PerformImplicitConversion(
13729             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13730             AA_Passing, CCK_ForBuiltinOverloadedOp);
13731         if (ArgsRes0.isInvalid())
13732           return ExprError();
13733         Args[0] = ArgsRes0.get();
13734 
13735         ExprResult ArgsRes1 = PerformImplicitConversion(
13736             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13737             AA_Passing, CCK_ForBuiltinOverloadedOp);
13738         if (ArgsRes1.isInvalid())
13739           return ExprError();
13740         Args[1] = ArgsRes1.get();
13741 
13742         break;
13743       }
13744     }
13745 
13746     case OR_No_Viable_Function: {
13747       PartialDiagnostic PD = CandidateSet.empty()
13748           ? (PDiag(diag::err_ovl_no_oper)
13749              << Args[0]->getType() << /*subscript*/ 0
13750              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13751           : (PDiag(diag::err_ovl_no_viable_subscript)
13752              << Args[0]->getType() << Args[0]->getSourceRange()
13753              << Args[1]->getSourceRange());
13754       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13755                                   OCD_AllCandidates, Args, "[]", LLoc);
13756       return ExprError();
13757     }
13758 
13759     case OR_Ambiguous:
13760       CandidateSet.NoteCandidates(
13761           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13762                                         << "[]" << Args[0]->getType()
13763                                         << Args[1]->getType()
13764                                         << Args[0]->getSourceRange()
13765                                         << Args[1]->getSourceRange()),
13766           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13767       return ExprError();
13768 
13769     case OR_Deleted:
13770       CandidateSet.NoteCandidates(
13771           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13772                                         << "[]" << Args[0]->getSourceRange()
13773                                         << Args[1]->getSourceRange()),
13774           *this, OCD_AllCandidates, Args, "[]", LLoc);
13775       return ExprError();
13776     }
13777 
13778   // We matched a built-in operator; build it.
13779   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13780 }
13781 
13782 /// BuildCallToMemberFunction - Build a call to a member
13783 /// function. MemExpr is the expression that refers to the member
13784 /// function (and includes the object parameter), Args/NumArgs are the
13785 /// arguments to the function call (not including the object
13786 /// parameter). The caller needs to validate that the member
13787 /// expression refers to a non-static member function or an overloaded
13788 /// member function.
13789 ExprResult
13790 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13791                                 SourceLocation LParenLoc,
13792                                 MultiExprArg Args,
13793                                 SourceLocation RParenLoc) {
13794   assert(MemExprE->getType() == Context.BoundMemberTy ||
13795          MemExprE->getType() == Context.OverloadTy);
13796 
13797   // Dig out the member expression. This holds both the object
13798   // argument and the member function we're referring to.
13799   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13800 
13801   // Determine whether this is a call to a pointer-to-member function.
13802   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13803     assert(op->getType() == Context.BoundMemberTy);
13804     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13805 
13806     QualType fnType =
13807       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13808 
13809     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13810     QualType resultType = proto->getCallResultType(Context);
13811     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13812 
13813     // Check that the object type isn't more qualified than the
13814     // member function we're calling.
13815     Qualifiers funcQuals = proto->getMethodQuals();
13816 
13817     QualType objectType = op->getLHS()->getType();
13818     if (op->getOpcode() == BO_PtrMemI)
13819       objectType = objectType->castAs<PointerType>()->getPointeeType();
13820     Qualifiers objectQuals = objectType.getQualifiers();
13821 
13822     Qualifiers difference = objectQuals - funcQuals;
13823     difference.removeObjCGCAttr();
13824     difference.removeAddressSpace();
13825     if (difference) {
13826       std::string qualsString = difference.getAsString();
13827       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13828         << fnType.getUnqualifiedType()
13829         << qualsString
13830         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13831     }
13832 
13833     CXXMemberCallExpr *call =
13834         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13835                                   valueKind, RParenLoc, proto->getNumParams());
13836 
13837     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13838                             call, nullptr))
13839       return ExprError();
13840 
13841     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13842       return ExprError();
13843 
13844     if (CheckOtherCall(call, proto))
13845       return ExprError();
13846 
13847     return MaybeBindToTemporary(call);
13848   }
13849 
13850   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13851     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13852                             RParenLoc);
13853 
13854   UnbridgedCastsSet UnbridgedCasts;
13855   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13856     return ExprError();
13857 
13858   MemberExpr *MemExpr;
13859   CXXMethodDecl *Method = nullptr;
13860   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13861   NestedNameSpecifier *Qualifier = nullptr;
13862   if (isa<MemberExpr>(NakedMemExpr)) {
13863     MemExpr = cast<MemberExpr>(NakedMemExpr);
13864     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13865     FoundDecl = MemExpr->getFoundDecl();
13866     Qualifier = MemExpr->getQualifier();
13867     UnbridgedCasts.restore();
13868   } else {
13869     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13870     Qualifier = UnresExpr->getQualifier();
13871 
13872     QualType ObjectType = UnresExpr->getBaseType();
13873     Expr::Classification ObjectClassification
13874       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13875                             : UnresExpr->getBase()->Classify(Context);
13876 
13877     // Add overload candidates
13878     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13879                                       OverloadCandidateSet::CSK_Normal);
13880 
13881     // FIXME: avoid copy.
13882     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13883     if (UnresExpr->hasExplicitTemplateArgs()) {
13884       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13885       TemplateArgs = &TemplateArgsBuffer;
13886     }
13887 
13888     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13889            E = UnresExpr->decls_end(); I != E; ++I) {
13890 
13891       NamedDecl *Func = *I;
13892       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13893       if (isa<UsingShadowDecl>(Func))
13894         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13895 
13896 
13897       // Microsoft supports direct constructor calls.
13898       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13899         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13900                              CandidateSet,
13901                              /*SuppressUserConversions*/ false);
13902       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13903         // If explicit template arguments were provided, we can't call a
13904         // non-template member function.
13905         if (TemplateArgs)
13906           continue;
13907 
13908         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13909                            ObjectClassification, Args, CandidateSet,
13910                            /*SuppressUserConversions=*/false);
13911       } else {
13912         AddMethodTemplateCandidate(
13913             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13914             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13915             /*SuppressUserConversions=*/false);
13916       }
13917     }
13918 
13919     DeclarationName DeclName = UnresExpr->getMemberName();
13920 
13921     UnbridgedCasts.restore();
13922 
13923     OverloadCandidateSet::iterator Best;
13924     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13925                                             Best)) {
13926     case OR_Success:
13927       Method = cast<CXXMethodDecl>(Best->Function);
13928       FoundDecl = Best->FoundDecl;
13929       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13930       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13931         return ExprError();
13932       // If FoundDecl is different from Method (such as if one is a template
13933       // and the other a specialization), make sure DiagnoseUseOfDecl is
13934       // called on both.
13935       // FIXME: This would be more comprehensively addressed by modifying
13936       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13937       // being used.
13938       if (Method != FoundDecl.getDecl() &&
13939                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13940         return ExprError();
13941       break;
13942 
13943     case OR_No_Viable_Function:
13944       CandidateSet.NoteCandidates(
13945           PartialDiagnosticAt(
13946               UnresExpr->getMemberLoc(),
13947               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13948                   << DeclName << MemExprE->getSourceRange()),
13949           *this, OCD_AllCandidates, Args);
13950       // FIXME: Leaking incoming expressions!
13951       return ExprError();
13952 
13953     case OR_Ambiguous:
13954       CandidateSet.NoteCandidates(
13955           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13956                               PDiag(diag::err_ovl_ambiguous_member_call)
13957                                   << DeclName << MemExprE->getSourceRange()),
13958           *this, OCD_AmbiguousCandidates, Args);
13959       // FIXME: Leaking incoming expressions!
13960       return ExprError();
13961 
13962     case OR_Deleted:
13963       CandidateSet.NoteCandidates(
13964           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13965                               PDiag(diag::err_ovl_deleted_member_call)
13966                                   << DeclName << MemExprE->getSourceRange()),
13967           *this, OCD_AllCandidates, Args);
13968       // FIXME: Leaking incoming expressions!
13969       return ExprError();
13970     }
13971 
13972     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13973 
13974     // If overload resolution picked a static member, build a
13975     // non-member call based on that function.
13976     if (Method->isStatic()) {
13977       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13978                                    RParenLoc);
13979     }
13980 
13981     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13982   }
13983 
13984   QualType ResultType = Method->getReturnType();
13985   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13986   ResultType = ResultType.getNonLValueExprType(Context);
13987 
13988   assert(Method && "Member call to something that isn't a method?");
13989   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13990   CXXMemberCallExpr *TheCall =
13991       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13992                                 RParenLoc, Proto->getNumParams());
13993 
13994   // Check for a valid return type.
13995   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13996                           TheCall, Method))
13997     return ExprError();
13998 
13999   // Convert the object argument (for a non-static member function call).
14000   // We only need to do this if there was actually an overload; otherwise
14001   // it was done at lookup.
14002   if (!Method->isStatic()) {
14003     ExprResult ObjectArg =
14004       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
14005                                           FoundDecl, Method);
14006     if (ObjectArg.isInvalid())
14007       return ExprError();
14008     MemExpr->setBase(ObjectArg.get());
14009   }
14010 
14011   // Convert the rest of the arguments
14012   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14013                               RParenLoc))
14014     return ExprError();
14015 
14016   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14017 
14018   if (CheckFunctionCall(Method, TheCall, Proto))
14019     return ExprError();
14020 
14021   // In the case the method to call was not selected by the overloading
14022   // resolution process, we still need to handle the enable_if attribute. Do
14023   // that here, so it will not hide previous -- and more relevant -- errors.
14024   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14025     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14026       Diag(MemE->getMemberLoc(),
14027            diag::err_ovl_no_viable_member_function_in_call)
14028           << Method << Method->getSourceRange();
14029       Diag(Method->getLocation(),
14030            diag::note_ovl_candidate_disabled_by_function_cond_attr)
14031           << Attr->getCond()->getSourceRange() << Attr->getMessage();
14032       return ExprError();
14033     }
14034   }
14035 
14036   if ((isa<CXXConstructorDecl>(CurContext) ||
14037        isa<CXXDestructorDecl>(CurContext)) &&
14038       TheCall->getMethodDecl()->isPure()) {
14039     const CXXMethodDecl *MD = TheCall->getMethodDecl();
14040 
14041     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14042         MemExpr->performsVirtualDispatch(getLangOpts())) {
14043       Diag(MemExpr->getBeginLoc(),
14044            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14045           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14046           << MD->getParent()->getDeclName();
14047 
14048       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14049       if (getLangOpts().AppleKext)
14050         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14051             << MD->getParent()->getDeclName() << MD->getDeclName();
14052     }
14053   }
14054 
14055   if (CXXDestructorDecl *DD =
14056           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14057     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14058     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14059     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14060                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14061                          MemExpr->getMemberLoc());
14062   }
14063 
14064   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
14065                                      TheCall->getMethodDecl());
14066 }
14067 
14068 /// BuildCallToObjectOfClassType - Build a call to an object of class
14069 /// type (C++ [over.call.object]), which can end up invoking an
14070 /// overloaded function call operator (@c operator()) or performing a
14071 /// user-defined conversion on the object argument.
14072 ExprResult
14073 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14074                                    SourceLocation LParenLoc,
14075                                    MultiExprArg Args,
14076                                    SourceLocation RParenLoc) {
14077   if (checkPlaceholderForOverload(*this, Obj))
14078     return ExprError();
14079   ExprResult Object = Obj;
14080 
14081   UnbridgedCastsSet UnbridgedCasts;
14082   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14083     return ExprError();
14084 
14085   assert(Object.get()->getType()->isRecordType() &&
14086          "Requires object type argument");
14087 
14088   // C++ [over.call.object]p1:
14089   //  If the primary-expression E in the function call syntax
14090   //  evaluates to a class object of type "cv T", then the set of
14091   //  candidate functions includes at least the function call
14092   //  operators of T. The function call operators of T are obtained by
14093   //  ordinary lookup of the name operator() in the context of
14094   //  (E).operator().
14095   OverloadCandidateSet CandidateSet(LParenLoc,
14096                                     OverloadCandidateSet::CSK_Operator);
14097   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14098 
14099   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14100                           diag::err_incomplete_object_call, Object.get()))
14101     return true;
14102 
14103   const auto *Record = Object.get()->getType()->castAs<RecordType>();
14104   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14105   LookupQualifiedName(R, Record->getDecl());
14106   R.suppressDiagnostics();
14107 
14108   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14109        Oper != OperEnd; ++Oper) {
14110     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14111                        Object.get()->Classify(Context), Args, CandidateSet,
14112                        /*SuppressUserConversion=*/false);
14113   }
14114 
14115   // C++ [over.call.object]p2:
14116   //   In addition, for each (non-explicit in C++0x) conversion function
14117   //   declared in T of the form
14118   //
14119   //        operator conversion-type-id () cv-qualifier;
14120   //
14121   //   where cv-qualifier is the same cv-qualification as, or a
14122   //   greater cv-qualification than, cv, and where conversion-type-id
14123   //   denotes the type "pointer to function of (P1,...,Pn) returning
14124   //   R", or the type "reference to pointer to function of
14125   //   (P1,...,Pn) returning R", or the type "reference to function
14126   //   of (P1,...,Pn) returning R", a surrogate call function [...]
14127   //   is also considered as a candidate function. Similarly,
14128   //   surrogate call functions are added to the set of candidate
14129   //   functions for each conversion function declared in an
14130   //   accessible base class provided the function is not hidden
14131   //   within T by another intervening declaration.
14132   const auto &Conversions =
14133       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14134   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14135     NamedDecl *D = *I;
14136     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14137     if (isa<UsingShadowDecl>(D))
14138       D = cast<UsingShadowDecl>(D)->getTargetDecl();
14139 
14140     // Skip over templated conversion functions; they aren't
14141     // surrogates.
14142     if (isa<FunctionTemplateDecl>(D))
14143       continue;
14144 
14145     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14146     if (!Conv->isExplicit()) {
14147       // Strip the reference type (if any) and then the pointer type (if
14148       // any) to get down to what might be a function type.
14149       QualType ConvType = Conv->getConversionType().getNonReferenceType();
14150       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14151         ConvType = ConvPtrType->getPointeeType();
14152 
14153       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14154       {
14155         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14156                               Object.get(), Args, CandidateSet);
14157       }
14158     }
14159   }
14160 
14161   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14162 
14163   // Perform overload resolution.
14164   OverloadCandidateSet::iterator Best;
14165   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14166                                           Best)) {
14167   case OR_Success:
14168     // Overload resolution succeeded; we'll build the appropriate call
14169     // below.
14170     break;
14171 
14172   case OR_No_Viable_Function: {
14173     PartialDiagnostic PD =
14174         CandidateSet.empty()
14175             ? (PDiag(diag::err_ovl_no_oper)
14176                << Object.get()->getType() << /*call*/ 1
14177                << Object.get()->getSourceRange())
14178             : (PDiag(diag::err_ovl_no_viable_object_call)
14179                << Object.get()->getType() << Object.get()->getSourceRange());
14180     CandidateSet.NoteCandidates(
14181         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14182         OCD_AllCandidates, Args);
14183     break;
14184   }
14185   case OR_Ambiguous:
14186     CandidateSet.NoteCandidates(
14187         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14188                             PDiag(diag::err_ovl_ambiguous_object_call)
14189                                 << Object.get()->getType()
14190                                 << Object.get()->getSourceRange()),
14191         *this, OCD_AmbiguousCandidates, Args);
14192     break;
14193 
14194   case OR_Deleted:
14195     CandidateSet.NoteCandidates(
14196         PartialDiagnosticAt(Object.get()->getBeginLoc(),
14197                             PDiag(diag::err_ovl_deleted_object_call)
14198                                 << Object.get()->getType()
14199                                 << Object.get()->getSourceRange()),
14200         *this, OCD_AllCandidates, Args);
14201     break;
14202   }
14203 
14204   if (Best == CandidateSet.end())
14205     return true;
14206 
14207   UnbridgedCasts.restore();
14208 
14209   if (Best->Function == nullptr) {
14210     // Since there is no function declaration, this is one of the
14211     // surrogate candidates. Dig out the conversion function.
14212     CXXConversionDecl *Conv
14213       = cast<CXXConversionDecl>(
14214                          Best->Conversions[0].UserDefined.ConversionFunction);
14215 
14216     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14217                               Best->FoundDecl);
14218     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14219       return ExprError();
14220     assert(Conv == Best->FoundDecl.getDecl() &&
14221              "Found Decl & conversion-to-functionptr should be same, right?!");
14222     // We selected one of the surrogate functions that converts the
14223     // object parameter to a function pointer. Perform the conversion
14224     // on the object argument, then let BuildCallExpr finish the job.
14225 
14226     // Create an implicit member expr to refer to the conversion operator.
14227     // and then call it.
14228     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14229                                              Conv, HadMultipleCandidates);
14230     if (Call.isInvalid())
14231       return ExprError();
14232     // Record usage of conversion in an implicit cast.
14233     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14234                                     CK_UserDefinedConversion, Call.get(),
14235                                     nullptr, VK_RValue);
14236 
14237     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14238   }
14239 
14240   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14241 
14242   // We found an overloaded operator(). Build a CXXOperatorCallExpr
14243   // that calls this method, using Object for the implicit object
14244   // parameter and passing along the remaining arguments.
14245   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14246 
14247   // An error diagnostic has already been printed when parsing the declaration.
14248   if (Method->isInvalidDecl())
14249     return ExprError();
14250 
14251   const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14252   unsigned NumParams = Proto->getNumParams();
14253 
14254   DeclarationNameInfo OpLocInfo(
14255                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14256   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14257   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14258                                            Obj, HadMultipleCandidates,
14259                                            OpLocInfo.getLoc(),
14260                                            OpLocInfo.getInfo());
14261   if (NewFn.isInvalid())
14262     return true;
14263 
14264   // The number of argument slots to allocate in the call. If we have default
14265   // arguments we need to allocate space for them as well. We additionally
14266   // need one more slot for the object parameter.
14267   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14268 
14269   // Build the full argument list for the method call (the implicit object
14270   // parameter is placed at the beginning of the list).
14271   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14272 
14273   bool IsError = false;
14274 
14275   // Initialize the implicit object parameter.
14276   ExprResult ObjRes =
14277     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14278                                         Best->FoundDecl, Method);
14279   if (ObjRes.isInvalid())
14280     IsError = true;
14281   else
14282     Object = ObjRes;
14283   MethodArgs[0] = Object.get();
14284 
14285   // Check the argument types.
14286   for (unsigned i = 0; i != NumParams; i++) {
14287     Expr *Arg;
14288     if (i < Args.size()) {
14289       Arg = Args[i];
14290 
14291       // Pass the argument.
14292 
14293       ExprResult InputInit
14294         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14295                                                     Context,
14296                                                     Method->getParamDecl(i)),
14297                                     SourceLocation(), Arg);
14298 
14299       IsError |= InputInit.isInvalid();
14300       Arg = InputInit.getAs<Expr>();
14301     } else {
14302       ExprResult DefArg
14303         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14304       if (DefArg.isInvalid()) {
14305         IsError = true;
14306         break;
14307       }
14308 
14309       Arg = DefArg.getAs<Expr>();
14310     }
14311 
14312     MethodArgs[i + 1] = Arg;
14313   }
14314 
14315   // If this is a variadic call, handle args passed through "...".
14316   if (Proto->isVariadic()) {
14317     // Promote the arguments (C99 6.5.2.2p7).
14318     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14319       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14320                                                         nullptr);
14321       IsError |= Arg.isInvalid();
14322       MethodArgs[i + 1] = Arg.get();
14323     }
14324   }
14325 
14326   if (IsError)
14327     return true;
14328 
14329   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14330 
14331   // Once we've built TheCall, all of the expressions are properly owned.
14332   QualType ResultTy = Method->getReturnType();
14333   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14334   ResultTy = ResultTy.getNonLValueExprType(Context);
14335 
14336   CXXOperatorCallExpr *TheCall =
14337       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14338                                   ResultTy, VK, RParenLoc, FPOptions());
14339 
14340   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14341     return true;
14342 
14343   if (CheckFunctionCall(Method, TheCall, Proto))
14344     return true;
14345 
14346   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
14347 }
14348 
14349 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14350 ///  (if one exists), where @c Base is an expression of class type and
14351 /// @c Member is the name of the member we're trying to find.
14352 ExprResult
14353 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14354                                bool *NoArrowOperatorFound) {
14355   assert(Base->getType()->isRecordType() &&
14356          "left-hand side must have class type");
14357 
14358   if (checkPlaceholderForOverload(*this, Base))
14359     return ExprError();
14360 
14361   SourceLocation Loc = Base->getExprLoc();
14362 
14363   // C++ [over.ref]p1:
14364   //
14365   //   [...] An expression x->m is interpreted as (x.operator->())->m
14366   //   for a class object x of type T if T::operator->() exists and if
14367   //   the operator is selected as the best match function by the
14368   //   overload resolution mechanism (13.3).
14369   DeclarationName OpName =
14370     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14371   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14372 
14373   if (RequireCompleteType(Loc, Base->getType(),
14374                           diag::err_typecheck_incomplete_tag, Base))
14375     return ExprError();
14376 
14377   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14378   LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14379   R.suppressDiagnostics();
14380 
14381   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14382        Oper != OperEnd; ++Oper) {
14383     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14384                        None, CandidateSet, /*SuppressUserConversion=*/false);
14385   }
14386 
14387   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14388 
14389   // Perform overload resolution.
14390   OverloadCandidateSet::iterator Best;
14391   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14392   case OR_Success:
14393     // Overload resolution succeeded; we'll build the call below.
14394     break;
14395 
14396   case OR_No_Viable_Function: {
14397     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14398     if (CandidateSet.empty()) {
14399       QualType BaseType = Base->getType();
14400       if (NoArrowOperatorFound) {
14401         // Report this specific error to the caller instead of emitting a
14402         // diagnostic, as requested.
14403         *NoArrowOperatorFound = true;
14404         return ExprError();
14405       }
14406       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14407         << BaseType << Base->getSourceRange();
14408       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14409         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14410           << FixItHint::CreateReplacement(OpLoc, ".");
14411       }
14412     } else
14413       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14414         << "operator->" << Base->getSourceRange();
14415     CandidateSet.NoteCandidates(*this, Base, Cands);
14416     return ExprError();
14417   }
14418   case OR_Ambiguous:
14419     CandidateSet.NoteCandidates(
14420         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14421                                        << "->" << Base->getType()
14422                                        << Base->getSourceRange()),
14423         *this, OCD_AmbiguousCandidates, Base);
14424     return ExprError();
14425 
14426   case OR_Deleted:
14427     CandidateSet.NoteCandidates(
14428         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14429                                        << "->" << Base->getSourceRange()),
14430         *this, OCD_AllCandidates, Base);
14431     return ExprError();
14432   }
14433 
14434   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14435 
14436   // Convert the object parameter.
14437   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14438   ExprResult BaseResult =
14439     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14440                                         Best->FoundDecl, Method);
14441   if (BaseResult.isInvalid())
14442     return ExprError();
14443   Base = BaseResult.get();
14444 
14445   // Build the operator call.
14446   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14447                                             Base, HadMultipleCandidates, OpLoc);
14448   if (FnExpr.isInvalid())
14449     return ExprError();
14450 
14451   QualType ResultTy = Method->getReturnType();
14452   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14453   ResultTy = ResultTy.getNonLValueExprType(Context);
14454   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14455       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14456 
14457   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14458     return ExprError();
14459 
14460   if (CheckFunctionCall(Method, TheCall,
14461                         Method->getType()->castAs<FunctionProtoType>()))
14462     return ExprError();
14463 
14464   return MaybeBindToTemporary(TheCall);
14465 }
14466 
14467 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14468 /// a literal operator described by the provided lookup results.
14469 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14470                                           DeclarationNameInfo &SuffixInfo,
14471                                           ArrayRef<Expr*> Args,
14472                                           SourceLocation LitEndLoc,
14473                                        TemplateArgumentListInfo *TemplateArgs) {
14474   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14475 
14476   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14477                                     OverloadCandidateSet::CSK_Normal);
14478   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14479                                  TemplateArgs);
14480 
14481   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14482 
14483   // Perform overload resolution. This will usually be trivial, but might need
14484   // to perform substitutions for a literal operator template.
14485   OverloadCandidateSet::iterator Best;
14486   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14487   case OR_Success:
14488   case OR_Deleted:
14489     break;
14490 
14491   case OR_No_Viable_Function:
14492     CandidateSet.NoteCandidates(
14493         PartialDiagnosticAt(UDSuffixLoc,
14494                             PDiag(diag::err_ovl_no_viable_function_in_call)
14495                                 << R.getLookupName()),
14496         *this, OCD_AllCandidates, Args);
14497     return ExprError();
14498 
14499   case OR_Ambiguous:
14500     CandidateSet.NoteCandidates(
14501         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14502                                                 << R.getLookupName()),
14503         *this, OCD_AmbiguousCandidates, Args);
14504     return ExprError();
14505   }
14506 
14507   FunctionDecl *FD = Best->Function;
14508   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14509                                         nullptr, HadMultipleCandidates,
14510                                         SuffixInfo.getLoc(),
14511                                         SuffixInfo.getInfo());
14512   if (Fn.isInvalid())
14513     return true;
14514 
14515   // Check the argument types. This should almost always be a no-op, except
14516   // that array-to-pointer decay is applied to string literals.
14517   Expr *ConvArgs[2];
14518   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14519     ExprResult InputInit = PerformCopyInitialization(
14520       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14521       SourceLocation(), Args[ArgIdx]);
14522     if (InputInit.isInvalid())
14523       return true;
14524     ConvArgs[ArgIdx] = InputInit.get();
14525   }
14526 
14527   QualType ResultTy = FD->getReturnType();
14528   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14529   ResultTy = ResultTy.getNonLValueExprType(Context);
14530 
14531   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14532       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14533       VK, LitEndLoc, UDSuffixLoc);
14534 
14535   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14536     return ExprError();
14537 
14538   if (CheckFunctionCall(FD, UDL, nullptr))
14539     return ExprError();
14540 
14541   return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
14542 }
14543 
14544 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14545 /// given LookupResult is non-empty, it is assumed to describe a member which
14546 /// will be invoked. Otherwise, the function will be found via argument
14547 /// dependent lookup.
14548 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14549 /// otherwise CallExpr is set to ExprError() and some non-success value
14550 /// is returned.
14551 Sema::ForRangeStatus
14552 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14553                                 SourceLocation RangeLoc,
14554                                 const DeclarationNameInfo &NameInfo,
14555                                 LookupResult &MemberLookup,
14556                                 OverloadCandidateSet *CandidateSet,
14557                                 Expr *Range, ExprResult *CallExpr) {
14558   Scope *S = nullptr;
14559 
14560   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14561   if (!MemberLookup.empty()) {
14562     ExprResult MemberRef =
14563         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14564                                  /*IsPtr=*/false, CXXScopeSpec(),
14565                                  /*TemplateKWLoc=*/SourceLocation(),
14566                                  /*FirstQualifierInScope=*/nullptr,
14567                                  MemberLookup,
14568                                  /*TemplateArgs=*/nullptr, S);
14569     if (MemberRef.isInvalid()) {
14570       *CallExpr = ExprError();
14571       return FRS_DiagnosticIssued;
14572     }
14573     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14574     if (CallExpr->isInvalid()) {
14575       *CallExpr = ExprError();
14576       return FRS_DiagnosticIssued;
14577     }
14578   } else {
14579     UnresolvedSet<0> FoundNames;
14580     UnresolvedLookupExpr *Fn =
14581       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14582                                    NestedNameSpecifierLoc(), NameInfo,
14583                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14584                                    FoundNames.begin(), FoundNames.end());
14585 
14586     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14587                                                     CandidateSet, CallExpr);
14588     if (CandidateSet->empty() || CandidateSetError) {
14589       *CallExpr = ExprError();
14590       return FRS_NoViableFunction;
14591     }
14592     OverloadCandidateSet::iterator Best;
14593     OverloadingResult OverloadResult =
14594         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14595 
14596     if (OverloadResult == OR_No_Viable_Function) {
14597       *CallExpr = ExprError();
14598       return FRS_NoViableFunction;
14599     }
14600     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14601                                          Loc, nullptr, CandidateSet, &Best,
14602                                          OverloadResult,
14603                                          /*AllowTypoCorrection=*/false);
14604     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14605       *CallExpr = ExprError();
14606       return FRS_DiagnosticIssued;
14607     }
14608   }
14609   return FRS_Success;
14610 }
14611 
14612 
14613 /// FixOverloadedFunctionReference - E is an expression that refers to
14614 /// a C++ overloaded function (possibly with some parentheses and
14615 /// perhaps a '&' around it). We have resolved the overloaded function
14616 /// to the function declaration Fn, so patch up the expression E to
14617 /// refer (possibly indirectly) to Fn. Returns the new expr.
14618 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14619                                            FunctionDecl *Fn) {
14620   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14621     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14622                                                    Found, Fn);
14623     if (SubExpr == PE->getSubExpr())
14624       return PE;
14625 
14626     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14627   }
14628 
14629   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14630     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14631                                                    Found, Fn);
14632     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14633                                SubExpr->getType()) &&
14634            "Implicit cast type cannot be determined from overload");
14635     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14636     if (SubExpr == ICE->getSubExpr())
14637       return ICE;
14638 
14639     return ImplicitCastExpr::Create(Context, ICE->getType(),
14640                                     ICE->getCastKind(),
14641                                     SubExpr, nullptr,
14642                                     ICE->getValueKind());
14643   }
14644 
14645   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14646     if (!GSE->isResultDependent()) {
14647       Expr *SubExpr =
14648           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14649       if (SubExpr == GSE->getResultExpr())
14650         return GSE;
14651 
14652       // Replace the resulting type information before rebuilding the generic
14653       // selection expression.
14654       ArrayRef<Expr *> A = GSE->getAssocExprs();
14655       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14656       unsigned ResultIdx = GSE->getResultIndex();
14657       AssocExprs[ResultIdx] = SubExpr;
14658 
14659       return GenericSelectionExpr::Create(
14660           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14661           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14662           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14663           ResultIdx);
14664     }
14665     // Rather than fall through to the unreachable, return the original generic
14666     // selection expression.
14667     return GSE;
14668   }
14669 
14670   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14671     assert(UnOp->getOpcode() == UO_AddrOf &&
14672            "Can only take the address of an overloaded function");
14673     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14674       if (Method->isStatic()) {
14675         // Do nothing: static member functions aren't any different
14676         // from non-member functions.
14677       } else {
14678         // Fix the subexpression, which really has to be an
14679         // UnresolvedLookupExpr holding an overloaded member function
14680         // or template.
14681         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14682                                                        Found, Fn);
14683         if (SubExpr == UnOp->getSubExpr())
14684           return UnOp;
14685 
14686         assert(isa<DeclRefExpr>(SubExpr)
14687                && "fixed to something other than a decl ref");
14688         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14689                && "fixed to a member ref with no nested name qualifier");
14690 
14691         // We have taken the address of a pointer to member
14692         // function. Perform the computation here so that we get the
14693         // appropriate pointer to member type.
14694         QualType ClassType
14695           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14696         QualType MemPtrType
14697           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14698         // Under the MS ABI, lock down the inheritance model now.
14699         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14700           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14701 
14702         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14703                                            VK_RValue, OK_Ordinary,
14704                                            UnOp->getOperatorLoc(), false);
14705       }
14706     }
14707     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14708                                                    Found, Fn);
14709     if (SubExpr == UnOp->getSubExpr())
14710       return UnOp;
14711 
14712     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14713                                      Context.getPointerType(SubExpr->getType()),
14714                                        VK_RValue, OK_Ordinary,
14715                                        UnOp->getOperatorLoc(), false);
14716   }
14717 
14718   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14719     // FIXME: avoid copy.
14720     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14721     if (ULE->hasExplicitTemplateArgs()) {
14722       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14723       TemplateArgs = &TemplateArgsBuffer;
14724     }
14725 
14726     DeclRefExpr *DRE =
14727         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14728                          ULE->getQualifierLoc(), Found.getDecl(),
14729                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14730     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14731     return DRE;
14732   }
14733 
14734   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14735     // FIXME: avoid copy.
14736     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14737     if (MemExpr->hasExplicitTemplateArgs()) {
14738       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14739       TemplateArgs = &TemplateArgsBuffer;
14740     }
14741 
14742     Expr *Base;
14743 
14744     // If we're filling in a static method where we used to have an
14745     // implicit member access, rewrite to a simple decl ref.
14746     if (MemExpr->isImplicitAccess()) {
14747       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14748         DeclRefExpr *DRE = BuildDeclRefExpr(
14749             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14750             MemExpr->getQualifierLoc(), Found.getDecl(),
14751             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14752         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14753         return DRE;
14754       } else {
14755         SourceLocation Loc = MemExpr->getMemberLoc();
14756         if (MemExpr->getQualifier())
14757           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14758         Base =
14759             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14760       }
14761     } else
14762       Base = MemExpr->getBase();
14763 
14764     ExprValueKind valueKind;
14765     QualType type;
14766     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14767       valueKind = VK_LValue;
14768       type = Fn->getType();
14769     } else {
14770       valueKind = VK_RValue;
14771       type = Context.BoundMemberTy;
14772     }
14773 
14774     return BuildMemberExpr(
14775         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14776         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14777         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14778         type, valueKind, OK_Ordinary, TemplateArgs);
14779   }
14780 
14781   llvm_unreachable("Invalid reference to overloaded function");
14782 }
14783 
14784 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14785                                                 DeclAccessPair Found,
14786                                                 FunctionDecl *Fn) {
14787   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14788 }
14789