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 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42   return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43     return P->hasAttr<PassObjectSizeAttr>();
44   });
45 }
46 
47 /// A convenience routine for creating a decayed reference to a function.
48 static ExprResult
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50                       const Expr *Base, bool HadMultipleCandidates,
51                       SourceLocation Loc = SourceLocation(),
52                       const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53   if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54     return ExprError();
55   // If FoundDecl is different from Fn (such as if one is a template
56   // and the other a specialization), make sure DiagnoseUseOfDecl is
57   // called on both.
58   // FIXME: This would be more comprehensively addressed by modifying
59   // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60   // being used.
61   if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62     return ExprError();
63   DeclRefExpr *DRE = new (S.Context)
64       DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65   if (HadMultipleCandidates)
66     DRE->setHadMultipleCandidates(true);
67 
68   S.MarkDeclRefReferenced(DRE, Base);
69   if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71       S.ResolveExceptionSpec(Loc, FPT);
72       DRE->setType(Fn->getType());
73     }
74   }
75   return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76                              CK_FunctionToPointerDecay);
77 }
78 
79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80                                  bool InOverloadResolution,
81                                  StandardConversionSequence &SCS,
82                                  bool CStyle,
83                                  bool AllowObjCWritebackConversion);
84 
85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
86                                                  QualType &ToType,
87                                                  bool InOverloadResolution,
88                                                  StandardConversionSequence &SCS,
89                                                  bool CStyle);
90 static OverloadingResult
91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92                         UserDefinedConversionSequence& User,
93                         OverloadCandidateSet& Conversions,
94                         bool AllowExplicit,
95                         bool AllowObjCConversionOnExplicit);
96 
97 
98 static ImplicitConversionSequence::CompareKind
99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100                                    const StandardConversionSequence& SCS1,
101                                    const StandardConversionSequence& SCS2);
102 
103 static ImplicitConversionSequence::CompareKind
104 CompareQualificationConversions(Sema &S,
105                                 const StandardConversionSequence& SCS1,
106                                 const StandardConversionSequence& SCS2);
107 
108 static ImplicitConversionSequence::CompareKind
109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110                                 const StandardConversionSequence& SCS1,
111                                 const StandardConversionSequence& SCS2);
112 
113 /// GetConversionRank - Retrieve the implicit conversion rank
114 /// corresponding to the given implicit conversion kind.
115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116   static const ImplicitConversionRank
117     Rank[(int)ICK_Num_Conversion_Kinds] = {
118     ICR_Exact_Match,
119     ICR_Exact_Match,
120     ICR_Exact_Match,
121     ICR_Exact_Match,
122     ICR_Exact_Match,
123     ICR_Exact_Match,
124     ICR_Promotion,
125     ICR_Promotion,
126     ICR_Promotion,
127     ICR_Conversion,
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_OCL_Scalar_Widening,
138     ICR_Complex_Real_Conversion,
139     ICR_Conversion,
140     ICR_Conversion,
141     ICR_Writeback_Conversion,
142     ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143                      // it was omitted by the patch that added
144                      // ICK_Zero_Event_Conversion
145     ICR_C_Conversion,
146     ICR_C_Conversion_Extension
147   };
148   return Rank[(int)Kind];
149 }
150 
151 /// GetImplicitConversionName - Return the name of this kind of
152 /// implicit conversion.
153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154   static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
155     "No conversion",
156     "Lvalue-to-rvalue",
157     "Array-to-pointer",
158     "Function-to-pointer",
159     "Function pointer conversion",
160     "Qualification",
161     "Integral promotion",
162     "Floating point promotion",
163     "Complex promotion",
164     "Integral conversion",
165     "Floating conversion",
166     "Complex conversion",
167     "Floating-integral conversion",
168     "Pointer conversion",
169     "Pointer-to-member conversion",
170     "Boolean conversion",
171     "Compatible-types conversion",
172     "Derived-to-base conversion",
173     "Vector conversion",
174     "Vector splat",
175     "Complex-real conversion",
176     "Block Pointer conversion",
177     "Transparent Union Conversion",
178     "Writeback conversion",
179     "OpenCL Zero Event Conversion",
180     "C specific type conversion",
181     "Incompatible pointer conversion"
182   };
183   return Name[Kind];
184 }
185 
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
188 void StandardConversionSequence::setAsIdentityConversion() {
189   First = ICK_Identity;
190   Second = ICK_Identity;
191   Third = ICK_Identity;
192   DeprecatedStringLiteralToCharPtr = false;
193   QualificationIncludesObjCLifetime = false;
194   ReferenceBinding = false;
195   DirectBinding = false;
196   IsLvalueReference = true;
197   BindsToFunctionLvalue = false;
198   BindsToRvalue = false;
199   BindsImplicitObjectArgumentWithoutRefQualifier = false;
200   ObjCLifetimeConversionBinding = false;
201   CopyConstructor = nullptr;
202 }
203 
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208   ImplicitConversionRank Rank = ICR_Exact_Match;
209   if  (GetConversionRank(First) > Rank)
210     Rank = GetConversionRank(First);
211   if  (GetConversionRank(Second) > Rank)
212     Rank = GetConversionRank(Second);
213   if  (GetConversionRank(Third) > Rank)
214     Rank = GetConversionRank(Third);
215   return Rank;
216 }
217 
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
222 bool StandardConversionSequence::isPointerConversionToBool() const {
223   // Note that FromType has not necessarily been transformed by the
224   // array-to-pointer or function-to-pointer implicit conversions, so
225   // check for their presence as well as checking whether FromType is
226   // a pointer.
227   if (getToType(1)->isBooleanType() &&
228       (getFromType()->isPointerType() ||
229        getFromType()->isMemberPointerType() ||
230        getFromType()->isObjCObjectPointerType() ||
231        getFromType()->isBlockPointerType() ||
232        getFromType()->isNullPtrType() ||
233        First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234     return true;
235 
236   return false;
237 }
238 
239 /// isPointerConversionToVoidPointer - Determines whether this
240 /// conversion is a conversion of a pointer to a void pointer. This is
241 /// used as part of the ranking of standard conversion sequences (C++
242 /// 13.3.3.2p4).
243 bool
244 StandardConversionSequence::
245 isPointerConversionToVoidPointer(ASTContext& Context) const {
246   QualType FromType = getFromType();
247   QualType ToType = getToType(1);
248 
249   // Note that FromType has not necessarily been transformed by the
250   // array-to-pointer implicit conversion, so check for its presence
251   // and redo the conversion to get a pointer.
252   if (First == ICK_Array_To_Pointer)
253     FromType = Context.getArrayDecayedType(FromType);
254 
255   if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256     if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257       return ToPtrType->getPointeeType()->isVoidType();
258 
259   return false;
260 }
261 
262 /// Skip any implicit casts which could be either part of a narrowing conversion
263 /// or after one in an implicit conversion.
264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265                                              const Expr *Converted) {
266   // We can have cleanups wrapping the converted expression; these need to be
267   // preserved so that destructors run if necessary.
268   if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
269     Expr *Inner =
270         const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271     return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
272                                     EWC->getObjects());
273   }
274 
275   while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276     switch (ICE->getCastKind()) {
277     case CK_NoOp:
278     case CK_IntegralCast:
279     case CK_IntegralToBoolean:
280     case CK_IntegralToFloating:
281     case CK_BooleanToSignedIntegral:
282     case CK_FloatingToIntegral:
283     case CK_FloatingToBoolean:
284     case CK_FloatingCast:
285       Converted = ICE->getSubExpr();
286       continue;
287 
288     default:
289       return Converted;
290     }
291   }
292 
293   return Converted;
294 }
295 
296 /// Check if this standard conversion sequence represents a narrowing
297 /// conversion, according to C++11 [dcl.init.list]p7.
298 ///
299 /// \param Ctx  The AST context.
300 /// \param Converted  The result of applying this standard conversion sequence.
301 /// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, the
302 ///        value of the expression prior to the narrowing conversion.
303 /// \param ConstantType  If this is an NK_Constant_Narrowing conversion, the
304 ///        type of the expression prior to the narrowing conversion.
305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306 ///        from floating point types to integral types should be ignored.
307 NarrowingKind StandardConversionSequence::getNarrowingKind(
308     ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309     QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310   assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
311 
312   // C++11 [dcl.init.list]p7:
313   //   A narrowing conversion is an implicit conversion ...
314   QualType FromType = getToType(0);
315   QualType ToType = getToType(1);
316 
317   // A conversion to an enumeration type is narrowing if the conversion to
318   // the underlying type is narrowing. This only arises for expressions of
319   // the form 'Enum{init}'.
320   if (auto *ET = ToType->getAs<EnumType>())
321     ToType = ET->getDecl()->getIntegerType();
322 
323   switch (Second) {
324   // 'bool' is an integral type; dispatch to the right place to handle it.
325   case ICK_Boolean_Conversion:
326     if (FromType->isRealFloatingType())
327       goto FloatingIntegralConversion;
328     if (FromType->isIntegralOrUnscopedEnumerationType())
329       goto IntegralConversion;
330     // Boolean conversions can be from pointers and pointers to members
331     // [conv.bool], and those aren't considered narrowing conversions.
332     return NK_Not_Narrowing;
333 
334   // -- from a floating-point type to an integer type, or
335   //
336   // -- from an integer type or unscoped enumeration type to a floating-point
337   //    type, except where the source is a constant expression and the actual
338   //    value after conversion will fit into the target type and will produce
339   //    the original value when converted back to the original type, or
340   case ICK_Floating_Integral:
341   FloatingIntegralConversion:
342     if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343       return NK_Type_Narrowing;
344     } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345                ToType->isRealFloatingType()) {
346       if (IgnoreFloatToIntegralConversion)
347         return NK_Not_Narrowing;
348       llvm::APSInt IntConstantValue;
349       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350       assert(Initializer && "Unknown conversion expression");
351 
352       // If it's value-dependent, we can't tell whether it's narrowing.
353       if (Initializer->isValueDependent())
354         return NK_Dependent_Narrowing;
355 
356       if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357         // Convert the integer to the floating type.
358         llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359         Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360                                 llvm::APFloat::rmNearestTiesToEven);
361         // And back.
362         llvm::APSInt ConvertedValue = IntConstantValue;
363         bool ignored;
364         Result.convertToInteger(ConvertedValue,
365                                 llvm::APFloat::rmTowardZero, &ignored);
366         // If the resulting value is different, this was a narrowing conversion.
367         if (IntConstantValue != ConvertedValue) {
368           ConstantValue = APValue(IntConstantValue);
369           ConstantType = Initializer->getType();
370           return NK_Constant_Narrowing;
371         }
372       } else {
373         // Variables are always narrowings.
374         return NK_Variable_Narrowing;
375       }
376     }
377     return NK_Not_Narrowing;
378 
379   // -- from long double to double or float, or from double to float, except
380   //    where the source is a constant expression and the actual value after
381   //    conversion is within the range of values that can be represented (even
382   //    if it cannot be represented exactly), or
383   case ICK_Floating_Conversion:
384     if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385         Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386       // FromType is larger than ToType.
387       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
388 
389       // If it's value-dependent, we can't tell whether it's narrowing.
390       if (Initializer->isValueDependent())
391         return NK_Dependent_Narrowing;
392 
393       if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
394         // Constant!
395         assert(ConstantValue.isFloat());
396         llvm::APFloat FloatVal = ConstantValue.getFloat();
397         // Convert the source value into the target type.
398         bool ignored;
399         llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400           Ctx.getFloatTypeSemantics(ToType),
401           llvm::APFloat::rmNearestTiesToEven, &ignored);
402         // If there was no overflow, the source value is within the range of
403         // values that can be represented.
404         if (ConvertStatus & llvm::APFloat::opOverflow) {
405           ConstantType = Initializer->getType();
406           return NK_Constant_Narrowing;
407         }
408       } else {
409         return NK_Variable_Narrowing;
410       }
411     }
412     return NK_Not_Narrowing;
413 
414   // -- from an integer type or unscoped enumeration type to an integer type
415   //    that cannot represent all the values of the original type, except where
416   //    the source is a constant expression and the actual value after
417   //    conversion will fit into the target type and will produce the original
418   //    value when converted back to the original type.
419   case ICK_Integral_Conversion:
420   IntegralConversion: {
421     assert(FromType->isIntegralOrUnscopedEnumerationType());
422     assert(ToType->isIntegralOrUnscopedEnumerationType());
423     const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424     const unsigned FromWidth = Ctx.getIntWidth(FromType);
425     const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426     const unsigned ToWidth = Ctx.getIntWidth(ToType);
427 
428     if (FromWidth > ToWidth ||
429         (FromWidth == ToWidth && FromSigned != ToSigned) ||
430         (FromSigned && !ToSigned)) {
431       // Not all values of FromType can be represented in ToType.
432       llvm::APSInt InitializerValue;
433       const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
434 
435       // If it's value-dependent, we can't tell whether it's narrowing.
436       if (Initializer->isValueDependent())
437         return NK_Dependent_Narrowing;
438 
439       if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440         // Such conversions on variables are always narrowing.
441         return NK_Variable_Narrowing;
442       }
443       bool Narrowing = false;
444       if (FromWidth < ToWidth) {
445         // Negative -> unsigned is narrowing. Otherwise, more bits is never
446         // narrowing.
447         if (InitializerValue.isSigned() && InitializerValue.isNegative())
448           Narrowing = true;
449       } else {
450         // Add a bit to the InitializerValue so we don't have to worry about
451         // signed vs. unsigned comparisons.
452         InitializerValue = InitializerValue.extend(
453           InitializerValue.getBitWidth() + 1);
454         // Convert the initializer to and from the target width and signed-ness.
455         llvm::APSInt ConvertedValue = InitializerValue;
456         ConvertedValue = ConvertedValue.trunc(ToWidth);
457         ConvertedValue.setIsSigned(ToSigned);
458         ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459         ConvertedValue.setIsSigned(InitializerValue.isSigned());
460         // If the result is different, this was a narrowing conversion.
461         if (ConvertedValue != InitializerValue)
462           Narrowing = true;
463       }
464       if (Narrowing) {
465         ConstantType = Initializer->getType();
466         ConstantValue = APValue(InitializerValue);
467         return NK_Constant_Narrowing;
468       }
469     }
470     return NK_Not_Narrowing;
471   }
472 
473   default:
474     // Other kinds of conversions are not narrowings.
475     return NK_Not_Narrowing;
476   }
477 }
478 
479 /// dump - Print this standard conversion sequence to standard
480 /// error. Useful for debugging overloading issues.
481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
482   raw_ostream &OS = llvm::errs();
483   bool PrintedSomething = false;
484   if (First != ICK_Identity) {
485     OS << GetImplicitConversionName(First);
486     PrintedSomething = true;
487   }
488 
489   if (Second != ICK_Identity) {
490     if (PrintedSomething) {
491       OS << " -> ";
492     }
493     OS << GetImplicitConversionName(Second);
494 
495     if (CopyConstructor) {
496       OS << " (by copy constructor)";
497     } else if (DirectBinding) {
498       OS << " (direct reference binding)";
499     } else if (ReferenceBinding) {
500       OS << " (reference binding)";
501     }
502     PrintedSomething = true;
503   }
504 
505   if (Third != ICK_Identity) {
506     if (PrintedSomething) {
507       OS << " -> ";
508     }
509     OS << GetImplicitConversionName(Third);
510     PrintedSomething = true;
511   }
512 
513   if (!PrintedSomething) {
514     OS << "No conversions required";
515   }
516 }
517 
518 /// dump - Print this user-defined conversion sequence to standard
519 /// error. Useful for debugging overloading issues.
520 void UserDefinedConversionSequence::dump() const {
521   raw_ostream &OS = llvm::errs();
522   if (Before.First || Before.Second || Before.Third) {
523     Before.dump();
524     OS << " -> ";
525   }
526   if (ConversionFunction)
527     OS << '\'' << *ConversionFunction << '\'';
528   else
529     OS << "aggregate initialization";
530   if (After.First || After.Second || After.Third) {
531     OS << " -> ";
532     After.dump();
533   }
534 }
535 
536 /// dump - Print this implicit conversion sequence to standard
537 /// error. Useful for debugging overloading issues.
538 void ImplicitConversionSequence::dump() const {
539   raw_ostream &OS = llvm::errs();
540   if (isStdInitializerListElement())
541     OS << "Worst std::initializer_list element conversion: ";
542   switch (ConversionKind) {
543   case StandardConversion:
544     OS << "Standard conversion: ";
545     Standard.dump();
546     break;
547   case UserDefinedConversion:
548     OS << "User-defined conversion: ";
549     UserDefined.dump();
550     break;
551   case EllipsisConversion:
552     OS << "Ellipsis conversion";
553     break;
554   case AmbiguousConversion:
555     OS << "Ambiguous conversion";
556     break;
557   case BadConversion:
558     OS << "Bad conversion";
559     break;
560   }
561 
562   OS << "\n";
563 }
564 
565 void AmbiguousConversionSequence::construct() {
566   new (&conversions()) ConversionSet();
567 }
568 
569 void AmbiguousConversionSequence::destruct() {
570   conversions().~ConversionSet();
571 }
572 
573 void
574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575   FromTypePtr = O.FromTypePtr;
576   ToTypePtr = O.ToTypePtr;
577   new (&conversions()) ConversionSet(O.conversions());
578 }
579 
580 namespace {
581   // Structure used by DeductionFailureInfo to store
582   // template argument information.
583   struct DFIArguments {
584     TemplateArgument FirstArg;
585     TemplateArgument SecondArg;
586   };
587   // Structure used by DeductionFailureInfo to store
588   // template parameter and template argument information.
589   struct DFIParamWithArguments : DFIArguments {
590     TemplateParameter Param;
591   };
592   // Structure used by DeductionFailureInfo to store template argument
593   // information and the index of the problematic call argument.
594   struct DFIDeducedMismatchArgs : DFIArguments {
595     TemplateArgumentList *TemplateArgs;
596     unsigned CallArgIndex;
597   };
598   // Structure used by DeductionFailureInfo to store information about
599   // unsatisfied constraints.
600   struct CNSInfo {
601     TemplateArgumentList *TemplateArgs;
602     ConstraintSatisfaction Satisfaction;
603   };
604 }
605 
606 /// Convert from Sema's representation of template deduction information
607 /// to the form used in overload-candidate information.
608 DeductionFailureInfo
609 clang::MakeDeductionFailureInfo(ASTContext &Context,
610                                 Sema::TemplateDeductionResult TDK,
611                                 TemplateDeductionInfo &Info) {
612   DeductionFailureInfo Result;
613   Result.Result = static_cast<unsigned>(TDK);
614   Result.HasDiagnostic = false;
615   switch (TDK) {
616   case Sema::TDK_Invalid:
617   case Sema::TDK_InstantiationDepth:
618   case Sema::TDK_TooManyArguments:
619   case Sema::TDK_TooFewArguments:
620   case Sema::TDK_MiscellaneousDeductionFailure:
621   case Sema::TDK_CUDATargetMismatch:
622     Result.Data = nullptr;
623     break;
624 
625   case Sema::TDK_Incomplete:
626   case Sema::TDK_InvalidExplicitArguments:
627     Result.Data = Info.Param.getOpaqueValue();
628     break;
629 
630   case Sema::TDK_DeducedMismatch:
631   case Sema::TDK_DeducedMismatchNested: {
632     // FIXME: Should allocate from normal heap so that we can free this later.
633     auto *Saved = new (Context) DFIDeducedMismatchArgs;
634     Saved->FirstArg = Info.FirstArg;
635     Saved->SecondArg = Info.SecondArg;
636     Saved->TemplateArgs = Info.take();
637     Saved->CallArgIndex = Info.CallArgIndex;
638     Result.Data = Saved;
639     break;
640   }
641 
642   case Sema::TDK_NonDeducedMismatch: {
643     // FIXME: Should allocate from normal heap so that we can free this later.
644     DFIArguments *Saved = new (Context) DFIArguments;
645     Saved->FirstArg = Info.FirstArg;
646     Saved->SecondArg = Info.SecondArg;
647     Result.Data = Saved;
648     break;
649   }
650 
651   case Sema::TDK_IncompletePack:
652     // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653   case Sema::TDK_Inconsistent:
654   case Sema::TDK_Underqualified: {
655     // FIXME: Should allocate from normal heap so that we can free this later.
656     DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657     Saved->Param = Info.Param;
658     Saved->FirstArg = Info.FirstArg;
659     Saved->SecondArg = Info.SecondArg;
660     Result.Data = Saved;
661     break;
662   }
663 
664   case Sema::TDK_SubstitutionFailure:
665     Result.Data = Info.take();
666     if (Info.hasSFINAEDiagnostic()) {
667       PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668           SourceLocation(), PartialDiagnostic::NullDiagnostic());
669       Info.takeSFINAEDiagnostic(*Diag);
670       Result.HasDiagnostic = true;
671     }
672     break;
673 
674   case Sema::TDK_ConstraintsNotSatisfied: {
675     CNSInfo *Saved = new (Context) CNSInfo;
676     Saved->TemplateArgs = Info.take();
677     Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
678     Result.Data = Saved;
679     break;
680   }
681 
682   case Sema::TDK_Success:
683   case Sema::TDK_NonDependentConversionFailure:
684     llvm_unreachable("not a deduction failure");
685   }
686 
687   return Result;
688 }
689 
690 void DeductionFailureInfo::Destroy() {
691   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692   case Sema::TDK_Success:
693   case Sema::TDK_Invalid:
694   case Sema::TDK_InstantiationDepth:
695   case Sema::TDK_Incomplete:
696   case Sema::TDK_TooManyArguments:
697   case Sema::TDK_TooFewArguments:
698   case Sema::TDK_InvalidExplicitArguments:
699   case Sema::TDK_CUDATargetMismatch:
700   case Sema::TDK_NonDependentConversionFailure:
701     break;
702 
703   case Sema::TDK_IncompletePack:
704   case Sema::TDK_Inconsistent:
705   case Sema::TDK_Underqualified:
706   case Sema::TDK_DeducedMismatch:
707   case Sema::TDK_DeducedMismatchNested:
708   case Sema::TDK_NonDeducedMismatch:
709     // FIXME: Destroy the data?
710     Data = nullptr;
711     break;
712 
713   case Sema::TDK_SubstitutionFailure:
714     // FIXME: Destroy the template argument list?
715     Data = nullptr;
716     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717       Diag->~PartialDiagnosticAt();
718       HasDiagnostic = false;
719     }
720     break;
721 
722   case Sema::TDK_ConstraintsNotSatisfied:
723     // FIXME: Destroy the template argument list?
724     Data = nullptr;
725     if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726       Diag->~PartialDiagnosticAt();
727       HasDiagnostic = false;
728     }
729     break;
730 
731   // Unhandled
732   case Sema::TDK_MiscellaneousDeductionFailure:
733     break;
734   }
735 }
736 
737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
738   if (HasDiagnostic)
739     return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
740   return nullptr;
741 }
742 
743 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745   case Sema::TDK_Success:
746   case Sema::TDK_Invalid:
747   case Sema::TDK_InstantiationDepth:
748   case Sema::TDK_TooManyArguments:
749   case Sema::TDK_TooFewArguments:
750   case Sema::TDK_SubstitutionFailure:
751   case Sema::TDK_DeducedMismatch:
752   case Sema::TDK_DeducedMismatchNested:
753   case Sema::TDK_NonDeducedMismatch:
754   case Sema::TDK_CUDATargetMismatch:
755   case Sema::TDK_NonDependentConversionFailure:
756   case Sema::TDK_ConstraintsNotSatisfied:
757     return TemplateParameter();
758 
759   case Sema::TDK_Incomplete:
760   case Sema::TDK_InvalidExplicitArguments:
761     return TemplateParameter::getFromOpaqueValue(Data);
762 
763   case Sema::TDK_IncompletePack:
764   case Sema::TDK_Inconsistent:
765   case Sema::TDK_Underqualified:
766     return static_cast<DFIParamWithArguments*>(Data)->Param;
767 
768   // Unhandled
769   case Sema::TDK_MiscellaneousDeductionFailure:
770     break;
771   }
772 
773   return TemplateParameter();
774 }
775 
776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778   case Sema::TDK_Success:
779   case Sema::TDK_Invalid:
780   case Sema::TDK_InstantiationDepth:
781   case Sema::TDK_TooManyArguments:
782   case Sema::TDK_TooFewArguments:
783   case Sema::TDK_Incomplete:
784   case Sema::TDK_IncompletePack:
785   case Sema::TDK_InvalidExplicitArguments:
786   case Sema::TDK_Inconsistent:
787   case Sema::TDK_Underqualified:
788   case Sema::TDK_NonDeducedMismatch:
789   case Sema::TDK_CUDATargetMismatch:
790   case Sema::TDK_NonDependentConversionFailure:
791     return nullptr;
792 
793   case Sema::TDK_DeducedMismatch:
794   case Sema::TDK_DeducedMismatchNested:
795     return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
796 
797   case Sema::TDK_SubstitutionFailure:
798     return static_cast<TemplateArgumentList*>(Data);
799 
800   case Sema::TDK_ConstraintsNotSatisfied:
801     return static_cast<CNSInfo*>(Data)->TemplateArgs;
802 
803   // Unhandled
804   case Sema::TDK_MiscellaneousDeductionFailure:
805     break;
806   }
807 
808   return nullptr;
809 }
810 
811 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813   case Sema::TDK_Success:
814   case Sema::TDK_Invalid:
815   case Sema::TDK_InstantiationDepth:
816   case Sema::TDK_Incomplete:
817   case Sema::TDK_TooManyArguments:
818   case Sema::TDK_TooFewArguments:
819   case Sema::TDK_InvalidExplicitArguments:
820   case Sema::TDK_SubstitutionFailure:
821   case Sema::TDK_CUDATargetMismatch:
822   case Sema::TDK_NonDependentConversionFailure:
823   case Sema::TDK_ConstraintsNotSatisfied:
824     return nullptr;
825 
826   case Sema::TDK_IncompletePack:
827   case Sema::TDK_Inconsistent:
828   case Sema::TDK_Underqualified:
829   case Sema::TDK_DeducedMismatch:
830   case Sema::TDK_DeducedMismatchNested:
831   case Sema::TDK_NonDeducedMismatch:
832     return &static_cast<DFIArguments*>(Data)->FirstArg;
833 
834   // Unhandled
835   case Sema::TDK_MiscellaneousDeductionFailure:
836     break;
837   }
838 
839   return nullptr;
840 }
841 
842 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844   case Sema::TDK_Success:
845   case Sema::TDK_Invalid:
846   case Sema::TDK_InstantiationDepth:
847   case Sema::TDK_Incomplete:
848   case Sema::TDK_IncompletePack:
849   case Sema::TDK_TooManyArguments:
850   case Sema::TDK_TooFewArguments:
851   case Sema::TDK_InvalidExplicitArguments:
852   case Sema::TDK_SubstitutionFailure:
853   case Sema::TDK_CUDATargetMismatch:
854   case Sema::TDK_NonDependentConversionFailure:
855   case Sema::TDK_ConstraintsNotSatisfied:
856     return nullptr;
857 
858   case Sema::TDK_Inconsistent:
859   case Sema::TDK_Underqualified:
860   case Sema::TDK_DeducedMismatch:
861   case Sema::TDK_DeducedMismatchNested:
862   case Sema::TDK_NonDeducedMismatch:
863     return &static_cast<DFIArguments*>(Data)->SecondArg;
864 
865   // Unhandled
866   case Sema::TDK_MiscellaneousDeductionFailure:
867     break;
868   }
869 
870   return nullptr;
871 }
872 
873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874   switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875   case Sema::TDK_DeducedMismatch:
876   case Sema::TDK_DeducedMismatchNested:
877     return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
878 
879   default:
880     return llvm::None;
881   }
882 }
883 
884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885     OverloadedOperatorKind Op) {
886   if (!AllowRewrittenCandidates)
887     return false;
888   return Op == OO_EqualEqual || Op == OO_Spaceship;
889 }
890 
891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892     ASTContext &Ctx, const FunctionDecl *FD) {
893   if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
894     return false;
895   // Don't bother adding a reversed candidate that can never be a better
896   // match than the non-reversed version.
897   return FD->getNumParams() != 2 ||
898          !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899                                      FD->getParamDecl(1)->getType()) ||
900          FD->hasAttr<EnableIfAttr>();
901 }
902 
903 void OverloadCandidateSet::destroyCandidates() {
904   for (iterator i = begin(), e = end(); i != e; ++i) {
905     for (auto &C : i->Conversions)
906       C.~ImplicitConversionSequence();
907     if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908       i->DeductionFailure.Destroy();
909   }
910 }
911 
912 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
913   destroyCandidates();
914   SlabAllocator.Reset();
915   NumInlineBytesUsed = 0;
916   Candidates.clear();
917   Functions.clear();
918   Kind = CSK;
919 }
920 
921 namespace {
922   class UnbridgedCastsSet {
923     struct Entry {
924       Expr **Addr;
925       Expr *Saved;
926     };
927     SmallVector<Entry, 2> Entries;
928 
929   public:
930     void save(Sema &S, Expr *&E) {
931       assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
932       Entry entry = { &E, E };
933       Entries.push_back(entry);
934       E = S.stripARCUnbridgedCast(E);
935     }
936 
937     void restore() {
938       for (SmallVectorImpl<Entry>::iterator
939              i = Entries.begin(), e = Entries.end(); i != e; ++i)
940         *i->Addr = i->Saved;
941     }
942   };
943 }
944 
945 /// checkPlaceholderForOverload - Do any interesting placeholder-like
946 /// preprocessing on the given expression.
947 ///
948 /// \param unbridgedCasts a collection to which to add unbridged casts;
949 ///   without this, they will be immediately diagnosed as errors
950 ///
951 /// Return true on unrecoverable error.
952 static bool
953 checkPlaceholderForOverload(Sema &S, Expr *&E,
954                             UnbridgedCastsSet *unbridgedCasts = nullptr) {
955   if (const BuiltinType *placeholder =  E->getType()->getAsPlaceholderType()) {
956     // We can't handle overloaded expressions here because overload
957     // resolution might reasonably tweak them.
958     if (placeholder->getKind() == BuiltinType::Overload) return false;
959 
960     // If the context potentially accepts unbridged ARC casts, strip
961     // the unbridged cast and add it to the collection for later restoration.
962     if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
963         unbridgedCasts) {
964       unbridgedCasts->save(S, E);
965       return false;
966     }
967 
968     // Go ahead and check everything else.
969     ExprResult result = S.CheckPlaceholderExpr(E);
970     if (result.isInvalid())
971       return true;
972 
973     E = result.get();
974     return false;
975   }
976 
977   // Nothing to do.
978   return false;
979 }
980 
981 /// checkArgPlaceholdersForOverload - Check a set of call operands for
982 /// placeholders.
983 static bool checkArgPlaceholdersForOverload(Sema &S,
984                                             MultiExprArg Args,
985                                             UnbridgedCastsSet &unbridged) {
986   for (unsigned i = 0, e = Args.size(); i != e; ++i)
987     if (checkPlaceholderForOverload(S, Args[i], &unbridged))
988       return true;
989 
990   return false;
991 }
992 
993 /// Determine whether the given New declaration is an overload of the
994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995 /// New and Old cannot be overloaded, e.g., if New has the same signature as
996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997 /// functions (or function templates) at all. When it does return Ovl_Match or
998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1000 /// declaration.
1001 ///
1002 /// Example: Given the following input:
1003 ///
1004 ///   void f(int, float); // #1
1005 ///   void f(int, int); // #2
1006 ///   int f(int, int); // #3
1007 ///
1008 /// When we process #1, there is no previous declaration of "f", so IsOverload
1009 /// will not be used.
1010 ///
1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1014 /// unchanged.
1015 ///
1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1020 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1021 ///
1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023 /// by a using declaration. The rules for whether to hide shadow declarations
1024 /// ignore some properties which otherwise figure into a function template's
1025 /// signature.
1026 Sema::OverloadKind
1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028                     NamedDecl *&Match, bool NewIsUsingDecl) {
1029   for (LookupResult::iterator I = Old.begin(), E = Old.end();
1030          I != E; ++I) {
1031     NamedDecl *OldD = *I;
1032 
1033     bool OldIsUsingDecl = false;
1034     if (isa<UsingShadowDecl>(OldD)) {
1035       OldIsUsingDecl = true;
1036 
1037       // We can always introduce two using declarations into the same
1038       // context, even if they have identical signatures.
1039       if (NewIsUsingDecl) continue;
1040 
1041       OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1042     }
1043 
1044     // A using-declaration does not conflict with another declaration
1045     // if one of them is hidden.
1046     if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1047       continue;
1048 
1049     // If either declaration was introduced by a using declaration,
1050     // we'll need to use slightly different rules for matching.
1051     // Essentially, these rules are the normal rules, except that
1052     // function templates hide function templates with different
1053     // return types or template parameter lists.
1054     bool UseMemberUsingDeclRules =
1055       (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056       !New->getFriendObjectKind();
1057 
1058     if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059       if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060         if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061           HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1062           continue;
1063         }
1064 
1065         if (!isa<FunctionTemplateDecl>(OldD) &&
1066             !shouldLinkPossiblyHiddenDecl(*I, New))
1067           continue;
1068 
1069         Match = *I;
1070         return Ovl_Match;
1071       }
1072 
1073       // Builtins that have custom typechecking or have a reference should
1074       // not be overloadable or redeclarable.
1075       if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1076         Match = *I;
1077         return Ovl_NonFunction;
1078       }
1079     } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080       // We can overload with these, which can show up when doing
1081       // redeclaration checks for UsingDecls.
1082       assert(Old.getLookupKind() == LookupUsingDeclName);
1083     } else if (isa<TagDecl>(OldD)) {
1084       // We can always overload with tags by hiding them.
1085     } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086       // Optimistically assume that an unresolved using decl will
1087       // overload; if it doesn't, we'll have to diagnose during
1088       // template instantiation.
1089       //
1090       // Exception: if the scope is dependent and this is not a class
1091       // member, the using declaration can only introduce an enumerator.
1092       if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1093         Match = *I;
1094         return Ovl_NonFunction;
1095       }
1096     } else {
1097       // (C++ 13p1):
1098       //   Only function declarations can be overloaded; object and type
1099       //   declarations cannot be overloaded.
1100       Match = *I;
1101       return Ovl_NonFunction;
1102     }
1103   }
1104 
1105   // C++ [temp.friend]p1:
1106   //   For a friend function declaration that is not a template declaration:
1107   //    -- if the name of the friend is a qualified or unqualified template-id,
1108   //       [...], otherwise
1109   //    -- if the name of the friend is a qualified-id and a matching
1110   //       non-template function is found in the specified class or namespace,
1111   //       the friend declaration refers to that function, otherwise,
1112   //    -- if the name of the friend is a qualified-id and a matching function
1113   //       template is found in the specified class or namespace, the friend
1114   //       declaration refers to the deduced specialization of that function
1115   //       template, otherwise
1116   //    -- the name shall be an unqualified-id [...]
1117   // If we get here for a qualified friend declaration, we've just reached the
1118   // third bullet. If the type of the friend is dependent, skip this lookup
1119   // until instantiation.
1120   if (New->getFriendObjectKind() && New->getQualifier() &&
1121       !New->getDescribedFunctionTemplate() &&
1122       !New->getDependentSpecializationInfo() &&
1123       !New->getType()->isDependentType()) {
1124     LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125     TemplateSpecResult.addAllDecls(Old);
1126     if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127                                             /*QualifiedFriend*/true)) {
1128       New->setInvalidDecl();
1129       return Ovl_Overload;
1130     }
1131 
1132     Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1133     return Ovl_Match;
1134   }
1135 
1136   return Ovl_Overload;
1137 }
1138 
1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140                       bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1141   // C++ [basic.start.main]p2: This function shall not be overloaded.
1142   if (New->isMain())
1143     return false;
1144 
1145   // MSVCRT user defined entry points cannot be overloaded.
1146   if (New->isMSVCRTEntryPoint())
1147     return false;
1148 
1149   FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1150   FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1151 
1152   // C++ [temp.fct]p2:
1153   //   A function template can be overloaded with other function templates
1154   //   and with normal (non-template) functions.
1155   if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1156     return true;
1157 
1158   // Is the function New an overload of the function Old?
1159   QualType OldQType = Context.getCanonicalType(Old->getType());
1160   QualType NewQType = Context.getCanonicalType(New->getType());
1161 
1162   // Compare the signatures (C++ 1.3.10) of the two functions to
1163   // determine whether they are overloads. If we find any mismatch
1164   // in the signature, they are overloads.
1165 
1166   // If either of these functions is a K&R-style function (no
1167   // prototype), then we consider them to have matching signatures.
1168   if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1169       isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1170     return false;
1171 
1172   const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1173   const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1174 
1175   // The signature of a function includes the types of its
1176   // parameters (C++ 1.3.10), which includes the presence or absence
1177   // of the ellipsis; see C++ DR 357).
1178   if (OldQType != NewQType &&
1179       (OldType->getNumParams() != NewType->getNumParams() ||
1180        OldType->isVariadic() != NewType->isVariadic() ||
1181        !FunctionParamTypesAreEqual(OldType, NewType)))
1182     return true;
1183 
1184   // C++ [temp.over.link]p4:
1185   //   The signature of a function template consists of its function
1186   //   signature, its return type and its template parameter list. The names
1187   //   of the template parameters are significant only for establishing the
1188   //   relationship between the template parameters and the rest of the
1189   //   signature.
1190   //
1191   // We check the return type and template parameter lists for function
1192   // templates first; the remaining checks follow.
1193   //
1194   // However, we don't consider either of these when deciding whether
1195   // a member introduced by a shadow declaration is hidden.
1196   if (!UseMemberUsingDeclRules && NewTemplate &&
1197       (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1198                                        OldTemplate->getTemplateParameters(),
1199                                        false, TPL_TemplateMatch) ||
1200        !Context.hasSameType(Old->getDeclaredReturnType(),
1201                             New->getDeclaredReturnType())))
1202     return true;
1203 
1204   // If the function is a class member, its signature includes the
1205   // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1206   //
1207   // As part of this, also check whether one of the member functions
1208   // is static, in which case they are not overloads (C++
1209   // 13.1p2). While not part of the definition of the signature,
1210   // this check is important to determine whether these functions
1211   // can be overloaded.
1212   CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1213   CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1214   if (OldMethod && NewMethod &&
1215       !OldMethod->isStatic() && !NewMethod->isStatic()) {
1216     if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1217       if (!UseMemberUsingDeclRules &&
1218           (OldMethod->getRefQualifier() == RQ_None ||
1219            NewMethod->getRefQualifier() == RQ_None)) {
1220         // C++0x [over.load]p2:
1221         //   - Member function declarations with the same name and the same
1222         //     parameter-type-list as well as member function template
1223         //     declarations with the same name, the same parameter-type-list, and
1224         //     the same template parameter lists cannot be overloaded if any of
1225         //     them, but not all, have a ref-qualifier (8.3.5).
1226         Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1227           << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1228         Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1229       }
1230       return true;
1231     }
1232 
1233     // We may not have applied the implicit const for a constexpr member
1234     // function yet (because we haven't yet resolved whether this is a static
1235     // or non-static member function). Add it now, on the assumption that this
1236     // is a redeclaration of OldMethod.
1237     auto OldQuals = OldMethod->getMethodQualifiers();
1238     auto NewQuals = NewMethod->getMethodQualifiers();
1239     if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1240         !isa<CXXConstructorDecl>(NewMethod))
1241       NewQuals.addConst();
1242     // We do not allow overloading based off of '__restrict'.
1243     OldQuals.removeRestrict();
1244     NewQuals.removeRestrict();
1245     if (OldQuals != NewQuals)
1246       return true;
1247   }
1248 
1249   // Though pass_object_size is placed on parameters and takes an argument, we
1250   // consider it to be a function-level modifier for the sake of function
1251   // identity. Either the function has one or more parameters with
1252   // pass_object_size or it doesn't.
1253   if (functionHasPassObjectSizeParams(New) !=
1254       functionHasPassObjectSizeParams(Old))
1255     return true;
1256 
1257   // enable_if attributes are an order-sensitive part of the signature.
1258   for (specific_attr_iterator<EnableIfAttr>
1259          NewI = New->specific_attr_begin<EnableIfAttr>(),
1260          NewE = New->specific_attr_end<EnableIfAttr>(),
1261          OldI = Old->specific_attr_begin<EnableIfAttr>(),
1262          OldE = Old->specific_attr_end<EnableIfAttr>();
1263        NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1264     if (NewI == NewE || OldI == OldE)
1265       return true;
1266     llvm::FoldingSetNodeID NewID, OldID;
1267     NewI->getCond()->Profile(NewID, Context, true);
1268     OldI->getCond()->Profile(OldID, Context, true);
1269     if (NewID != OldID)
1270       return true;
1271   }
1272 
1273   if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1274     // Don't allow overloading of destructors.  (In theory we could, but it
1275     // would be a giant change to clang.)
1276     if (isa<CXXDestructorDecl>(New))
1277       return false;
1278 
1279     CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1280                        OldTarget = IdentifyCUDATarget(Old);
1281     if (NewTarget == CFT_InvalidTarget)
1282       return false;
1283 
1284     assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1285 
1286     // Allow overloading of functions with same signature and different CUDA
1287     // target attributes.
1288     return NewTarget != OldTarget;
1289   }
1290 
1291   // TODO: Concepts: Check function trailing requires clauses here.
1292 
1293   // The signatures match; this is not an overload.
1294   return false;
1295 }
1296 
1297 /// Tries a user-defined conversion from From to ToType.
1298 ///
1299 /// Produces an implicit conversion sequence for when a standard conversion
1300 /// is not an option. See TryImplicitConversion for more information.
1301 static ImplicitConversionSequence
1302 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1303                          bool SuppressUserConversions,
1304                          bool AllowExplicit,
1305                          bool InOverloadResolution,
1306                          bool CStyle,
1307                          bool AllowObjCWritebackConversion,
1308                          bool AllowObjCConversionOnExplicit) {
1309   ImplicitConversionSequence ICS;
1310 
1311   if (SuppressUserConversions) {
1312     // We're not in the case above, so there is no conversion that
1313     // we can perform.
1314     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1315     return ICS;
1316   }
1317 
1318   // Attempt user-defined conversion.
1319   OverloadCandidateSet Conversions(From->getExprLoc(),
1320                                    OverloadCandidateSet::CSK_Normal);
1321   switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1322                                   Conversions, AllowExplicit,
1323                                   AllowObjCConversionOnExplicit)) {
1324   case OR_Success:
1325   case OR_Deleted:
1326     ICS.setUserDefined();
1327     // C++ [over.ics.user]p4:
1328     //   A conversion of an expression of class type to the same class
1329     //   type is given Exact Match rank, and a conversion of an
1330     //   expression of class type to a base class of that type is
1331     //   given Conversion rank, in spite of the fact that a copy
1332     //   constructor (i.e., a user-defined conversion function) is
1333     //   called for those cases.
1334     if (CXXConstructorDecl *Constructor
1335           = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1336       QualType FromCanon
1337         = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1338       QualType ToCanon
1339         = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1340       if (Constructor->isCopyConstructor() &&
1341           (FromCanon == ToCanon ||
1342            S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1343         // Turn this into a "standard" conversion sequence, so that it
1344         // gets ranked with standard conversion sequences.
1345         DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1346         ICS.setStandard();
1347         ICS.Standard.setAsIdentityConversion();
1348         ICS.Standard.setFromType(From->getType());
1349         ICS.Standard.setAllToTypes(ToType);
1350         ICS.Standard.CopyConstructor = Constructor;
1351         ICS.Standard.FoundCopyConstructor = Found;
1352         if (ToCanon != FromCanon)
1353           ICS.Standard.Second = ICK_Derived_To_Base;
1354       }
1355     }
1356     break;
1357 
1358   case OR_Ambiguous:
1359     ICS.setAmbiguous();
1360     ICS.Ambiguous.setFromType(From->getType());
1361     ICS.Ambiguous.setToType(ToType);
1362     for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1363          Cand != Conversions.end(); ++Cand)
1364       if (Cand->Best)
1365         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1366     break;
1367 
1368     // Fall through.
1369   case OR_No_Viable_Function:
1370     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1371     break;
1372   }
1373 
1374   return ICS;
1375 }
1376 
1377 /// TryImplicitConversion - Attempt to perform an implicit conversion
1378 /// from the given expression (Expr) to the given type (ToType). This
1379 /// function returns an implicit conversion sequence that can be used
1380 /// to perform the initialization. Given
1381 ///
1382 ///   void f(float f);
1383 ///   void g(int i) { f(i); }
1384 ///
1385 /// this routine would produce an implicit conversion sequence to
1386 /// describe the initialization of f from i, which will be a standard
1387 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1388 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1389 //
1390 /// Note that this routine only determines how the conversion can be
1391 /// performed; it does not actually perform the conversion. As such,
1392 /// it will not produce any diagnostics if no conversion is available,
1393 /// but will instead return an implicit conversion sequence of kind
1394 /// "BadConversion".
1395 ///
1396 /// If @p SuppressUserConversions, then user-defined conversions are
1397 /// not permitted.
1398 /// If @p AllowExplicit, then explicit user-defined conversions are
1399 /// permitted.
1400 ///
1401 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1402 /// writeback conversion, which allows __autoreleasing id* parameters to
1403 /// be initialized with __strong id* or __weak id* arguments.
1404 static ImplicitConversionSequence
1405 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1406                       bool SuppressUserConversions,
1407                       bool AllowExplicit,
1408                       bool InOverloadResolution,
1409                       bool CStyle,
1410                       bool AllowObjCWritebackConversion,
1411                       bool AllowObjCConversionOnExplicit) {
1412   ImplicitConversionSequence ICS;
1413   if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1414                            ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1415     ICS.setStandard();
1416     return ICS;
1417   }
1418 
1419   if (!S.getLangOpts().CPlusPlus) {
1420     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1421     return ICS;
1422   }
1423 
1424   // C++ [over.ics.user]p4:
1425   //   A conversion of an expression of class type to the same class
1426   //   type is given Exact Match rank, and a conversion of an
1427   //   expression of class type to a base class of that type is
1428   //   given Conversion rank, in spite of the fact that a copy/move
1429   //   constructor (i.e., a user-defined conversion function) is
1430   //   called for those cases.
1431   QualType FromType = From->getType();
1432   if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1433       (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1434        S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1435     ICS.setStandard();
1436     ICS.Standard.setAsIdentityConversion();
1437     ICS.Standard.setFromType(FromType);
1438     ICS.Standard.setAllToTypes(ToType);
1439 
1440     // We don't actually check at this point whether there is a valid
1441     // copy/move constructor, since overloading just assumes that it
1442     // exists. When we actually perform initialization, we'll find the
1443     // appropriate constructor to copy the returned object, if needed.
1444     ICS.Standard.CopyConstructor = nullptr;
1445 
1446     // Determine whether this is considered a derived-to-base conversion.
1447     if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1448       ICS.Standard.Second = ICK_Derived_To_Base;
1449 
1450     return ICS;
1451   }
1452 
1453   return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1454                                   AllowExplicit, InOverloadResolution, CStyle,
1455                                   AllowObjCWritebackConversion,
1456                                   AllowObjCConversionOnExplicit);
1457 }
1458 
1459 ImplicitConversionSequence
1460 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1461                             bool SuppressUserConversions,
1462                             bool AllowExplicit,
1463                             bool InOverloadResolution,
1464                             bool CStyle,
1465                             bool AllowObjCWritebackConversion) {
1466   return ::TryImplicitConversion(*this, From, ToType,
1467                                  SuppressUserConversions, AllowExplicit,
1468                                  InOverloadResolution, CStyle,
1469                                  AllowObjCWritebackConversion,
1470                                  /*AllowObjCConversionOnExplicit=*/false);
1471 }
1472 
1473 /// PerformImplicitConversion - Perform an implicit conversion of the
1474 /// expression From to the type ToType. Returns the
1475 /// converted expression. Flavor is the kind of conversion we're
1476 /// performing, used in the error message. If @p AllowExplicit,
1477 /// explicit user-defined conversions are permitted.
1478 ExprResult
1479 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1480                                 AssignmentAction Action, bool AllowExplicit) {
1481   ImplicitConversionSequence ICS;
1482   return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1483 }
1484 
1485 ExprResult
1486 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1487                                 AssignmentAction Action, bool AllowExplicit,
1488                                 ImplicitConversionSequence& ICS) {
1489   if (checkPlaceholderForOverload(*this, From))
1490     return ExprError();
1491 
1492   // Objective-C ARC: Determine whether we will allow the writeback conversion.
1493   bool AllowObjCWritebackConversion
1494     = getLangOpts().ObjCAutoRefCount &&
1495       (Action == AA_Passing || Action == AA_Sending);
1496   if (getLangOpts().ObjC)
1497     CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1498                                       From->getType(), From);
1499   ICS = ::TryImplicitConversion(*this, From, ToType,
1500                                 /*SuppressUserConversions=*/false,
1501                                 AllowExplicit,
1502                                 /*InOverloadResolution=*/false,
1503                                 /*CStyle=*/false,
1504                                 AllowObjCWritebackConversion,
1505                                 /*AllowObjCConversionOnExplicit=*/false);
1506   return PerformImplicitConversion(From, ToType, ICS, Action);
1507 }
1508 
1509 /// Determine whether the conversion from FromType to ToType is a valid
1510 /// conversion that strips "noexcept" or "noreturn" off the nested function
1511 /// type.
1512 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1513                                 QualType &ResultTy) {
1514   if (Context.hasSameUnqualifiedType(FromType, ToType))
1515     return false;
1516 
1517   // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1518   //                    or F(t noexcept) -> F(t)
1519   // where F adds one of the following at most once:
1520   //   - a pointer
1521   //   - a member pointer
1522   //   - a block pointer
1523   // Changes here need matching changes in FindCompositePointerType.
1524   CanQualType CanTo = Context.getCanonicalType(ToType);
1525   CanQualType CanFrom = Context.getCanonicalType(FromType);
1526   Type::TypeClass TyClass = CanTo->getTypeClass();
1527   if (TyClass != CanFrom->getTypeClass()) return false;
1528   if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1529     if (TyClass == Type::Pointer) {
1530       CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1531       CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1532     } else if (TyClass == Type::BlockPointer) {
1533       CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1534       CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1535     } else if (TyClass == Type::MemberPointer) {
1536       auto ToMPT = CanTo.castAs<MemberPointerType>();
1537       auto FromMPT = CanFrom.castAs<MemberPointerType>();
1538       // A function pointer conversion cannot change the class of the function.
1539       if (ToMPT->getClass() != FromMPT->getClass())
1540         return false;
1541       CanTo = ToMPT->getPointeeType();
1542       CanFrom = FromMPT->getPointeeType();
1543     } else {
1544       return false;
1545     }
1546 
1547     TyClass = CanTo->getTypeClass();
1548     if (TyClass != CanFrom->getTypeClass()) return false;
1549     if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1550       return false;
1551   }
1552 
1553   const auto *FromFn = cast<FunctionType>(CanFrom);
1554   FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1555 
1556   const auto *ToFn = cast<FunctionType>(CanTo);
1557   FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1558 
1559   bool Changed = false;
1560 
1561   // Drop 'noreturn' if not present in target type.
1562   if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1563     FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1564     Changed = true;
1565   }
1566 
1567   // Drop 'noexcept' if not present in target type.
1568   if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1569     const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1570     if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1571       FromFn = cast<FunctionType>(
1572           Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1573                                                    EST_None)
1574                  .getTypePtr());
1575       Changed = true;
1576     }
1577 
1578     // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1579     // only if the ExtParameterInfo lists of the two function prototypes can be
1580     // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1581     SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1582     bool CanUseToFPT, CanUseFromFPT;
1583     if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1584                                       CanUseFromFPT, NewParamInfos) &&
1585         CanUseToFPT && !CanUseFromFPT) {
1586       FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1587       ExtInfo.ExtParameterInfos =
1588           NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1589       QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1590                                             FromFPT->getParamTypes(), ExtInfo);
1591       FromFn = QT->getAs<FunctionType>();
1592       Changed = true;
1593     }
1594   }
1595 
1596   if (!Changed)
1597     return false;
1598 
1599   assert(QualType(FromFn, 0).isCanonical());
1600   if (QualType(FromFn, 0) != CanTo) return false;
1601 
1602   ResultTy = ToType;
1603   return true;
1604 }
1605 
1606 /// Determine whether the conversion from FromType to ToType is a valid
1607 /// vector conversion.
1608 ///
1609 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1610 /// conversion.
1611 static bool IsVectorConversion(Sema &S, QualType FromType,
1612                                QualType ToType, ImplicitConversionKind &ICK) {
1613   // We need at least one of these types to be a vector type to have a vector
1614   // conversion.
1615   if (!ToType->isVectorType() && !FromType->isVectorType())
1616     return false;
1617 
1618   // Identical types require no conversions.
1619   if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1620     return false;
1621 
1622   // There are no conversions between extended vector types, only identity.
1623   if (ToType->isExtVectorType()) {
1624     // There are no conversions between extended vector types other than the
1625     // identity conversion.
1626     if (FromType->isExtVectorType())
1627       return false;
1628 
1629     // Vector splat from any arithmetic type to a vector.
1630     if (FromType->isArithmeticType()) {
1631       ICK = ICK_Vector_Splat;
1632       return true;
1633     }
1634   }
1635 
1636   // We can perform the conversion between vector types in the following cases:
1637   // 1)vector types are equivalent AltiVec and GCC vector types
1638   // 2)lax vector conversions are permitted and the vector types are of the
1639   //   same size
1640   if (ToType->isVectorType() && FromType->isVectorType()) {
1641     if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1642         S.isLaxVectorConversion(FromType, ToType)) {
1643       ICK = ICK_Vector_Conversion;
1644       return true;
1645     }
1646   }
1647 
1648   return false;
1649 }
1650 
1651 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1652                                 bool InOverloadResolution,
1653                                 StandardConversionSequence &SCS,
1654                                 bool CStyle);
1655 
1656 /// IsStandardConversion - Determines whether there is a standard
1657 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1658 /// expression From to the type ToType. Standard conversion sequences
1659 /// only consider non-class types; for conversions that involve class
1660 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1661 /// contain the standard conversion sequence required to perform this
1662 /// conversion and this routine will return true. Otherwise, this
1663 /// routine will return false and the value of SCS is unspecified.
1664 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1665                                  bool InOverloadResolution,
1666                                  StandardConversionSequence &SCS,
1667                                  bool CStyle,
1668                                  bool AllowObjCWritebackConversion) {
1669   QualType FromType = From->getType();
1670 
1671   // Standard conversions (C++ [conv])
1672   SCS.setAsIdentityConversion();
1673   SCS.IncompatibleObjC = false;
1674   SCS.setFromType(FromType);
1675   SCS.CopyConstructor = nullptr;
1676 
1677   // There are no standard conversions for class types in C++, so
1678   // abort early. When overloading in C, however, we do permit them.
1679   if (S.getLangOpts().CPlusPlus &&
1680       (FromType->isRecordType() || ToType->isRecordType()))
1681     return false;
1682 
1683   // The first conversion can be an lvalue-to-rvalue conversion,
1684   // array-to-pointer conversion, or function-to-pointer conversion
1685   // (C++ 4p1).
1686 
1687   if (FromType == S.Context.OverloadTy) {
1688     DeclAccessPair AccessPair;
1689     if (FunctionDecl *Fn
1690           = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1691                                                  AccessPair)) {
1692       // We were able to resolve the address of the overloaded function,
1693       // so we can convert to the type of that function.
1694       FromType = Fn->getType();
1695       SCS.setFromType(FromType);
1696 
1697       // we can sometimes resolve &foo<int> regardless of ToType, so check
1698       // if the type matches (identity) or we are converting to bool
1699       if (!S.Context.hasSameUnqualifiedType(
1700                       S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1701         QualType resultTy;
1702         // if the function type matches except for [[noreturn]], it's ok
1703         if (!S.IsFunctionConversion(FromType,
1704               S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1705           // otherwise, only a boolean conversion is standard
1706           if (!ToType->isBooleanType())
1707             return false;
1708       }
1709 
1710       // Check if the "from" expression is taking the address of an overloaded
1711       // function and recompute the FromType accordingly. Take advantage of the
1712       // fact that non-static member functions *must* have such an address-of
1713       // expression.
1714       CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1715       if (Method && !Method->isStatic()) {
1716         assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1717                "Non-unary operator on non-static member address");
1718         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1719                == UO_AddrOf &&
1720                "Non-address-of operator on non-static member address");
1721         const Type *ClassType
1722           = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1723         FromType = S.Context.getMemberPointerType(FromType, ClassType);
1724       } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1725         assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1726                UO_AddrOf &&
1727                "Non-address-of operator for overloaded function expression");
1728         FromType = S.Context.getPointerType(FromType);
1729       }
1730 
1731       // Check that we've computed the proper type after overload resolution.
1732       // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1733       // be calling it from within an NDEBUG block.
1734       assert(S.Context.hasSameType(
1735         FromType,
1736         S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1737     } else {
1738       return false;
1739     }
1740   }
1741   // Lvalue-to-rvalue conversion (C++11 4.1):
1742   //   A glvalue (3.10) of a non-function, non-array type T can
1743   //   be converted to a prvalue.
1744   bool argIsLValue = From->isGLValue();
1745   if (argIsLValue &&
1746       !FromType->isFunctionType() && !FromType->isArrayType() &&
1747       S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1748     SCS.First = ICK_Lvalue_To_Rvalue;
1749 
1750     // C11 6.3.2.1p2:
1751     //   ... if the lvalue has atomic type, the value has the non-atomic version
1752     //   of the type of the lvalue ...
1753     if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1754       FromType = Atomic->getValueType();
1755 
1756     // If T is a non-class type, the type of the rvalue is the
1757     // cv-unqualified version of T. Otherwise, the type of the rvalue
1758     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1759     // just strip the qualifiers because they don't matter.
1760     FromType = FromType.getUnqualifiedType();
1761   } else if (FromType->isArrayType()) {
1762     // Array-to-pointer conversion (C++ 4.2)
1763     SCS.First = ICK_Array_To_Pointer;
1764 
1765     // An lvalue or rvalue of type "array of N T" or "array of unknown
1766     // bound of T" can be converted to an rvalue of type "pointer to
1767     // T" (C++ 4.2p1).
1768     FromType = S.Context.getArrayDecayedType(FromType);
1769 
1770     if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1771       // This conversion is deprecated in C++03 (D.4)
1772       SCS.DeprecatedStringLiteralToCharPtr = true;
1773 
1774       // For the purpose of ranking in overload resolution
1775       // (13.3.3.1.1), this conversion is considered an
1776       // array-to-pointer conversion followed by a qualification
1777       // conversion (4.4). (C++ 4.2p2)
1778       SCS.Second = ICK_Identity;
1779       SCS.Third = ICK_Qualification;
1780       SCS.QualificationIncludesObjCLifetime = false;
1781       SCS.setAllToTypes(FromType);
1782       return true;
1783     }
1784   } else if (FromType->isFunctionType() && argIsLValue) {
1785     // Function-to-pointer conversion (C++ 4.3).
1786     SCS.First = ICK_Function_To_Pointer;
1787 
1788     if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1789       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1790         if (!S.checkAddressOfFunctionIsAvailable(FD))
1791           return false;
1792 
1793     // An lvalue of function type T can be converted to an rvalue of
1794     // type "pointer to T." The result is a pointer to the
1795     // function. (C++ 4.3p1).
1796     FromType = S.Context.getPointerType(FromType);
1797   } else {
1798     // We don't require any conversions for the first step.
1799     SCS.First = ICK_Identity;
1800   }
1801   SCS.setToType(0, FromType);
1802 
1803   // The second conversion can be an integral promotion, floating
1804   // point promotion, integral conversion, floating point conversion,
1805   // floating-integral conversion, pointer conversion,
1806   // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1807   // For overloading in C, this can also be a "compatible-type"
1808   // conversion.
1809   bool IncompatibleObjC = false;
1810   ImplicitConversionKind SecondICK = ICK_Identity;
1811   if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1812     // The unqualified versions of the types are the same: there's no
1813     // conversion to do.
1814     SCS.Second = ICK_Identity;
1815   } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1816     // Integral promotion (C++ 4.5).
1817     SCS.Second = ICK_Integral_Promotion;
1818     FromType = ToType.getUnqualifiedType();
1819   } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1820     // Floating point promotion (C++ 4.6).
1821     SCS.Second = ICK_Floating_Promotion;
1822     FromType = ToType.getUnqualifiedType();
1823   } else if (S.IsComplexPromotion(FromType, ToType)) {
1824     // Complex promotion (Clang extension)
1825     SCS.Second = ICK_Complex_Promotion;
1826     FromType = ToType.getUnqualifiedType();
1827   } else if (ToType->isBooleanType() &&
1828              (FromType->isArithmeticType() ||
1829               FromType->isAnyPointerType() ||
1830               FromType->isBlockPointerType() ||
1831               FromType->isMemberPointerType() ||
1832               FromType->isNullPtrType())) {
1833     // Boolean conversions (C++ 4.12).
1834     SCS.Second = ICK_Boolean_Conversion;
1835     FromType = S.Context.BoolTy;
1836   } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1837              ToType->isIntegralType(S.Context)) {
1838     // Integral conversions (C++ 4.7).
1839     SCS.Second = ICK_Integral_Conversion;
1840     FromType = ToType.getUnqualifiedType();
1841   } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1842     // Complex conversions (C99 6.3.1.6)
1843     SCS.Second = ICK_Complex_Conversion;
1844     FromType = ToType.getUnqualifiedType();
1845   } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1846              (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1847     // Complex-real conversions (C99 6.3.1.7)
1848     SCS.Second = ICK_Complex_Real;
1849     FromType = ToType.getUnqualifiedType();
1850   } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1851     // FIXME: disable conversions between long double and __float128 if
1852     // their representation is different until there is back end support
1853     // We of course allow this conversion if long double is really double.
1854     if (&S.Context.getFloatTypeSemantics(FromType) !=
1855         &S.Context.getFloatTypeSemantics(ToType)) {
1856       bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1857                                     ToType == S.Context.LongDoubleTy) ||
1858                                    (FromType == S.Context.LongDoubleTy &&
1859                                     ToType == S.Context.Float128Ty));
1860       if (Float128AndLongDouble &&
1861           (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1862            &llvm::APFloat::PPCDoubleDouble()))
1863         return false;
1864     }
1865     // Floating point conversions (C++ 4.8).
1866     SCS.Second = ICK_Floating_Conversion;
1867     FromType = ToType.getUnqualifiedType();
1868   } else if ((FromType->isRealFloatingType() &&
1869               ToType->isIntegralType(S.Context)) ||
1870              (FromType->isIntegralOrUnscopedEnumerationType() &&
1871               ToType->isRealFloatingType())) {
1872     // Floating-integral conversions (C++ 4.9).
1873     SCS.Second = ICK_Floating_Integral;
1874     FromType = ToType.getUnqualifiedType();
1875   } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1876     SCS.Second = ICK_Block_Pointer_Conversion;
1877   } else if (AllowObjCWritebackConversion &&
1878              S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1879     SCS.Second = ICK_Writeback_Conversion;
1880   } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1881                                    FromType, IncompatibleObjC)) {
1882     // Pointer conversions (C++ 4.10).
1883     SCS.Second = ICK_Pointer_Conversion;
1884     SCS.IncompatibleObjC = IncompatibleObjC;
1885     FromType = FromType.getUnqualifiedType();
1886   } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1887                                          InOverloadResolution, FromType)) {
1888     // Pointer to member conversions (4.11).
1889     SCS.Second = ICK_Pointer_Member;
1890   } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1891     SCS.Second = SecondICK;
1892     FromType = ToType.getUnqualifiedType();
1893   } else if (!S.getLangOpts().CPlusPlus &&
1894              S.Context.typesAreCompatible(ToType, FromType)) {
1895     // Compatible conversions (Clang extension for C function overloading)
1896     SCS.Second = ICK_Compatible_Conversion;
1897     FromType = ToType.getUnqualifiedType();
1898   } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1899                                              InOverloadResolution,
1900                                              SCS, CStyle)) {
1901     SCS.Second = ICK_TransparentUnionConversion;
1902     FromType = ToType;
1903   } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1904                                  CStyle)) {
1905     // tryAtomicConversion has updated the standard conversion sequence
1906     // appropriately.
1907     return true;
1908   } else if (ToType->isEventT() &&
1909              From->isIntegerConstantExpr(S.getASTContext()) &&
1910              From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1911     SCS.Second = ICK_Zero_Event_Conversion;
1912     FromType = ToType;
1913   } else if (ToType->isQueueT() &&
1914              From->isIntegerConstantExpr(S.getASTContext()) &&
1915              (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1916     SCS.Second = ICK_Zero_Queue_Conversion;
1917     FromType = ToType;
1918   } else if (ToType->isSamplerT() &&
1919              From->isIntegerConstantExpr(S.getASTContext())) {
1920     SCS.Second = ICK_Compatible_Conversion;
1921     FromType = ToType;
1922   } else {
1923     // No second conversion required.
1924     SCS.Second = ICK_Identity;
1925   }
1926   SCS.setToType(1, FromType);
1927 
1928   // The third conversion can be a function pointer conversion or a
1929   // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1930   bool ObjCLifetimeConversion;
1931   if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1932     // Function pointer conversions (removing 'noexcept') including removal of
1933     // 'noreturn' (Clang extension).
1934     SCS.Third = ICK_Function_Conversion;
1935   } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1936                                          ObjCLifetimeConversion)) {
1937     SCS.Third = ICK_Qualification;
1938     SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1939     FromType = ToType;
1940   } else {
1941     // No conversion required
1942     SCS.Third = ICK_Identity;
1943   }
1944 
1945   // C++ [over.best.ics]p6:
1946   //   [...] Any difference in top-level cv-qualification is
1947   //   subsumed by the initialization itself and does not constitute
1948   //   a conversion. [...]
1949   QualType CanonFrom = S.Context.getCanonicalType(FromType);
1950   QualType CanonTo = S.Context.getCanonicalType(ToType);
1951   if (CanonFrom.getLocalUnqualifiedType()
1952                                      == CanonTo.getLocalUnqualifiedType() &&
1953       CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1954     FromType = ToType;
1955     CanonFrom = CanonTo;
1956   }
1957 
1958   SCS.setToType(2, FromType);
1959 
1960   if (CanonFrom == CanonTo)
1961     return true;
1962 
1963   // If we have not converted the argument type to the parameter type,
1964   // this is a bad conversion sequence, unless we're resolving an overload in C.
1965   if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1966     return false;
1967 
1968   ExprResult ER = ExprResult{From};
1969   Sema::AssignConvertType Conv =
1970       S.CheckSingleAssignmentConstraints(ToType, ER,
1971                                          /*Diagnose=*/false,
1972                                          /*DiagnoseCFAudited=*/false,
1973                                          /*ConvertRHS=*/false);
1974   ImplicitConversionKind SecondConv;
1975   switch (Conv) {
1976   case Sema::Compatible:
1977     SecondConv = ICK_C_Only_Conversion;
1978     break;
1979   // For our purposes, discarding qualifiers is just as bad as using an
1980   // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1981   // qualifiers, as well.
1982   case Sema::CompatiblePointerDiscardsQualifiers:
1983   case Sema::IncompatiblePointer:
1984   case Sema::IncompatiblePointerSign:
1985     SecondConv = ICK_Incompatible_Pointer_Conversion;
1986     break;
1987   default:
1988     return false;
1989   }
1990 
1991   // First can only be an lvalue conversion, so we pretend that this was the
1992   // second conversion. First should already be valid from earlier in the
1993   // function.
1994   SCS.Second = SecondConv;
1995   SCS.setToType(1, ToType);
1996 
1997   // Third is Identity, because Second should rank us worse than any other
1998   // conversion. This could also be ICK_Qualification, but it's simpler to just
1999   // lump everything in with the second conversion, and we don't gain anything
2000   // from making this ICK_Qualification.
2001   SCS.Third = ICK_Identity;
2002   SCS.setToType(2, ToType);
2003   return true;
2004 }
2005 
2006 static bool
2007 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2008                                      QualType &ToType,
2009                                      bool InOverloadResolution,
2010                                      StandardConversionSequence &SCS,
2011                                      bool CStyle) {
2012 
2013   const RecordType *UT = ToType->getAsUnionType();
2014   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2015     return false;
2016   // The field to initialize within the transparent union.
2017   RecordDecl *UD = UT->getDecl();
2018   // It's compatible if the expression matches any of the fields.
2019   for (const auto *it : UD->fields()) {
2020     if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2021                              CStyle, /*AllowObjCWritebackConversion=*/false)) {
2022       ToType = it->getType();
2023       return true;
2024     }
2025   }
2026   return false;
2027 }
2028 
2029 /// IsIntegralPromotion - Determines whether the conversion from the
2030 /// expression From (whose potentially-adjusted type is FromType) to
2031 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2032 /// sets PromotedType to the promoted type.
2033 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2034   const BuiltinType *To = ToType->getAs<BuiltinType>();
2035   // All integers are built-in.
2036   if (!To) {
2037     return false;
2038   }
2039 
2040   // An rvalue of type char, signed char, unsigned char, short int, or
2041   // unsigned short int can be converted to an rvalue of type int if
2042   // int can represent all the values of the source type; otherwise,
2043   // the source rvalue can be converted to an rvalue of type unsigned
2044   // int (C++ 4.5p1).
2045   if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2046       !FromType->isEnumeralType()) {
2047     if (// We can promote any signed, promotable integer type to an int
2048         (FromType->isSignedIntegerType() ||
2049          // We can promote any unsigned integer type whose size is
2050          // less than int to an int.
2051          Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2052       return To->getKind() == BuiltinType::Int;
2053     }
2054 
2055     return To->getKind() == BuiltinType::UInt;
2056   }
2057 
2058   // C++11 [conv.prom]p3:
2059   //   A prvalue of an unscoped enumeration type whose underlying type is not
2060   //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2061   //   following types that can represent all the values of the enumeration
2062   //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
2063   //   unsigned int, long int, unsigned long int, long long int, or unsigned
2064   //   long long int. If none of the types in that list can represent all the
2065   //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2066   //   type can be converted to an rvalue a prvalue of the extended integer type
2067   //   with lowest integer conversion rank (4.13) greater than the rank of long
2068   //   long in which all the values of the enumeration can be represented. If
2069   //   there are two such extended types, the signed one is chosen.
2070   // C++11 [conv.prom]p4:
2071   //   A prvalue of an unscoped enumeration type whose underlying type is fixed
2072   //   can be converted to a prvalue of its underlying type. Moreover, if
2073   //   integral promotion can be applied to its underlying type, a prvalue of an
2074   //   unscoped enumeration type whose underlying type is fixed can also be
2075   //   converted to a prvalue of the promoted underlying type.
2076   if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2077     // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2078     // provided for a scoped enumeration.
2079     if (FromEnumType->getDecl()->isScoped())
2080       return false;
2081 
2082     // We can perform an integral promotion to the underlying type of the enum,
2083     // even if that's not the promoted type. Note that the check for promoting
2084     // the underlying type is based on the type alone, and does not consider
2085     // the bitfield-ness of the actual source expression.
2086     if (FromEnumType->getDecl()->isFixed()) {
2087       QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2088       return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2089              IsIntegralPromotion(nullptr, Underlying, ToType);
2090     }
2091 
2092     // We have already pre-calculated the promotion type, so this is trivial.
2093     if (ToType->isIntegerType() &&
2094         isCompleteType(From->getBeginLoc(), FromType))
2095       return Context.hasSameUnqualifiedType(
2096           ToType, FromEnumType->getDecl()->getPromotionType());
2097 
2098     // C++ [conv.prom]p5:
2099     //   If the bit-field has an enumerated type, it is treated as any other
2100     //   value of that type for promotion purposes.
2101     //
2102     // ... so do not fall through into the bit-field checks below in C++.
2103     if (getLangOpts().CPlusPlus)
2104       return false;
2105   }
2106 
2107   // C++0x [conv.prom]p2:
2108   //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2109   //   to an rvalue a prvalue of the first of the following types that can
2110   //   represent all the values of its underlying type: int, unsigned int,
2111   //   long int, unsigned long int, long long int, or unsigned long long int.
2112   //   If none of the types in that list can represent all the values of its
2113   //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
2114   //   or wchar_t can be converted to an rvalue a prvalue of its underlying
2115   //   type.
2116   if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2117       ToType->isIntegerType()) {
2118     // Determine whether the type we're converting from is signed or
2119     // unsigned.
2120     bool FromIsSigned = FromType->isSignedIntegerType();
2121     uint64_t FromSize = Context.getTypeSize(FromType);
2122 
2123     // The types we'll try to promote to, in the appropriate
2124     // order. Try each of these types.
2125     QualType PromoteTypes[6] = {
2126       Context.IntTy, Context.UnsignedIntTy,
2127       Context.LongTy, Context.UnsignedLongTy ,
2128       Context.LongLongTy, Context.UnsignedLongLongTy
2129     };
2130     for (int Idx = 0; Idx < 6; ++Idx) {
2131       uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2132       if (FromSize < ToSize ||
2133           (FromSize == ToSize &&
2134            FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2135         // We found the type that we can promote to. If this is the
2136         // type we wanted, we have a promotion. Otherwise, no
2137         // promotion.
2138         return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2139       }
2140     }
2141   }
2142 
2143   // An rvalue for an integral bit-field (9.6) can be converted to an
2144   // rvalue of type int if int can represent all the values of the
2145   // bit-field; otherwise, it can be converted to unsigned int if
2146   // unsigned int can represent all the values of the bit-field. If
2147   // the bit-field is larger yet, no integral promotion applies to
2148   // it. If the bit-field has an enumerated type, it is treated as any
2149   // other value of that type for promotion purposes (C++ 4.5p3).
2150   // FIXME: We should delay checking of bit-fields until we actually perform the
2151   // conversion.
2152   //
2153   // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2154   // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2155   // bit-fields and those whose underlying type is larger than int) for GCC
2156   // compatibility.
2157   if (From) {
2158     if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2159       llvm::APSInt BitWidth;
2160       if (FromType->isIntegralType(Context) &&
2161           MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2162         llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2163         ToSize = Context.getTypeSize(ToType);
2164 
2165         // Are we promoting to an int from a bitfield that fits in an int?
2166         if (BitWidth < ToSize ||
2167             (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2168           return To->getKind() == BuiltinType::Int;
2169         }
2170 
2171         // Are we promoting to an unsigned int from an unsigned bitfield
2172         // that fits into an unsigned int?
2173         if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2174           return To->getKind() == BuiltinType::UInt;
2175         }
2176 
2177         return false;
2178       }
2179     }
2180   }
2181 
2182   // An rvalue of type bool can be converted to an rvalue of type int,
2183   // with false becoming zero and true becoming one (C++ 4.5p4).
2184   if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2185     return true;
2186   }
2187 
2188   return false;
2189 }
2190 
2191 /// IsFloatingPointPromotion - Determines whether the conversion from
2192 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2193 /// returns true and sets PromotedType to the promoted type.
2194 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2195   if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2196     if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2197       /// An rvalue of type float can be converted to an rvalue of type
2198       /// double. (C++ 4.6p1).
2199       if (FromBuiltin->getKind() == BuiltinType::Float &&
2200           ToBuiltin->getKind() == BuiltinType::Double)
2201         return true;
2202 
2203       // C99 6.3.1.5p1:
2204       //   When a float is promoted to double or long double, or a
2205       //   double is promoted to long double [...].
2206       if (!getLangOpts().CPlusPlus &&
2207           (FromBuiltin->getKind() == BuiltinType::Float ||
2208            FromBuiltin->getKind() == BuiltinType::Double) &&
2209           (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2210            ToBuiltin->getKind() == BuiltinType::Float128))
2211         return true;
2212 
2213       // Half can be promoted to float.
2214       if (!getLangOpts().NativeHalfType &&
2215            FromBuiltin->getKind() == BuiltinType::Half &&
2216           ToBuiltin->getKind() == BuiltinType::Float)
2217         return true;
2218     }
2219 
2220   return false;
2221 }
2222 
2223 /// Determine if a conversion is a complex promotion.
2224 ///
2225 /// A complex promotion is defined as a complex -> complex conversion
2226 /// where the conversion between the underlying real types is a
2227 /// floating-point or integral promotion.
2228 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2229   const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2230   if (!FromComplex)
2231     return false;
2232 
2233   const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2234   if (!ToComplex)
2235     return false;
2236 
2237   return IsFloatingPointPromotion(FromComplex->getElementType(),
2238                                   ToComplex->getElementType()) ||
2239     IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2240                         ToComplex->getElementType());
2241 }
2242 
2243 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2244 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2245 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2246 /// if non-empty, will be a pointer to ToType that may or may not have
2247 /// the right set of qualifiers on its pointee.
2248 ///
2249 static QualType
2250 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2251                                    QualType ToPointee, QualType ToType,
2252                                    ASTContext &Context,
2253                                    bool StripObjCLifetime = false) {
2254   assert((FromPtr->getTypeClass() == Type::Pointer ||
2255           FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2256          "Invalid similarly-qualified pointer type");
2257 
2258   /// Conversions to 'id' subsume cv-qualifier conversions.
2259   if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2260     return ToType.getUnqualifiedType();
2261 
2262   QualType CanonFromPointee
2263     = Context.getCanonicalType(FromPtr->getPointeeType());
2264   QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2265   Qualifiers Quals = CanonFromPointee.getQualifiers();
2266 
2267   if (StripObjCLifetime)
2268     Quals.removeObjCLifetime();
2269 
2270   // Exact qualifier match -> return the pointer type we're converting to.
2271   if (CanonToPointee.getLocalQualifiers() == Quals) {
2272     // ToType is exactly what we need. Return it.
2273     if (!ToType.isNull())
2274       return ToType.getUnqualifiedType();
2275 
2276     // Build a pointer to ToPointee. It has the right qualifiers
2277     // already.
2278     if (isa<ObjCObjectPointerType>(ToType))
2279       return Context.getObjCObjectPointerType(ToPointee);
2280     return Context.getPointerType(ToPointee);
2281   }
2282 
2283   // Just build a canonical type that has the right qualifiers.
2284   QualType QualifiedCanonToPointee
2285     = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2286 
2287   if (isa<ObjCObjectPointerType>(ToType))
2288     return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2289   return Context.getPointerType(QualifiedCanonToPointee);
2290 }
2291 
2292 static bool isNullPointerConstantForConversion(Expr *Expr,
2293                                                bool InOverloadResolution,
2294                                                ASTContext &Context) {
2295   // Handle value-dependent integral null pointer constants correctly.
2296   // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2297   if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2298       Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2299     return !InOverloadResolution;
2300 
2301   return Expr->isNullPointerConstant(Context,
2302                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2303                                         : Expr::NPC_ValueDependentIsNull);
2304 }
2305 
2306 /// IsPointerConversion - Determines whether the conversion of the
2307 /// expression From, which has the (possibly adjusted) type FromType,
2308 /// can be converted to the type ToType via a pointer conversion (C++
2309 /// 4.10). If so, returns true and places the converted type (that
2310 /// might differ from ToType in its cv-qualifiers at some level) into
2311 /// ConvertedType.
2312 ///
2313 /// This routine also supports conversions to and from block pointers
2314 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2315 /// pointers to interfaces. FIXME: Once we've determined the
2316 /// appropriate overloading rules for Objective-C, we may want to
2317 /// split the Objective-C checks into a different routine; however,
2318 /// GCC seems to consider all of these conversions to be pointer
2319 /// conversions, so for now they live here. IncompatibleObjC will be
2320 /// set if the conversion is an allowed Objective-C conversion that
2321 /// should result in a warning.
2322 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2323                                bool InOverloadResolution,
2324                                QualType& ConvertedType,
2325                                bool &IncompatibleObjC) {
2326   IncompatibleObjC = false;
2327   if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2328                               IncompatibleObjC))
2329     return true;
2330 
2331   // Conversion from a null pointer constant to any Objective-C pointer type.
2332   if (ToType->isObjCObjectPointerType() &&
2333       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2334     ConvertedType = ToType;
2335     return true;
2336   }
2337 
2338   // Blocks: Block pointers can be converted to void*.
2339   if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2340       ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2341     ConvertedType = ToType;
2342     return true;
2343   }
2344   // Blocks: A null pointer constant can be converted to a block
2345   // pointer type.
2346   if (ToType->isBlockPointerType() &&
2347       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2348     ConvertedType = ToType;
2349     return true;
2350   }
2351 
2352   // If the left-hand-side is nullptr_t, the right side can be a null
2353   // pointer constant.
2354   if (ToType->isNullPtrType() &&
2355       isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2356     ConvertedType = ToType;
2357     return true;
2358   }
2359 
2360   const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2361   if (!ToTypePtr)
2362     return false;
2363 
2364   // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2365   if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2366     ConvertedType = ToType;
2367     return true;
2368   }
2369 
2370   // Beyond this point, both types need to be pointers
2371   // , including objective-c pointers.
2372   QualType ToPointeeType = ToTypePtr->getPointeeType();
2373   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2374       !getLangOpts().ObjCAutoRefCount) {
2375     ConvertedType = BuildSimilarlyQualifiedPointerType(
2376                                       FromType->getAs<ObjCObjectPointerType>(),
2377                                                        ToPointeeType,
2378                                                        ToType, Context);
2379     return true;
2380   }
2381   const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2382   if (!FromTypePtr)
2383     return false;
2384 
2385   QualType FromPointeeType = FromTypePtr->getPointeeType();
2386 
2387   // If the unqualified pointee types are the same, this can't be a
2388   // pointer conversion, so don't do all of the work below.
2389   if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2390     return false;
2391 
2392   // An rvalue of type "pointer to cv T," where T is an object type,
2393   // can be converted to an rvalue of type "pointer to cv void" (C++
2394   // 4.10p2).
2395   if (FromPointeeType->isIncompleteOrObjectType() &&
2396       ToPointeeType->isVoidType()) {
2397     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2398                                                        ToPointeeType,
2399                                                        ToType, Context,
2400                                                    /*StripObjCLifetime=*/true);
2401     return true;
2402   }
2403 
2404   // MSVC allows implicit function to void* type conversion.
2405   if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2406       ToPointeeType->isVoidType()) {
2407     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2408                                                        ToPointeeType,
2409                                                        ToType, Context);
2410     return true;
2411   }
2412 
2413   // When we're overloading in C, we allow a special kind of pointer
2414   // conversion for compatible-but-not-identical pointee types.
2415   if (!getLangOpts().CPlusPlus &&
2416       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2417     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2418                                                        ToPointeeType,
2419                                                        ToType, Context);
2420     return true;
2421   }
2422 
2423   // C++ [conv.ptr]p3:
2424   //
2425   //   An rvalue of type "pointer to cv D," where D is a class type,
2426   //   can be converted to an rvalue of type "pointer to cv B," where
2427   //   B is a base class (clause 10) of D. If B is an inaccessible
2428   //   (clause 11) or ambiguous (10.2) base class of D, a program that
2429   //   necessitates this conversion is ill-formed. The result of the
2430   //   conversion is a pointer to the base class sub-object of the
2431   //   derived class object. The null pointer value is converted to
2432   //   the null pointer value of the destination type.
2433   //
2434   // Note that we do not check for ambiguity or inaccessibility
2435   // here. That is handled by CheckPointerConversion.
2436   if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2437       ToPointeeType->isRecordType() &&
2438       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2439       IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2440     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2441                                                        ToPointeeType,
2442                                                        ToType, Context);
2443     return true;
2444   }
2445 
2446   if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2447       Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2448     ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2449                                                        ToPointeeType,
2450                                                        ToType, Context);
2451     return true;
2452   }
2453 
2454   return false;
2455 }
2456 
2457 /// Adopt the given qualifiers for the given type.
2458 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2459   Qualifiers TQs = T.getQualifiers();
2460 
2461   // Check whether qualifiers already match.
2462   if (TQs == Qs)
2463     return T;
2464 
2465   if (Qs.compatiblyIncludes(TQs))
2466     return Context.getQualifiedType(T, Qs);
2467 
2468   return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2469 }
2470 
2471 /// isObjCPointerConversion - Determines whether this is an
2472 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2473 /// with the same arguments and return values.
2474 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2475                                    QualType& ConvertedType,
2476                                    bool &IncompatibleObjC) {
2477   if (!getLangOpts().ObjC)
2478     return false;
2479 
2480   // The set of qualifiers on the type we're converting from.
2481   Qualifiers FromQualifiers = FromType.getQualifiers();
2482 
2483   // First, we handle all conversions on ObjC object pointer types.
2484   const ObjCObjectPointerType* ToObjCPtr =
2485     ToType->getAs<ObjCObjectPointerType>();
2486   const ObjCObjectPointerType *FromObjCPtr =
2487     FromType->getAs<ObjCObjectPointerType>();
2488 
2489   if (ToObjCPtr && FromObjCPtr) {
2490     // If the pointee types are the same (ignoring qualifications),
2491     // then this is not a pointer conversion.
2492     if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2493                                        FromObjCPtr->getPointeeType()))
2494       return false;
2495 
2496     // Conversion between Objective-C pointers.
2497     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2498       const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2499       const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2500       if (getLangOpts().CPlusPlus && LHS && RHS &&
2501           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2502                                                 FromObjCPtr->getPointeeType()))
2503         return false;
2504       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2505                                                    ToObjCPtr->getPointeeType(),
2506                                                          ToType, Context);
2507       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2508       return true;
2509     }
2510 
2511     if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2512       // Okay: this is some kind of implicit downcast of Objective-C
2513       // interfaces, which is permitted. However, we're going to
2514       // complain about it.
2515       IncompatibleObjC = true;
2516       ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2517                                                    ToObjCPtr->getPointeeType(),
2518                                                          ToType, Context);
2519       ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2520       return true;
2521     }
2522   }
2523   // Beyond this point, both types need to be C pointers or block pointers.
2524   QualType ToPointeeType;
2525   if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2526     ToPointeeType = ToCPtr->getPointeeType();
2527   else if (const BlockPointerType *ToBlockPtr =
2528             ToType->getAs<BlockPointerType>()) {
2529     // Objective C++: We're able to convert from a pointer to any object
2530     // to a block pointer type.
2531     if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2532       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2533       return true;
2534     }
2535     ToPointeeType = ToBlockPtr->getPointeeType();
2536   }
2537   else if (FromType->getAs<BlockPointerType>() &&
2538            ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2539     // Objective C++: We're able to convert from a block pointer type to a
2540     // pointer to any object.
2541     ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2542     return true;
2543   }
2544   else
2545     return false;
2546 
2547   QualType FromPointeeType;
2548   if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2549     FromPointeeType = FromCPtr->getPointeeType();
2550   else if (const BlockPointerType *FromBlockPtr =
2551            FromType->getAs<BlockPointerType>())
2552     FromPointeeType = FromBlockPtr->getPointeeType();
2553   else
2554     return false;
2555 
2556   // If we have pointers to pointers, recursively check whether this
2557   // is an Objective-C conversion.
2558   if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2559       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2560                               IncompatibleObjC)) {
2561     // We always complain about this conversion.
2562     IncompatibleObjC = true;
2563     ConvertedType = Context.getPointerType(ConvertedType);
2564     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2565     return true;
2566   }
2567   // Allow conversion of pointee being objective-c pointer to another one;
2568   // as in I* to id.
2569   if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2570       ToPointeeType->getAs<ObjCObjectPointerType>() &&
2571       isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2572                               IncompatibleObjC)) {
2573 
2574     ConvertedType = Context.getPointerType(ConvertedType);
2575     ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2576     return true;
2577   }
2578 
2579   // If we have pointers to functions or blocks, check whether the only
2580   // differences in the argument and result types are in Objective-C
2581   // pointer conversions. If so, we permit the conversion (but
2582   // complain about it).
2583   const FunctionProtoType *FromFunctionType
2584     = FromPointeeType->getAs<FunctionProtoType>();
2585   const FunctionProtoType *ToFunctionType
2586     = ToPointeeType->getAs<FunctionProtoType>();
2587   if (FromFunctionType && ToFunctionType) {
2588     // If the function types are exactly the same, this isn't an
2589     // Objective-C pointer conversion.
2590     if (Context.getCanonicalType(FromPointeeType)
2591           == Context.getCanonicalType(ToPointeeType))
2592       return false;
2593 
2594     // Perform the quick checks that will tell us whether these
2595     // function types are obviously different.
2596     if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2597         FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2598         FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2599       return false;
2600 
2601     bool HasObjCConversion = false;
2602     if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2603         Context.getCanonicalType(ToFunctionType->getReturnType())) {
2604       // Okay, the types match exactly. Nothing to do.
2605     } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2606                                        ToFunctionType->getReturnType(),
2607                                        ConvertedType, IncompatibleObjC)) {
2608       // Okay, we have an Objective-C pointer conversion.
2609       HasObjCConversion = true;
2610     } else {
2611       // Function types are too different. Abort.
2612       return false;
2613     }
2614 
2615     // Check argument types.
2616     for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2617          ArgIdx != NumArgs; ++ArgIdx) {
2618       QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2619       QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2620       if (Context.getCanonicalType(FromArgType)
2621             == Context.getCanonicalType(ToArgType)) {
2622         // Okay, the types match exactly. Nothing to do.
2623       } else if (isObjCPointerConversion(FromArgType, ToArgType,
2624                                          ConvertedType, IncompatibleObjC)) {
2625         // Okay, we have an Objective-C pointer conversion.
2626         HasObjCConversion = true;
2627       } else {
2628         // Argument types are too different. Abort.
2629         return false;
2630       }
2631     }
2632 
2633     if (HasObjCConversion) {
2634       // We had an Objective-C conversion. Allow this pointer
2635       // conversion, but complain about it.
2636       ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2637       IncompatibleObjC = true;
2638       return true;
2639     }
2640   }
2641 
2642   return false;
2643 }
2644 
2645 /// Determine whether this is an Objective-C writeback conversion,
2646 /// used for parameter passing when performing automatic reference counting.
2647 ///
2648 /// \param FromType The type we're converting form.
2649 ///
2650 /// \param ToType The type we're converting to.
2651 ///
2652 /// \param ConvertedType The type that will be produced after applying
2653 /// this conversion.
2654 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2655                                      QualType &ConvertedType) {
2656   if (!getLangOpts().ObjCAutoRefCount ||
2657       Context.hasSameUnqualifiedType(FromType, ToType))
2658     return false;
2659 
2660   // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2661   QualType ToPointee;
2662   if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2663     ToPointee = ToPointer->getPointeeType();
2664   else
2665     return false;
2666 
2667   Qualifiers ToQuals = ToPointee.getQualifiers();
2668   if (!ToPointee->isObjCLifetimeType() ||
2669       ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2670       !ToQuals.withoutObjCLifetime().empty())
2671     return false;
2672 
2673   // Argument must be a pointer to __strong to __weak.
2674   QualType FromPointee;
2675   if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2676     FromPointee = FromPointer->getPointeeType();
2677   else
2678     return false;
2679 
2680   Qualifiers FromQuals = FromPointee.getQualifiers();
2681   if (!FromPointee->isObjCLifetimeType() ||
2682       (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2683        FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2684     return false;
2685 
2686   // Make sure that we have compatible qualifiers.
2687   FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2688   if (!ToQuals.compatiblyIncludes(FromQuals))
2689     return false;
2690 
2691   // Remove qualifiers from the pointee type we're converting from; they
2692   // aren't used in the compatibility check belong, and we'll be adding back
2693   // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2694   FromPointee = FromPointee.getUnqualifiedType();
2695 
2696   // The unqualified form of the pointee types must be compatible.
2697   ToPointee = ToPointee.getUnqualifiedType();
2698   bool IncompatibleObjC;
2699   if (Context.typesAreCompatible(FromPointee, ToPointee))
2700     FromPointee = ToPointee;
2701   else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2702                                     IncompatibleObjC))
2703     return false;
2704 
2705   /// Construct the type we're converting to, which is a pointer to
2706   /// __autoreleasing pointee.
2707   FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2708   ConvertedType = Context.getPointerType(FromPointee);
2709   return true;
2710 }
2711 
2712 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2713                                     QualType& ConvertedType) {
2714   QualType ToPointeeType;
2715   if (const BlockPointerType *ToBlockPtr =
2716         ToType->getAs<BlockPointerType>())
2717     ToPointeeType = ToBlockPtr->getPointeeType();
2718   else
2719     return false;
2720 
2721   QualType FromPointeeType;
2722   if (const BlockPointerType *FromBlockPtr =
2723       FromType->getAs<BlockPointerType>())
2724     FromPointeeType = FromBlockPtr->getPointeeType();
2725   else
2726     return false;
2727   // We have pointer to blocks, check whether the only
2728   // differences in the argument and result types are in Objective-C
2729   // pointer conversions. If so, we permit the conversion.
2730 
2731   const FunctionProtoType *FromFunctionType
2732     = FromPointeeType->getAs<FunctionProtoType>();
2733   const FunctionProtoType *ToFunctionType
2734     = ToPointeeType->getAs<FunctionProtoType>();
2735 
2736   if (!FromFunctionType || !ToFunctionType)
2737     return false;
2738 
2739   if (Context.hasSameType(FromPointeeType, ToPointeeType))
2740     return true;
2741 
2742   // Perform the quick checks that will tell us whether these
2743   // function types are obviously different.
2744   if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2745       FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2746     return false;
2747 
2748   FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2749   FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2750   if (FromEInfo != ToEInfo)
2751     return false;
2752 
2753   bool IncompatibleObjC = false;
2754   if (Context.hasSameType(FromFunctionType->getReturnType(),
2755                           ToFunctionType->getReturnType())) {
2756     // Okay, the types match exactly. Nothing to do.
2757   } else {
2758     QualType RHS = FromFunctionType->getReturnType();
2759     QualType LHS = ToFunctionType->getReturnType();
2760     if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2761         !RHS.hasQualifiers() && LHS.hasQualifiers())
2762        LHS = LHS.getUnqualifiedType();
2763 
2764      if (Context.hasSameType(RHS,LHS)) {
2765        // OK exact match.
2766      } else if (isObjCPointerConversion(RHS, LHS,
2767                                         ConvertedType, IncompatibleObjC)) {
2768      if (IncompatibleObjC)
2769        return false;
2770      // Okay, we have an Objective-C pointer conversion.
2771      }
2772      else
2773        return false;
2774    }
2775 
2776    // Check argument types.
2777    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2778         ArgIdx != NumArgs; ++ArgIdx) {
2779      IncompatibleObjC = false;
2780      QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2781      QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2782      if (Context.hasSameType(FromArgType, ToArgType)) {
2783        // Okay, the types match exactly. Nothing to do.
2784      } else if (isObjCPointerConversion(ToArgType, FromArgType,
2785                                         ConvertedType, IncompatibleObjC)) {
2786        if (IncompatibleObjC)
2787          return false;
2788        // Okay, we have an Objective-C pointer conversion.
2789      } else
2790        // Argument types are too different. Abort.
2791        return false;
2792    }
2793 
2794    SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2795    bool CanUseToFPT, CanUseFromFPT;
2796    if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2797                                       CanUseToFPT, CanUseFromFPT,
2798                                       NewParamInfos))
2799      return false;
2800 
2801    ConvertedType = ToType;
2802    return true;
2803 }
2804 
2805 enum {
2806   ft_default,
2807   ft_different_class,
2808   ft_parameter_arity,
2809   ft_parameter_mismatch,
2810   ft_return_type,
2811   ft_qualifer_mismatch,
2812   ft_noexcept
2813 };
2814 
2815 /// Attempts to get the FunctionProtoType from a Type. Handles
2816 /// MemberFunctionPointers properly.
2817 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2818   if (auto *FPT = FromType->getAs<FunctionProtoType>())
2819     return FPT;
2820 
2821   if (auto *MPT = FromType->getAs<MemberPointerType>())
2822     return MPT->getPointeeType()->getAs<FunctionProtoType>();
2823 
2824   return nullptr;
2825 }
2826 
2827 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2828 /// function types.  Catches different number of parameter, mismatch in
2829 /// parameter types, and different return types.
2830 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2831                                       QualType FromType, QualType ToType) {
2832   // If either type is not valid, include no extra info.
2833   if (FromType.isNull() || ToType.isNull()) {
2834     PDiag << ft_default;
2835     return;
2836   }
2837 
2838   // Get the function type from the pointers.
2839   if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2840     const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2841                             *ToMember = ToType->getAs<MemberPointerType>();
2842     if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2843       PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2844             << QualType(FromMember->getClass(), 0);
2845       return;
2846     }
2847     FromType = FromMember->getPointeeType();
2848     ToType = ToMember->getPointeeType();
2849   }
2850 
2851   if (FromType->isPointerType())
2852     FromType = FromType->getPointeeType();
2853   if (ToType->isPointerType())
2854     ToType = ToType->getPointeeType();
2855 
2856   // Remove references.
2857   FromType = FromType.getNonReferenceType();
2858   ToType = ToType.getNonReferenceType();
2859 
2860   // Don't print extra info for non-specialized template functions.
2861   if (FromType->isInstantiationDependentType() &&
2862       !FromType->getAs<TemplateSpecializationType>()) {
2863     PDiag << ft_default;
2864     return;
2865   }
2866 
2867   // No extra info for same types.
2868   if (Context.hasSameType(FromType, ToType)) {
2869     PDiag << ft_default;
2870     return;
2871   }
2872 
2873   const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2874                           *ToFunction = tryGetFunctionProtoType(ToType);
2875 
2876   // Both types need to be function types.
2877   if (!FromFunction || !ToFunction) {
2878     PDiag << ft_default;
2879     return;
2880   }
2881 
2882   if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2883     PDiag << ft_parameter_arity << ToFunction->getNumParams()
2884           << FromFunction->getNumParams();
2885     return;
2886   }
2887 
2888   // Handle different parameter types.
2889   unsigned ArgPos;
2890   if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2891     PDiag << ft_parameter_mismatch << ArgPos + 1
2892           << ToFunction->getParamType(ArgPos)
2893           << FromFunction->getParamType(ArgPos);
2894     return;
2895   }
2896 
2897   // Handle different return type.
2898   if (!Context.hasSameType(FromFunction->getReturnType(),
2899                            ToFunction->getReturnType())) {
2900     PDiag << ft_return_type << ToFunction->getReturnType()
2901           << FromFunction->getReturnType();
2902     return;
2903   }
2904 
2905   if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2906     PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2907           << FromFunction->getMethodQuals();
2908     return;
2909   }
2910 
2911   // Handle exception specification differences on canonical type (in C++17
2912   // onwards).
2913   if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2914           ->isNothrow() !=
2915       cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2916           ->isNothrow()) {
2917     PDiag << ft_noexcept;
2918     return;
2919   }
2920 
2921   // Unable to find a difference, so add no extra info.
2922   PDiag << ft_default;
2923 }
2924 
2925 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2926 /// for equality of their argument types. Caller has already checked that
2927 /// they have same number of arguments.  If the parameters are different,
2928 /// ArgPos will have the parameter index of the first different parameter.
2929 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2930                                       const FunctionProtoType *NewType,
2931                                       unsigned *ArgPos) {
2932   for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2933                                               N = NewType->param_type_begin(),
2934                                               E = OldType->param_type_end();
2935        O && (O != E); ++O, ++N) {
2936     // Ignore address spaces in pointee type. This is to disallow overloading
2937     // on __ptr32/__ptr64 address spaces.
2938     QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2939     QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2940 
2941     if (!Context.hasSameType(Old, New)) {
2942       if (ArgPos)
2943         *ArgPos = O - OldType->param_type_begin();
2944       return false;
2945     }
2946   }
2947   return true;
2948 }
2949 
2950 /// CheckPointerConversion - Check the pointer conversion from the
2951 /// expression From to the type ToType. This routine checks for
2952 /// ambiguous or inaccessible derived-to-base pointer
2953 /// conversions for which IsPointerConversion has already returned
2954 /// true. It returns true and produces a diagnostic if there was an
2955 /// error, or returns false otherwise.
2956 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2957                                   CastKind &Kind,
2958                                   CXXCastPath& BasePath,
2959                                   bool IgnoreBaseAccess,
2960                                   bool Diagnose) {
2961   QualType FromType = From->getType();
2962   bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2963 
2964   Kind = CK_BitCast;
2965 
2966   if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2967       From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2968           Expr::NPCK_ZeroExpression) {
2969     if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2970       DiagRuntimeBehavior(From->getExprLoc(), From,
2971                           PDiag(diag::warn_impcast_bool_to_null_pointer)
2972                             << ToType << From->getSourceRange());
2973     else if (!isUnevaluatedContext())
2974       Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2975         << ToType << From->getSourceRange();
2976   }
2977   if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2978     if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2979       QualType FromPointeeType = FromPtrType->getPointeeType(),
2980                ToPointeeType   = ToPtrType->getPointeeType();
2981 
2982       if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2983           !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2984         // We must have a derived-to-base conversion. Check an
2985         // ambiguous or inaccessible conversion.
2986         unsigned InaccessibleID = 0;
2987         unsigned AmbigiousID = 0;
2988         if (Diagnose) {
2989           InaccessibleID = diag::err_upcast_to_inaccessible_base;
2990           AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2991         }
2992         if (CheckDerivedToBaseConversion(
2993                 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2994                 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2995                 &BasePath, IgnoreBaseAccess))
2996           return true;
2997 
2998         // The conversion was successful.
2999         Kind = CK_DerivedToBase;
3000       }
3001 
3002       if (Diagnose && !IsCStyleOrFunctionalCast &&
3003           FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3004         assert(getLangOpts().MSVCCompat &&
3005                "this should only be possible with MSVCCompat!");
3006         Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3007             << From->getSourceRange();
3008       }
3009     }
3010   } else if (const ObjCObjectPointerType *ToPtrType =
3011                ToType->getAs<ObjCObjectPointerType>()) {
3012     if (const ObjCObjectPointerType *FromPtrType =
3013           FromType->getAs<ObjCObjectPointerType>()) {
3014       // Objective-C++ conversions are always okay.
3015       // FIXME: We should have a different class of conversions for the
3016       // Objective-C++ implicit conversions.
3017       if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3018         return false;
3019     } else if (FromType->isBlockPointerType()) {
3020       Kind = CK_BlockPointerToObjCPointerCast;
3021     } else {
3022       Kind = CK_CPointerToObjCPointerCast;
3023     }
3024   } else if (ToType->isBlockPointerType()) {
3025     if (!FromType->isBlockPointerType())
3026       Kind = CK_AnyPointerToBlockPointerCast;
3027   }
3028 
3029   // We shouldn't fall into this case unless it's valid for other
3030   // reasons.
3031   if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3032     Kind = CK_NullToPointer;
3033 
3034   return false;
3035 }
3036 
3037 /// IsMemberPointerConversion - Determines whether the conversion of the
3038 /// expression From, which has the (possibly adjusted) type FromType, can be
3039 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3040 /// If so, returns true and places the converted type (that might differ from
3041 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3042 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3043                                      QualType ToType,
3044                                      bool InOverloadResolution,
3045                                      QualType &ConvertedType) {
3046   const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3047   if (!ToTypePtr)
3048     return false;
3049 
3050   // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3051   if (From->isNullPointerConstant(Context,
3052                     InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3053                                         : Expr::NPC_ValueDependentIsNull)) {
3054     ConvertedType = ToType;
3055     return true;
3056   }
3057 
3058   // Otherwise, both types have to be member pointers.
3059   const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3060   if (!FromTypePtr)
3061     return false;
3062 
3063   // A pointer to member of B can be converted to a pointer to member of D,
3064   // where D is derived from B (C++ 4.11p2).
3065   QualType FromClass(FromTypePtr->getClass(), 0);
3066   QualType ToClass(ToTypePtr->getClass(), 0);
3067 
3068   if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3069       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3070     ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3071                                                  ToClass.getTypePtr());
3072     return true;
3073   }
3074 
3075   return false;
3076 }
3077 
3078 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3079 /// expression From to the type ToType. This routine checks for ambiguous or
3080 /// virtual or inaccessible base-to-derived member pointer conversions
3081 /// for which IsMemberPointerConversion has already returned true. It returns
3082 /// true and produces a diagnostic if there was an error, or returns false
3083 /// otherwise.
3084 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3085                                         CastKind &Kind,
3086                                         CXXCastPath &BasePath,
3087                                         bool IgnoreBaseAccess) {
3088   QualType FromType = From->getType();
3089   const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3090   if (!FromPtrType) {
3091     // This must be a null pointer to member pointer conversion
3092     assert(From->isNullPointerConstant(Context,
3093                                        Expr::NPC_ValueDependentIsNull) &&
3094            "Expr must be null pointer constant!");
3095     Kind = CK_NullToMemberPointer;
3096     return false;
3097   }
3098 
3099   const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3100   assert(ToPtrType && "No member pointer cast has a target type "
3101                       "that is not a member pointer.");
3102 
3103   QualType FromClass = QualType(FromPtrType->getClass(), 0);
3104   QualType ToClass   = QualType(ToPtrType->getClass(), 0);
3105 
3106   // FIXME: What about dependent types?
3107   assert(FromClass->isRecordType() && "Pointer into non-class.");
3108   assert(ToClass->isRecordType() && "Pointer into non-class.");
3109 
3110   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3111                      /*DetectVirtual=*/true);
3112   bool DerivationOkay =
3113       IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3114   assert(DerivationOkay &&
3115          "Should not have been called if derivation isn't OK.");
3116   (void)DerivationOkay;
3117 
3118   if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3119                                   getUnqualifiedType())) {
3120     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3121     Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3122       << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3123     return true;
3124   }
3125 
3126   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3127     Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3128       << FromClass << ToClass << QualType(VBase, 0)
3129       << From->getSourceRange();
3130     return true;
3131   }
3132 
3133   if (!IgnoreBaseAccess)
3134     CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3135                          Paths.front(),
3136                          diag::err_downcast_from_inaccessible_base);
3137 
3138   // Must be a base to derived member conversion.
3139   BuildBasePathArray(Paths, BasePath);
3140   Kind = CK_BaseToDerivedMemberPointer;
3141   return false;
3142 }
3143 
3144 /// Determine whether the lifetime conversion between the two given
3145 /// qualifiers sets is nontrivial.
3146 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3147                                                Qualifiers ToQuals) {
3148   // Converting anything to const __unsafe_unretained is trivial.
3149   if (ToQuals.hasConst() &&
3150       ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3151     return false;
3152 
3153   return true;
3154 }
3155 
3156 /// IsQualificationConversion - Determines whether the conversion from
3157 /// an rvalue of type FromType to ToType is a qualification conversion
3158 /// (C++ 4.4).
3159 ///
3160 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3161 /// when the qualification conversion involves a change in the Objective-C
3162 /// object lifetime.
3163 bool
3164 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3165                                 bool CStyle, bool &ObjCLifetimeConversion) {
3166   FromType = Context.getCanonicalType(FromType);
3167   ToType = Context.getCanonicalType(ToType);
3168   ObjCLifetimeConversion = false;
3169 
3170   // If FromType and ToType are the same type, this is not a
3171   // qualification conversion.
3172   if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3173     return false;
3174 
3175   // (C++ 4.4p4):
3176   //   A conversion can add cv-qualifiers at levels other than the first
3177   //   in multi-level pointers, subject to the following rules: [...]
3178   bool PreviousToQualsIncludeConst = true;
3179   bool UnwrappedAnyPointer = false;
3180   while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3181     // Within each iteration of the loop, we check the qualifiers to
3182     // determine if this still looks like a qualification
3183     // conversion. Then, if all is well, we unwrap one more level of
3184     // pointers or pointers-to-members and do it all again
3185     // until there are no more pointers or pointers-to-members left to
3186     // unwrap.
3187     UnwrappedAnyPointer = true;
3188 
3189     Qualifiers FromQuals = FromType.getQualifiers();
3190     Qualifiers ToQuals = ToType.getQualifiers();
3191 
3192     // Ignore __unaligned qualifier if this type is void.
3193     if (ToType.getUnqualifiedType()->isVoidType())
3194       FromQuals.removeUnaligned();
3195 
3196     // Objective-C ARC:
3197     //   Check Objective-C lifetime conversions.
3198     if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3199         UnwrappedAnyPointer) {
3200       if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3201         if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3202           ObjCLifetimeConversion = true;
3203         FromQuals.removeObjCLifetime();
3204         ToQuals.removeObjCLifetime();
3205       } else {
3206         // Qualification conversions cannot cast between different
3207         // Objective-C lifetime qualifiers.
3208         return false;
3209       }
3210     }
3211 
3212     // Allow addition/removal of GC attributes but not changing GC attributes.
3213     if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3214         (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3215       FromQuals.removeObjCGCAttr();
3216       ToQuals.removeObjCGCAttr();
3217     }
3218 
3219     //   -- for every j > 0, if const is in cv 1,j then const is in cv
3220     //      2,j, and similarly for volatile.
3221     if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3222       return false;
3223 
3224     //   -- if the cv 1,j and cv 2,j are different, then const is in
3225     //      every cv for 0 < k < j.
3226     if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3227         && !PreviousToQualsIncludeConst)
3228       return false;
3229 
3230     // Keep track of whether all prior cv-qualifiers in the "to" type
3231     // include const.
3232     PreviousToQualsIncludeConst
3233       = PreviousToQualsIncludeConst && ToQuals.hasConst();
3234   }
3235 
3236   // Allows address space promotion by language rules implemented in
3237   // Type::Qualifiers::isAddressSpaceSupersetOf.
3238   Qualifiers FromQuals = FromType.getQualifiers();
3239   Qualifiers ToQuals = ToType.getQualifiers();
3240   if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3241       !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3242     return false;
3243   }
3244 
3245   // We are left with FromType and ToType being the pointee types
3246   // after unwrapping the original FromType and ToType the same number
3247   // of types. If we unwrapped any pointers, and if FromType and
3248   // ToType have the same unqualified type (since we checked
3249   // qualifiers above), then this is a qualification conversion.
3250   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3251 }
3252 
3253 /// - Determine whether this is a conversion from a scalar type to an
3254 /// atomic type.
3255 ///
3256 /// If successful, updates \c SCS's second and third steps in the conversion
3257 /// sequence to finish the conversion.
3258 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3259                                 bool InOverloadResolution,
3260                                 StandardConversionSequence &SCS,
3261                                 bool CStyle) {
3262   const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3263   if (!ToAtomic)
3264     return false;
3265 
3266   StandardConversionSequence InnerSCS;
3267   if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3268                             InOverloadResolution, InnerSCS,
3269                             CStyle, /*AllowObjCWritebackConversion=*/false))
3270     return false;
3271 
3272   SCS.Second = InnerSCS.Second;
3273   SCS.setToType(1, InnerSCS.getToType(1));
3274   SCS.Third = InnerSCS.Third;
3275   SCS.QualificationIncludesObjCLifetime
3276     = InnerSCS.QualificationIncludesObjCLifetime;
3277   SCS.setToType(2, InnerSCS.getToType(2));
3278   return true;
3279 }
3280 
3281 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3282                                               CXXConstructorDecl *Constructor,
3283                                               QualType Type) {
3284   const FunctionProtoType *CtorType =
3285       Constructor->getType()->getAs<FunctionProtoType>();
3286   if (CtorType->getNumParams() > 0) {
3287     QualType FirstArg = CtorType->getParamType(0);
3288     if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3289       return true;
3290   }
3291   return false;
3292 }
3293 
3294 static OverloadingResult
3295 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3296                                        CXXRecordDecl *To,
3297                                        UserDefinedConversionSequence &User,
3298                                        OverloadCandidateSet &CandidateSet,
3299                                        bool AllowExplicit) {
3300   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3301   for (auto *D : S.LookupConstructors(To)) {
3302     auto Info = getConstructorInfo(D);
3303     if (!Info)
3304       continue;
3305 
3306     bool Usable = !Info.Constructor->isInvalidDecl() &&
3307                   S.isInitListConstructor(Info.Constructor) &&
3308                   (AllowExplicit || !Info.Constructor->isExplicit());
3309     if (Usable) {
3310       // If the first argument is (a reference to) the target type,
3311       // suppress conversions.
3312       bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3313           S.Context, Info.Constructor, ToType);
3314       if (Info.ConstructorTmpl)
3315         S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3316                                        /*ExplicitArgs*/ nullptr, From,
3317                                        CandidateSet, SuppressUserConversions,
3318                                        /*PartialOverloading*/ false,
3319                                        AllowExplicit);
3320       else
3321         S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3322                                CandidateSet, SuppressUserConversions,
3323                                /*PartialOverloading*/ false, AllowExplicit);
3324     }
3325   }
3326 
3327   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3328 
3329   OverloadCandidateSet::iterator Best;
3330   switch (auto Result =
3331               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3332   case OR_Deleted:
3333   case OR_Success: {
3334     // Record the standard conversion we used and the conversion function.
3335     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3336     QualType ThisType = Constructor->getThisType();
3337     // Initializer lists don't have conversions as such.
3338     User.Before.setAsIdentityConversion();
3339     User.HadMultipleCandidates = HadMultipleCandidates;
3340     User.ConversionFunction = Constructor;
3341     User.FoundConversionFunction = Best->FoundDecl;
3342     User.After.setAsIdentityConversion();
3343     User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3344     User.After.setAllToTypes(ToType);
3345     return Result;
3346   }
3347 
3348   case OR_No_Viable_Function:
3349     return OR_No_Viable_Function;
3350   case OR_Ambiguous:
3351     return OR_Ambiguous;
3352   }
3353 
3354   llvm_unreachable("Invalid OverloadResult!");
3355 }
3356 
3357 /// Determines whether there is a user-defined conversion sequence
3358 /// (C++ [over.ics.user]) that converts expression From to the type
3359 /// ToType. If such a conversion exists, User will contain the
3360 /// user-defined conversion sequence that performs such a conversion
3361 /// and this routine will return true. Otherwise, this routine returns
3362 /// false and User is unspecified.
3363 ///
3364 /// \param AllowExplicit  true if the conversion should consider C++0x
3365 /// "explicit" conversion functions as well as non-explicit conversion
3366 /// functions (C++0x [class.conv.fct]p2).
3367 ///
3368 /// \param AllowObjCConversionOnExplicit true if the conversion should
3369 /// allow an extra Objective-C pointer conversion on uses of explicit
3370 /// constructors. Requires \c AllowExplicit to also be set.
3371 static OverloadingResult
3372 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3373                         UserDefinedConversionSequence &User,
3374                         OverloadCandidateSet &CandidateSet,
3375                         bool AllowExplicit,
3376                         bool AllowObjCConversionOnExplicit) {
3377   assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3378   CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3379 
3380   // Whether we will only visit constructors.
3381   bool ConstructorsOnly = false;
3382 
3383   // If the type we are conversion to is a class type, enumerate its
3384   // constructors.
3385   if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3386     // C++ [over.match.ctor]p1:
3387     //   When objects of class type are direct-initialized (8.5), or
3388     //   copy-initialized from an expression of the same or a
3389     //   derived class type (8.5), overload resolution selects the
3390     //   constructor. [...] For copy-initialization, the candidate
3391     //   functions are all the converting constructors (12.3.1) of
3392     //   that class. The argument list is the expression-list within
3393     //   the parentheses of the initializer.
3394     if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3395         (From->getType()->getAs<RecordType>() &&
3396          S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3397       ConstructorsOnly = true;
3398 
3399     if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3400       // We're not going to find any constructors.
3401     } else if (CXXRecordDecl *ToRecordDecl
3402                  = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3403 
3404       Expr **Args = &From;
3405       unsigned NumArgs = 1;
3406       bool ListInitializing = false;
3407       if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3408         // But first, see if there is an init-list-constructor that will work.
3409         OverloadingResult Result = IsInitializerListConstructorConversion(
3410             S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3411         if (Result != OR_No_Viable_Function)
3412           return Result;
3413         // Never mind.
3414         CandidateSet.clear(
3415             OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3416 
3417         // If we're list-initializing, we pass the individual elements as
3418         // arguments, not the entire list.
3419         Args = InitList->getInits();
3420         NumArgs = InitList->getNumInits();
3421         ListInitializing = true;
3422       }
3423 
3424       for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3425         auto Info = getConstructorInfo(D);
3426         if (!Info)
3427           continue;
3428 
3429         bool Usable = !Info.Constructor->isInvalidDecl();
3430         if (ListInitializing)
3431           Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3432         else
3433           Usable = Usable &&
3434                    Info.Constructor->isConvertingConstructor(AllowExplicit);
3435         if (Usable) {
3436           bool SuppressUserConversions = !ConstructorsOnly;
3437           if (SuppressUserConversions && ListInitializing) {
3438             SuppressUserConversions = false;
3439             if (NumArgs == 1) {
3440               // If the first argument is (a reference to) the target type,
3441               // suppress conversions.
3442               SuppressUserConversions = isFirstArgumentCompatibleWithType(
3443                   S.Context, Info.Constructor, ToType);
3444             }
3445           }
3446           if (Info.ConstructorTmpl)
3447             S.AddTemplateOverloadCandidate(
3448                 Info.ConstructorTmpl, Info.FoundDecl,
3449                 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3450                 CandidateSet, SuppressUserConversions,
3451                 /*PartialOverloading*/ false, AllowExplicit);
3452           else
3453             // Allow one user-defined conversion when user specifies a
3454             // From->ToType conversion via an static cast (c-style, etc).
3455             S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3456                                    llvm::makeArrayRef(Args, NumArgs),
3457                                    CandidateSet, SuppressUserConversions,
3458                                    /*PartialOverloading*/ false, AllowExplicit);
3459         }
3460       }
3461     }
3462   }
3463 
3464   // Enumerate conversion functions, if we're allowed to.
3465   if (ConstructorsOnly || isa<InitListExpr>(From)) {
3466   } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3467     // No conversion functions from incomplete types.
3468   } else if (const RecordType *FromRecordType =
3469                  From->getType()->getAs<RecordType>()) {
3470     if (CXXRecordDecl *FromRecordDecl
3471          = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3472       // Add all of the conversion functions as candidates.
3473       const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3474       for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3475         DeclAccessPair FoundDecl = I.getPair();
3476         NamedDecl *D = FoundDecl.getDecl();
3477         CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3478         if (isa<UsingShadowDecl>(D))
3479           D = cast<UsingShadowDecl>(D)->getTargetDecl();
3480 
3481         CXXConversionDecl *Conv;
3482         FunctionTemplateDecl *ConvTemplate;
3483         if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3484           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3485         else
3486           Conv = cast<CXXConversionDecl>(D);
3487 
3488         if (AllowExplicit || !Conv->isExplicit()) {
3489           if (ConvTemplate)
3490             S.AddTemplateConversionCandidate(
3491                 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3492                 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3493           else
3494             S.AddConversionCandidate(
3495                 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3496                 AllowObjCConversionOnExplicit, AllowExplicit);
3497         }
3498       }
3499     }
3500   }
3501 
3502   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3503 
3504   OverloadCandidateSet::iterator Best;
3505   switch (auto Result =
3506               CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3507   case OR_Success:
3508   case OR_Deleted:
3509     // Record the standard conversion we used and the conversion function.
3510     if (CXXConstructorDecl *Constructor
3511           = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3512       // C++ [over.ics.user]p1:
3513       //   If the user-defined conversion is specified by a
3514       //   constructor (12.3.1), the initial standard conversion
3515       //   sequence converts the source type to the type required by
3516       //   the argument of the constructor.
3517       //
3518       QualType ThisType = Constructor->getThisType();
3519       if (isa<InitListExpr>(From)) {
3520         // Initializer lists don't have conversions as such.
3521         User.Before.setAsIdentityConversion();
3522       } else {
3523         if (Best->Conversions[0].isEllipsis())
3524           User.EllipsisConversion = true;
3525         else {
3526           User.Before = Best->Conversions[0].Standard;
3527           User.EllipsisConversion = false;
3528         }
3529       }
3530       User.HadMultipleCandidates = HadMultipleCandidates;
3531       User.ConversionFunction = Constructor;
3532       User.FoundConversionFunction = Best->FoundDecl;
3533       User.After.setAsIdentityConversion();
3534       User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3535       User.After.setAllToTypes(ToType);
3536       return Result;
3537     }
3538     if (CXXConversionDecl *Conversion
3539                  = dyn_cast<CXXConversionDecl>(Best->Function)) {
3540       // C++ [over.ics.user]p1:
3541       //
3542       //   [...] If the user-defined conversion is specified by a
3543       //   conversion function (12.3.2), the initial standard
3544       //   conversion sequence converts the source type to the
3545       //   implicit object parameter of the conversion function.
3546       User.Before = Best->Conversions[0].Standard;
3547       User.HadMultipleCandidates = HadMultipleCandidates;
3548       User.ConversionFunction = Conversion;
3549       User.FoundConversionFunction = Best->FoundDecl;
3550       User.EllipsisConversion = false;
3551 
3552       // C++ [over.ics.user]p2:
3553       //   The second standard conversion sequence converts the
3554       //   result of the user-defined conversion to the target type
3555       //   for the sequence. Since an implicit conversion sequence
3556       //   is an initialization, the special rules for
3557       //   initialization by user-defined conversion apply when
3558       //   selecting the best user-defined conversion for a
3559       //   user-defined conversion sequence (see 13.3.3 and
3560       //   13.3.3.1).
3561       User.After = Best->FinalConversion;
3562       return Result;
3563     }
3564     llvm_unreachable("Not a constructor or conversion function?");
3565 
3566   case OR_No_Viable_Function:
3567     return OR_No_Viable_Function;
3568 
3569   case OR_Ambiguous:
3570     return OR_Ambiguous;
3571   }
3572 
3573   llvm_unreachable("Invalid OverloadResult!");
3574 }
3575 
3576 bool
3577 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3578   ImplicitConversionSequence ICS;
3579   OverloadCandidateSet CandidateSet(From->getExprLoc(),
3580                                     OverloadCandidateSet::CSK_Normal);
3581   OverloadingResult OvResult =
3582     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3583                             CandidateSet, false, false);
3584 
3585   if (!(OvResult == OR_Ambiguous ||
3586         (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3587     return false;
3588 
3589   auto Cands = CandidateSet.CompleteCandidates(
3590       *this,
3591       OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3592       From);
3593   if (OvResult == OR_Ambiguous)
3594     Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3595         << From->getType() << ToType << From->getSourceRange();
3596   else { // OR_No_Viable_Function && !CandidateSet.empty()
3597     if (!RequireCompleteType(From->getBeginLoc(), ToType,
3598                              diag::err_typecheck_nonviable_condition_incomplete,
3599                              From->getType(), From->getSourceRange()))
3600       Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3601           << false << From->getType() << From->getSourceRange() << ToType;
3602   }
3603 
3604   CandidateSet.NoteCandidates(
3605                               *this, From, Cands);
3606   return true;
3607 }
3608 
3609 /// Compare the user-defined conversion functions or constructors
3610 /// of two user-defined conversion sequences to determine whether any ordering
3611 /// is possible.
3612 static ImplicitConversionSequence::CompareKind
3613 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3614                            FunctionDecl *Function2) {
3615   if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3616     return ImplicitConversionSequence::Indistinguishable;
3617 
3618   // Objective-C++:
3619   //   If both conversion functions are implicitly-declared conversions from
3620   //   a lambda closure type to a function pointer and a block pointer,
3621   //   respectively, always prefer the conversion to a function pointer,
3622   //   because the function pointer is more lightweight and is more likely
3623   //   to keep code working.
3624   CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3625   if (!Conv1)
3626     return ImplicitConversionSequence::Indistinguishable;
3627 
3628   CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3629   if (!Conv2)
3630     return ImplicitConversionSequence::Indistinguishable;
3631 
3632   if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3633     bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3634     bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3635     if (Block1 != Block2)
3636       return Block1 ? ImplicitConversionSequence::Worse
3637                     : ImplicitConversionSequence::Better;
3638   }
3639 
3640   return ImplicitConversionSequence::Indistinguishable;
3641 }
3642 
3643 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3644     const ImplicitConversionSequence &ICS) {
3645   return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3646          (ICS.isUserDefined() &&
3647           ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3648 }
3649 
3650 /// CompareImplicitConversionSequences - Compare two implicit
3651 /// conversion sequences to determine whether one is better than the
3652 /// other or if they are indistinguishable (C++ 13.3.3.2).
3653 static ImplicitConversionSequence::CompareKind
3654 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3655                                    const ImplicitConversionSequence& ICS1,
3656                                    const ImplicitConversionSequence& ICS2)
3657 {
3658   // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3659   // conversion sequences (as defined in 13.3.3.1)
3660   //   -- a standard conversion sequence (13.3.3.1.1) is a better
3661   //      conversion sequence than a user-defined conversion sequence or
3662   //      an ellipsis conversion sequence, and
3663   //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
3664   //      conversion sequence than an ellipsis conversion sequence
3665   //      (13.3.3.1.3).
3666   //
3667   // C++0x [over.best.ics]p10:
3668   //   For the purpose of ranking implicit conversion sequences as
3669   //   described in 13.3.3.2, the ambiguous conversion sequence is
3670   //   treated as a user-defined sequence that is indistinguishable
3671   //   from any other user-defined conversion sequence.
3672 
3673   // String literal to 'char *' conversion has been deprecated in C++03. It has
3674   // been removed from C++11. We still accept this conversion, if it happens at
3675   // the best viable function. Otherwise, this conversion is considered worse
3676   // than ellipsis conversion. Consider this as an extension; this is not in the
3677   // standard. For example:
3678   //
3679   // int &f(...);    // #1
3680   // void f(char*);  // #2
3681   // void g() { int &r = f("foo"); }
3682   //
3683   // In C++03, we pick #2 as the best viable function.
3684   // In C++11, we pick #1 as the best viable function, because ellipsis
3685   // conversion is better than string-literal to char* conversion (since there
3686   // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3687   // convert arguments, #2 would be the best viable function in C++11.
3688   // If the best viable function has this conversion, a warning will be issued
3689   // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3690 
3691   if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3692       hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3693       hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3694     return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3695                ? ImplicitConversionSequence::Worse
3696                : ImplicitConversionSequence::Better;
3697 
3698   if (ICS1.getKindRank() < ICS2.getKindRank())
3699     return ImplicitConversionSequence::Better;
3700   if (ICS2.getKindRank() < ICS1.getKindRank())
3701     return ImplicitConversionSequence::Worse;
3702 
3703   // The following checks require both conversion sequences to be of
3704   // the same kind.
3705   if (ICS1.getKind() != ICS2.getKind())
3706     return ImplicitConversionSequence::Indistinguishable;
3707 
3708   ImplicitConversionSequence::CompareKind Result =
3709       ImplicitConversionSequence::Indistinguishable;
3710 
3711   // Two implicit conversion sequences of the same form are
3712   // indistinguishable conversion sequences unless one of the
3713   // following rules apply: (C++ 13.3.3.2p3):
3714 
3715   // List-initialization sequence L1 is a better conversion sequence than
3716   // list-initialization sequence L2 if:
3717   // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3718   //   if not that,
3719   // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3720   //   and N1 is smaller than N2.,
3721   // even if one of the other rules in this paragraph would otherwise apply.
3722   if (!ICS1.isBad()) {
3723     if (ICS1.isStdInitializerListElement() &&
3724         !ICS2.isStdInitializerListElement())
3725       return ImplicitConversionSequence::Better;
3726     if (!ICS1.isStdInitializerListElement() &&
3727         ICS2.isStdInitializerListElement())
3728       return ImplicitConversionSequence::Worse;
3729   }
3730 
3731   if (ICS1.isStandard())
3732     // Standard conversion sequence S1 is a better conversion sequence than
3733     // standard conversion sequence S2 if [...]
3734     Result = CompareStandardConversionSequences(S, Loc,
3735                                                 ICS1.Standard, ICS2.Standard);
3736   else if (ICS1.isUserDefined()) {
3737     // User-defined conversion sequence U1 is a better conversion
3738     // sequence than another user-defined conversion sequence U2 if
3739     // they contain the same user-defined conversion function or
3740     // constructor and if the second standard conversion sequence of
3741     // U1 is better than the second standard conversion sequence of
3742     // U2 (C++ 13.3.3.2p3).
3743     if (ICS1.UserDefined.ConversionFunction ==
3744           ICS2.UserDefined.ConversionFunction)
3745       Result = CompareStandardConversionSequences(S, Loc,
3746                                                   ICS1.UserDefined.After,
3747                                                   ICS2.UserDefined.After);
3748     else
3749       Result = compareConversionFunctions(S,
3750                                           ICS1.UserDefined.ConversionFunction,
3751                                           ICS2.UserDefined.ConversionFunction);
3752   }
3753 
3754   return Result;
3755 }
3756 
3757 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3758 // determine if one is a proper subset of the other.
3759 static ImplicitConversionSequence::CompareKind
3760 compareStandardConversionSubsets(ASTContext &Context,
3761                                  const StandardConversionSequence& SCS1,
3762                                  const StandardConversionSequence& SCS2) {
3763   ImplicitConversionSequence::CompareKind Result
3764     = ImplicitConversionSequence::Indistinguishable;
3765 
3766   // the identity conversion sequence is considered to be a subsequence of
3767   // any non-identity conversion sequence
3768   if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3769     return ImplicitConversionSequence::Better;
3770   else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3771     return ImplicitConversionSequence::Worse;
3772 
3773   if (SCS1.Second != SCS2.Second) {
3774     if (SCS1.Second == ICK_Identity)
3775       Result = ImplicitConversionSequence::Better;
3776     else if (SCS2.Second == ICK_Identity)
3777       Result = ImplicitConversionSequence::Worse;
3778     else
3779       return ImplicitConversionSequence::Indistinguishable;
3780   } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3781     return ImplicitConversionSequence::Indistinguishable;
3782 
3783   if (SCS1.Third == SCS2.Third) {
3784     return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3785                              : ImplicitConversionSequence::Indistinguishable;
3786   }
3787 
3788   if (SCS1.Third == ICK_Identity)
3789     return Result == ImplicitConversionSequence::Worse
3790              ? ImplicitConversionSequence::Indistinguishable
3791              : ImplicitConversionSequence::Better;
3792 
3793   if (SCS2.Third == ICK_Identity)
3794     return Result == ImplicitConversionSequence::Better
3795              ? ImplicitConversionSequence::Indistinguishable
3796              : ImplicitConversionSequence::Worse;
3797 
3798   return ImplicitConversionSequence::Indistinguishable;
3799 }
3800 
3801 /// Determine whether one of the given reference bindings is better
3802 /// than the other based on what kind of bindings they are.
3803 static bool
3804 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3805                              const StandardConversionSequence &SCS2) {
3806   // C++0x [over.ics.rank]p3b4:
3807   //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3808   //      implicit object parameter of a non-static member function declared
3809   //      without a ref-qualifier, and *either* S1 binds an rvalue reference
3810   //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
3811   //      lvalue reference to a function lvalue and S2 binds an rvalue
3812   //      reference*.
3813   //
3814   // FIXME: Rvalue references. We're going rogue with the above edits,
3815   // because the semantics in the current C++0x working paper (N3225 at the
3816   // time of this writing) break the standard definition of std::forward
3817   // and std::reference_wrapper when dealing with references to functions.
3818   // Proposed wording changes submitted to CWG for consideration.
3819   if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3820       SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3821     return false;
3822 
3823   return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3824           SCS2.IsLvalueReference) ||
3825          (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3826           !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3827 }
3828 
3829 enum class FixedEnumPromotion {
3830   None,
3831   ToUnderlyingType,
3832   ToPromotedUnderlyingType
3833 };
3834 
3835 /// Returns kind of fixed enum promotion the \a SCS uses.
3836 static FixedEnumPromotion
3837 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3838 
3839   if (SCS.Second != ICK_Integral_Promotion)
3840     return FixedEnumPromotion::None;
3841 
3842   QualType FromType = SCS.getFromType();
3843   if (!FromType->isEnumeralType())
3844     return FixedEnumPromotion::None;
3845 
3846   EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3847   if (!Enum->isFixed())
3848     return FixedEnumPromotion::None;
3849 
3850   QualType UnderlyingType = Enum->getIntegerType();
3851   if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3852     return FixedEnumPromotion::ToUnderlyingType;
3853 
3854   return FixedEnumPromotion::ToPromotedUnderlyingType;
3855 }
3856 
3857 /// CompareStandardConversionSequences - Compare two standard
3858 /// conversion sequences to determine whether one is better than the
3859 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3860 static ImplicitConversionSequence::CompareKind
3861 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3862                                    const StandardConversionSequence& SCS1,
3863                                    const StandardConversionSequence& SCS2)
3864 {
3865   // Standard conversion sequence S1 is a better conversion sequence
3866   // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3867 
3868   //  -- S1 is a proper subsequence of S2 (comparing the conversion
3869   //     sequences in the canonical form defined by 13.3.3.1.1,
3870   //     excluding any Lvalue Transformation; the identity conversion
3871   //     sequence is considered to be a subsequence of any
3872   //     non-identity conversion sequence) or, if not that,
3873   if (ImplicitConversionSequence::CompareKind CK
3874         = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3875     return CK;
3876 
3877   //  -- the rank of S1 is better than the rank of S2 (by the rules
3878   //     defined below), or, if not that,
3879   ImplicitConversionRank Rank1 = SCS1.getRank();
3880   ImplicitConversionRank Rank2 = SCS2.getRank();
3881   if (Rank1 < Rank2)
3882     return ImplicitConversionSequence::Better;
3883   else if (Rank2 < Rank1)
3884     return ImplicitConversionSequence::Worse;
3885 
3886   // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3887   // are indistinguishable unless one of the following rules
3888   // applies:
3889 
3890   //   A conversion that is not a conversion of a pointer, or
3891   //   pointer to member, to bool is better than another conversion
3892   //   that is such a conversion.
3893   if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3894     return SCS2.isPointerConversionToBool()
3895              ? ImplicitConversionSequence::Better
3896              : ImplicitConversionSequence::Worse;
3897 
3898   // C++14 [over.ics.rank]p4b2:
3899   // This is retroactively applied to C++11 by CWG 1601.
3900   //
3901   //   A conversion that promotes an enumeration whose underlying type is fixed
3902   //   to its underlying type is better than one that promotes to the promoted
3903   //   underlying type, if the two are different.
3904   FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3905   FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3906   if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3907       FEP1 != FEP2)
3908     return FEP1 == FixedEnumPromotion::ToUnderlyingType
3909                ? ImplicitConversionSequence::Better
3910                : ImplicitConversionSequence::Worse;
3911 
3912   // C++ [over.ics.rank]p4b2:
3913   //
3914   //   If class B is derived directly or indirectly from class A,
3915   //   conversion of B* to A* is better than conversion of B* to
3916   //   void*, and conversion of A* to void* is better than conversion
3917   //   of B* to void*.
3918   bool SCS1ConvertsToVoid
3919     = SCS1.isPointerConversionToVoidPointer(S.Context);
3920   bool SCS2ConvertsToVoid
3921     = SCS2.isPointerConversionToVoidPointer(S.Context);
3922   if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3923     // Exactly one of the conversion sequences is a conversion to
3924     // a void pointer; it's the worse conversion.
3925     return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3926                               : ImplicitConversionSequence::Worse;
3927   } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3928     // Neither conversion sequence converts to a void pointer; compare
3929     // their derived-to-base conversions.
3930     if (ImplicitConversionSequence::CompareKind DerivedCK
3931           = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3932       return DerivedCK;
3933   } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3934              !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3935     // Both conversion sequences are conversions to void
3936     // pointers. Compare the source types to determine if there's an
3937     // inheritance relationship in their sources.
3938     QualType FromType1 = SCS1.getFromType();
3939     QualType FromType2 = SCS2.getFromType();
3940 
3941     // Adjust the types we're converting from via the array-to-pointer
3942     // conversion, if we need to.
3943     if (SCS1.First == ICK_Array_To_Pointer)
3944       FromType1 = S.Context.getArrayDecayedType(FromType1);
3945     if (SCS2.First == ICK_Array_To_Pointer)
3946       FromType2 = S.Context.getArrayDecayedType(FromType2);
3947 
3948     QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3949     QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3950 
3951     if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3952       return ImplicitConversionSequence::Better;
3953     else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3954       return ImplicitConversionSequence::Worse;
3955 
3956     // Objective-C++: If one interface is more specific than the
3957     // other, it is the better one.
3958     const ObjCObjectPointerType* FromObjCPtr1
3959       = FromType1->getAs<ObjCObjectPointerType>();
3960     const ObjCObjectPointerType* FromObjCPtr2
3961       = FromType2->getAs<ObjCObjectPointerType>();
3962     if (FromObjCPtr1 && FromObjCPtr2) {
3963       bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3964                                                           FromObjCPtr2);
3965       bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3966                                                            FromObjCPtr1);
3967       if (AssignLeft != AssignRight) {
3968         return AssignLeft? ImplicitConversionSequence::Better
3969                          : ImplicitConversionSequence::Worse;
3970       }
3971     }
3972   }
3973 
3974   // Compare based on qualification conversions (C++ 13.3.3.2p3,
3975   // bullet 3).
3976   if (ImplicitConversionSequence::CompareKind QualCK
3977         = CompareQualificationConversions(S, SCS1, SCS2))
3978     return QualCK;
3979 
3980   if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3981     // Check for a better reference binding based on the kind of bindings.
3982     if (isBetterReferenceBindingKind(SCS1, SCS2))
3983       return ImplicitConversionSequence::Better;
3984     else if (isBetterReferenceBindingKind(SCS2, SCS1))
3985       return ImplicitConversionSequence::Worse;
3986 
3987     // C++ [over.ics.rank]p3b4:
3988     //   -- S1 and S2 are reference bindings (8.5.3), and the types to
3989     //      which the references refer are the same type except for
3990     //      top-level cv-qualifiers, and the type to which the reference
3991     //      initialized by S2 refers is more cv-qualified than the type
3992     //      to which the reference initialized by S1 refers.
3993     QualType T1 = SCS1.getToType(2);
3994     QualType T2 = SCS2.getToType(2);
3995     T1 = S.Context.getCanonicalType(T1);
3996     T2 = S.Context.getCanonicalType(T2);
3997     Qualifiers T1Quals, T2Quals;
3998     QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3999     QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4000     if (UnqualT1 == UnqualT2) {
4001       // Objective-C++ ARC: If the references refer to objects with different
4002       // lifetimes, prefer bindings that don't change lifetime.
4003       if (SCS1.ObjCLifetimeConversionBinding !=
4004                                           SCS2.ObjCLifetimeConversionBinding) {
4005         return SCS1.ObjCLifetimeConversionBinding
4006                                            ? ImplicitConversionSequence::Worse
4007                                            : ImplicitConversionSequence::Better;
4008       }
4009 
4010       // If the type is an array type, promote the element qualifiers to the
4011       // type for comparison.
4012       if (isa<ArrayType>(T1) && T1Quals)
4013         T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4014       if (isa<ArrayType>(T2) && T2Quals)
4015         T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4016       if (T2.isMoreQualifiedThan(T1))
4017         return ImplicitConversionSequence::Better;
4018       else if (T1.isMoreQualifiedThan(T2))
4019         return ImplicitConversionSequence::Worse;
4020     }
4021   }
4022 
4023   // In Microsoft mode, prefer an integral conversion to a
4024   // floating-to-integral conversion if the integral conversion
4025   // is between types of the same size.
4026   // For example:
4027   // void f(float);
4028   // void f(int);
4029   // int main {
4030   //    long a;
4031   //    f(a);
4032   // }
4033   // Here, MSVC will call f(int) instead of generating a compile error
4034   // as clang will do in standard mode.
4035   if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4036       SCS2.Second == ICK_Floating_Integral &&
4037       S.Context.getTypeSize(SCS1.getFromType()) ==
4038           S.Context.getTypeSize(SCS1.getToType(2)))
4039     return ImplicitConversionSequence::Better;
4040 
4041   // Prefer a compatible vector conversion over a lax vector conversion
4042   // For example:
4043   //
4044   // typedef float __v4sf __attribute__((__vector_size__(16)));
4045   // void f(vector float);
4046   // void f(vector signed int);
4047   // int main() {
4048   //   __v4sf a;
4049   //   f(a);
4050   // }
4051   // Here, we'd like to choose f(vector float) and not
4052   // report an ambiguous call error
4053   if (SCS1.Second == ICK_Vector_Conversion &&
4054       SCS2.Second == ICK_Vector_Conversion) {
4055     bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4056         SCS1.getFromType(), SCS1.getToType(2));
4057     bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4058         SCS2.getFromType(), SCS2.getToType(2));
4059 
4060     if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4061       return SCS1IsCompatibleVectorConversion
4062                  ? ImplicitConversionSequence::Better
4063                  : ImplicitConversionSequence::Worse;
4064   }
4065 
4066   return ImplicitConversionSequence::Indistinguishable;
4067 }
4068 
4069 /// CompareQualificationConversions - Compares two standard conversion
4070 /// sequences to determine whether they can be ranked based on their
4071 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4072 static ImplicitConversionSequence::CompareKind
4073 CompareQualificationConversions(Sema &S,
4074                                 const StandardConversionSequence& SCS1,
4075                                 const StandardConversionSequence& SCS2) {
4076   // C++ 13.3.3.2p3:
4077   //  -- S1 and S2 differ only in their qualification conversion and
4078   //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
4079   //     cv-qualification signature of type T1 is a proper subset of
4080   //     the cv-qualification signature of type T2, and S1 is not the
4081   //     deprecated string literal array-to-pointer conversion (4.2).
4082   if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4083       SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4084     return ImplicitConversionSequence::Indistinguishable;
4085 
4086   // FIXME: the example in the standard doesn't use a qualification
4087   // conversion (!)
4088   QualType T1 = SCS1.getToType(2);
4089   QualType T2 = SCS2.getToType(2);
4090   T1 = S.Context.getCanonicalType(T1);
4091   T2 = S.Context.getCanonicalType(T2);
4092   Qualifiers T1Quals, T2Quals;
4093   QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4094   QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4095 
4096   // If the types are the same, we won't learn anything by unwrapped
4097   // them.
4098   if (UnqualT1 == UnqualT2)
4099     return ImplicitConversionSequence::Indistinguishable;
4100 
4101   // If the type is an array type, promote the element qualifiers to the type
4102   // for comparison.
4103   if (isa<ArrayType>(T1) && T1Quals)
4104     T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4105   if (isa<ArrayType>(T2) && T2Quals)
4106     T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4107 
4108   ImplicitConversionSequence::CompareKind Result
4109     = ImplicitConversionSequence::Indistinguishable;
4110 
4111   // Objective-C++ ARC:
4112   //   Prefer qualification conversions not involving a change in lifetime
4113   //   to qualification conversions that do not change lifetime.
4114   if (SCS1.QualificationIncludesObjCLifetime !=
4115                                       SCS2.QualificationIncludesObjCLifetime) {
4116     Result = SCS1.QualificationIncludesObjCLifetime
4117                ? ImplicitConversionSequence::Worse
4118                : ImplicitConversionSequence::Better;
4119   }
4120 
4121   while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4122     // Within each iteration of the loop, we check the qualifiers to
4123     // determine if this still looks like a qualification
4124     // conversion. Then, if all is well, we unwrap one more level of
4125     // pointers or pointers-to-members and do it all again
4126     // until there are no more pointers or pointers-to-members left
4127     // to unwrap. This essentially mimics what
4128     // IsQualificationConversion does, but here we're checking for a
4129     // strict subset of qualifiers.
4130     if (T1.getQualifiers().withoutObjCLifetime() ==
4131         T2.getQualifiers().withoutObjCLifetime())
4132       // The qualifiers are the same, so this doesn't tell us anything
4133       // about how the sequences rank.
4134       // ObjC ownership quals are omitted above as they interfere with
4135       // the ARC overload rule.
4136       ;
4137     else if (T2.isMoreQualifiedThan(T1)) {
4138       // T1 has fewer qualifiers, so it could be the better sequence.
4139       if (Result == ImplicitConversionSequence::Worse)
4140         // Neither has qualifiers that are a subset of the other's
4141         // qualifiers.
4142         return ImplicitConversionSequence::Indistinguishable;
4143 
4144       Result = ImplicitConversionSequence::Better;
4145     } else if (T1.isMoreQualifiedThan(T2)) {
4146       // T2 has fewer qualifiers, so it could be the better sequence.
4147       if (Result == ImplicitConversionSequence::Better)
4148         // Neither has qualifiers that are a subset of the other's
4149         // qualifiers.
4150         return ImplicitConversionSequence::Indistinguishable;
4151 
4152       Result = ImplicitConversionSequence::Worse;
4153     } else {
4154       // Qualifiers are disjoint.
4155       return ImplicitConversionSequence::Indistinguishable;
4156     }
4157 
4158     // If the types after this point are equivalent, we're done.
4159     if (S.Context.hasSameUnqualifiedType(T1, T2))
4160       break;
4161   }
4162 
4163   // Check that the winning standard conversion sequence isn't using
4164   // the deprecated string literal array to pointer conversion.
4165   switch (Result) {
4166   case ImplicitConversionSequence::Better:
4167     if (SCS1.DeprecatedStringLiteralToCharPtr)
4168       Result = ImplicitConversionSequence::Indistinguishable;
4169     break;
4170 
4171   case ImplicitConversionSequence::Indistinguishable:
4172     break;
4173 
4174   case ImplicitConversionSequence::Worse:
4175     if (SCS2.DeprecatedStringLiteralToCharPtr)
4176       Result = ImplicitConversionSequence::Indistinguishable;
4177     break;
4178   }
4179 
4180   return Result;
4181 }
4182 
4183 /// CompareDerivedToBaseConversions - Compares two standard conversion
4184 /// sequences to determine whether they can be ranked based on their
4185 /// various kinds of derived-to-base conversions (C++
4186 /// [over.ics.rank]p4b3).  As part of these checks, we also look at
4187 /// conversions between Objective-C interface types.
4188 static ImplicitConversionSequence::CompareKind
4189 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4190                                 const StandardConversionSequence& SCS1,
4191                                 const StandardConversionSequence& SCS2) {
4192   QualType FromType1 = SCS1.getFromType();
4193   QualType ToType1 = SCS1.getToType(1);
4194   QualType FromType2 = SCS2.getFromType();
4195   QualType ToType2 = SCS2.getToType(1);
4196 
4197   // Adjust the types we're converting from via the array-to-pointer
4198   // conversion, if we need to.
4199   if (SCS1.First == ICK_Array_To_Pointer)
4200     FromType1 = S.Context.getArrayDecayedType(FromType1);
4201   if (SCS2.First == ICK_Array_To_Pointer)
4202     FromType2 = S.Context.getArrayDecayedType(FromType2);
4203 
4204   // Canonicalize all of the types.
4205   FromType1 = S.Context.getCanonicalType(FromType1);
4206   ToType1 = S.Context.getCanonicalType(ToType1);
4207   FromType2 = S.Context.getCanonicalType(FromType2);
4208   ToType2 = S.Context.getCanonicalType(ToType2);
4209 
4210   // C++ [over.ics.rank]p4b3:
4211   //
4212   //   If class B is derived directly or indirectly from class A and
4213   //   class C is derived directly or indirectly from B,
4214   //
4215   // Compare based on pointer conversions.
4216   if (SCS1.Second == ICK_Pointer_Conversion &&
4217       SCS2.Second == ICK_Pointer_Conversion &&
4218       /*FIXME: Remove if Objective-C id conversions get their own rank*/
4219       FromType1->isPointerType() && FromType2->isPointerType() &&
4220       ToType1->isPointerType() && ToType2->isPointerType()) {
4221     QualType FromPointee1 =
4222         FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4223     QualType ToPointee1 =
4224         ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4225     QualType FromPointee2 =
4226         FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4227     QualType ToPointee2 =
4228         ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4229 
4230     //   -- conversion of C* to B* is better than conversion of C* to A*,
4231     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4232       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4233         return ImplicitConversionSequence::Better;
4234       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4235         return ImplicitConversionSequence::Worse;
4236     }
4237 
4238     //   -- conversion of B* to A* is better than conversion of C* to A*,
4239     if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4240       if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4241         return ImplicitConversionSequence::Better;
4242       else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4243         return ImplicitConversionSequence::Worse;
4244     }
4245   } else if (SCS1.Second == ICK_Pointer_Conversion &&
4246              SCS2.Second == ICK_Pointer_Conversion) {
4247     const ObjCObjectPointerType *FromPtr1
4248       = FromType1->getAs<ObjCObjectPointerType>();
4249     const ObjCObjectPointerType *FromPtr2
4250       = FromType2->getAs<ObjCObjectPointerType>();
4251     const ObjCObjectPointerType *ToPtr1
4252       = ToType1->getAs<ObjCObjectPointerType>();
4253     const ObjCObjectPointerType *ToPtr2
4254       = ToType2->getAs<ObjCObjectPointerType>();
4255 
4256     if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4257       // Apply the same conversion ranking rules for Objective-C pointer types
4258       // that we do for C++ pointers to class types. However, we employ the
4259       // Objective-C pseudo-subtyping relationship used for assignment of
4260       // Objective-C pointer types.
4261       bool FromAssignLeft
4262         = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4263       bool FromAssignRight
4264         = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4265       bool ToAssignLeft
4266         = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4267       bool ToAssignRight
4268         = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4269 
4270       // A conversion to an a non-id object pointer type or qualified 'id'
4271       // type is better than a conversion to 'id'.
4272       if (ToPtr1->isObjCIdType() &&
4273           (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4274         return ImplicitConversionSequence::Worse;
4275       if (ToPtr2->isObjCIdType() &&
4276           (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4277         return ImplicitConversionSequence::Better;
4278 
4279       // A conversion to a non-id object pointer type is better than a
4280       // conversion to a qualified 'id' type
4281       if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4282         return ImplicitConversionSequence::Worse;
4283       if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4284         return ImplicitConversionSequence::Better;
4285 
4286       // A conversion to an a non-Class object pointer type or qualified 'Class'
4287       // type is better than a conversion to 'Class'.
4288       if (ToPtr1->isObjCClassType() &&
4289           (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4290         return ImplicitConversionSequence::Worse;
4291       if (ToPtr2->isObjCClassType() &&
4292           (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4293         return ImplicitConversionSequence::Better;
4294 
4295       // A conversion to a non-Class object pointer type is better than a
4296       // conversion to a qualified 'Class' type.
4297       if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4298         return ImplicitConversionSequence::Worse;
4299       if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4300         return ImplicitConversionSequence::Better;
4301 
4302       //   -- "conversion of C* to B* is better than conversion of C* to A*,"
4303       if (S.Context.hasSameType(FromType1, FromType2) &&
4304           !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4305           (ToAssignLeft != ToAssignRight)) {
4306         if (FromPtr1->isSpecialized()) {
4307           // "conversion of B<A> * to B * is better than conversion of B * to
4308           // C *.
4309           bool IsFirstSame =
4310               FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4311           bool IsSecondSame =
4312               FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4313           if (IsFirstSame) {
4314             if (!IsSecondSame)
4315               return ImplicitConversionSequence::Better;
4316           } else if (IsSecondSame)
4317             return ImplicitConversionSequence::Worse;
4318         }
4319         return ToAssignLeft? ImplicitConversionSequence::Worse
4320                            : ImplicitConversionSequence::Better;
4321       }
4322 
4323       //   -- "conversion of B* to A* is better than conversion of C* to A*,"
4324       if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4325           (FromAssignLeft != FromAssignRight))
4326         return FromAssignLeft? ImplicitConversionSequence::Better
4327         : ImplicitConversionSequence::Worse;
4328     }
4329   }
4330 
4331   // Ranking of member-pointer types.
4332   if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4333       FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4334       ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4335     const MemberPointerType * FromMemPointer1 =
4336                                         FromType1->getAs<MemberPointerType>();
4337     const MemberPointerType * ToMemPointer1 =
4338                                           ToType1->getAs<MemberPointerType>();
4339     const MemberPointerType * FromMemPointer2 =
4340                                           FromType2->getAs<MemberPointerType>();
4341     const MemberPointerType * ToMemPointer2 =
4342                                           ToType2->getAs<MemberPointerType>();
4343     const Type *FromPointeeType1 = FromMemPointer1->getClass();
4344     const Type *ToPointeeType1 = ToMemPointer1->getClass();
4345     const Type *FromPointeeType2 = FromMemPointer2->getClass();
4346     const Type *ToPointeeType2 = ToMemPointer2->getClass();
4347     QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4348     QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4349     QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4350     QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4351     // conversion of A::* to B::* is better than conversion of A::* to C::*,
4352     if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4353       if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4354         return ImplicitConversionSequence::Worse;
4355       else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4356         return ImplicitConversionSequence::Better;
4357     }
4358     // conversion of B::* to C::* is better than conversion of A::* to C::*
4359     if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4360       if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4361         return ImplicitConversionSequence::Better;
4362       else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4363         return ImplicitConversionSequence::Worse;
4364     }
4365   }
4366 
4367   if (SCS1.Second == ICK_Derived_To_Base) {
4368     //   -- conversion of C to B is better than conversion of C to A,
4369     //   -- binding of an expression of type C to a reference of type
4370     //      B& is better than binding an expression of type C to a
4371     //      reference of type A&,
4372     if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4373         !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4374       if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4375         return ImplicitConversionSequence::Better;
4376       else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4377         return ImplicitConversionSequence::Worse;
4378     }
4379 
4380     //   -- conversion of B to A is better than conversion of C to A.
4381     //   -- binding of an expression of type B to a reference of type
4382     //      A& is better than binding an expression of type C to a
4383     //      reference of type A&,
4384     if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4385         S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4386       if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4387         return ImplicitConversionSequence::Better;
4388       else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4389         return ImplicitConversionSequence::Worse;
4390     }
4391   }
4392 
4393   return ImplicitConversionSequence::Indistinguishable;
4394 }
4395 
4396 /// Determine whether the given type is valid, e.g., it is not an invalid
4397 /// C++ class.
4398 static bool isTypeValid(QualType T) {
4399   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4400     return !Record->isInvalidDecl();
4401 
4402   return true;
4403 }
4404 
4405 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4406 /// determine whether they are reference-related,
4407 /// reference-compatible, reference-compatible with added
4408 /// qualification, or incompatible, for use in C++ initialization by
4409 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4410 /// type, and the first type (T1) is the pointee type of the reference
4411 /// type being initialized.
4412 Sema::ReferenceCompareResult
4413 Sema::CompareReferenceRelationship(SourceLocation Loc,
4414                                    QualType OrigT1, QualType OrigT2,
4415                                    ReferenceConversions *ConvOut) {
4416   assert(!OrigT1->isReferenceType() &&
4417     "T1 must be the pointee type of the reference type");
4418   assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4419 
4420   QualType T1 = Context.getCanonicalType(OrigT1);
4421   QualType T2 = Context.getCanonicalType(OrigT2);
4422   Qualifiers T1Quals, T2Quals;
4423   QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4424   QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4425 
4426   ReferenceConversions ConvTmp;
4427   ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4428   Conv = ReferenceConversions();
4429 
4430   // C++ [dcl.init.ref]p4:
4431   //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4432   //   reference-related to "cv2 T2" if T1 is the same type as T2, or
4433   //   T1 is a base class of T2.
4434   QualType ConvertedT2;
4435   if (UnqualT1 == UnqualT2) {
4436     // Nothing to do.
4437   } else if (isCompleteType(Loc, OrigT2) &&
4438              isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4439              IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4440     Conv |= ReferenceConversions::DerivedToBase;
4441   else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4442            UnqualT2->isObjCObjectOrInterfaceType() &&
4443            Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4444     Conv |= ReferenceConversions::ObjC;
4445   else if (UnqualT2->isFunctionType() &&
4446            IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4447     // C++1z [dcl.init.ref]p4:
4448     //   cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4449     //   function" and T1 is "function"
4450     //
4451     // We extend this to also apply to 'noreturn', so allow any function
4452     // conversion between function types.
4453     Conv |= ReferenceConversions::Function;
4454     return Ref_Compatible;
4455   } else
4456     return Ref_Incompatible;
4457 
4458   // At this point, we know that T1 and T2 are reference-related (at
4459   // least).
4460 
4461   // If the type is an array type, promote the element qualifiers to the type
4462   // for comparison.
4463   if (isa<ArrayType>(T1) && T1Quals)
4464     T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4465   if (isa<ArrayType>(T2) && T2Quals)
4466     T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4467 
4468   // C++ [dcl.init.ref]p4:
4469   //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4470   //   reference-related to T2 and cv1 is the same cv-qualification
4471   //   as, or greater cv-qualification than, cv2. For purposes of
4472   //   overload resolution, cases for which cv1 is greater
4473   //   cv-qualification than cv2 are identified as
4474   //   reference-compatible with added qualification (see 13.3.3.2).
4475   //
4476   // Note that we also require equivalence of Objective-C GC and address-space
4477   // qualifiers when performing these computations, so that e.g., an int in
4478   // address space 1 is not reference-compatible with an int in address
4479   // space 2.
4480   if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4481       T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4482     if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4483       Conv |= ReferenceConversions::ObjCLifetime;
4484 
4485     T1Quals.removeObjCLifetime();
4486     T2Quals.removeObjCLifetime();
4487   }
4488 
4489   // MS compiler ignores __unaligned qualifier for references; do the same.
4490   T1Quals.removeUnaligned();
4491   T2Quals.removeUnaligned();
4492 
4493   if (T1Quals != T2Quals)
4494     Conv |= ReferenceConversions::Qualification;
4495 
4496   if (T1Quals.compatiblyIncludes(T2Quals))
4497     return Ref_Compatible;
4498   else
4499     return Ref_Related;
4500 }
4501 
4502 /// Look for a user-defined conversion to a value reference-compatible
4503 ///        with DeclType. Return true if something definite is found.
4504 static bool
4505 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4506                          QualType DeclType, SourceLocation DeclLoc,
4507                          Expr *Init, QualType T2, bool AllowRvalues,
4508                          bool AllowExplicit) {
4509   assert(T2->isRecordType() && "Can only find conversions of record types.");
4510   CXXRecordDecl *T2RecordDecl
4511     = dyn_cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4512 
4513   OverloadCandidateSet CandidateSet(
4514       DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4515   const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4516   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4517     NamedDecl *D = *I;
4518     CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4519     if (isa<UsingShadowDecl>(D))
4520       D = cast<UsingShadowDecl>(D)->getTargetDecl();
4521 
4522     FunctionTemplateDecl *ConvTemplate
4523       = dyn_cast<FunctionTemplateDecl>(D);
4524     CXXConversionDecl *Conv;
4525     if (ConvTemplate)
4526       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4527     else
4528       Conv = cast<CXXConversionDecl>(D);
4529 
4530     // If this is an explicit conversion, and we're not allowed to consider
4531     // explicit conversions, skip it.
4532     if (!AllowExplicit && Conv->isExplicit())
4533       continue;
4534 
4535     if (AllowRvalues) {
4536       // If we are initializing an rvalue reference, don't permit conversion
4537       // functions that return lvalues.
4538       if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4539         const ReferenceType *RefType
4540           = Conv->getConversionType()->getAs<LValueReferenceType>();
4541         if (RefType && !RefType->getPointeeType()->isFunctionType())
4542           continue;
4543       }
4544 
4545       if (!ConvTemplate &&
4546           S.CompareReferenceRelationship(
4547               DeclLoc,
4548               Conv->getConversionType()
4549                   .getNonReferenceType()
4550                   .getUnqualifiedType(),
4551               DeclType.getNonReferenceType().getUnqualifiedType()) ==
4552               Sema::Ref_Incompatible)
4553         continue;
4554     } else {
4555       // If the conversion function doesn't return a reference type,
4556       // it can't be considered for this conversion. An rvalue reference
4557       // is only acceptable if its referencee is a function type.
4558 
4559       const ReferenceType *RefType =
4560         Conv->getConversionType()->getAs<ReferenceType>();
4561       if (!RefType ||
4562           (!RefType->isLValueReferenceType() &&
4563            !RefType->getPointeeType()->isFunctionType()))
4564         continue;
4565     }
4566 
4567     if (ConvTemplate)
4568       S.AddTemplateConversionCandidate(
4569           ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4570           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4571     else
4572       S.AddConversionCandidate(
4573           Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4574           /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4575   }
4576 
4577   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4578 
4579   OverloadCandidateSet::iterator Best;
4580   switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4581   case OR_Success:
4582     // C++ [over.ics.ref]p1:
4583     //
4584     //   [...] If the parameter binds directly to the result of
4585     //   applying a conversion function to the argument
4586     //   expression, the implicit conversion sequence is a
4587     //   user-defined conversion sequence (13.3.3.1.2), with the
4588     //   second standard conversion sequence either an identity
4589     //   conversion or, if the conversion function returns an
4590     //   entity of a type that is a derived class of the parameter
4591     //   type, a derived-to-base Conversion.
4592     if (!Best->FinalConversion.DirectBinding)
4593       return false;
4594 
4595     ICS.setUserDefined();
4596     ICS.UserDefined.Before = Best->Conversions[0].Standard;
4597     ICS.UserDefined.After = Best->FinalConversion;
4598     ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4599     ICS.UserDefined.ConversionFunction = Best->Function;
4600     ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4601     ICS.UserDefined.EllipsisConversion = false;
4602     assert(ICS.UserDefined.After.ReferenceBinding &&
4603            ICS.UserDefined.After.DirectBinding &&
4604            "Expected a direct reference binding!");
4605     return true;
4606 
4607   case OR_Ambiguous:
4608     ICS.setAmbiguous();
4609     for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4610          Cand != CandidateSet.end(); ++Cand)
4611       if (Cand->Best)
4612         ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4613     return true;
4614 
4615   case OR_No_Viable_Function:
4616   case OR_Deleted:
4617     // There was no suitable conversion, or we found a deleted
4618     // conversion; continue with other checks.
4619     return false;
4620   }
4621 
4622   llvm_unreachable("Invalid OverloadResult!");
4623 }
4624 
4625 /// Compute an implicit conversion sequence for reference
4626 /// initialization.
4627 static ImplicitConversionSequence
4628 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4629                  SourceLocation DeclLoc,
4630                  bool SuppressUserConversions,
4631                  bool AllowExplicit) {
4632   assert(DeclType->isReferenceType() && "Reference init needs a reference");
4633 
4634   // Most paths end in a failed conversion.
4635   ImplicitConversionSequence ICS;
4636   ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4637 
4638   QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4639   QualType T2 = Init->getType();
4640 
4641   // If the initializer is the address of an overloaded function, try
4642   // to resolve the overloaded function. If all goes well, T2 is the
4643   // type of the resulting function.
4644   if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4645     DeclAccessPair Found;
4646     if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4647                                                                 false, Found))
4648       T2 = Fn->getType();
4649   }
4650 
4651   // Compute some basic properties of the types and the initializer.
4652   bool isRValRef = DeclType->isRValueReferenceType();
4653   Expr::Classification InitCategory = Init->Classify(S.Context);
4654 
4655   Sema::ReferenceConversions RefConv;
4656   Sema::ReferenceCompareResult RefRelationship =
4657       S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4658 
4659   auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4660     ICS.setStandard();
4661     ICS.Standard.First = ICK_Identity;
4662     ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4663                               ? ICK_Derived_To_Base
4664                               : (RefConv & Sema::ReferenceConversions::ObjC)
4665                                     ? ICK_Compatible_Conversion
4666                                     : ICK_Identity;
4667     ICS.Standard.Third = ICK_Identity;
4668     ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4669     ICS.Standard.setToType(0, T2);
4670     ICS.Standard.setToType(1, T1);
4671     ICS.Standard.setToType(2, T1);
4672     ICS.Standard.ReferenceBinding = true;
4673     ICS.Standard.DirectBinding = BindsDirectly;
4674     ICS.Standard.IsLvalueReference = !isRValRef;
4675     ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4676     ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4677     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4678     ICS.Standard.ObjCLifetimeConversionBinding =
4679         (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4680     ICS.Standard.CopyConstructor = nullptr;
4681     ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4682   };
4683 
4684   // C++0x [dcl.init.ref]p5:
4685   //   A reference to type "cv1 T1" is initialized by an expression
4686   //   of type "cv2 T2" as follows:
4687 
4688   //     -- If reference is an lvalue reference and the initializer expression
4689   if (!isRValRef) {
4690     //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4691     //        reference-compatible with "cv2 T2," or
4692     //
4693     // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4694     if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4695       // C++ [over.ics.ref]p1:
4696       //   When a parameter of reference type binds directly (8.5.3)
4697       //   to an argument expression, the implicit conversion sequence
4698       //   is the identity conversion, unless the argument expression
4699       //   has a type that is a derived class of the parameter type,
4700       //   in which case the implicit conversion sequence is a
4701       //   derived-to-base Conversion (13.3.3.1).
4702       SetAsReferenceBinding(/*BindsDirectly=*/true);
4703 
4704       // Nothing more to do: the inaccessibility/ambiguity check for
4705       // derived-to-base conversions is suppressed when we're
4706       // computing the implicit conversion sequence (C++
4707       // [over.best.ics]p2).
4708       return ICS;
4709     }
4710 
4711     //       -- has a class type (i.e., T2 is a class type), where T1 is
4712     //          not reference-related to T2, and can be implicitly
4713     //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
4714     //          is reference-compatible with "cv3 T3" 92) (this
4715     //          conversion is selected by enumerating the applicable
4716     //          conversion functions (13.3.1.6) and choosing the best
4717     //          one through overload resolution (13.3)),
4718     if (!SuppressUserConversions && T2->isRecordType() &&
4719         S.isCompleteType(DeclLoc, T2) &&
4720         RefRelationship == Sema::Ref_Incompatible) {
4721       if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4722                                    Init, T2, /*AllowRvalues=*/false,
4723                                    AllowExplicit))
4724         return ICS;
4725     }
4726   }
4727 
4728   //     -- Otherwise, the reference shall be an lvalue reference to a
4729   //        non-volatile const type (i.e., cv1 shall be const), or the reference
4730   //        shall be an rvalue reference.
4731   if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4732     return ICS;
4733 
4734   //       -- If the initializer expression
4735   //
4736   //            -- is an xvalue, class prvalue, array prvalue or function
4737   //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4738   if (RefRelationship == Sema::Ref_Compatible &&
4739       (InitCategory.isXValue() ||
4740        (InitCategory.isPRValue() &&
4741           (T2->isRecordType() || T2->isArrayType())) ||
4742        (InitCategory.isLValue() && T2->isFunctionType()))) {
4743     // In C++11, this is always a direct binding. In C++98/03, it's a direct
4744     // binding unless we're binding to a class prvalue.
4745     // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4746     // allow the use of rvalue references in C++98/03 for the benefit of
4747     // standard library implementors; therefore, we need the xvalue check here.
4748     SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4749                           !(InitCategory.isPRValue() || T2->isRecordType()));
4750     return ICS;
4751   }
4752 
4753   //            -- has a class type (i.e., T2 is a class type), where T1 is not
4754   //               reference-related to T2, and can be implicitly converted to
4755   //               an xvalue, class prvalue, or function lvalue of type
4756   //               "cv3 T3", where "cv1 T1" is reference-compatible with
4757   //               "cv3 T3",
4758   //
4759   //          then the reference is bound to the value of the initializer
4760   //          expression in the first case and to the result of the conversion
4761   //          in the second case (or, in either case, to an appropriate base
4762   //          class subobject).
4763   if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4764       T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4765       FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4766                                Init, T2, /*AllowRvalues=*/true,
4767                                AllowExplicit)) {
4768     // In the second case, if the reference is an rvalue reference
4769     // and the second standard conversion sequence of the
4770     // user-defined conversion sequence includes an lvalue-to-rvalue
4771     // conversion, the program is ill-formed.
4772     if (ICS.isUserDefined() && isRValRef &&
4773         ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4774       ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4775 
4776     return ICS;
4777   }
4778 
4779   // A temporary of function type cannot be created; don't even try.
4780   if (T1->isFunctionType())
4781     return ICS;
4782 
4783   //       -- Otherwise, a temporary of type "cv1 T1" is created and
4784   //          initialized from the initializer expression using the
4785   //          rules for a non-reference copy initialization (8.5). The
4786   //          reference is then bound to the temporary. If T1 is
4787   //          reference-related to T2, cv1 must be the same
4788   //          cv-qualification as, or greater cv-qualification than,
4789   //          cv2; otherwise, the program is ill-formed.
4790   if (RefRelationship == Sema::Ref_Related) {
4791     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4792     // we would be reference-compatible or reference-compatible with
4793     // added qualification. But that wasn't the case, so the reference
4794     // initialization fails.
4795     //
4796     // Note that we only want to check address spaces and cvr-qualifiers here.
4797     // ObjC GC, lifetime and unaligned qualifiers aren't important.
4798     Qualifiers T1Quals = T1.getQualifiers();
4799     Qualifiers T2Quals = T2.getQualifiers();
4800     T1Quals.removeObjCGCAttr();
4801     T1Quals.removeObjCLifetime();
4802     T2Quals.removeObjCGCAttr();
4803     T2Quals.removeObjCLifetime();
4804     // MS compiler ignores __unaligned qualifier for references; do the same.
4805     T1Quals.removeUnaligned();
4806     T2Quals.removeUnaligned();
4807     if (!T1Quals.compatiblyIncludes(T2Quals))
4808       return ICS;
4809   }
4810 
4811   // If at least one of the types is a class type, the types are not
4812   // related, and we aren't allowed any user conversions, the
4813   // reference binding fails. This case is important for breaking
4814   // recursion, since TryImplicitConversion below will attempt to
4815   // create a temporary through the use of a copy constructor.
4816   if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4817       (T1->isRecordType() || T2->isRecordType()))
4818     return ICS;
4819 
4820   // If T1 is reference-related to T2 and the reference is an rvalue
4821   // reference, the initializer expression shall not be an lvalue.
4822   if (RefRelationship >= Sema::Ref_Related &&
4823       isRValRef && Init->Classify(S.Context).isLValue())
4824     return ICS;
4825 
4826   // C++ [over.ics.ref]p2:
4827   //   When a parameter of reference type is not bound directly to
4828   //   an argument expression, the conversion sequence is the one
4829   //   required to convert the argument expression to the
4830   //   underlying type of the reference according to
4831   //   13.3.3.1. Conceptually, this conversion sequence corresponds
4832   //   to copy-initializing a temporary of the underlying type with
4833   //   the argument expression. Any difference in top-level
4834   //   cv-qualification is subsumed by the initialization itself
4835   //   and does not constitute a conversion.
4836   ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4837                               /*AllowExplicit=*/false,
4838                               /*InOverloadResolution=*/false,
4839                               /*CStyle=*/false,
4840                               /*AllowObjCWritebackConversion=*/false,
4841                               /*AllowObjCConversionOnExplicit=*/false);
4842 
4843   // Of course, that's still a reference binding.
4844   if (ICS.isStandard()) {
4845     ICS.Standard.ReferenceBinding = true;
4846     ICS.Standard.IsLvalueReference = !isRValRef;
4847     ICS.Standard.BindsToFunctionLvalue = false;
4848     ICS.Standard.BindsToRvalue = true;
4849     ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4850     ICS.Standard.ObjCLifetimeConversionBinding = false;
4851   } else if (ICS.isUserDefined()) {
4852     const ReferenceType *LValRefType =
4853         ICS.UserDefined.ConversionFunction->getReturnType()
4854             ->getAs<LValueReferenceType>();
4855 
4856     // C++ [over.ics.ref]p3:
4857     //   Except for an implicit object parameter, for which see 13.3.1, a
4858     //   standard conversion sequence cannot be formed if it requires [...]
4859     //   binding an rvalue reference to an lvalue other than a function
4860     //   lvalue.
4861     // Note that the function case is not possible here.
4862     if (DeclType->isRValueReferenceType() && LValRefType) {
4863       // FIXME: This is the wrong BadConversionSequence. The problem is binding
4864       // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4865       // reference to an rvalue!
4866       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4867       return ICS;
4868     }
4869 
4870     ICS.UserDefined.After.ReferenceBinding = true;
4871     ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4872     ICS.UserDefined.After.BindsToFunctionLvalue = false;
4873     ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4874     ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4875     ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4876   }
4877 
4878   return ICS;
4879 }
4880 
4881 static ImplicitConversionSequence
4882 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4883                       bool SuppressUserConversions,
4884                       bool InOverloadResolution,
4885                       bool AllowObjCWritebackConversion,
4886                       bool AllowExplicit = false);
4887 
4888 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4889 /// initializer list From.
4890 static ImplicitConversionSequence
4891 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4892                   bool SuppressUserConversions,
4893                   bool InOverloadResolution,
4894                   bool AllowObjCWritebackConversion) {
4895   // C++11 [over.ics.list]p1:
4896   //   When an argument is an initializer list, it is not an expression and
4897   //   special rules apply for converting it to a parameter type.
4898 
4899   ImplicitConversionSequence Result;
4900   Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4901 
4902   // We need a complete type for what follows. Incomplete types can never be
4903   // initialized from init lists.
4904   if (!S.isCompleteType(From->getBeginLoc(), ToType))
4905     return Result;
4906 
4907   // Per DR1467:
4908   //   If the parameter type is a class X and the initializer list has a single
4909   //   element of type cv U, where U is X or a class derived from X, the
4910   //   implicit conversion sequence is the one required to convert the element
4911   //   to the parameter type.
4912   //
4913   //   Otherwise, if the parameter type is a character array [... ]
4914   //   and the initializer list has a single element that is an
4915   //   appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4916   //   implicit conversion sequence is the identity conversion.
4917   if (From->getNumInits() == 1) {
4918     if (ToType->isRecordType()) {
4919       QualType InitType = From->getInit(0)->getType();
4920       if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4921           S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4922         return TryCopyInitialization(S, From->getInit(0), ToType,
4923                                      SuppressUserConversions,
4924                                      InOverloadResolution,
4925                                      AllowObjCWritebackConversion);
4926     }
4927     // FIXME: Check the other conditions here: array of character type,
4928     // initializer is a string literal.
4929     if (ToType->isArrayType()) {
4930       InitializedEntity Entity =
4931         InitializedEntity::InitializeParameter(S.Context, ToType,
4932                                                /*Consumed=*/false);
4933       if (S.CanPerformCopyInitialization(Entity, From)) {
4934         Result.setStandard();
4935         Result.Standard.setAsIdentityConversion();
4936         Result.Standard.setFromType(ToType);
4937         Result.Standard.setAllToTypes(ToType);
4938         return Result;
4939       }
4940     }
4941   }
4942 
4943   // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4944   // C++11 [over.ics.list]p2:
4945   //   If the parameter type is std::initializer_list<X> or "array of X" and
4946   //   all the elements can be implicitly converted to X, the implicit
4947   //   conversion sequence is the worst conversion necessary to convert an
4948   //   element of the list to X.
4949   //
4950   // C++14 [over.ics.list]p3:
4951   //   Otherwise, if the parameter type is "array of N X", if the initializer
4952   //   list has exactly N elements or if it has fewer than N elements and X is
4953   //   default-constructible, and if all the elements of the initializer list
4954   //   can be implicitly converted to X, the implicit conversion sequence is
4955   //   the worst conversion necessary to convert an element of the list to X.
4956   //
4957   // FIXME: We're missing a lot of these checks.
4958   bool toStdInitializerList = false;
4959   QualType X;
4960   if (ToType->isArrayType())
4961     X = S.Context.getAsArrayType(ToType)->getElementType();
4962   else
4963     toStdInitializerList = S.isStdInitializerList(ToType, &X);
4964   if (!X.isNull()) {
4965     for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4966       Expr *Init = From->getInit(i);
4967       ImplicitConversionSequence ICS =
4968           TryCopyInitialization(S, Init, X, SuppressUserConversions,
4969                                 InOverloadResolution,
4970                                 AllowObjCWritebackConversion);
4971       // If a single element isn't convertible, fail.
4972       if (ICS.isBad()) {
4973         Result = ICS;
4974         break;
4975       }
4976       // Otherwise, look for the worst conversion.
4977       if (Result.isBad() || CompareImplicitConversionSequences(
4978                                 S, From->getBeginLoc(), ICS, Result) ==
4979                                 ImplicitConversionSequence::Worse)
4980         Result = ICS;
4981     }
4982 
4983     // For an empty list, we won't have computed any conversion sequence.
4984     // Introduce the identity conversion sequence.
4985     if (From->getNumInits() == 0) {
4986       Result.setStandard();
4987       Result.Standard.setAsIdentityConversion();
4988       Result.Standard.setFromType(ToType);
4989       Result.Standard.setAllToTypes(ToType);
4990     }
4991 
4992     Result.setStdInitializerListElement(toStdInitializerList);
4993     return Result;
4994   }
4995 
4996   // C++14 [over.ics.list]p4:
4997   // C++11 [over.ics.list]p3:
4998   //   Otherwise, if the parameter is a non-aggregate class X and overload
4999   //   resolution chooses a single best constructor [...] the implicit
5000   //   conversion sequence is a user-defined conversion sequence. If multiple
5001   //   constructors are viable but none is better than the others, the
5002   //   implicit conversion sequence is a user-defined conversion sequence.
5003   if (ToType->isRecordType() && !ToType->isAggregateType()) {
5004     // This function can deal with initializer lists.
5005     return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5006                                     /*AllowExplicit=*/false,
5007                                     InOverloadResolution, /*CStyle=*/false,
5008                                     AllowObjCWritebackConversion,
5009                                     /*AllowObjCConversionOnExplicit=*/false);
5010   }
5011 
5012   // C++14 [over.ics.list]p5:
5013   // C++11 [over.ics.list]p4:
5014   //   Otherwise, if the parameter has an aggregate type which can be
5015   //   initialized from the initializer list [...] the implicit conversion
5016   //   sequence is a user-defined conversion sequence.
5017   if (ToType->isAggregateType()) {
5018     // Type is an aggregate, argument is an init list. At this point it comes
5019     // down to checking whether the initialization works.
5020     // FIXME: Find out whether this parameter is consumed or not.
5021     InitializedEntity Entity =
5022         InitializedEntity::InitializeParameter(S.Context, ToType,
5023                                                /*Consumed=*/false);
5024     if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5025                                                                  From)) {
5026       Result.setUserDefined();
5027       Result.UserDefined.Before.setAsIdentityConversion();
5028       // Initializer lists don't have a type.
5029       Result.UserDefined.Before.setFromType(QualType());
5030       Result.UserDefined.Before.setAllToTypes(QualType());
5031 
5032       Result.UserDefined.After.setAsIdentityConversion();
5033       Result.UserDefined.After.setFromType(ToType);
5034       Result.UserDefined.After.setAllToTypes(ToType);
5035       Result.UserDefined.ConversionFunction = nullptr;
5036     }
5037     return Result;
5038   }
5039 
5040   // C++14 [over.ics.list]p6:
5041   // C++11 [over.ics.list]p5:
5042   //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5043   if (ToType->isReferenceType()) {
5044     // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5045     // mention initializer lists in any way. So we go by what list-
5046     // initialization would do and try to extrapolate from that.
5047 
5048     QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5049 
5050     // If the initializer list has a single element that is reference-related
5051     // to the parameter type, we initialize the reference from that.
5052     if (From->getNumInits() == 1) {
5053       Expr *Init = From->getInit(0);
5054 
5055       QualType T2 = Init->getType();
5056 
5057       // If the initializer is the address of an overloaded function, try
5058       // to resolve the overloaded function. If all goes well, T2 is the
5059       // type of the resulting function.
5060       if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5061         DeclAccessPair Found;
5062         if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5063                                    Init, ToType, false, Found))
5064           T2 = Fn->getType();
5065       }
5066 
5067       // Compute some basic properties of the types and the initializer.
5068       Sema::ReferenceCompareResult RefRelationship =
5069           S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5070 
5071       if (RefRelationship >= Sema::Ref_Related) {
5072         return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5073                                 SuppressUserConversions,
5074                                 /*AllowExplicit=*/false);
5075       }
5076     }
5077 
5078     // Otherwise, we bind the reference to a temporary created from the
5079     // initializer list.
5080     Result = TryListConversion(S, From, T1, SuppressUserConversions,
5081                                InOverloadResolution,
5082                                AllowObjCWritebackConversion);
5083     if (Result.isFailure())
5084       return Result;
5085     assert(!Result.isEllipsis() &&
5086            "Sub-initialization cannot result in ellipsis conversion.");
5087 
5088     // Can we even bind to a temporary?
5089     if (ToType->isRValueReferenceType() ||
5090         (T1.isConstQualified() && !T1.isVolatileQualified())) {
5091       StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5092                                             Result.UserDefined.After;
5093       SCS.ReferenceBinding = true;
5094       SCS.IsLvalueReference = ToType->isLValueReferenceType();
5095       SCS.BindsToRvalue = true;
5096       SCS.BindsToFunctionLvalue = false;
5097       SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5098       SCS.ObjCLifetimeConversionBinding = false;
5099     } else
5100       Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5101                     From, ToType);
5102     return Result;
5103   }
5104 
5105   // C++14 [over.ics.list]p7:
5106   // C++11 [over.ics.list]p6:
5107   //   Otherwise, if the parameter type is not a class:
5108   if (!ToType->isRecordType()) {
5109     //    - if the initializer list has one element that is not itself an
5110     //      initializer list, the implicit conversion sequence is the one
5111     //      required to convert the element to the parameter type.
5112     unsigned NumInits = From->getNumInits();
5113     if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5114       Result = TryCopyInitialization(S, From->getInit(0), ToType,
5115                                      SuppressUserConversions,
5116                                      InOverloadResolution,
5117                                      AllowObjCWritebackConversion);
5118     //    - if the initializer list has no elements, the implicit conversion
5119     //      sequence is the identity conversion.
5120     else if (NumInits == 0) {
5121       Result.setStandard();
5122       Result.Standard.setAsIdentityConversion();
5123       Result.Standard.setFromType(ToType);
5124       Result.Standard.setAllToTypes(ToType);
5125     }
5126     return Result;
5127   }
5128 
5129   // C++14 [over.ics.list]p8:
5130   // C++11 [over.ics.list]p7:
5131   //   In all cases other than those enumerated above, no conversion is possible
5132   return Result;
5133 }
5134 
5135 /// TryCopyInitialization - Try to copy-initialize a value of type
5136 /// ToType from the expression From. Return the implicit conversion
5137 /// sequence required to pass this argument, which may be a bad
5138 /// conversion sequence (meaning that the argument cannot be passed to
5139 /// a parameter of this type). If @p SuppressUserConversions, then we
5140 /// do not permit any user-defined conversion sequences.
5141 static ImplicitConversionSequence
5142 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5143                       bool SuppressUserConversions,
5144                       bool InOverloadResolution,
5145                       bool AllowObjCWritebackConversion,
5146                       bool AllowExplicit) {
5147   if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5148     return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5149                              InOverloadResolution,AllowObjCWritebackConversion);
5150 
5151   if (ToType->isReferenceType())
5152     return TryReferenceInit(S, From, ToType,
5153                             /*FIXME:*/ From->getBeginLoc(),
5154                             SuppressUserConversions, AllowExplicit);
5155 
5156   return TryImplicitConversion(S, From, ToType,
5157                                SuppressUserConversions,
5158                                /*AllowExplicit=*/false,
5159                                InOverloadResolution,
5160                                /*CStyle=*/false,
5161                                AllowObjCWritebackConversion,
5162                                /*AllowObjCConversionOnExplicit=*/false);
5163 }
5164 
5165 static bool TryCopyInitialization(const CanQualType FromQTy,
5166                                   const CanQualType ToQTy,
5167                                   Sema &S,
5168                                   SourceLocation Loc,
5169                                   ExprValueKind FromVK) {
5170   OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5171   ImplicitConversionSequence ICS =
5172     TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5173 
5174   return !ICS.isBad();
5175 }
5176 
5177 /// TryObjectArgumentInitialization - Try to initialize the object
5178 /// parameter of the given member function (@c Method) from the
5179 /// expression @p From.
5180 static ImplicitConversionSequence
5181 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5182                                 Expr::Classification FromClassification,
5183                                 CXXMethodDecl *Method,
5184                                 CXXRecordDecl *ActingContext) {
5185   QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5186   // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5187   //                 const volatile object.
5188   Qualifiers Quals = Method->getMethodQualifiers();
5189   if (isa<CXXDestructorDecl>(Method)) {
5190     Quals.addConst();
5191     Quals.addVolatile();
5192   }
5193 
5194   QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5195 
5196   // Set up the conversion sequence as a "bad" conversion, to allow us
5197   // to exit early.
5198   ImplicitConversionSequence ICS;
5199 
5200   // We need to have an object of class type.
5201   if (const PointerType *PT = FromType->getAs<PointerType>()) {
5202     FromType = PT->getPointeeType();
5203 
5204     // When we had a pointer, it's implicitly dereferenced, so we
5205     // better have an lvalue.
5206     assert(FromClassification.isLValue());
5207   }
5208 
5209   assert(FromType->isRecordType());
5210 
5211   // C++0x [over.match.funcs]p4:
5212   //   For non-static member functions, the type of the implicit object
5213   //   parameter is
5214   //
5215   //     - "lvalue reference to cv X" for functions declared without a
5216   //        ref-qualifier or with the & ref-qualifier
5217   //     - "rvalue reference to cv X" for functions declared with the &&
5218   //        ref-qualifier
5219   //
5220   // where X is the class of which the function is a member and cv is the
5221   // cv-qualification on the member function declaration.
5222   //
5223   // However, when finding an implicit conversion sequence for the argument, we
5224   // are not allowed to perform user-defined conversions
5225   // (C++ [over.match.funcs]p5). We perform a simplified version of
5226   // reference binding here, that allows class rvalues to bind to
5227   // non-constant references.
5228 
5229   // First check the qualifiers.
5230   QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5231   if (ImplicitParamType.getCVRQualifiers()
5232                                     != FromTypeCanon.getLocalCVRQualifiers() &&
5233       !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5234     ICS.setBad(BadConversionSequence::bad_qualifiers,
5235                FromType, ImplicitParamType);
5236     return ICS;
5237   }
5238 
5239   if (FromTypeCanon.hasAddressSpace()) {
5240     Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5241     Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5242     if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5243       ICS.setBad(BadConversionSequence::bad_qualifiers,
5244                  FromType, ImplicitParamType);
5245       return ICS;
5246     }
5247   }
5248 
5249   // Check that we have either the same type or a derived type. It
5250   // affects the conversion rank.
5251   QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5252   ImplicitConversionKind SecondKind;
5253   if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5254     SecondKind = ICK_Identity;
5255   } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5256     SecondKind = ICK_Derived_To_Base;
5257   else {
5258     ICS.setBad(BadConversionSequence::unrelated_class,
5259                FromType, ImplicitParamType);
5260     return ICS;
5261   }
5262 
5263   // Check the ref-qualifier.
5264   switch (Method->getRefQualifier()) {
5265   case RQ_None:
5266     // Do nothing; we don't care about lvalueness or rvalueness.
5267     break;
5268 
5269   case RQ_LValue:
5270     if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5271       // non-const lvalue reference cannot bind to an rvalue
5272       ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5273                  ImplicitParamType);
5274       return ICS;
5275     }
5276     break;
5277 
5278   case RQ_RValue:
5279     if (!FromClassification.isRValue()) {
5280       // rvalue reference cannot bind to an lvalue
5281       ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5282                  ImplicitParamType);
5283       return ICS;
5284     }
5285     break;
5286   }
5287 
5288   // Success. Mark this as a reference binding.
5289   ICS.setStandard();
5290   ICS.Standard.setAsIdentityConversion();
5291   ICS.Standard.Second = SecondKind;
5292   ICS.Standard.setFromType(FromType);
5293   ICS.Standard.setAllToTypes(ImplicitParamType);
5294   ICS.Standard.ReferenceBinding = true;
5295   ICS.Standard.DirectBinding = true;
5296   ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5297   ICS.Standard.BindsToFunctionLvalue = false;
5298   ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5299   ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5300     = (Method->getRefQualifier() == RQ_None);
5301   return ICS;
5302 }
5303 
5304 /// PerformObjectArgumentInitialization - Perform initialization of
5305 /// the implicit object parameter for the given Method with the given
5306 /// expression.
5307 ExprResult
5308 Sema::PerformObjectArgumentInitialization(Expr *From,
5309                                           NestedNameSpecifier *Qualifier,
5310                                           NamedDecl *FoundDecl,
5311                                           CXXMethodDecl *Method) {
5312   QualType FromRecordType, DestType;
5313   QualType ImplicitParamRecordType  =
5314     Method->getThisType()->castAs<PointerType>()->getPointeeType();
5315 
5316   Expr::Classification FromClassification;
5317   if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5318     FromRecordType = PT->getPointeeType();
5319     DestType = Method->getThisType();
5320     FromClassification = Expr::Classification::makeSimpleLValue();
5321   } else {
5322     FromRecordType = From->getType();
5323     DestType = ImplicitParamRecordType;
5324     FromClassification = From->Classify(Context);
5325 
5326     // When performing member access on an rvalue, materialize a temporary.
5327     if (From->isRValue()) {
5328       From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5329                                             Method->getRefQualifier() !=
5330                                                 RefQualifierKind::RQ_RValue);
5331     }
5332   }
5333 
5334   // Note that we always use the true parent context when performing
5335   // the actual argument initialization.
5336   ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5337       *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5338       Method->getParent());
5339   if (ICS.isBad()) {
5340     switch (ICS.Bad.Kind) {
5341     case BadConversionSequence::bad_qualifiers: {
5342       Qualifiers FromQs = FromRecordType.getQualifiers();
5343       Qualifiers ToQs = DestType.getQualifiers();
5344       unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5345       if (CVR) {
5346         Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5347             << Method->getDeclName() << FromRecordType << (CVR - 1)
5348             << From->getSourceRange();
5349         Diag(Method->getLocation(), diag::note_previous_decl)
5350           << Method->getDeclName();
5351         return ExprError();
5352       }
5353       break;
5354     }
5355 
5356     case BadConversionSequence::lvalue_ref_to_rvalue:
5357     case BadConversionSequence::rvalue_ref_to_lvalue: {
5358       bool IsRValueQualified =
5359         Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5360       Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5361           << Method->getDeclName() << FromClassification.isRValue()
5362           << IsRValueQualified;
5363       Diag(Method->getLocation(), diag::note_previous_decl)
5364         << Method->getDeclName();
5365       return ExprError();
5366     }
5367 
5368     case BadConversionSequence::no_conversion:
5369     case BadConversionSequence::unrelated_class:
5370       break;
5371     }
5372 
5373     return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5374            << ImplicitParamRecordType << FromRecordType
5375            << From->getSourceRange();
5376   }
5377 
5378   if (ICS.Standard.Second == ICK_Derived_To_Base) {
5379     ExprResult FromRes =
5380       PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5381     if (FromRes.isInvalid())
5382       return ExprError();
5383     From = FromRes.get();
5384   }
5385 
5386   if (!Context.hasSameType(From->getType(), DestType)) {
5387     CastKind CK;
5388     QualType PteeTy = DestType->getPointeeType();
5389     LangAS DestAS =
5390         PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5391     if (FromRecordType.getAddressSpace() != DestAS)
5392       CK = CK_AddressSpaceConversion;
5393     else
5394       CK = CK_NoOp;
5395     From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5396   }
5397   return From;
5398 }
5399 
5400 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5401 /// expression From to bool (C++0x [conv]p3).
5402 static ImplicitConversionSequence
5403 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5404   return TryImplicitConversion(S, From, S.Context.BoolTy,
5405                                /*SuppressUserConversions=*/false,
5406                                /*AllowExplicit=*/true,
5407                                /*InOverloadResolution=*/false,
5408                                /*CStyle=*/false,
5409                                /*AllowObjCWritebackConversion=*/false,
5410                                /*AllowObjCConversionOnExplicit=*/false);
5411 }
5412 
5413 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5414 /// of the expression From to bool (C++0x [conv]p3).
5415 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5416   if (checkPlaceholderForOverload(*this, From))
5417     return ExprError();
5418 
5419   ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5420   if (!ICS.isBad())
5421     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5422 
5423   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5424     return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5425            << From->getType() << From->getSourceRange();
5426   return ExprError();
5427 }
5428 
5429 /// Check that the specified conversion is permitted in a converted constant
5430 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5431 /// is acceptable.
5432 static bool CheckConvertedConstantConversions(Sema &S,
5433                                               StandardConversionSequence &SCS) {
5434   // Since we know that the target type is an integral or unscoped enumeration
5435   // type, most conversion kinds are impossible. All possible First and Third
5436   // conversions are fine.
5437   switch (SCS.Second) {
5438   case ICK_Identity:
5439   case ICK_Function_Conversion:
5440   case ICK_Integral_Promotion:
5441   case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5442   case ICK_Zero_Queue_Conversion:
5443     return true;
5444 
5445   case ICK_Boolean_Conversion:
5446     // Conversion from an integral or unscoped enumeration type to bool is
5447     // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5448     // conversion, so we allow it in a converted constant expression.
5449     //
5450     // FIXME: Per core issue 1407, we should not allow this, but that breaks
5451     // a lot of popular code. We should at least add a warning for this
5452     // (non-conforming) extension.
5453     return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5454            SCS.getToType(2)->isBooleanType();
5455 
5456   case ICK_Pointer_Conversion:
5457   case ICK_Pointer_Member:
5458     // C++1z: null pointer conversions and null member pointer conversions are
5459     // only permitted if the source type is std::nullptr_t.
5460     return SCS.getFromType()->isNullPtrType();
5461 
5462   case ICK_Floating_Promotion:
5463   case ICK_Complex_Promotion:
5464   case ICK_Floating_Conversion:
5465   case ICK_Complex_Conversion:
5466   case ICK_Floating_Integral:
5467   case ICK_Compatible_Conversion:
5468   case ICK_Derived_To_Base:
5469   case ICK_Vector_Conversion:
5470   case ICK_Vector_Splat:
5471   case ICK_Complex_Real:
5472   case ICK_Block_Pointer_Conversion:
5473   case ICK_TransparentUnionConversion:
5474   case ICK_Writeback_Conversion:
5475   case ICK_Zero_Event_Conversion:
5476   case ICK_C_Only_Conversion:
5477   case ICK_Incompatible_Pointer_Conversion:
5478     return false;
5479 
5480   case ICK_Lvalue_To_Rvalue:
5481   case ICK_Array_To_Pointer:
5482   case ICK_Function_To_Pointer:
5483     llvm_unreachable("found a first conversion kind in Second");
5484 
5485   case ICK_Qualification:
5486     llvm_unreachable("found a third conversion kind in Second");
5487 
5488   case ICK_Num_Conversion_Kinds:
5489     break;
5490   }
5491 
5492   llvm_unreachable("unknown conversion kind");
5493 }
5494 
5495 /// CheckConvertedConstantExpression - Check that the expression From is a
5496 /// converted constant expression of type T, perform the conversion and produce
5497 /// the converted expression, per C++11 [expr.const]p3.
5498 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5499                                                    QualType T, APValue &Value,
5500                                                    Sema::CCEKind CCE,
5501                                                    bool RequireInt) {
5502   assert(S.getLangOpts().CPlusPlus11 &&
5503          "converted constant expression outside C++11");
5504 
5505   if (checkPlaceholderForOverload(S, From))
5506     return ExprError();
5507 
5508   // C++1z [expr.const]p3:
5509   //  A converted constant expression of type T is an expression,
5510   //  implicitly converted to type T, where the converted
5511   //  expression is a constant expression and the implicit conversion
5512   //  sequence contains only [... list of conversions ...].
5513   // C++1z [stmt.if]p2:
5514   //  If the if statement is of the form if constexpr, the value of the
5515   //  condition shall be a contextually converted constant expression of type
5516   //  bool.
5517   ImplicitConversionSequence ICS =
5518       CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5519           ? TryContextuallyConvertToBool(S, From)
5520           : TryCopyInitialization(S, From, T,
5521                                   /*SuppressUserConversions=*/false,
5522                                   /*InOverloadResolution=*/false,
5523                                   /*AllowObjCWritebackConversion=*/false,
5524                                   /*AllowExplicit=*/false);
5525   StandardConversionSequence *SCS = nullptr;
5526   switch (ICS.getKind()) {
5527   case ImplicitConversionSequence::StandardConversion:
5528     SCS = &ICS.Standard;
5529     break;
5530   case ImplicitConversionSequence::UserDefinedConversion:
5531     // We are converting to a non-class type, so the Before sequence
5532     // must be trivial.
5533     SCS = &ICS.UserDefined.After;
5534     break;
5535   case ImplicitConversionSequence::AmbiguousConversion:
5536   case ImplicitConversionSequence::BadConversion:
5537     if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5538       return S.Diag(From->getBeginLoc(),
5539                     diag::err_typecheck_converted_constant_expression)
5540              << From->getType() << From->getSourceRange() << T;
5541     return ExprError();
5542 
5543   case ImplicitConversionSequence::EllipsisConversion:
5544     llvm_unreachable("ellipsis conversion in converted constant expression");
5545   }
5546 
5547   // Check that we would only use permitted conversions.
5548   if (!CheckConvertedConstantConversions(S, *SCS)) {
5549     return S.Diag(From->getBeginLoc(),
5550                   diag::err_typecheck_converted_constant_expression_disallowed)
5551            << From->getType() << From->getSourceRange() << T;
5552   }
5553   // [...] and where the reference binding (if any) binds directly.
5554   if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5555     return S.Diag(From->getBeginLoc(),
5556                   diag::err_typecheck_converted_constant_expression_indirect)
5557            << From->getType() << From->getSourceRange() << T;
5558   }
5559 
5560   ExprResult Result =
5561       S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5562   if (Result.isInvalid())
5563     return Result;
5564 
5565   // C++2a [intro.execution]p5:
5566   //   A full-expression is [...] a constant-expression [...]
5567   Result =
5568       S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5569                             /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5570   if (Result.isInvalid())
5571     return Result;
5572 
5573   // Check for a narrowing implicit conversion.
5574   APValue PreNarrowingValue;
5575   QualType PreNarrowingType;
5576   switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5577                                 PreNarrowingType)) {
5578   case NK_Dependent_Narrowing:
5579     // Implicit conversion to a narrower type, but the expression is
5580     // value-dependent so we can't tell whether it's actually narrowing.
5581   case NK_Variable_Narrowing:
5582     // Implicit conversion to a narrower type, and the value is not a constant
5583     // expression. We'll diagnose this in a moment.
5584   case NK_Not_Narrowing:
5585     break;
5586 
5587   case NK_Constant_Narrowing:
5588     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5589         << CCE << /*Constant*/ 1
5590         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5591     break;
5592 
5593   case NK_Type_Narrowing:
5594     S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5595         << CCE << /*Constant*/ 0 << From->getType() << T;
5596     break;
5597   }
5598 
5599   if (Result.get()->isValueDependent()) {
5600     Value = APValue();
5601     return Result;
5602   }
5603 
5604   // Check the expression is a constant expression.
5605   SmallVector<PartialDiagnosticAt, 8> Notes;
5606   Expr::EvalResult Eval;
5607   Eval.Diag = &Notes;
5608   Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5609                                    ? Expr::EvaluateForMangling
5610                                    : Expr::EvaluateForCodeGen;
5611 
5612   if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5613       (RequireInt && !Eval.Val.isInt())) {
5614     // The expression can't be folded, so we can't keep it at this position in
5615     // the AST.
5616     Result = ExprError();
5617   } else {
5618     Value = Eval.Val;
5619 
5620     if (Notes.empty()) {
5621       // It's a constant expression.
5622       return ConstantExpr::Create(S.Context, Result.get(), Value);
5623     }
5624   }
5625 
5626   // It's not a constant expression. Produce an appropriate diagnostic.
5627   if (Notes.size() == 1 &&
5628       Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5629     S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5630   else {
5631     S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5632         << CCE << From->getSourceRange();
5633     for (unsigned I = 0; I < Notes.size(); ++I)
5634       S.Diag(Notes[I].first, Notes[I].second);
5635   }
5636   return ExprError();
5637 }
5638 
5639 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5640                                                   APValue &Value, CCEKind CCE) {
5641   return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5642 }
5643 
5644 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5645                                                   llvm::APSInt &Value,
5646                                                   CCEKind CCE) {
5647   assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5648 
5649   APValue V;
5650   auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5651   if (!R.isInvalid() && !R.get()->isValueDependent())
5652     Value = V.getInt();
5653   return R;
5654 }
5655 
5656 
5657 /// dropPointerConversions - If the given standard conversion sequence
5658 /// involves any pointer conversions, remove them.  This may change
5659 /// the result type of the conversion sequence.
5660 static void dropPointerConversion(StandardConversionSequence &SCS) {
5661   if (SCS.Second == ICK_Pointer_Conversion) {
5662     SCS.Second = ICK_Identity;
5663     SCS.Third = ICK_Identity;
5664     SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5665   }
5666 }
5667 
5668 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5669 /// convert the expression From to an Objective-C pointer type.
5670 static ImplicitConversionSequence
5671 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5672   // Do an implicit conversion to 'id'.
5673   QualType Ty = S.Context.getObjCIdType();
5674   ImplicitConversionSequence ICS
5675     = TryImplicitConversion(S, From, Ty,
5676                             // FIXME: Are these flags correct?
5677                             /*SuppressUserConversions=*/false,
5678                             /*AllowExplicit=*/true,
5679                             /*InOverloadResolution=*/false,
5680                             /*CStyle=*/false,
5681                             /*AllowObjCWritebackConversion=*/false,
5682                             /*AllowObjCConversionOnExplicit=*/true);
5683 
5684   // Strip off any final conversions to 'id'.
5685   switch (ICS.getKind()) {
5686   case ImplicitConversionSequence::BadConversion:
5687   case ImplicitConversionSequence::AmbiguousConversion:
5688   case ImplicitConversionSequence::EllipsisConversion:
5689     break;
5690 
5691   case ImplicitConversionSequence::UserDefinedConversion:
5692     dropPointerConversion(ICS.UserDefined.After);
5693     break;
5694 
5695   case ImplicitConversionSequence::StandardConversion:
5696     dropPointerConversion(ICS.Standard);
5697     break;
5698   }
5699 
5700   return ICS;
5701 }
5702 
5703 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5704 /// conversion of the expression From to an Objective-C pointer type.
5705 /// Returns a valid but null ExprResult if no conversion sequence exists.
5706 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5707   if (checkPlaceholderForOverload(*this, From))
5708     return ExprError();
5709 
5710   QualType Ty = Context.getObjCIdType();
5711   ImplicitConversionSequence ICS =
5712     TryContextuallyConvertToObjCPointer(*this, From);
5713   if (!ICS.isBad())
5714     return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5715   return ExprResult();
5716 }
5717 
5718 /// Determine whether the provided type is an integral type, or an enumeration
5719 /// type of a permitted flavor.
5720 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5721   return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5722                                  : T->isIntegralOrUnscopedEnumerationType();
5723 }
5724 
5725 static ExprResult
5726 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5727                             Sema::ContextualImplicitConverter &Converter,
5728                             QualType T, UnresolvedSetImpl &ViableConversions) {
5729 
5730   if (Converter.Suppress)
5731     return ExprError();
5732 
5733   Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5734   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5735     CXXConversionDecl *Conv =
5736         cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5737     QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5738     Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5739   }
5740   return From;
5741 }
5742 
5743 static bool
5744 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5745                            Sema::ContextualImplicitConverter &Converter,
5746                            QualType T, bool HadMultipleCandidates,
5747                            UnresolvedSetImpl &ExplicitConversions) {
5748   if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5749     DeclAccessPair Found = ExplicitConversions[0];
5750     CXXConversionDecl *Conversion =
5751         cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5752 
5753     // The user probably meant to invoke the given explicit
5754     // conversion; use it.
5755     QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5756     std::string TypeStr;
5757     ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5758 
5759     Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5760         << FixItHint::CreateInsertion(From->getBeginLoc(),
5761                                       "static_cast<" + TypeStr + ">(")
5762         << FixItHint::CreateInsertion(
5763                SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5764     Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5765 
5766     // If we aren't in a SFINAE context, build a call to the
5767     // explicit conversion function.
5768     if (SemaRef.isSFINAEContext())
5769       return true;
5770 
5771     SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5772     ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5773                                                        HadMultipleCandidates);
5774     if (Result.isInvalid())
5775       return true;
5776     // Record usage of conversion in an implicit cast.
5777     From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5778                                     CK_UserDefinedConversion, Result.get(),
5779                                     nullptr, Result.get()->getValueKind());
5780   }
5781   return false;
5782 }
5783 
5784 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5785                              Sema::ContextualImplicitConverter &Converter,
5786                              QualType T, bool HadMultipleCandidates,
5787                              DeclAccessPair &Found) {
5788   CXXConversionDecl *Conversion =
5789       cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5790   SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5791 
5792   QualType ToType = Conversion->getConversionType().getNonReferenceType();
5793   if (!Converter.SuppressConversion) {
5794     if (SemaRef.isSFINAEContext())
5795       return true;
5796 
5797     Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5798         << From->getSourceRange();
5799   }
5800 
5801   ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5802                                                      HadMultipleCandidates);
5803   if (Result.isInvalid())
5804     return true;
5805   // Record usage of conversion in an implicit cast.
5806   From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5807                                   CK_UserDefinedConversion, Result.get(),
5808                                   nullptr, Result.get()->getValueKind());
5809   return false;
5810 }
5811 
5812 static ExprResult finishContextualImplicitConversion(
5813     Sema &SemaRef, SourceLocation Loc, Expr *From,
5814     Sema::ContextualImplicitConverter &Converter) {
5815   if (!Converter.match(From->getType()) && !Converter.Suppress)
5816     Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5817         << From->getSourceRange();
5818 
5819   return SemaRef.DefaultLvalueConversion(From);
5820 }
5821 
5822 static void
5823 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5824                                   UnresolvedSetImpl &ViableConversions,
5825                                   OverloadCandidateSet &CandidateSet) {
5826   for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5827     DeclAccessPair FoundDecl = ViableConversions[I];
5828     NamedDecl *D = FoundDecl.getDecl();
5829     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5830     if (isa<UsingShadowDecl>(D))
5831       D = cast<UsingShadowDecl>(D)->getTargetDecl();
5832 
5833     CXXConversionDecl *Conv;
5834     FunctionTemplateDecl *ConvTemplate;
5835     if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5836       Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5837     else
5838       Conv = cast<CXXConversionDecl>(D);
5839 
5840     if (ConvTemplate)
5841       SemaRef.AddTemplateConversionCandidate(
5842           ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5843           /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5844     else
5845       SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5846                                      ToType, CandidateSet,
5847                                      /*AllowObjCConversionOnExplicit=*/false,
5848                                      /*AllowExplicit*/ true);
5849   }
5850 }
5851 
5852 /// Attempt to convert the given expression to a type which is accepted
5853 /// by the given converter.
5854 ///
5855 /// This routine will attempt to convert an expression of class type to a
5856 /// type accepted by the specified converter. In C++11 and before, the class
5857 /// must have a single non-explicit conversion function converting to a matching
5858 /// type. In C++1y, there can be multiple such conversion functions, but only
5859 /// one target type.
5860 ///
5861 /// \param Loc The source location of the construct that requires the
5862 /// conversion.
5863 ///
5864 /// \param From The expression we're converting from.
5865 ///
5866 /// \param Converter Used to control and diagnose the conversion process.
5867 ///
5868 /// \returns The expression, converted to an integral or enumeration type if
5869 /// successful.
5870 ExprResult Sema::PerformContextualImplicitConversion(
5871     SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5872   // We can't perform any more checking for type-dependent expressions.
5873   if (From->isTypeDependent())
5874     return From;
5875 
5876   // Process placeholders immediately.
5877   if (From->hasPlaceholderType()) {
5878     ExprResult result = CheckPlaceholderExpr(From);
5879     if (result.isInvalid())
5880       return result;
5881     From = result.get();
5882   }
5883 
5884   // If the expression already has a matching type, we're golden.
5885   QualType T = From->getType();
5886   if (Converter.match(T))
5887     return DefaultLvalueConversion(From);
5888 
5889   // FIXME: Check for missing '()' if T is a function type?
5890 
5891   // We can only perform contextual implicit conversions on objects of class
5892   // type.
5893   const RecordType *RecordTy = T->getAs<RecordType>();
5894   if (!RecordTy || !getLangOpts().CPlusPlus) {
5895     if (!Converter.Suppress)
5896       Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5897     return From;
5898   }
5899 
5900   // We must have a complete class type.
5901   struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5902     ContextualImplicitConverter &Converter;
5903     Expr *From;
5904 
5905     TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5906         : Converter(Converter), From(From) {}
5907 
5908     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5909       Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5910     }
5911   } IncompleteDiagnoser(Converter, From);
5912 
5913   if (Converter.Suppress ? !isCompleteType(Loc, T)
5914                          : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5915     return From;
5916 
5917   // Look for a conversion to an integral or enumeration type.
5918   UnresolvedSet<4>
5919       ViableConversions; // These are *potentially* viable in C++1y.
5920   UnresolvedSet<4> ExplicitConversions;
5921   const auto &Conversions =
5922       cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5923 
5924   bool HadMultipleCandidates =
5925       (std::distance(Conversions.begin(), Conversions.end()) > 1);
5926 
5927   // To check that there is only one target type, in C++1y:
5928   QualType ToType;
5929   bool HasUniqueTargetType = true;
5930 
5931   // Collect explicit or viable (potentially in C++1y) conversions.
5932   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5933     NamedDecl *D = (*I)->getUnderlyingDecl();
5934     CXXConversionDecl *Conversion;
5935     FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5936     if (ConvTemplate) {
5937       if (getLangOpts().CPlusPlus14)
5938         Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5939       else
5940         continue; // C++11 does not consider conversion operator templates(?).
5941     } else
5942       Conversion = cast<CXXConversionDecl>(D);
5943 
5944     assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5945            "Conversion operator templates are considered potentially "
5946            "viable in C++1y");
5947 
5948     QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5949     if (Converter.match(CurToType) || ConvTemplate) {
5950 
5951       if (Conversion->isExplicit()) {
5952         // FIXME: For C++1y, do we need this restriction?
5953         // cf. diagnoseNoViableConversion()
5954         if (!ConvTemplate)
5955           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5956       } else {
5957         if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5958           if (ToType.isNull())
5959             ToType = CurToType.getUnqualifiedType();
5960           else if (HasUniqueTargetType &&
5961                    (CurToType.getUnqualifiedType() != ToType))
5962             HasUniqueTargetType = false;
5963         }
5964         ViableConversions.addDecl(I.getDecl(), I.getAccess());
5965       }
5966     }
5967   }
5968 
5969   if (getLangOpts().CPlusPlus14) {
5970     // C++1y [conv]p6:
5971     // ... An expression e of class type E appearing in such a context
5972     // is said to be contextually implicitly converted to a specified
5973     // type T and is well-formed if and only if e can be implicitly
5974     // converted to a type T that is determined as follows: E is searched
5975     // for conversion functions whose return type is cv T or reference to
5976     // cv T such that T is allowed by the context. There shall be
5977     // exactly one such T.
5978 
5979     // If no unique T is found:
5980     if (ToType.isNull()) {
5981       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5982                                      HadMultipleCandidates,
5983                                      ExplicitConversions))
5984         return ExprError();
5985       return finishContextualImplicitConversion(*this, Loc, From, Converter);
5986     }
5987 
5988     // If more than one unique Ts are found:
5989     if (!HasUniqueTargetType)
5990       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5991                                          ViableConversions);
5992 
5993     // If one unique T is found:
5994     // First, build a candidate set from the previously recorded
5995     // potentially viable conversions.
5996     OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5997     collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5998                                       CandidateSet);
5999 
6000     // Then, perform overload resolution over the candidate set.
6001     OverloadCandidateSet::iterator Best;
6002     switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6003     case OR_Success: {
6004       // Apply this conversion.
6005       DeclAccessPair Found =
6006           DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6007       if (recordConversion(*this, Loc, From, Converter, T,
6008                            HadMultipleCandidates, Found))
6009         return ExprError();
6010       break;
6011     }
6012     case OR_Ambiguous:
6013       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6014                                          ViableConversions);
6015     case OR_No_Viable_Function:
6016       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6017                                      HadMultipleCandidates,
6018                                      ExplicitConversions))
6019         return ExprError();
6020       LLVM_FALLTHROUGH;
6021     case OR_Deleted:
6022       // We'll complain below about a non-integral condition type.
6023       break;
6024     }
6025   } else {
6026     switch (ViableConversions.size()) {
6027     case 0: {
6028       if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6029                                      HadMultipleCandidates,
6030                                      ExplicitConversions))
6031         return ExprError();
6032 
6033       // We'll complain below about a non-integral condition type.
6034       break;
6035     }
6036     case 1: {
6037       // Apply this conversion.
6038       DeclAccessPair Found = ViableConversions[0];
6039       if (recordConversion(*this, Loc, From, Converter, T,
6040                            HadMultipleCandidates, Found))
6041         return ExprError();
6042       break;
6043     }
6044     default:
6045       return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6046                                          ViableConversions);
6047     }
6048   }
6049 
6050   return finishContextualImplicitConversion(*this, Loc, From, Converter);
6051 }
6052 
6053 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6054 /// an acceptable non-member overloaded operator for a call whose
6055 /// arguments have types T1 (and, if non-empty, T2). This routine
6056 /// implements the check in C++ [over.match.oper]p3b2 concerning
6057 /// enumeration types.
6058 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6059                                                    FunctionDecl *Fn,
6060                                                    ArrayRef<Expr *> Args) {
6061   QualType T1 = Args[0]->getType();
6062   QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6063 
6064   if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6065     return true;
6066 
6067   if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6068     return true;
6069 
6070   const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
6071   if (Proto->getNumParams() < 1)
6072     return false;
6073 
6074   if (T1->isEnumeralType()) {
6075     QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6076     if (Context.hasSameUnqualifiedType(T1, ArgType))
6077       return true;
6078   }
6079 
6080   if (Proto->getNumParams() < 2)
6081     return false;
6082 
6083   if (!T2.isNull() && T2->isEnumeralType()) {
6084     QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6085     if (Context.hasSameUnqualifiedType(T2, ArgType))
6086       return true;
6087   }
6088 
6089   return false;
6090 }
6091 
6092 /// AddOverloadCandidate - Adds the given function to the set of
6093 /// candidate functions, using the given function call arguments.  If
6094 /// @p SuppressUserConversions, then don't allow user-defined
6095 /// conversions via constructors or conversion operators.
6096 ///
6097 /// \param PartialOverloading true if we are performing "partial" overloading
6098 /// based on an incomplete set of function arguments. This feature is used by
6099 /// code completion.
6100 void Sema::AddOverloadCandidate(
6101     FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6102     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6103     bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6104     ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6105     OverloadCandidateParamOrder PO) {
6106   const FunctionProtoType *Proto
6107     = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6108   assert(Proto && "Functions without a prototype cannot be overloaded");
6109   assert(!Function->getDescribedFunctionTemplate() &&
6110          "Use AddTemplateOverloadCandidate for function templates");
6111 
6112   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6113     if (!isa<CXXConstructorDecl>(Method)) {
6114       // If we get here, it's because we're calling a member function
6115       // that is named without a member access expression (e.g.,
6116       // "this->f") that was either written explicitly or created
6117       // implicitly. This can happen with a qualified call to a member
6118       // function, e.g., X::f(). We use an empty type for the implied
6119       // object argument (C++ [over.call.func]p3), and the acting context
6120       // is irrelevant.
6121       AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6122                          Expr::Classification::makeSimpleLValue(), Args,
6123                          CandidateSet, SuppressUserConversions,
6124                          PartialOverloading, EarlyConversions, PO);
6125       return;
6126     }
6127     // We treat a constructor like a non-member function, since its object
6128     // argument doesn't participate in overload resolution.
6129   }
6130 
6131   if (!CandidateSet.isNewCandidate(Function, PO))
6132     return;
6133 
6134   // C++11 [class.copy]p11: [DR1402]
6135   //   A defaulted move constructor that is defined as deleted is ignored by
6136   //   overload resolution.
6137   CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6138   if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6139       Constructor->isMoveConstructor())
6140     return;
6141 
6142   // Overload resolution is always an unevaluated context.
6143   EnterExpressionEvaluationContext Unevaluated(
6144       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6145 
6146   // C++ [over.match.oper]p3:
6147   //   if no operand has a class type, only those non-member functions in the
6148   //   lookup set that have a first parameter of type T1 or "reference to
6149   //   (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6150   //   is a right operand) a second parameter of type T2 or "reference to
6151   //   (possibly cv-qualified) T2", when T2 is an enumeration type, are
6152   //   candidate functions.
6153   if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6154       !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6155     return;
6156 
6157   // Add this candidate
6158   OverloadCandidate &Candidate =
6159       CandidateSet.addCandidate(Args.size(), EarlyConversions);
6160   Candidate.FoundDecl = FoundDecl;
6161   Candidate.Function = Function;
6162   Candidate.Viable = true;
6163   Candidate.RewriteKind =
6164       CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6165   Candidate.IsSurrogate = false;
6166   Candidate.IsADLCandidate = IsADLCandidate;
6167   Candidate.IgnoreObjectArgument = false;
6168   Candidate.ExplicitCallArguments = Args.size();
6169 
6170   if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6171       !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6172     Candidate.Viable = false;
6173     Candidate.FailureKind = ovl_non_default_multiversion_function;
6174     return;
6175   }
6176 
6177   if (Constructor) {
6178     // C++ [class.copy]p3:
6179     //   A member function template is never instantiated to perform the copy
6180     //   of a class object to an object of its class type.
6181     QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6182     if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6183         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6184          IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6185                        ClassType))) {
6186       Candidate.Viable = false;
6187       Candidate.FailureKind = ovl_fail_illegal_constructor;
6188       return;
6189     }
6190 
6191     // C++ [over.match.funcs]p8: (proposed DR resolution)
6192     //   A constructor inherited from class type C that has a first parameter
6193     //   of type "reference to P" (including such a constructor instantiated
6194     //   from a template) is excluded from the set of candidate functions when
6195     //   constructing an object of type cv D if the argument list has exactly
6196     //   one argument and D is reference-related to P and P is reference-related
6197     //   to C.
6198     auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6199     if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6200         Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6201       QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6202       QualType C = Context.getRecordType(Constructor->getParent());
6203       QualType D = Context.getRecordType(Shadow->getParent());
6204       SourceLocation Loc = Args.front()->getExprLoc();
6205       if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6206           (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6207         Candidate.Viable = false;
6208         Candidate.FailureKind = ovl_fail_inhctor_slice;
6209         return;
6210       }
6211     }
6212 
6213     // Check that the constructor is capable of constructing an object in the
6214     // destination address space.
6215     if (!Qualifiers::isAddressSpaceSupersetOf(
6216             Constructor->getMethodQualifiers().getAddressSpace(),
6217             CandidateSet.getDestAS())) {
6218       Candidate.Viable = false;
6219       Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6220     }
6221   }
6222 
6223   unsigned NumParams = Proto->getNumParams();
6224 
6225   // (C++ 13.3.2p2): A candidate function having fewer than m
6226   // parameters is viable only if it has an ellipsis in its parameter
6227   // list (8.3.5).
6228   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6229       !Proto->isVariadic()) {
6230     Candidate.Viable = false;
6231     Candidate.FailureKind = ovl_fail_too_many_arguments;
6232     return;
6233   }
6234 
6235   // (C++ 13.3.2p2): A candidate function having more than m parameters
6236   // is viable only if the (m+1)st parameter has a default argument
6237   // (8.3.6). For the purposes of overload resolution, the
6238   // parameter list is truncated on the right, so that there are
6239   // exactly m parameters.
6240   unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6241   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6242     // Not enough arguments.
6243     Candidate.Viable = false;
6244     Candidate.FailureKind = ovl_fail_too_few_arguments;
6245     return;
6246   }
6247 
6248   // (CUDA B.1): Check for invalid calls between targets.
6249   if (getLangOpts().CUDA)
6250     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6251       // Skip the check for callers that are implicit members, because in this
6252       // case we may not yet know what the member's target is; the target is
6253       // inferred for the member automatically, based on the bases and fields of
6254       // the class.
6255       if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6256         Candidate.Viable = false;
6257         Candidate.FailureKind = ovl_fail_bad_target;
6258         return;
6259       }
6260 
6261   // Determine the implicit conversion sequences for each of the
6262   // arguments.
6263   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6264     unsigned ConvIdx =
6265         PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6266     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6267       // We already formed a conversion sequence for this parameter during
6268       // template argument deduction.
6269     } else if (ArgIdx < NumParams) {
6270       // (C++ 13.3.2p3): for F to be a viable function, there shall
6271       // exist for each argument an implicit conversion sequence
6272       // (13.3.3.1) that converts that argument to the corresponding
6273       // parameter of F.
6274       QualType ParamType = Proto->getParamType(ArgIdx);
6275       Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6276           *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6277           /*InOverloadResolution=*/true,
6278           /*AllowObjCWritebackConversion=*/
6279           getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6280       if (Candidate.Conversions[ConvIdx].isBad()) {
6281         Candidate.Viable = false;
6282         Candidate.FailureKind = ovl_fail_bad_conversion;
6283         return;
6284       }
6285     } else {
6286       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6287       // argument for which there is no corresponding parameter is
6288       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6289       Candidate.Conversions[ConvIdx].setEllipsis();
6290     }
6291   }
6292 
6293   if (!AllowExplicit) {
6294     ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6295     if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6296       Candidate.Viable = false;
6297       Candidate.FailureKind = ovl_fail_explicit_resolved;
6298       return;
6299     }
6300   }
6301 
6302   if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6303     Candidate.Viable = false;
6304     Candidate.FailureKind = ovl_fail_enable_if;
6305     Candidate.DeductionFailure.Data = FailedAttr;
6306     return;
6307   }
6308 
6309   if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6310     Candidate.Viable = false;
6311     Candidate.FailureKind = ovl_fail_ext_disabled;
6312     return;
6313   }
6314 }
6315 
6316 ObjCMethodDecl *
6317 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6318                        SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6319   if (Methods.size() <= 1)
6320     return nullptr;
6321 
6322   for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6323     bool Match = true;
6324     ObjCMethodDecl *Method = Methods[b];
6325     unsigned NumNamedArgs = Sel.getNumArgs();
6326     // Method might have more arguments than selector indicates. This is due
6327     // to addition of c-style arguments in method.
6328     if (Method->param_size() > NumNamedArgs)
6329       NumNamedArgs = Method->param_size();
6330     if (Args.size() < NumNamedArgs)
6331       continue;
6332 
6333     for (unsigned i = 0; i < NumNamedArgs; i++) {
6334       // We can't do any type-checking on a type-dependent argument.
6335       if (Args[i]->isTypeDependent()) {
6336         Match = false;
6337         break;
6338       }
6339 
6340       ParmVarDecl *param = Method->parameters()[i];
6341       Expr *argExpr = Args[i];
6342       assert(argExpr && "SelectBestMethod(): missing expression");
6343 
6344       // Strip the unbridged-cast placeholder expression off unless it's
6345       // a consumed argument.
6346       if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6347           !param->hasAttr<CFConsumedAttr>())
6348         argExpr = stripARCUnbridgedCast(argExpr);
6349 
6350       // If the parameter is __unknown_anytype, move on to the next method.
6351       if (param->getType() == Context.UnknownAnyTy) {
6352         Match = false;
6353         break;
6354       }
6355 
6356       ImplicitConversionSequence ConversionState
6357         = TryCopyInitialization(*this, argExpr, param->getType(),
6358                                 /*SuppressUserConversions*/false,
6359                                 /*InOverloadResolution=*/true,
6360                                 /*AllowObjCWritebackConversion=*/
6361                                 getLangOpts().ObjCAutoRefCount,
6362                                 /*AllowExplicit*/false);
6363       // This function looks for a reasonably-exact match, so we consider
6364       // incompatible pointer conversions to be a failure here.
6365       if (ConversionState.isBad() ||
6366           (ConversionState.isStandard() &&
6367            ConversionState.Standard.Second ==
6368                ICK_Incompatible_Pointer_Conversion)) {
6369         Match = false;
6370         break;
6371       }
6372     }
6373     // Promote additional arguments to variadic methods.
6374     if (Match && Method->isVariadic()) {
6375       for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6376         if (Args[i]->isTypeDependent()) {
6377           Match = false;
6378           break;
6379         }
6380         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6381                                                           nullptr);
6382         if (Arg.isInvalid()) {
6383           Match = false;
6384           break;
6385         }
6386       }
6387     } else {
6388       // Check for extra arguments to non-variadic methods.
6389       if (Args.size() != NumNamedArgs)
6390         Match = false;
6391       else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6392         // Special case when selectors have no argument. In this case, select
6393         // one with the most general result type of 'id'.
6394         for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6395           QualType ReturnT = Methods[b]->getReturnType();
6396           if (ReturnT->isObjCIdType())
6397             return Methods[b];
6398         }
6399       }
6400     }
6401 
6402     if (Match)
6403       return Method;
6404   }
6405   return nullptr;
6406 }
6407 
6408 static bool
6409 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6410                                  ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6411                                  bool MissingImplicitThis, Expr *&ConvertedThis,
6412                                  SmallVectorImpl<Expr *> &ConvertedArgs) {
6413   if (ThisArg) {
6414     CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6415     assert(!isa<CXXConstructorDecl>(Method) &&
6416            "Shouldn't have `this` for ctors!");
6417     assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6418     ExprResult R = S.PerformObjectArgumentInitialization(
6419         ThisArg, /*Qualifier=*/nullptr, Method, Method);
6420     if (R.isInvalid())
6421       return false;
6422     ConvertedThis = R.get();
6423   } else {
6424     if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6425       (void)MD;
6426       assert((MissingImplicitThis || MD->isStatic() ||
6427               isa<CXXConstructorDecl>(MD)) &&
6428              "Expected `this` for non-ctor instance methods");
6429     }
6430     ConvertedThis = nullptr;
6431   }
6432 
6433   // Ignore any variadic arguments. Converting them is pointless, since the
6434   // user can't refer to them in the function condition.
6435   unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6436 
6437   // Convert the arguments.
6438   for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6439     ExprResult R;
6440     R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6441                                         S.Context, Function->getParamDecl(I)),
6442                                     SourceLocation(), Args[I]);
6443 
6444     if (R.isInvalid())
6445       return false;
6446 
6447     ConvertedArgs.push_back(R.get());
6448   }
6449 
6450   if (Trap.hasErrorOccurred())
6451     return false;
6452 
6453   // Push default arguments if needed.
6454   if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6455     for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6456       ParmVarDecl *P = Function->getParamDecl(i);
6457       Expr *DefArg = P->hasUninstantiatedDefaultArg()
6458                          ? P->getUninstantiatedDefaultArg()
6459                          : P->getDefaultArg();
6460       // This can only happen in code completion, i.e. when PartialOverloading
6461       // is true.
6462       if (!DefArg)
6463         return false;
6464       ExprResult R =
6465           S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6466                                           S.Context, Function->getParamDecl(i)),
6467                                       SourceLocation(), DefArg);
6468       if (R.isInvalid())
6469         return false;
6470       ConvertedArgs.push_back(R.get());
6471     }
6472 
6473     if (Trap.hasErrorOccurred())
6474       return false;
6475   }
6476   return true;
6477 }
6478 
6479 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6480                                   bool MissingImplicitThis) {
6481   auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6482   if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6483     return nullptr;
6484 
6485   SFINAETrap Trap(*this);
6486   SmallVector<Expr *, 16> ConvertedArgs;
6487   // FIXME: We should look into making enable_if late-parsed.
6488   Expr *DiscardedThis;
6489   if (!convertArgsForAvailabilityChecks(
6490           *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6491           /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6492     return *EnableIfAttrs.begin();
6493 
6494   for (auto *EIA : EnableIfAttrs) {
6495     APValue Result;
6496     // FIXME: This doesn't consider value-dependent cases, because doing so is
6497     // very difficult. Ideally, we should handle them more gracefully.
6498     if (EIA->getCond()->isValueDependent() ||
6499         !EIA->getCond()->EvaluateWithSubstitution(
6500             Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6501       return EIA;
6502 
6503     if (!Result.isInt() || !Result.getInt().getBoolValue())
6504       return EIA;
6505   }
6506   return nullptr;
6507 }
6508 
6509 template <typename CheckFn>
6510 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6511                                         bool ArgDependent, SourceLocation Loc,
6512                                         CheckFn &&IsSuccessful) {
6513   SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6514   for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6515     if (ArgDependent == DIA->getArgDependent())
6516       Attrs.push_back(DIA);
6517   }
6518 
6519   // Common case: No diagnose_if attributes, so we can quit early.
6520   if (Attrs.empty())
6521     return false;
6522 
6523   auto WarningBegin = std::stable_partition(
6524       Attrs.begin(), Attrs.end(),
6525       [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6526 
6527   // Note that diagnose_if attributes are late-parsed, so they appear in the
6528   // correct order (unlike enable_if attributes).
6529   auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6530                                IsSuccessful);
6531   if (ErrAttr != WarningBegin) {
6532     const DiagnoseIfAttr *DIA = *ErrAttr;
6533     S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6534     S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6535         << DIA->getParent() << DIA->getCond()->getSourceRange();
6536     return true;
6537   }
6538 
6539   for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6540     if (IsSuccessful(DIA)) {
6541       S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6542       S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6543           << DIA->getParent() << DIA->getCond()->getSourceRange();
6544     }
6545 
6546   return false;
6547 }
6548 
6549 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6550                                                const Expr *ThisArg,
6551                                                ArrayRef<const Expr *> Args,
6552                                                SourceLocation Loc) {
6553   return diagnoseDiagnoseIfAttrsWith(
6554       *this, Function, /*ArgDependent=*/true, Loc,
6555       [&](const DiagnoseIfAttr *DIA) {
6556         APValue Result;
6557         // It's sane to use the same Args for any redecl of this function, since
6558         // EvaluateWithSubstitution only cares about the position of each
6559         // argument in the arg list, not the ParmVarDecl* it maps to.
6560         if (!DIA->getCond()->EvaluateWithSubstitution(
6561                 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6562           return false;
6563         return Result.isInt() && Result.getInt().getBoolValue();
6564       });
6565 }
6566 
6567 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6568                                                  SourceLocation Loc) {
6569   return diagnoseDiagnoseIfAttrsWith(
6570       *this, ND, /*ArgDependent=*/false, Loc,
6571       [&](const DiagnoseIfAttr *DIA) {
6572         bool Result;
6573         return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6574                Result;
6575       });
6576 }
6577 
6578 /// Add all of the function declarations in the given function set to
6579 /// the overload candidate set.
6580 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6581                                  ArrayRef<Expr *> Args,
6582                                  OverloadCandidateSet &CandidateSet,
6583                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
6584                                  bool SuppressUserConversions,
6585                                  bool PartialOverloading,
6586                                  bool FirstArgumentIsBase) {
6587   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6588     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6589     ArrayRef<Expr *> FunctionArgs = Args;
6590 
6591     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6592     FunctionDecl *FD =
6593         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6594 
6595     if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6596       QualType ObjectType;
6597       Expr::Classification ObjectClassification;
6598       if (Args.size() > 0) {
6599         if (Expr *E = Args[0]) {
6600           // Use the explicit base to restrict the lookup:
6601           ObjectType = E->getType();
6602           // Pointers in the object arguments are implicitly dereferenced, so we
6603           // always classify them as l-values.
6604           if (!ObjectType.isNull() && ObjectType->isPointerType())
6605             ObjectClassification = Expr::Classification::makeSimpleLValue();
6606           else
6607             ObjectClassification = E->Classify(Context);
6608         } // .. else there is an implicit base.
6609         FunctionArgs = Args.slice(1);
6610       }
6611       if (FunTmpl) {
6612         AddMethodTemplateCandidate(
6613             FunTmpl, F.getPair(),
6614             cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6615             ExplicitTemplateArgs, ObjectType, ObjectClassification,
6616             FunctionArgs, CandidateSet, SuppressUserConversions,
6617             PartialOverloading);
6618       } else {
6619         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6620                            cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6621                            ObjectClassification, FunctionArgs, CandidateSet,
6622                            SuppressUserConversions, PartialOverloading);
6623       }
6624     } else {
6625       // This branch handles both standalone functions and static methods.
6626 
6627       // Slice the first argument (which is the base) when we access
6628       // static method as non-static.
6629       if (Args.size() > 0 &&
6630           (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6631                         !isa<CXXConstructorDecl>(FD)))) {
6632         assert(cast<CXXMethodDecl>(FD)->isStatic());
6633         FunctionArgs = Args.slice(1);
6634       }
6635       if (FunTmpl) {
6636         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6637                                      ExplicitTemplateArgs, FunctionArgs,
6638                                      CandidateSet, SuppressUserConversions,
6639                                      PartialOverloading);
6640       } else {
6641         AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6642                              SuppressUserConversions, PartialOverloading);
6643       }
6644     }
6645   }
6646 }
6647 
6648 /// AddMethodCandidate - Adds a named decl (which is some kind of
6649 /// method) as a method candidate to the given overload set.
6650 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6651                               Expr::Classification ObjectClassification,
6652                               ArrayRef<Expr *> Args,
6653                               OverloadCandidateSet &CandidateSet,
6654                               bool SuppressUserConversions,
6655                               OverloadCandidateParamOrder PO) {
6656   NamedDecl *Decl = FoundDecl.getDecl();
6657   CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6658 
6659   if (isa<UsingShadowDecl>(Decl))
6660     Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6661 
6662   if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6663     assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6664            "Expected a member function template");
6665     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6666                                /*ExplicitArgs*/ nullptr, ObjectType,
6667                                ObjectClassification, Args, CandidateSet,
6668                                SuppressUserConversions, false, PO);
6669   } else {
6670     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6671                        ObjectType, ObjectClassification, Args, CandidateSet,
6672                        SuppressUserConversions, false, None, PO);
6673   }
6674 }
6675 
6676 /// AddMethodCandidate - Adds the given C++ member function to the set
6677 /// of candidate functions, using the given function call arguments
6678 /// and the object argument (@c Object). For example, in a call
6679 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6680 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6681 /// allow user-defined conversions via constructors or conversion
6682 /// operators.
6683 void
6684 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6685                          CXXRecordDecl *ActingContext, QualType ObjectType,
6686                          Expr::Classification ObjectClassification,
6687                          ArrayRef<Expr *> Args,
6688                          OverloadCandidateSet &CandidateSet,
6689                          bool SuppressUserConversions,
6690                          bool PartialOverloading,
6691                          ConversionSequenceList EarlyConversions,
6692                          OverloadCandidateParamOrder PO) {
6693   const FunctionProtoType *Proto
6694     = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6695   assert(Proto && "Methods without a prototype cannot be overloaded");
6696   assert(!isa<CXXConstructorDecl>(Method) &&
6697          "Use AddOverloadCandidate for constructors");
6698 
6699   if (!CandidateSet.isNewCandidate(Method, PO))
6700     return;
6701 
6702   // C++11 [class.copy]p23: [DR1402]
6703   //   A defaulted move assignment operator that is defined as deleted is
6704   //   ignored by overload resolution.
6705   if (Method->isDefaulted() && Method->isDeleted() &&
6706       Method->isMoveAssignmentOperator())
6707     return;
6708 
6709   // Overload resolution is always an unevaluated context.
6710   EnterExpressionEvaluationContext Unevaluated(
6711       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6712 
6713   // Add this candidate
6714   OverloadCandidate &Candidate =
6715       CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6716   Candidate.FoundDecl = FoundDecl;
6717   Candidate.Function = Method;
6718   Candidate.RewriteKind =
6719       CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6720   Candidate.IsSurrogate = false;
6721   Candidate.IgnoreObjectArgument = false;
6722   Candidate.ExplicitCallArguments = Args.size();
6723 
6724   unsigned NumParams = Proto->getNumParams();
6725 
6726   // (C++ 13.3.2p2): A candidate function having fewer than m
6727   // parameters is viable only if it has an ellipsis in its parameter
6728   // list (8.3.5).
6729   if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6730       !Proto->isVariadic()) {
6731     Candidate.Viable = false;
6732     Candidate.FailureKind = ovl_fail_too_many_arguments;
6733     return;
6734   }
6735 
6736   // (C++ 13.3.2p2): A candidate function having more than m parameters
6737   // is viable only if the (m+1)st parameter has a default argument
6738   // (8.3.6). For the purposes of overload resolution, the
6739   // parameter list is truncated on the right, so that there are
6740   // exactly m parameters.
6741   unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6742   if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6743     // Not enough arguments.
6744     Candidate.Viable = false;
6745     Candidate.FailureKind = ovl_fail_too_few_arguments;
6746     return;
6747   }
6748 
6749   Candidate.Viable = true;
6750 
6751   if (Method->isStatic() || ObjectType.isNull())
6752     // The implicit object argument is ignored.
6753     Candidate.IgnoreObjectArgument = true;
6754   else {
6755     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6756     // Determine the implicit conversion sequence for the object
6757     // parameter.
6758     Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6759         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6760         Method, ActingContext);
6761     if (Candidate.Conversions[ConvIdx].isBad()) {
6762       Candidate.Viable = false;
6763       Candidate.FailureKind = ovl_fail_bad_conversion;
6764       return;
6765     }
6766   }
6767 
6768   // (CUDA B.1): Check for invalid calls between targets.
6769   if (getLangOpts().CUDA)
6770     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6771       if (!IsAllowedCUDACall(Caller, Method)) {
6772         Candidate.Viable = false;
6773         Candidate.FailureKind = ovl_fail_bad_target;
6774         return;
6775       }
6776 
6777   // Determine the implicit conversion sequences for each of the
6778   // arguments.
6779   for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6780     unsigned ConvIdx =
6781         PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6782     if (Candidate.Conversions[ConvIdx].isInitialized()) {
6783       // We already formed a conversion sequence for this parameter during
6784       // template argument deduction.
6785     } else if (ArgIdx < NumParams) {
6786       // (C++ 13.3.2p3): for F to be a viable function, there shall
6787       // exist for each argument an implicit conversion sequence
6788       // (13.3.3.1) that converts that argument to the corresponding
6789       // parameter of F.
6790       QualType ParamType = Proto->getParamType(ArgIdx);
6791       Candidate.Conversions[ConvIdx]
6792         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6793                                 SuppressUserConversions,
6794                                 /*InOverloadResolution=*/true,
6795                                 /*AllowObjCWritebackConversion=*/
6796                                   getLangOpts().ObjCAutoRefCount);
6797       if (Candidate.Conversions[ConvIdx].isBad()) {
6798         Candidate.Viable = false;
6799         Candidate.FailureKind = ovl_fail_bad_conversion;
6800         return;
6801       }
6802     } else {
6803       // (C++ 13.3.2p2): For the purposes of overload resolution, any
6804       // argument for which there is no corresponding parameter is
6805       // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6806       Candidate.Conversions[ConvIdx].setEllipsis();
6807     }
6808   }
6809 
6810   if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6811     Candidate.Viable = false;
6812     Candidate.FailureKind = ovl_fail_enable_if;
6813     Candidate.DeductionFailure.Data = FailedAttr;
6814     return;
6815   }
6816 
6817   if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6818       !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6819     Candidate.Viable = false;
6820     Candidate.FailureKind = ovl_non_default_multiversion_function;
6821   }
6822 }
6823 
6824 /// Add a C++ member function template as a candidate to the candidate
6825 /// set, using template argument deduction to produce an appropriate member
6826 /// function template specialization.
6827 void Sema::AddMethodTemplateCandidate(
6828     FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6829     CXXRecordDecl *ActingContext,
6830     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6831     Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6832     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6833     bool PartialOverloading, OverloadCandidateParamOrder PO) {
6834   if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6835     return;
6836 
6837   // C++ [over.match.funcs]p7:
6838   //   In each case where a candidate is a function template, candidate
6839   //   function template specializations are generated using template argument
6840   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6841   //   candidate functions in the usual way.113) A given name can refer to one
6842   //   or more function templates and also to a set of overloaded non-template
6843   //   functions. In such a case, the candidate functions generated from each
6844   //   function template are combined with the set of non-template candidate
6845   //   functions.
6846   TemplateDeductionInfo Info(CandidateSet.getLocation());
6847   FunctionDecl *Specialization = nullptr;
6848   ConversionSequenceList Conversions;
6849   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6850           MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6851           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6852             return CheckNonDependentConversions(
6853                 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6854                 SuppressUserConversions, ActingContext, ObjectType,
6855                 ObjectClassification, PO);
6856           })) {
6857     OverloadCandidate &Candidate =
6858         CandidateSet.addCandidate(Conversions.size(), Conversions);
6859     Candidate.FoundDecl = FoundDecl;
6860     Candidate.Function = MethodTmpl->getTemplatedDecl();
6861     Candidate.Viable = false;
6862     Candidate.RewriteKind =
6863       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6864     Candidate.IsSurrogate = false;
6865     Candidate.IgnoreObjectArgument =
6866         cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6867         ObjectType.isNull();
6868     Candidate.ExplicitCallArguments = Args.size();
6869     if (Result == TDK_NonDependentConversionFailure)
6870       Candidate.FailureKind = ovl_fail_bad_conversion;
6871     else {
6872       Candidate.FailureKind = ovl_fail_bad_deduction;
6873       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6874                                                             Info);
6875     }
6876     return;
6877   }
6878 
6879   // Add the function template specialization produced by template argument
6880   // deduction as a candidate.
6881   assert(Specialization && "Missing member function template specialization?");
6882   assert(isa<CXXMethodDecl>(Specialization) &&
6883          "Specialization is not a member function?");
6884   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6885                      ActingContext, ObjectType, ObjectClassification, Args,
6886                      CandidateSet, SuppressUserConversions, PartialOverloading,
6887                      Conversions, PO);
6888 }
6889 
6890 /// Add a C++ function template specialization as a candidate
6891 /// in the candidate set, using template argument deduction to produce
6892 /// an appropriate function template specialization.
6893 void Sema::AddTemplateOverloadCandidate(
6894     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6895     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6896     OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6897     bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6898     OverloadCandidateParamOrder PO) {
6899   if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6900     return;
6901 
6902   // C++ [over.match.funcs]p7:
6903   //   In each case where a candidate is a function template, candidate
6904   //   function template specializations are generated using template argument
6905   //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
6906   //   candidate functions in the usual way.113) A given name can refer to one
6907   //   or more function templates and also to a set of overloaded non-template
6908   //   functions. In such a case, the candidate functions generated from each
6909   //   function template are combined with the set of non-template candidate
6910   //   functions.
6911   TemplateDeductionInfo Info(CandidateSet.getLocation());
6912   FunctionDecl *Specialization = nullptr;
6913   ConversionSequenceList Conversions;
6914   if (TemplateDeductionResult Result = DeduceTemplateArguments(
6915           FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6916           PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6917             return CheckNonDependentConversions(
6918                 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6919                 SuppressUserConversions, nullptr, QualType(), {}, PO);
6920           })) {
6921     OverloadCandidate &Candidate =
6922         CandidateSet.addCandidate(Conversions.size(), Conversions);
6923     Candidate.FoundDecl = FoundDecl;
6924     Candidate.Function = FunctionTemplate->getTemplatedDecl();
6925     Candidate.Viable = false;
6926     Candidate.RewriteKind =
6927       CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6928     Candidate.IsSurrogate = false;
6929     Candidate.IsADLCandidate = IsADLCandidate;
6930     // Ignore the object argument if there is one, since we don't have an object
6931     // type.
6932     Candidate.IgnoreObjectArgument =
6933         isa<CXXMethodDecl>(Candidate.Function) &&
6934         !isa<CXXConstructorDecl>(Candidate.Function);
6935     Candidate.ExplicitCallArguments = Args.size();
6936     if (Result == TDK_NonDependentConversionFailure)
6937       Candidate.FailureKind = ovl_fail_bad_conversion;
6938     else {
6939       Candidate.FailureKind = ovl_fail_bad_deduction;
6940       Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6941                                                             Info);
6942     }
6943     return;
6944   }
6945 
6946   // Add the function template specialization produced by template argument
6947   // deduction as a candidate.
6948   assert(Specialization && "Missing function template specialization?");
6949   AddOverloadCandidate(
6950       Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6951       PartialOverloading, AllowExplicit,
6952       /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
6953 }
6954 
6955 /// Check that implicit conversion sequences can be formed for each argument
6956 /// whose corresponding parameter has a non-dependent type, per DR1391's
6957 /// [temp.deduct.call]p10.
6958 bool Sema::CheckNonDependentConversions(
6959     FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6960     ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6961     ConversionSequenceList &Conversions, bool SuppressUserConversions,
6962     CXXRecordDecl *ActingContext, QualType ObjectType,
6963     Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
6964   // FIXME: The cases in which we allow explicit conversions for constructor
6965   // arguments never consider calling a constructor template. It's not clear
6966   // that is correct.
6967   const bool AllowExplicit = false;
6968 
6969   auto *FD = FunctionTemplate->getTemplatedDecl();
6970   auto *Method = dyn_cast<CXXMethodDecl>(FD);
6971   bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6972   unsigned ThisConversions = HasThisConversion ? 1 : 0;
6973 
6974   Conversions =
6975       CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6976 
6977   // Overload resolution is always an unevaluated context.
6978   EnterExpressionEvaluationContext Unevaluated(
6979       *this, Sema::ExpressionEvaluationContext::Unevaluated);
6980 
6981   // For a method call, check the 'this' conversion here too. DR1391 doesn't
6982   // require that, but this check should never result in a hard error, and
6983   // overload resolution is permitted to sidestep instantiations.
6984   if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6985       !ObjectType.isNull()) {
6986     unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6987     Conversions[ConvIdx] = TryObjectArgumentInitialization(
6988         *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6989         Method, ActingContext);
6990     if (Conversions[ConvIdx].isBad())
6991       return true;
6992   }
6993 
6994   for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6995        ++I) {
6996     QualType ParamType = ParamTypes[I];
6997     if (!ParamType->isDependentType()) {
6998       unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
6999                              ? 0
7000                              : (ThisConversions + I);
7001       Conversions[ConvIdx]
7002         = TryCopyInitialization(*this, Args[I], ParamType,
7003                                 SuppressUserConversions,
7004                                 /*InOverloadResolution=*/true,
7005                                 /*AllowObjCWritebackConversion=*/
7006                                   getLangOpts().ObjCAutoRefCount,
7007                                 AllowExplicit);
7008       if (Conversions[ConvIdx].isBad())
7009         return true;
7010     }
7011   }
7012 
7013   return false;
7014 }
7015 
7016 /// Determine whether this is an allowable conversion from the result
7017 /// of an explicit conversion operator to the expected type, per C++
7018 /// [over.match.conv]p1 and [over.match.ref]p1.
7019 ///
7020 /// \param ConvType The return type of the conversion function.
7021 ///
7022 /// \param ToType The type we are converting to.
7023 ///
7024 /// \param AllowObjCPointerConversion Allow a conversion from one
7025 /// Objective-C pointer to another.
7026 ///
7027 /// \returns true if the conversion is allowable, false otherwise.
7028 static bool isAllowableExplicitConversion(Sema &S,
7029                                           QualType ConvType, QualType ToType,
7030                                           bool AllowObjCPointerConversion) {
7031   QualType ToNonRefType = ToType.getNonReferenceType();
7032 
7033   // Easy case: the types are the same.
7034   if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7035     return true;
7036 
7037   // Allow qualification conversions.
7038   bool ObjCLifetimeConversion;
7039   if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7040                                   ObjCLifetimeConversion))
7041     return true;
7042 
7043   // If we're not allowed to consider Objective-C pointer conversions,
7044   // we're done.
7045   if (!AllowObjCPointerConversion)
7046     return false;
7047 
7048   // Is this an Objective-C pointer conversion?
7049   bool IncompatibleObjC = false;
7050   QualType ConvertedType;
7051   return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7052                                    IncompatibleObjC);
7053 }
7054 
7055 /// AddConversionCandidate - Add a C++ conversion function as a
7056 /// candidate in the candidate set (C++ [over.match.conv],
7057 /// C++ [over.match.copy]). From is the expression we're converting from,
7058 /// and ToType is the type that we're eventually trying to convert to
7059 /// (which may or may not be the same type as the type that the
7060 /// conversion function produces).
7061 void Sema::AddConversionCandidate(
7062     CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7063     CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7064     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7065     bool AllowExplicit, bool AllowResultConversion) {
7066   assert(!Conversion->getDescribedFunctionTemplate() &&
7067          "Conversion function templates use AddTemplateConversionCandidate");
7068   QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7069   if (!CandidateSet.isNewCandidate(Conversion))
7070     return;
7071 
7072   // If the conversion function has an undeduced return type, trigger its
7073   // deduction now.
7074   if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7075     if (DeduceReturnType(Conversion, From->getExprLoc()))
7076       return;
7077     ConvType = Conversion->getConversionType().getNonReferenceType();
7078   }
7079 
7080   // If we don't allow any conversion of the result type, ignore conversion
7081   // functions that don't convert to exactly (possibly cv-qualified) T.
7082   if (!AllowResultConversion &&
7083       !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7084     return;
7085 
7086   // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7087   // operator is only a candidate if its return type is the target type or
7088   // can be converted to the target type with a qualification conversion.
7089   if (Conversion->isExplicit() &&
7090       !isAllowableExplicitConversion(*this, ConvType, ToType,
7091                                      AllowObjCConversionOnExplicit))
7092     return;
7093 
7094   // Overload resolution is always an unevaluated context.
7095   EnterExpressionEvaluationContext Unevaluated(
7096       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7097 
7098   // Add this candidate
7099   OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7100   Candidate.FoundDecl = FoundDecl;
7101   Candidate.Function = Conversion;
7102   Candidate.IsSurrogate = false;
7103   Candidate.IgnoreObjectArgument = false;
7104   Candidate.FinalConversion.setAsIdentityConversion();
7105   Candidate.FinalConversion.setFromType(ConvType);
7106   Candidate.FinalConversion.setAllToTypes(ToType);
7107   Candidate.Viable = true;
7108   Candidate.ExplicitCallArguments = 1;
7109 
7110   // C++ [over.match.funcs]p4:
7111   //   For conversion functions, the function is considered to be a member of
7112   //   the class of the implicit implied object argument for the purpose of
7113   //   defining the type of the implicit object parameter.
7114   //
7115   // Determine the implicit conversion sequence for the implicit
7116   // object parameter.
7117   QualType ImplicitParamType = From->getType();
7118   if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7119     ImplicitParamType = FromPtrType->getPointeeType();
7120   CXXRecordDecl *ConversionContext
7121     = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7122 
7123   Candidate.Conversions[0] = TryObjectArgumentInitialization(
7124       *this, CandidateSet.getLocation(), From->getType(),
7125       From->Classify(Context), Conversion, ConversionContext);
7126 
7127   if (Candidate.Conversions[0].isBad()) {
7128     Candidate.Viable = false;
7129     Candidate.FailureKind = ovl_fail_bad_conversion;
7130     return;
7131   }
7132 
7133   // We won't go through a user-defined type conversion function to convert a
7134   // derived to base as such conversions are given Conversion Rank. They only
7135   // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7136   QualType FromCanon
7137     = Context.getCanonicalType(From->getType().getUnqualifiedType());
7138   QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7139   if (FromCanon == ToCanon ||
7140       IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7141     Candidate.Viable = false;
7142     Candidate.FailureKind = ovl_fail_trivial_conversion;
7143     return;
7144   }
7145 
7146   // To determine what the conversion from the result of calling the
7147   // conversion function to the type we're eventually trying to
7148   // convert to (ToType), we need to synthesize a call to the
7149   // conversion function and attempt copy initialization from it. This
7150   // makes sure that we get the right semantics with respect to
7151   // lvalues/rvalues and the type. Fortunately, we can allocate this
7152   // call on the stack and we don't need its arguments to be
7153   // well-formed.
7154   DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7155                             VK_LValue, From->getBeginLoc());
7156   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7157                                 Context.getPointerType(Conversion->getType()),
7158                                 CK_FunctionToPointerDecay,
7159                                 &ConversionRef, VK_RValue);
7160 
7161   QualType ConversionType = Conversion->getConversionType();
7162   if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7163     Candidate.Viable = false;
7164     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7165     return;
7166   }
7167 
7168   ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7169 
7170   // Note that it is safe to allocate CallExpr on the stack here because
7171   // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7172   // allocator).
7173   QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7174 
7175   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7176   CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7177       Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7178 
7179   ImplicitConversionSequence ICS =
7180       TryCopyInitialization(*this, TheTemporaryCall, ToType,
7181                             /*SuppressUserConversions=*/true,
7182                             /*InOverloadResolution=*/false,
7183                             /*AllowObjCWritebackConversion=*/false);
7184 
7185   switch (ICS.getKind()) {
7186   case ImplicitConversionSequence::StandardConversion:
7187     Candidate.FinalConversion = ICS.Standard;
7188 
7189     // C++ [over.ics.user]p3:
7190     //   If the user-defined conversion is specified by a specialization of a
7191     //   conversion function template, the second standard conversion sequence
7192     //   shall have exact match rank.
7193     if (Conversion->getPrimaryTemplate() &&
7194         GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7195       Candidate.Viable = false;
7196       Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7197       return;
7198     }
7199 
7200     // C++0x [dcl.init.ref]p5:
7201     //    In the second case, if the reference is an rvalue reference and
7202     //    the second standard conversion sequence of the user-defined
7203     //    conversion sequence includes an lvalue-to-rvalue conversion, the
7204     //    program is ill-formed.
7205     if (ToType->isRValueReferenceType() &&
7206         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7207       Candidate.Viable = false;
7208       Candidate.FailureKind = ovl_fail_bad_final_conversion;
7209       return;
7210     }
7211     break;
7212 
7213   case ImplicitConversionSequence::BadConversion:
7214     Candidate.Viable = false;
7215     Candidate.FailureKind = ovl_fail_bad_final_conversion;
7216     return;
7217 
7218   default:
7219     llvm_unreachable(
7220            "Can only end up with a standard conversion sequence or failure");
7221   }
7222 
7223   if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7224                             ExplicitSpecKind::ResolvedFalse) {
7225     Candidate.Viable = false;
7226     Candidate.FailureKind = ovl_fail_explicit_resolved;
7227     return;
7228   }
7229 
7230   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7231     Candidate.Viable = false;
7232     Candidate.FailureKind = ovl_fail_enable_if;
7233     Candidate.DeductionFailure.Data = FailedAttr;
7234     return;
7235   }
7236 
7237   if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7238       !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7239     Candidate.Viable = false;
7240     Candidate.FailureKind = ovl_non_default_multiversion_function;
7241   }
7242 }
7243 
7244 /// Adds a conversion function template specialization
7245 /// candidate to the overload set, using template argument deduction
7246 /// to deduce the template arguments of the conversion function
7247 /// template from the type that we are converting to (C++
7248 /// [temp.deduct.conv]).
7249 void Sema::AddTemplateConversionCandidate(
7250     FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7251     CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7252     OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7253     bool AllowExplicit, bool AllowResultConversion) {
7254   assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7255          "Only conversion function templates permitted here");
7256 
7257   if (!CandidateSet.isNewCandidate(FunctionTemplate))
7258     return;
7259 
7260   TemplateDeductionInfo Info(CandidateSet.getLocation());
7261   CXXConversionDecl *Specialization = nullptr;
7262   if (TemplateDeductionResult Result
7263         = DeduceTemplateArguments(FunctionTemplate, ToType,
7264                                   Specialization, Info)) {
7265     OverloadCandidate &Candidate = CandidateSet.addCandidate();
7266     Candidate.FoundDecl = FoundDecl;
7267     Candidate.Function = FunctionTemplate->getTemplatedDecl();
7268     Candidate.Viable = false;
7269     Candidate.FailureKind = ovl_fail_bad_deduction;
7270     Candidate.IsSurrogate = false;
7271     Candidate.IgnoreObjectArgument = false;
7272     Candidate.ExplicitCallArguments = 1;
7273     Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7274                                                           Info);
7275     return;
7276   }
7277 
7278   // Add the conversion function template specialization produced by
7279   // template argument deduction as a candidate.
7280   assert(Specialization && "Missing function template specialization?");
7281   AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7282                          CandidateSet, AllowObjCConversionOnExplicit,
7283                          AllowExplicit, AllowResultConversion);
7284 }
7285 
7286 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7287 /// converts the given @c Object to a function pointer via the
7288 /// conversion function @c Conversion, and then attempts to call it
7289 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7290 /// the type of function that we'll eventually be calling.
7291 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7292                                  DeclAccessPair FoundDecl,
7293                                  CXXRecordDecl *ActingContext,
7294                                  const FunctionProtoType *Proto,
7295                                  Expr *Object,
7296                                  ArrayRef<Expr *> Args,
7297                                  OverloadCandidateSet& CandidateSet) {
7298   if (!CandidateSet.isNewCandidate(Conversion))
7299     return;
7300 
7301   // Overload resolution is always an unevaluated context.
7302   EnterExpressionEvaluationContext Unevaluated(
7303       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7304 
7305   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7306   Candidate.FoundDecl = FoundDecl;
7307   Candidate.Function = nullptr;
7308   Candidate.Surrogate = Conversion;
7309   Candidate.Viable = true;
7310   Candidate.IsSurrogate = true;
7311   Candidate.IgnoreObjectArgument = false;
7312   Candidate.ExplicitCallArguments = Args.size();
7313 
7314   // Determine the implicit conversion sequence for the implicit
7315   // object parameter.
7316   ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7317       *this, CandidateSet.getLocation(), Object->getType(),
7318       Object->Classify(Context), Conversion, ActingContext);
7319   if (ObjectInit.isBad()) {
7320     Candidate.Viable = false;
7321     Candidate.FailureKind = ovl_fail_bad_conversion;
7322     Candidate.Conversions[0] = ObjectInit;
7323     return;
7324   }
7325 
7326   // The first conversion is actually a user-defined conversion whose
7327   // first conversion is ObjectInit's standard conversion (which is
7328   // effectively a reference binding). Record it as such.
7329   Candidate.Conversions[0].setUserDefined();
7330   Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7331   Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7332   Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7333   Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7334   Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7335   Candidate.Conversions[0].UserDefined.After
7336     = Candidate.Conversions[0].UserDefined.Before;
7337   Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7338 
7339   // Find the
7340   unsigned NumParams = Proto->getNumParams();
7341 
7342   // (C++ 13.3.2p2): A candidate function having fewer than m
7343   // parameters is viable only if it has an ellipsis in its parameter
7344   // list (8.3.5).
7345   if (Args.size() > NumParams && !Proto->isVariadic()) {
7346     Candidate.Viable = false;
7347     Candidate.FailureKind = ovl_fail_too_many_arguments;
7348     return;
7349   }
7350 
7351   // Function types don't have any default arguments, so just check if
7352   // we have enough arguments.
7353   if (Args.size() < NumParams) {
7354     // Not enough arguments.
7355     Candidate.Viable = false;
7356     Candidate.FailureKind = ovl_fail_too_few_arguments;
7357     return;
7358   }
7359 
7360   // Determine the implicit conversion sequences for each of the
7361   // arguments.
7362   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7363     if (ArgIdx < NumParams) {
7364       // (C++ 13.3.2p3): for F to be a viable function, there shall
7365       // exist for each argument an implicit conversion sequence
7366       // (13.3.3.1) that converts that argument to the corresponding
7367       // parameter of F.
7368       QualType ParamType = Proto->getParamType(ArgIdx);
7369       Candidate.Conversions[ArgIdx + 1]
7370         = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7371                                 /*SuppressUserConversions=*/false,
7372                                 /*InOverloadResolution=*/false,
7373                                 /*AllowObjCWritebackConversion=*/
7374                                   getLangOpts().ObjCAutoRefCount);
7375       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7376         Candidate.Viable = false;
7377         Candidate.FailureKind = ovl_fail_bad_conversion;
7378         return;
7379       }
7380     } else {
7381       // (C++ 13.3.2p2): For the purposes of overload resolution, any
7382       // argument for which there is no corresponding parameter is
7383       // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7384       Candidate.Conversions[ArgIdx + 1].setEllipsis();
7385     }
7386   }
7387 
7388   if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7389     Candidate.Viable = false;
7390     Candidate.FailureKind = ovl_fail_enable_if;
7391     Candidate.DeductionFailure.Data = FailedAttr;
7392     return;
7393   }
7394 }
7395 
7396 /// Add all of the non-member operator function declarations in the given
7397 /// function set to the overload candidate set.
7398 void Sema::AddNonMemberOperatorCandidates(
7399     const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7400     OverloadCandidateSet &CandidateSet,
7401     TemplateArgumentListInfo *ExplicitTemplateArgs) {
7402   for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7403     NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7404     ArrayRef<Expr *> FunctionArgs = Args;
7405 
7406     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7407     FunctionDecl *FD =
7408         FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7409 
7410     // Don't consider rewritten functions if we're not rewriting.
7411     if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7412       continue;
7413 
7414     assert(!isa<CXXMethodDecl>(FD) &&
7415            "unqualified operator lookup found a member function");
7416 
7417     if (FunTmpl) {
7418       AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7419                                    FunctionArgs, CandidateSet);
7420       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7421         AddTemplateOverloadCandidate(
7422             FunTmpl, F.getPair(), ExplicitTemplateArgs,
7423             {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7424             true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7425     } else {
7426       if (ExplicitTemplateArgs)
7427         continue;
7428       AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7429       if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7430         AddOverloadCandidate(FD, F.getPair(),
7431                              {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7432                              false, false, true, false, ADLCallKind::NotADL,
7433                              None, OverloadCandidateParamOrder::Reversed);
7434     }
7435   }
7436 }
7437 
7438 /// Add overload candidates for overloaded operators that are
7439 /// member functions.
7440 ///
7441 /// Add the overloaded operator candidates that are member functions
7442 /// for the operator Op that was used in an operator expression such
7443 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7444 /// CandidateSet will store the added overload candidates. (C++
7445 /// [over.match.oper]).
7446 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7447                                        SourceLocation OpLoc,
7448                                        ArrayRef<Expr *> Args,
7449                                        OverloadCandidateSet &CandidateSet,
7450                                        OverloadCandidateParamOrder PO) {
7451   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7452 
7453   // C++ [over.match.oper]p3:
7454   //   For a unary operator @ with an operand of a type whose
7455   //   cv-unqualified version is T1, and for a binary operator @ with
7456   //   a left operand of a type whose cv-unqualified version is T1 and
7457   //   a right operand of a type whose cv-unqualified version is T2,
7458   //   three sets of candidate functions, designated member
7459   //   candidates, non-member candidates and built-in candidates, are
7460   //   constructed as follows:
7461   QualType T1 = Args[0]->getType();
7462 
7463   //     -- If T1 is a complete class type or a class currently being
7464   //        defined, the set of member candidates is the result of the
7465   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7466   //        the set of member candidates is empty.
7467   if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7468     // Complete the type if it can be completed.
7469     if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7470       return;
7471     // If the type is neither complete nor being defined, bail out now.
7472     if (!T1Rec->getDecl()->getDefinition())
7473       return;
7474 
7475     LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7476     LookupQualifiedName(Operators, T1Rec->getDecl());
7477     Operators.suppressDiagnostics();
7478 
7479     for (LookupResult::iterator Oper = Operators.begin(),
7480                              OperEnd = Operators.end();
7481          Oper != OperEnd;
7482          ++Oper)
7483       AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7484                          Args[0]->Classify(Context), Args.slice(1),
7485                          CandidateSet, /*SuppressUserConversion=*/false, PO);
7486   }
7487 }
7488 
7489 /// AddBuiltinCandidate - Add a candidate for a built-in
7490 /// operator. ResultTy and ParamTys are the result and parameter types
7491 /// of the built-in candidate, respectively. Args and NumArgs are the
7492 /// arguments being passed to the candidate. IsAssignmentOperator
7493 /// should be true when this built-in candidate is an assignment
7494 /// operator. NumContextualBoolArguments is the number of arguments
7495 /// (at the beginning of the argument list) that will be contextually
7496 /// converted to bool.
7497 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7498                                OverloadCandidateSet& CandidateSet,
7499                                bool IsAssignmentOperator,
7500                                unsigned NumContextualBoolArguments) {
7501   // Overload resolution is always an unevaluated context.
7502   EnterExpressionEvaluationContext Unevaluated(
7503       *this, Sema::ExpressionEvaluationContext::Unevaluated);
7504 
7505   // Add this candidate
7506   OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7507   Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7508   Candidate.Function = nullptr;
7509   Candidate.IsSurrogate = false;
7510   Candidate.IgnoreObjectArgument = false;
7511   std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7512 
7513   // Determine the implicit conversion sequences for each of the
7514   // arguments.
7515   Candidate.Viable = true;
7516   Candidate.ExplicitCallArguments = Args.size();
7517   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7518     // C++ [over.match.oper]p4:
7519     //   For the built-in assignment operators, conversions of the
7520     //   left operand are restricted as follows:
7521     //     -- no temporaries are introduced to hold the left operand, and
7522     //     -- no user-defined conversions are applied to the left
7523     //        operand to achieve a type match with the left-most
7524     //        parameter of a built-in candidate.
7525     //
7526     // We block these conversions by turning off user-defined
7527     // conversions, since that is the only way that initialization of
7528     // a reference to a non-class type can occur from something that
7529     // is not of the same type.
7530     if (ArgIdx < NumContextualBoolArguments) {
7531       assert(ParamTys[ArgIdx] == Context.BoolTy &&
7532              "Contextual conversion to bool requires bool type");
7533       Candidate.Conversions[ArgIdx]
7534         = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7535     } else {
7536       Candidate.Conversions[ArgIdx]
7537         = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7538                                 ArgIdx == 0 && IsAssignmentOperator,
7539                                 /*InOverloadResolution=*/false,
7540                                 /*AllowObjCWritebackConversion=*/
7541                                   getLangOpts().ObjCAutoRefCount);
7542     }
7543     if (Candidate.Conversions[ArgIdx].isBad()) {
7544       Candidate.Viable = false;
7545       Candidate.FailureKind = ovl_fail_bad_conversion;
7546       break;
7547     }
7548   }
7549 }
7550 
7551 namespace {
7552 
7553 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7554 /// candidate operator functions for built-in operators (C++
7555 /// [over.built]). The types are separated into pointer types and
7556 /// enumeration types.
7557 class BuiltinCandidateTypeSet  {
7558   /// TypeSet - A set of types.
7559   typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7560                           llvm::SmallPtrSet<QualType, 8>> TypeSet;
7561 
7562   /// PointerTypes - The set of pointer types that will be used in the
7563   /// built-in candidates.
7564   TypeSet PointerTypes;
7565 
7566   /// MemberPointerTypes - The set of member pointer types that will be
7567   /// used in the built-in candidates.
7568   TypeSet MemberPointerTypes;
7569 
7570   /// EnumerationTypes - The set of enumeration types that will be
7571   /// used in the built-in candidates.
7572   TypeSet EnumerationTypes;
7573 
7574   /// The set of vector types that will be used in the built-in
7575   /// candidates.
7576   TypeSet VectorTypes;
7577 
7578   /// A flag indicating non-record types are viable candidates
7579   bool HasNonRecordTypes;
7580 
7581   /// A flag indicating whether either arithmetic or enumeration types
7582   /// were present in the candidate set.
7583   bool HasArithmeticOrEnumeralTypes;
7584 
7585   /// A flag indicating whether the nullptr type was present in the
7586   /// candidate set.
7587   bool HasNullPtrType;
7588 
7589   /// Sema - The semantic analysis instance where we are building the
7590   /// candidate type set.
7591   Sema &SemaRef;
7592 
7593   /// Context - The AST context in which we will build the type sets.
7594   ASTContext &Context;
7595 
7596   bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7597                                                const Qualifiers &VisibleQuals);
7598   bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7599 
7600 public:
7601   /// iterator - Iterates through the types that are part of the set.
7602   typedef TypeSet::iterator iterator;
7603 
7604   BuiltinCandidateTypeSet(Sema &SemaRef)
7605     : HasNonRecordTypes(false),
7606       HasArithmeticOrEnumeralTypes(false),
7607       HasNullPtrType(false),
7608       SemaRef(SemaRef),
7609       Context(SemaRef.Context) { }
7610 
7611   void AddTypesConvertedFrom(QualType Ty,
7612                              SourceLocation Loc,
7613                              bool AllowUserConversions,
7614                              bool AllowExplicitConversions,
7615                              const Qualifiers &VisibleTypeConversionsQuals);
7616 
7617   /// pointer_begin - First pointer type found;
7618   iterator pointer_begin() { return PointerTypes.begin(); }
7619 
7620   /// pointer_end - Past the last pointer type found;
7621   iterator pointer_end() { return PointerTypes.end(); }
7622 
7623   /// member_pointer_begin - First member pointer type found;
7624   iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7625 
7626   /// member_pointer_end - Past the last member pointer type found;
7627   iterator member_pointer_end() { return MemberPointerTypes.end(); }
7628 
7629   /// enumeration_begin - First enumeration type found;
7630   iterator enumeration_begin() { return EnumerationTypes.begin(); }
7631 
7632   /// enumeration_end - Past the last enumeration type found;
7633   iterator enumeration_end() { return EnumerationTypes.end(); }
7634 
7635   iterator vector_begin() { return VectorTypes.begin(); }
7636   iterator vector_end() { return VectorTypes.end(); }
7637 
7638   bool hasNonRecordTypes() { return HasNonRecordTypes; }
7639   bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7640   bool hasNullPtrType() const { return HasNullPtrType; }
7641 };
7642 
7643 } // end anonymous namespace
7644 
7645 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7646 /// the set of pointer types along with any more-qualified variants of
7647 /// that type. For example, if @p Ty is "int const *", this routine
7648 /// will add "int const *", "int const volatile *", "int const
7649 /// restrict *", and "int const volatile restrict *" to the set of
7650 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7651 /// false otherwise.
7652 ///
7653 /// FIXME: what to do about extended qualifiers?
7654 bool
7655 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7656                                              const Qualifiers &VisibleQuals) {
7657 
7658   // Insert this type.
7659   if (!PointerTypes.insert(Ty))
7660     return false;
7661 
7662   QualType PointeeTy;
7663   const PointerType *PointerTy = Ty->getAs<PointerType>();
7664   bool buildObjCPtr = false;
7665   if (!PointerTy) {
7666     const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7667     PointeeTy = PTy->getPointeeType();
7668     buildObjCPtr = true;
7669   } else {
7670     PointeeTy = PointerTy->getPointeeType();
7671   }
7672 
7673   // Don't add qualified variants of arrays. For one, they're not allowed
7674   // (the qualifier would sink to the element type), and for another, the
7675   // only overload situation where it matters is subscript or pointer +- int,
7676   // and those shouldn't have qualifier variants anyway.
7677   if (PointeeTy->isArrayType())
7678     return true;
7679 
7680   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7681   bool hasVolatile = VisibleQuals.hasVolatile();
7682   bool hasRestrict = VisibleQuals.hasRestrict();
7683 
7684   // Iterate through all strict supersets of BaseCVR.
7685   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7686     if ((CVR | BaseCVR) != CVR) continue;
7687     // Skip over volatile if no volatile found anywhere in the types.
7688     if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7689 
7690     // Skip over restrict if no restrict found anywhere in the types, or if
7691     // the type cannot be restrict-qualified.
7692     if ((CVR & Qualifiers::Restrict) &&
7693         (!hasRestrict ||
7694          (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7695       continue;
7696 
7697     // Build qualified pointee type.
7698     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7699 
7700     // Build qualified pointer type.
7701     QualType QPointerTy;
7702     if (!buildObjCPtr)
7703       QPointerTy = Context.getPointerType(QPointeeTy);
7704     else
7705       QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7706 
7707     // Insert qualified pointer type.
7708     PointerTypes.insert(QPointerTy);
7709   }
7710 
7711   return true;
7712 }
7713 
7714 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7715 /// to the set of pointer types along with any more-qualified variants of
7716 /// that type. For example, if @p Ty is "int const *", this routine
7717 /// will add "int const *", "int const volatile *", "int const
7718 /// restrict *", and "int const volatile restrict *" to the set of
7719 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7720 /// false otherwise.
7721 ///
7722 /// FIXME: what to do about extended qualifiers?
7723 bool
7724 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7725     QualType Ty) {
7726   // Insert this type.
7727   if (!MemberPointerTypes.insert(Ty))
7728     return false;
7729 
7730   const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7731   assert(PointerTy && "type was not a member pointer type!");
7732 
7733   QualType PointeeTy = PointerTy->getPointeeType();
7734   // Don't add qualified variants of arrays. For one, they're not allowed
7735   // (the qualifier would sink to the element type), and for another, the
7736   // only overload situation where it matters is subscript or pointer +- int,
7737   // and those shouldn't have qualifier variants anyway.
7738   if (PointeeTy->isArrayType())
7739     return true;
7740   const Type *ClassTy = PointerTy->getClass();
7741 
7742   // Iterate through all strict supersets of the pointee type's CVR
7743   // qualifiers.
7744   unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7745   for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7746     if ((CVR | BaseCVR) != CVR) continue;
7747 
7748     QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7749     MemberPointerTypes.insert(
7750       Context.getMemberPointerType(QPointeeTy, ClassTy));
7751   }
7752 
7753   return true;
7754 }
7755 
7756 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7757 /// Ty can be implicit converted to the given set of @p Types. We're
7758 /// primarily interested in pointer types and enumeration types. We also
7759 /// take member pointer types, for the conditional operator.
7760 /// AllowUserConversions is true if we should look at the conversion
7761 /// functions of a class type, and AllowExplicitConversions if we
7762 /// should also include the explicit conversion functions of a class
7763 /// type.
7764 void
7765 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7766                                                SourceLocation Loc,
7767                                                bool AllowUserConversions,
7768                                                bool AllowExplicitConversions,
7769                                                const Qualifiers &VisibleQuals) {
7770   // Only deal with canonical types.
7771   Ty = Context.getCanonicalType(Ty);
7772 
7773   // Look through reference types; they aren't part of the type of an
7774   // expression for the purposes of conversions.
7775   if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7776     Ty = RefTy->getPointeeType();
7777 
7778   // If we're dealing with an array type, decay to the pointer.
7779   if (Ty->isArrayType())
7780     Ty = SemaRef.Context.getArrayDecayedType(Ty);
7781 
7782   // Otherwise, we don't care about qualifiers on the type.
7783   Ty = Ty.getLocalUnqualifiedType();
7784 
7785   // Flag if we ever add a non-record type.
7786   const RecordType *TyRec = Ty->getAs<RecordType>();
7787   HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7788 
7789   // Flag if we encounter an arithmetic type.
7790   HasArithmeticOrEnumeralTypes =
7791     HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7792 
7793   if (Ty->isObjCIdType() || Ty->isObjCClassType())
7794     PointerTypes.insert(Ty);
7795   else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7796     // Insert our type, and its more-qualified variants, into the set
7797     // of types.
7798     if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7799       return;
7800   } else if (Ty->isMemberPointerType()) {
7801     // Member pointers are far easier, since the pointee can't be converted.
7802     if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7803       return;
7804   } else if (Ty->isEnumeralType()) {
7805     HasArithmeticOrEnumeralTypes = true;
7806     EnumerationTypes.insert(Ty);
7807   } else if (Ty->isVectorType()) {
7808     // We treat vector types as arithmetic types in many contexts as an
7809     // extension.
7810     HasArithmeticOrEnumeralTypes = true;
7811     VectorTypes.insert(Ty);
7812   } else if (Ty->isNullPtrType()) {
7813     HasNullPtrType = true;
7814   } else if (AllowUserConversions && TyRec) {
7815     // No conversion functions in incomplete types.
7816     if (!SemaRef.isCompleteType(Loc, Ty))
7817       return;
7818 
7819     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7820     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7821       if (isa<UsingShadowDecl>(D))
7822         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7823 
7824       // Skip conversion function templates; they don't tell us anything
7825       // about which builtin types we can convert to.
7826       if (isa<FunctionTemplateDecl>(D))
7827         continue;
7828 
7829       CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7830       if (AllowExplicitConversions || !Conv->isExplicit()) {
7831         AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7832                               VisibleQuals);
7833       }
7834     }
7835   }
7836 }
7837 /// Helper function for adjusting address spaces for the pointer or reference
7838 /// operands of builtin operators depending on the argument.
7839 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7840                                                         Expr *Arg) {
7841   return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7842 }
7843 
7844 /// Helper function for AddBuiltinOperatorCandidates() that adds
7845 /// the volatile- and non-volatile-qualified assignment operators for the
7846 /// given type to the candidate set.
7847 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7848                                                    QualType T,
7849                                                    ArrayRef<Expr *> Args,
7850                                     OverloadCandidateSet &CandidateSet) {
7851   QualType ParamTypes[2];
7852 
7853   // T& operator=(T&, T)
7854   ParamTypes[0] = S.Context.getLValueReferenceType(
7855       AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7856   ParamTypes[1] = T;
7857   S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7858                         /*IsAssignmentOperator=*/true);
7859 
7860   if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7861     // volatile T& operator=(volatile T&, T)
7862     ParamTypes[0] = S.Context.getLValueReferenceType(
7863         AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7864                                                 Args[0]));
7865     ParamTypes[1] = T;
7866     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7867                           /*IsAssignmentOperator=*/true);
7868   }
7869 }
7870 
7871 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7872 /// if any, found in visible type conversion functions found in ArgExpr's type.
7873 static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7874     Qualifiers VRQuals;
7875     const RecordType *TyRec;
7876     if (const MemberPointerType *RHSMPType =
7877         ArgExpr->getType()->getAs<MemberPointerType>())
7878       TyRec = RHSMPType->getClass()->getAs<RecordType>();
7879     else
7880       TyRec = ArgExpr->getType()->getAs<RecordType>();
7881     if (!TyRec) {
7882       // Just to be safe, assume the worst case.
7883       VRQuals.addVolatile();
7884       VRQuals.addRestrict();
7885       return VRQuals;
7886     }
7887 
7888     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7889     if (!ClassDecl->hasDefinition())
7890       return VRQuals;
7891 
7892     for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7893       if (isa<UsingShadowDecl>(D))
7894         D = cast<UsingShadowDecl>(D)->getTargetDecl();
7895       if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7896         QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7897         if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7898           CanTy = ResTypeRef->getPointeeType();
7899         // Need to go down the pointer/mempointer chain and add qualifiers
7900         // as see them.
7901         bool done = false;
7902         while (!done) {
7903           if (CanTy.isRestrictQualified())
7904             VRQuals.addRestrict();
7905           if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7906             CanTy = ResTypePtr->getPointeeType();
7907           else if (const MemberPointerType *ResTypeMPtr =
7908                 CanTy->getAs<MemberPointerType>())
7909             CanTy = ResTypeMPtr->getPointeeType();
7910           else
7911             done = true;
7912           if (CanTy.isVolatileQualified())
7913             VRQuals.addVolatile();
7914           if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7915             return VRQuals;
7916         }
7917       }
7918     }
7919     return VRQuals;
7920 }
7921 
7922 namespace {
7923 
7924 /// Helper class to manage the addition of builtin operator overload
7925 /// candidates. It provides shared state and utility methods used throughout
7926 /// the process, as well as a helper method to add each group of builtin
7927 /// operator overloads from the standard to a candidate set.
7928 class BuiltinOperatorOverloadBuilder {
7929   // Common instance state available to all overload candidate addition methods.
7930   Sema &S;
7931   ArrayRef<Expr *> Args;
7932   Qualifiers VisibleTypeConversionsQuals;
7933   bool HasArithmeticOrEnumeralCandidateType;
7934   SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7935   OverloadCandidateSet &CandidateSet;
7936 
7937   static constexpr int ArithmeticTypesCap = 24;
7938   SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7939 
7940   // Define some indices used to iterate over the arithmetic types in
7941   // ArithmeticTypes.  The "promoted arithmetic types" are the arithmetic
7942   // types are that preserved by promotion (C++ [over.built]p2).
7943   unsigned FirstIntegralType,
7944            LastIntegralType;
7945   unsigned FirstPromotedIntegralType,
7946            LastPromotedIntegralType;
7947   unsigned FirstPromotedArithmeticType,
7948            LastPromotedArithmeticType;
7949   unsigned NumArithmeticTypes;
7950 
7951   void InitArithmeticTypes() {
7952     // Start of promoted types.
7953     FirstPromotedArithmeticType = 0;
7954     ArithmeticTypes.push_back(S.Context.FloatTy);
7955     ArithmeticTypes.push_back(S.Context.DoubleTy);
7956     ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7957     if (S.Context.getTargetInfo().hasFloat128Type())
7958       ArithmeticTypes.push_back(S.Context.Float128Ty);
7959 
7960     // Start of integral types.
7961     FirstIntegralType = ArithmeticTypes.size();
7962     FirstPromotedIntegralType = ArithmeticTypes.size();
7963     ArithmeticTypes.push_back(S.Context.IntTy);
7964     ArithmeticTypes.push_back(S.Context.LongTy);
7965     ArithmeticTypes.push_back(S.Context.LongLongTy);
7966     if (S.Context.getTargetInfo().hasInt128Type())
7967       ArithmeticTypes.push_back(S.Context.Int128Ty);
7968     ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7969     ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7970     ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7971     if (S.Context.getTargetInfo().hasInt128Type())
7972       ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7973     LastPromotedIntegralType = ArithmeticTypes.size();
7974     LastPromotedArithmeticType = ArithmeticTypes.size();
7975     // End of promoted types.
7976 
7977     ArithmeticTypes.push_back(S.Context.BoolTy);
7978     ArithmeticTypes.push_back(S.Context.CharTy);
7979     ArithmeticTypes.push_back(S.Context.WCharTy);
7980     if (S.Context.getLangOpts().Char8)
7981       ArithmeticTypes.push_back(S.Context.Char8Ty);
7982     ArithmeticTypes.push_back(S.Context.Char16Ty);
7983     ArithmeticTypes.push_back(S.Context.Char32Ty);
7984     ArithmeticTypes.push_back(S.Context.SignedCharTy);
7985     ArithmeticTypes.push_back(S.Context.ShortTy);
7986     ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7987     ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7988     LastIntegralType = ArithmeticTypes.size();
7989     NumArithmeticTypes = ArithmeticTypes.size();
7990     // End of integral types.
7991     // FIXME: What about complex? What about half?
7992 
7993     assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7994            "Enough inline storage for all arithmetic types.");
7995   }
7996 
7997   /// Helper method to factor out the common pattern of adding overloads
7998   /// for '++' and '--' builtin operators.
7999   void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8000                                            bool HasVolatile,
8001                                            bool HasRestrict) {
8002     QualType ParamTypes[2] = {
8003       S.Context.getLValueReferenceType(CandidateTy),
8004       S.Context.IntTy
8005     };
8006 
8007     // Non-volatile version.
8008     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8009 
8010     // Use a heuristic to reduce number of builtin candidates in the set:
8011     // add volatile version only if there are conversions to a volatile type.
8012     if (HasVolatile) {
8013       ParamTypes[0] =
8014         S.Context.getLValueReferenceType(
8015           S.Context.getVolatileType(CandidateTy));
8016       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8017     }
8018 
8019     // Add restrict version only if there are conversions to a restrict type
8020     // and our candidate type is a non-restrict-qualified pointer.
8021     if (HasRestrict && CandidateTy->isAnyPointerType() &&
8022         !CandidateTy.isRestrictQualified()) {
8023       ParamTypes[0]
8024         = S.Context.getLValueReferenceType(
8025             S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8026       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8027 
8028       if (HasVolatile) {
8029         ParamTypes[0]
8030           = S.Context.getLValueReferenceType(
8031               S.Context.getCVRQualifiedType(CandidateTy,
8032                                             (Qualifiers::Volatile |
8033                                              Qualifiers::Restrict)));
8034         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8035       }
8036     }
8037 
8038   }
8039 
8040 public:
8041   BuiltinOperatorOverloadBuilder(
8042     Sema &S, ArrayRef<Expr *> Args,
8043     Qualifiers VisibleTypeConversionsQuals,
8044     bool HasArithmeticOrEnumeralCandidateType,
8045     SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8046     OverloadCandidateSet &CandidateSet)
8047     : S(S), Args(Args),
8048       VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8049       HasArithmeticOrEnumeralCandidateType(
8050         HasArithmeticOrEnumeralCandidateType),
8051       CandidateTypes(CandidateTypes),
8052       CandidateSet(CandidateSet) {
8053 
8054     InitArithmeticTypes();
8055   }
8056 
8057   // Increment is deprecated for bool since C++17.
8058   //
8059   // C++ [over.built]p3:
8060   //
8061   //   For every pair (T, VQ), where T is an arithmetic type other
8062   //   than bool, and VQ is either volatile or empty, there exist
8063   //   candidate operator functions of the form
8064   //
8065   //       VQ T&      operator++(VQ T&);
8066   //       T          operator++(VQ T&, int);
8067   //
8068   // C++ [over.built]p4:
8069   //
8070   //   For every pair (T, VQ), where T is an arithmetic type other
8071   //   than bool, and VQ is either volatile or empty, there exist
8072   //   candidate operator functions of the form
8073   //
8074   //       VQ T&      operator--(VQ T&);
8075   //       T          operator--(VQ T&, int);
8076   void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8077     if (!HasArithmeticOrEnumeralCandidateType)
8078       return;
8079 
8080     for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8081       const auto TypeOfT = ArithmeticTypes[Arith];
8082       if (TypeOfT == S.Context.BoolTy) {
8083         if (Op == OO_MinusMinus)
8084           continue;
8085         if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8086           continue;
8087       }
8088       addPlusPlusMinusMinusStyleOverloads(
8089         TypeOfT,
8090         VisibleTypeConversionsQuals.hasVolatile(),
8091         VisibleTypeConversionsQuals.hasRestrict());
8092     }
8093   }
8094 
8095   // C++ [over.built]p5:
8096   //
8097   //   For every pair (T, VQ), where T is a cv-qualified or
8098   //   cv-unqualified object type, and VQ is either volatile or
8099   //   empty, there exist candidate operator functions of the form
8100   //
8101   //       T*VQ&      operator++(T*VQ&);
8102   //       T*VQ&      operator--(T*VQ&);
8103   //       T*         operator++(T*VQ&, int);
8104   //       T*         operator--(T*VQ&, int);
8105   void addPlusPlusMinusMinusPointerOverloads() {
8106     for (BuiltinCandidateTypeSet::iterator
8107               Ptr = CandidateTypes[0].pointer_begin(),
8108            PtrEnd = CandidateTypes[0].pointer_end();
8109          Ptr != PtrEnd; ++Ptr) {
8110       // Skip pointer types that aren't pointers to object types.
8111       if (!(*Ptr)->getPointeeType()->isObjectType())
8112         continue;
8113 
8114       addPlusPlusMinusMinusStyleOverloads(*Ptr,
8115         (!(*Ptr).isVolatileQualified() &&
8116          VisibleTypeConversionsQuals.hasVolatile()),
8117         (!(*Ptr).isRestrictQualified() &&
8118          VisibleTypeConversionsQuals.hasRestrict()));
8119     }
8120   }
8121 
8122   // C++ [over.built]p6:
8123   //   For every cv-qualified or cv-unqualified object type T, there
8124   //   exist candidate operator functions of the form
8125   //
8126   //       T&         operator*(T*);
8127   //
8128   // C++ [over.built]p7:
8129   //   For every function type T that does not have cv-qualifiers or a
8130   //   ref-qualifier, there exist candidate operator functions of the form
8131   //       T&         operator*(T*);
8132   void addUnaryStarPointerOverloads() {
8133     for (BuiltinCandidateTypeSet::iterator
8134               Ptr = CandidateTypes[0].pointer_begin(),
8135            PtrEnd = CandidateTypes[0].pointer_end();
8136          Ptr != PtrEnd; ++Ptr) {
8137       QualType ParamTy = *Ptr;
8138       QualType PointeeTy = ParamTy->getPointeeType();
8139       if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8140         continue;
8141 
8142       if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8143         if (Proto->getMethodQuals() || Proto->getRefQualifier())
8144           continue;
8145 
8146       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8147     }
8148   }
8149 
8150   // C++ [over.built]p9:
8151   //  For every promoted arithmetic type T, there exist candidate
8152   //  operator functions of the form
8153   //
8154   //       T         operator+(T);
8155   //       T         operator-(T);
8156   void addUnaryPlusOrMinusArithmeticOverloads() {
8157     if (!HasArithmeticOrEnumeralCandidateType)
8158       return;
8159 
8160     for (unsigned Arith = FirstPromotedArithmeticType;
8161          Arith < LastPromotedArithmeticType; ++Arith) {
8162       QualType ArithTy = ArithmeticTypes[Arith];
8163       S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8164     }
8165 
8166     // Extension: We also add these operators for vector types.
8167     for (BuiltinCandidateTypeSet::iterator
8168               Vec = CandidateTypes[0].vector_begin(),
8169            VecEnd = CandidateTypes[0].vector_end();
8170          Vec != VecEnd; ++Vec) {
8171       QualType VecTy = *Vec;
8172       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8173     }
8174   }
8175 
8176   // C++ [over.built]p8:
8177   //   For every type T, there exist candidate operator functions of
8178   //   the form
8179   //
8180   //       T*         operator+(T*);
8181   void addUnaryPlusPointerOverloads() {
8182     for (BuiltinCandidateTypeSet::iterator
8183               Ptr = CandidateTypes[0].pointer_begin(),
8184            PtrEnd = CandidateTypes[0].pointer_end();
8185          Ptr != PtrEnd; ++Ptr) {
8186       QualType ParamTy = *Ptr;
8187       S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8188     }
8189   }
8190 
8191   // C++ [over.built]p10:
8192   //   For every promoted integral type T, there exist candidate
8193   //   operator functions of the form
8194   //
8195   //        T         operator~(T);
8196   void addUnaryTildePromotedIntegralOverloads() {
8197     if (!HasArithmeticOrEnumeralCandidateType)
8198       return;
8199 
8200     for (unsigned Int = FirstPromotedIntegralType;
8201          Int < LastPromotedIntegralType; ++Int) {
8202       QualType IntTy = ArithmeticTypes[Int];
8203       S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8204     }
8205 
8206     // Extension: We also add this operator for vector types.
8207     for (BuiltinCandidateTypeSet::iterator
8208               Vec = CandidateTypes[0].vector_begin(),
8209            VecEnd = CandidateTypes[0].vector_end();
8210          Vec != VecEnd; ++Vec) {
8211       QualType VecTy = *Vec;
8212       S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8213     }
8214   }
8215 
8216   // C++ [over.match.oper]p16:
8217   //   For every pointer to member type T or type std::nullptr_t, there
8218   //   exist candidate operator functions of the form
8219   //
8220   //        bool operator==(T,T);
8221   //        bool operator!=(T,T);
8222   void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8223     /// Set of (canonical) types that we've already handled.
8224     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8225 
8226     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8227       for (BuiltinCandidateTypeSet::iterator
8228                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8229              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8230            MemPtr != MemPtrEnd;
8231            ++MemPtr) {
8232         // Don't add the same builtin candidate twice.
8233         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8234           continue;
8235 
8236         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8237         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8238       }
8239 
8240       if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8241         CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8242         if (AddedTypes.insert(NullPtrTy).second) {
8243           QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8244           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8245         }
8246       }
8247     }
8248   }
8249 
8250   // C++ [over.built]p15:
8251   //
8252   //   For every T, where T is an enumeration type or a pointer type,
8253   //   there exist candidate operator functions of the form
8254   //
8255   //        bool       operator<(T, T);
8256   //        bool       operator>(T, T);
8257   //        bool       operator<=(T, T);
8258   //        bool       operator>=(T, T);
8259   //        bool       operator==(T, T);
8260   //        bool       operator!=(T, T);
8261   //           R       operator<=>(T, T)
8262   void addGenericBinaryPointerOrEnumeralOverloads() {
8263     // C++ [over.match.oper]p3:
8264     //   [...]the built-in candidates include all of the candidate operator
8265     //   functions defined in 13.6 that, compared to the given operator, [...]
8266     //   do not have the same parameter-type-list as any non-template non-member
8267     //   candidate.
8268     //
8269     // Note that in practice, this only affects enumeration types because there
8270     // aren't any built-in candidates of record type, and a user-defined operator
8271     // must have an operand of record or enumeration type. Also, the only other
8272     // overloaded operator with enumeration arguments, operator=,
8273     // cannot be overloaded for enumeration types, so this is the only place
8274     // where we must suppress candidates like this.
8275     llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8276       UserDefinedBinaryOperators;
8277 
8278     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8279       if (CandidateTypes[ArgIdx].enumeration_begin() !=
8280           CandidateTypes[ArgIdx].enumeration_end()) {
8281         for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8282                                          CEnd = CandidateSet.end();
8283              C != CEnd; ++C) {
8284           if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8285             continue;
8286 
8287           if (C->Function->isFunctionTemplateSpecialization())
8288             continue;
8289 
8290           // We interpret "same parameter-type-list" as applying to the
8291           // "synthesized candidate, with the order of the two parameters
8292           // reversed", not to the original function.
8293           bool Reversed = C->RewriteKind & CRK_Reversed;
8294           QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8295                                         ->getType()
8296                                         .getUnqualifiedType();
8297           QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8298                                          ->getType()
8299                                          .getUnqualifiedType();
8300 
8301           // Skip if either parameter isn't of enumeral type.
8302           if (!FirstParamType->isEnumeralType() ||
8303               !SecondParamType->isEnumeralType())
8304             continue;
8305 
8306           // Add this operator to the set of known user-defined operators.
8307           UserDefinedBinaryOperators.insert(
8308             std::make_pair(S.Context.getCanonicalType(FirstParamType),
8309                            S.Context.getCanonicalType(SecondParamType)));
8310         }
8311       }
8312     }
8313 
8314     /// Set of (canonical) types that we've already handled.
8315     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8316 
8317     for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8318       for (BuiltinCandidateTypeSet::iterator
8319                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8320              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8321            Ptr != PtrEnd; ++Ptr) {
8322         // Don't add the same builtin candidate twice.
8323         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8324           continue;
8325 
8326         QualType ParamTypes[2] = { *Ptr, *Ptr };
8327         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8328       }
8329       for (BuiltinCandidateTypeSet::iterator
8330                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8331              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8332            Enum != EnumEnd; ++Enum) {
8333         CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8334 
8335         // Don't add the same builtin candidate twice, or if a user defined
8336         // candidate exists.
8337         if (!AddedTypes.insert(CanonType).second ||
8338             UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8339                                                             CanonType)))
8340           continue;
8341         QualType ParamTypes[2] = { *Enum, *Enum };
8342         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8343       }
8344     }
8345   }
8346 
8347   // C++ [over.built]p13:
8348   //
8349   //   For every cv-qualified or cv-unqualified object type T
8350   //   there exist candidate operator functions of the form
8351   //
8352   //      T*         operator+(T*, ptrdiff_t);
8353   //      T&         operator[](T*, ptrdiff_t);    [BELOW]
8354   //      T*         operator-(T*, ptrdiff_t);
8355   //      T*         operator+(ptrdiff_t, T*);
8356   //      T&         operator[](ptrdiff_t, T*);    [BELOW]
8357   //
8358   // C++ [over.built]p14:
8359   //
8360   //   For every T, where T is a pointer to object type, there
8361   //   exist candidate operator functions of the form
8362   //
8363   //      ptrdiff_t  operator-(T, T);
8364   void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8365     /// Set of (canonical) types that we've already handled.
8366     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8367 
8368     for (int Arg = 0; Arg < 2; ++Arg) {
8369       QualType AsymmetricParamTypes[2] = {
8370         S.Context.getPointerDiffType(),
8371         S.Context.getPointerDiffType(),
8372       };
8373       for (BuiltinCandidateTypeSet::iterator
8374                 Ptr = CandidateTypes[Arg].pointer_begin(),
8375              PtrEnd = CandidateTypes[Arg].pointer_end();
8376            Ptr != PtrEnd; ++Ptr) {
8377         QualType PointeeTy = (*Ptr)->getPointeeType();
8378         if (!PointeeTy->isObjectType())
8379           continue;
8380 
8381         AsymmetricParamTypes[Arg] = *Ptr;
8382         if (Arg == 0 || Op == OO_Plus) {
8383           // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8384           // T* operator+(ptrdiff_t, T*);
8385           S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8386         }
8387         if (Op == OO_Minus) {
8388           // ptrdiff_t operator-(T, T);
8389           if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8390             continue;
8391 
8392           QualType ParamTypes[2] = { *Ptr, *Ptr };
8393           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8394         }
8395       }
8396     }
8397   }
8398 
8399   // C++ [over.built]p12:
8400   //
8401   //   For every pair of promoted arithmetic types L and R, there
8402   //   exist candidate operator functions of the form
8403   //
8404   //        LR         operator*(L, R);
8405   //        LR         operator/(L, R);
8406   //        LR         operator+(L, R);
8407   //        LR         operator-(L, R);
8408   //        bool       operator<(L, R);
8409   //        bool       operator>(L, R);
8410   //        bool       operator<=(L, R);
8411   //        bool       operator>=(L, R);
8412   //        bool       operator==(L, R);
8413   //        bool       operator!=(L, R);
8414   //
8415   //   where LR is the result of the usual arithmetic conversions
8416   //   between types L and R.
8417   //
8418   // C++ [over.built]p24:
8419   //
8420   //   For every pair of promoted arithmetic types L and R, there exist
8421   //   candidate operator functions of the form
8422   //
8423   //        LR       operator?(bool, L, R);
8424   //
8425   //   where LR is the result of the usual arithmetic conversions
8426   //   between types L and R.
8427   // Our candidates ignore the first parameter.
8428   void addGenericBinaryArithmeticOverloads() {
8429     if (!HasArithmeticOrEnumeralCandidateType)
8430       return;
8431 
8432     for (unsigned Left = FirstPromotedArithmeticType;
8433          Left < LastPromotedArithmeticType; ++Left) {
8434       for (unsigned Right = FirstPromotedArithmeticType;
8435            Right < LastPromotedArithmeticType; ++Right) {
8436         QualType LandR[2] = { ArithmeticTypes[Left],
8437                               ArithmeticTypes[Right] };
8438         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8439       }
8440     }
8441 
8442     // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8443     // conditional operator for vector types.
8444     for (BuiltinCandidateTypeSet::iterator
8445               Vec1 = CandidateTypes[0].vector_begin(),
8446            Vec1End = CandidateTypes[0].vector_end();
8447          Vec1 != Vec1End; ++Vec1) {
8448       for (BuiltinCandidateTypeSet::iterator
8449                 Vec2 = CandidateTypes[1].vector_begin(),
8450              Vec2End = CandidateTypes[1].vector_end();
8451            Vec2 != Vec2End; ++Vec2) {
8452         QualType LandR[2] = { *Vec1, *Vec2 };
8453         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8454       }
8455     }
8456   }
8457 
8458   // C++2a [over.built]p14:
8459   //
8460   //   For every integral type T there exists a candidate operator function
8461   //   of the form
8462   //
8463   //        std::strong_ordering operator<=>(T, T)
8464   //
8465   // C++2a [over.built]p15:
8466   //
8467   //   For every pair of floating-point types L and R, there exists a candidate
8468   //   operator function of the form
8469   //
8470   //       std::partial_ordering operator<=>(L, R);
8471   //
8472   // FIXME: The current specification for integral types doesn't play nice with
8473   // the direction of p0946r0, which allows mixed integral and unscoped-enum
8474   // comparisons. Under the current spec this can lead to ambiguity during
8475   // overload resolution. For example:
8476   //
8477   //   enum A : int {a};
8478   //   auto x = (a <=> (long)42);
8479   //
8480   //   error: call is ambiguous for arguments 'A' and 'long'.
8481   //   note: candidate operator<=>(int, int)
8482   //   note: candidate operator<=>(long, long)
8483   //
8484   // To avoid this error, this function deviates from the specification and adds
8485   // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8486   // arithmetic types (the same as the generic relational overloads).
8487   //
8488   // For now this function acts as a placeholder.
8489   void addThreeWayArithmeticOverloads() {
8490     addGenericBinaryArithmeticOverloads();
8491   }
8492 
8493   // C++ [over.built]p17:
8494   //
8495   //   For every pair of promoted integral types L and R, there
8496   //   exist candidate operator functions of the form
8497   //
8498   //      LR         operator%(L, R);
8499   //      LR         operator&(L, R);
8500   //      LR         operator^(L, R);
8501   //      LR         operator|(L, R);
8502   //      L          operator<<(L, R);
8503   //      L          operator>>(L, R);
8504   //
8505   //   where LR is the result of the usual arithmetic conversions
8506   //   between types L and R.
8507   void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8508     if (!HasArithmeticOrEnumeralCandidateType)
8509       return;
8510 
8511     for (unsigned Left = FirstPromotedIntegralType;
8512          Left < LastPromotedIntegralType; ++Left) {
8513       for (unsigned Right = FirstPromotedIntegralType;
8514            Right < LastPromotedIntegralType; ++Right) {
8515         QualType LandR[2] = { ArithmeticTypes[Left],
8516                               ArithmeticTypes[Right] };
8517         S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8518       }
8519     }
8520   }
8521 
8522   // C++ [over.built]p20:
8523   //
8524   //   For every pair (T, VQ), where T is an enumeration or
8525   //   pointer to member type and VQ is either volatile or
8526   //   empty, there exist candidate operator functions of the form
8527   //
8528   //        VQ T&      operator=(VQ T&, T);
8529   void addAssignmentMemberPointerOrEnumeralOverloads() {
8530     /// Set of (canonical) types that we've already handled.
8531     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8532 
8533     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8534       for (BuiltinCandidateTypeSet::iterator
8535                 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8536              EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8537            Enum != EnumEnd; ++Enum) {
8538         if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8539           continue;
8540 
8541         AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8542       }
8543 
8544       for (BuiltinCandidateTypeSet::iterator
8545                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8546              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8547            MemPtr != MemPtrEnd; ++MemPtr) {
8548         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8549           continue;
8550 
8551         AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8552       }
8553     }
8554   }
8555 
8556   // C++ [over.built]p19:
8557   //
8558   //   For every pair (T, VQ), where T is any type and VQ is either
8559   //   volatile or empty, there exist candidate operator functions
8560   //   of the form
8561   //
8562   //        T*VQ&      operator=(T*VQ&, T*);
8563   //
8564   // C++ [over.built]p21:
8565   //
8566   //   For every pair (T, VQ), where T is a cv-qualified or
8567   //   cv-unqualified object type and VQ is either volatile or
8568   //   empty, there exist candidate operator functions of the form
8569   //
8570   //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
8571   //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
8572   void addAssignmentPointerOverloads(bool isEqualOp) {
8573     /// Set of (canonical) types that we've already handled.
8574     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8575 
8576     for (BuiltinCandidateTypeSet::iterator
8577               Ptr = CandidateTypes[0].pointer_begin(),
8578            PtrEnd = CandidateTypes[0].pointer_end();
8579          Ptr != PtrEnd; ++Ptr) {
8580       // If this is operator=, keep track of the builtin candidates we added.
8581       if (isEqualOp)
8582         AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8583       else if (!(*Ptr)->getPointeeType()->isObjectType())
8584         continue;
8585 
8586       // non-volatile version
8587       QualType ParamTypes[2] = {
8588         S.Context.getLValueReferenceType(*Ptr),
8589         isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8590       };
8591       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8592                             /*IsAssignmentOperator=*/ isEqualOp);
8593 
8594       bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8595                           VisibleTypeConversionsQuals.hasVolatile();
8596       if (NeedVolatile) {
8597         // volatile version
8598         ParamTypes[0] =
8599           S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8600         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8601                               /*IsAssignmentOperator=*/isEqualOp);
8602       }
8603 
8604       if (!(*Ptr).isRestrictQualified() &&
8605           VisibleTypeConversionsQuals.hasRestrict()) {
8606         // restrict version
8607         ParamTypes[0]
8608           = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8609         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8610                               /*IsAssignmentOperator=*/isEqualOp);
8611 
8612         if (NeedVolatile) {
8613           // volatile restrict version
8614           ParamTypes[0]
8615             = S.Context.getLValueReferenceType(
8616                 S.Context.getCVRQualifiedType(*Ptr,
8617                                               (Qualifiers::Volatile |
8618                                                Qualifiers::Restrict)));
8619           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8620                                 /*IsAssignmentOperator=*/isEqualOp);
8621         }
8622       }
8623     }
8624 
8625     if (isEqualOp) {
8626       for (BuiltinCandidateTypeSet::iterator
8627                 Ptr = CandidateTypes[1].pointer_begin(),
8628              PtrEnd = CandidateTypes[1].pointer_end();
8629            Ptr != PtrEnd; ++Ptr) {
8630         // Make sure we don't add the same candidate twice.
8631         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8632           continue;
8633 
8634         QualType ParamTypes[2] = {
8635           S.Context.getLValueReferenceType(*Ptr),
8636           *Ptr,
8637         };
8638 
8639         // non-volatile version
8640         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8641                               /*IsAssignmentOperator=*/true);
8642 
8643         bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8644                            VisibleTypeConversionsQuals.hasVolatile();
8645         if (NeedVolatile) {
8646           // volatile version
8647           ParamTypes[0] =
8648             S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8649           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8650                                 /*IsAssignmentOperator=*/true);
8651         }
8652 
8653         if (!(*Ptr).isRestrictQualified() &&
8654             VisibleTypeConversionsQuals.hasRestrict()) {
8655           // restrict version
8656           ParamTypes[0]
8657             = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8658           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8659                                 /*IsAssignmentOperator=*/true);
8660 
8661           if (NeedVolatile) {
8662             // volatile restrict version
8663             ParamTypes[0]
8664               = S.Context.getLValueReferenceType(
8665                   S.Context.getCVRQualifiedType(*Ptr,
8666                                                 (Qualifiers::Volatile |
8667                                                  Qualifiers::Restrict)));
8668             S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8669                                   /*IsAssignmentOperator=*/true);
8670           }
8671         }
8672       }
8673     }
8674   }
8675 
8676   // C++ [over.built]p18:
8677   //
8678   //   For every triple (L, VQ, R), where L is an arithmetic type,
8679   //   VQ is either volatile or empty, and R is a promoted
8680   //   arithmetic type, there exist candidate operator functions of
8681   //   the form
8682   //
8683   //        VQ L&      operator=(VQ L&, R);
8684   //        VQ L&      operator*=(VQ L&, R);
8685   //        VQ L&      operator/=(VQ L&, R);
8686   //        VQ L&      operator+=(VQ L&, R);
8687   //        VQ L&      operator-=(VQ L&, R);
8688   void addAssignmentArithmeticOverloads(bool isEqualOp) {
8689     if (!HasArithmeticOrEnumeralCandidateType)
8690       return;
8691 
8692     for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8693       for (unsigned Right = FirstPromotedArithmeticType;
8694            Right < LastPromotedArithmeticType; ++Right) {
8695         QualType ParamTypes[2];
8696         ParamTypes[1] = ArithmeticTypes[Right];
8697         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8698             S, ArithmeticTypes[Left], Args[0]);
8699         // Add this built-in operator as a candidate (VQ is empty).
8700         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8701         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8702                               /*IsAssignmentOperator=*/isEqualOp);
8703 
8704         // Add this built-in operator as a candidate (VQ is 'volatile').
8705         if (VisibleTypeConversionsQuals.hasVolatile()) {
8706           ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8707           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8708           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8709                                 /*IsAssignmentOperator=*/isEqualOp);
8710         }
8711       }
8712     }
8713 
8714     // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8715     for (BuiltinCandidateTypeSet::iterator
8716               Vec1 = CandidateTypes[0].vector_begin(),
8717            Vec1End = CandidateTypes[0].vector_end();
8718          Vec1 != Vec1End; ++Vec1) {
8719       for (BuiltinCandidateTypeSet::iterator
8720                 Vec2 = CandidateTypes[1].vector_begin(),
8721              Vec2End = CandidateTypes[1].vector_end();
8722            Vec2 != Vec2End; ++Vec2) {
8723         QualType ParamTypes[2];
8724         ParamTypes[1] = *Vec2;
8725         // Add this built-in operator as a candidate (VQ is empty).
8726         ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8727         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8728                               /*IsAssignmentOperator=*/isEqualOp);
8729 
8730         // Add this built-in operator as a candidate (VQ is 'volatile').
8731         if (VisibleTypeConversionsQuals.hasVolatile()) {
8732           ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8733           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8734           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8735                                 /*IsAssignmentOperator=*/isEqualOp);
8736         }
8737       }
8738     }
8739   }
8740 
8741   // C++ [over.built]p22:
8742   //
8743   //   For every triple (L, VQ, R), where L is an integral type, VQ
8744   //   is either volatile or empty, and R is a promoted integral
8745   //   type, there exist candidate operator functions of the form
8746   //
8747   //        VQ L&       operator%=(VQ L&, R);
8748   //        VQ L&       operator<<=(VQ L&, R);
8749   //        VQ L&       operator>>=(VQ L&, R);
8750   //        VQ L&       operator&=(VQ L&, R);
8751   //        VQ L&       operator^=(VQ L&, R);
8752   //        VQ L&       operator|=(VQ L&, R);
8753   void addAssignmentIntegralOverloads() {
8754     if (!HasArithmeticOrEnumeralCandidateType)
8755       return;
8756 
8757     for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8758       for (unsigned Right = FirstPromotedIntegralType;
8759            Right < LastPromotedIntegralType; ++Right) {
8760         QualType ParamTypes[2];
8761         ParamTypes[1] = ArithmeticTypes[Right];
8762         auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8763             S, ArithmeticTypes[Left], Args[0]);
8764         // Add this built-in operator as a candidate (VQ is empty).
8765         ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8766         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8767         if (VisibleTypeConversionsQuals.hasVolatile()) {
8768           // Add this built-in operator as a candidate (VQ is 'volatile').
8769           ParamTypes[0] = LeftBaseTy;
8770           ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8771           ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8772           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8773         }
8774       }
8775     }
8776   }
8777 
8778   // C++ [over.operator]p23:
8779   //
8780   //   There also exist candidate operator functions of the form
8781   //
8782   //        bool        operator!(bool);
8783   //        bool        operator&&(bool, bool);
8784   //        bool        operator||(bool, bool);
8785   void addExclaimOverload() {
8786     QualType ParamTy = S.Context.BoolTy;
8787     S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8788                           /*IsAssignmentOperator=*/false,
8789                           /*NumContextualBoolArguments=*/1);
8790   }
8791   void addAmpAmpOrPipePipeOverload() {
8792     QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8793     S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8794                           /*IsAssignmentOperator=*/false,
8795                           /*NumContextualBoolArguments=*/2);
8796   }
8797 
8798   // C++ [over.built]p13:
8799   //
8800   //   For every cv-qualified or cv-unqualified object type T there
8801   //   exist candidate operator functions of the form
8802   //
8803   //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
8804   //        T&         operator[](T*, ptrdiff_t);
8805   //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
8806   //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
8807   //        T&         operator[](ptrdiff_t, T*);
8808   void addSubscriptOverloads() {
8809     for (BuiltinCandidateTypeSet::iterator
8810               Ptr = CandidateTypes[0].pointer_begin(),
8811            PtrEnd = CandidateTypes[0].pointer_end();
8812          Ptr != PtrEnd; ++Ptr) {
8813       QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8814       QualType PointeeType = (*Ptr)->getPointeeType();
8815       if (!PointeeType->isObjectType())
8816         continue;
8817 
8818       // T& operator[](T*, ptrdiff_t)
8819       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8820     }
8821 
8822     for (BuiltinCandidateTypeSet::iterator
8823               Ptr = CandidateTypes[1].pointer_begin(),
8824            PtrEnd = CandidateTypes[1].pointer_end();
8825          Ptr != PtrEnd; ++Ptr) {
8826       QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8827       QualType PointeeType = (*Ptr)->getPointeeType();
8828       if (!PointeeType->isObjectType())
8829         continue;
8830 
8831       // T& operator[](ptrdiff_t, T*)
8832       S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8833     }
8834   }
8835 
8836   // C++ [over.built]p11:
8837   //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8838   //    C1 is the same type as C2 or is a derived class of C2, T is an object
8839   //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8840   //    there exist candidate operator functions of the form
8841   //
8842   //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8843   //
8844   //    where CV12 is the union of CV1 and CV2.
8845   void addArrowStarOverloads() {
8846     for (BuiltinCandidateTypeSet::iterator
8847              Ptr = CandidateTypes[0].pointer_begin(),
8848            PtrEnd = CandidateTypes[0].pointer_end();
8849          Ptr != PtrEnd; ++Ptr) {
8850       QualType C1Ty = (*Ptr);
8851       QualType C1;
8852       QualifierCollector Q1;
8853       C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8854       if (!isa<RecordType>(C1))
8855         continue;
8856       // heuristic to reduce number of builtin candidates in the set.
8857       // Add volatile/restrict version only if there are conversions to a
8858       // volatile/restrict type.
8859       if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8860         continue;
8861       if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8862         continue;
8863       for (BuiltinCandidateTypeSet::iterator
8864                 MemPtr = CandidateTypes[1].member_pointer_begin(),
8865              MemPtrEnd = CandidateTypes[1].member_pointer_end();
8866            MemPtr != MemPtrEnd; ++MemPtr) {
8867         const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8868         QualType C2 = QualType(mptr->getClass(), 0);
8869         C2 = C2.getUnqualifiedType();
8870         if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8871           break;
8872         QualType ParamTypes[2] = { *Ptr, *MemPtr };
8873         // build CV12 T&
8874         QualType T = mptr->getPointeeType();
8875         if (!VisibleTypeConversionsQuals.hasVolatile() &&
8876             T.isVolatileQualified())
8877           continue;
8878         if (!VisibleTypeConversionsQuals.hasRestrict() &&
8879             T.isRestrictQualified())
8880           continue;
8881         T = Q1.apply(S.Context, T);
8882         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8883       }
8884     }
8885   }
8886 
8887   // Note that we don't consider the first argument, since it has been
8888   // contextually converted to bool long ago. The candidates below are
8889   // therefore added as binary.
8890   //
8891   // C++ [over.built]p25:
8892   //   For every type T, where T is a pointer, pointer-to-member, or scoped
8893   //   enumeration type, there exist candidate operator functions of the form
8894   //
8895   //        T        operator?(bool, T, T);
8896   //
8897   void addConditionalOperatorOverloads() {
8898     /// Set of (canonical) types that we've already handled.
8899     llvm::SmallPtrSet<QualType, 8> AddedTypes;
8900 
8901     for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8902       for (BuiltinCandidateTypeSet::iterator
8903                 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8904              PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8905            Ptr != PtrEnd; ++Ptr) {
8906         if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8907           continue;
8908 
8909         QualType ParamTypes[2] = { *Ptr, *Ptr };
8910         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8911       }
8912 
8913       for (BuiltinCandidateTypeSet::iterator
8914                 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8915              MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8916            MemPtr != MemPtrEnd; ++MemPtr) {
8917         if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8918           continue;
8919 
8920         QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8921         S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8922       }
8923 
8924       if (S.getLangOpts().CPlusPlus11) {
8925         for (BuiltinCandidateTypeSet::iterator
8926                   Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8927                EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8928              Enum != EnumEnd; ++Enum) {
8929           if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
8930             continue;
8931 
8932           if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8933             continue;
8934 
8935           QualType ParamTypes[2] = { *Enum, *Enum };
8936           S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8937         }
8938       }
8939     }
8940   }
8941 };
8942 
8943 } // end anonymous namespace
8944 
8945 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8946 /// operator overloads to the candidate set (C++ [over.built]), based
8947 /// on the operator @p Op and the arguments given. For example, if the
8948 /// operator is a binary '+', this routine might add "int
8949 /// operator+(int, int)" to cover integer addition.
8950 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8951                                         SourceLocation OpLoc,
8952                                         ArrayRef<Expr *> Args,
8953                                         OverloadCandidateSet &CandidateSet) {
8954   // Find all of the types that the arguments can convert to, but only
8955   // if the operator we're looking at has built-in operator candidates
8956   // that make use of these types. Also record whether we encounter non-record
8957   // candidate types or either arithmetic or enumeral candidate types.
8958   Qualifiers VisibleTypeConversionsQuals;
8959   VisibleTypeConversionsQuals.addConst();
8960   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8961     VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8962 
8963   bool HasNonRecordCandidateType = false;
8964   bool HasArithmeticOrEnumeralCandidateType = false;
8965   SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8966   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8967     CandidateTypes.emplace_back(*this);
8968     CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8969                                                  OpLoc,
8970                                                  true,
8971                                                  (Op == OO_Exclaim ||
8972                                                   Op == OO_AmpAmp ||
8973                                                   Op == OO_PipePipe),
8974                                                  VisibleTypeConversionsQuals);
8975     HasNonRecordCandidateType = HasNonRecordCandidateType ||
8976         CandidateTypes[ArgIdx].hasNonRecordTypes();
8977     HasArithmeticOrEnumeralCandidateType =
8978         HasArithmeticOrEnumeralCandidateType ||
8979         CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8980   }
8981 
8982   // Exit early when no non-record types have been added to the candidate set
8983   // for any of the arguments to the operator.
8984   //
8985   // We can't exit early for !, ||, or &&, since there we have always have
8986   // 'bool' overloads.
8987   if (!HasNonRecordCandidateType &&
8988       !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8989     return;
8990 
8991   // Setup an object to manage the common state for building overloads.
8992   BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8993                                            VisibleTypeConversionsQuals,
8994                                            HasArithmeticOrEnumeralCandidateType,
8995                                            CandidateTypes, CandidateSet);
8996 
8997   // Dispatch over the operation to add in only those overloads which apply.
8998   switch (Op) {
8999   case OO_None:
9000   case NUM_OVERLOADED_OPERATORS:
9001     llvm_unreachable("Expected an overloaded operator");
9002 
9003   case OO_New:
9004   case OO_Delete:
9005   case OO_Array_New:
9006   case OO_Array_Delete:
9007   case OO_Call:
9008     llvm_unreachable(
9009                     "Special operators don't use AddBuiltinOperatorCandidates");
9010 
9011   case OO_Comma:
9012   case OO_Arrow:
9013   case OO_Coawait:
9014     // C++ [over.match.oper]p3:
9015     //   -- For the operator ',', the unary operator '&', the
9016     //      operator '->', or the operator 'co_await', the
9017     //      built-in candidates set is empty.
9018     break;
9019 
9020   case OO_Plus: // '+' is either unary or binary
9021     if (Args.size() == 1)
9022       OpBuilder.addUnaryPlusPointerOverloads();
9023     LLVM_FALLTHROUGH;
9024 
9025   case OO_Minus: // '-' is either unary or binary
9026     if (Args.size() == 1) {
9027       OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9028     } else {
9029       OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9030       OpBuilder.addGenericBinaryArithmeticOverloads();
9031     }
9032     break;
9033 
9034   case OO_Star: // '*' is either unary or binary
9035     if (Args.size() == 1)
9036       OpBuilder.addUnaryStarPointerOverloads();
9037     else
9038       OpBuilder.addGenericBinaryArithmeticOverloads();
9039     break;
9040 
9041   case OO_Slash:
9042     OpBuilder.addGenericBinaryArithmeticOverloads();
9043     break;
9044 
9045   case OO_PlusPlus:
9046   case OO_MinusMinus:
9047     OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9048     OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9049     break;
9050 
9051   case OO_EqualEqual:
9052   case OO_ExclaimEqual:
9053     OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9054     LLVM_FALLTHROUGH;
9055 
9056   case OO_Less:
9057   case OO_Greater:
9058   case OO_LessEqual:
9059   case OO_GreaterEqual:
9060     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9061     OpBuilder.addGenericBinaryArithmeticOverloads();
9062     break;
9063 
9064   case OO_Spaceship:
9065     OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9066     OpBuilder.addThreeWayArithmeticOverloads();
9067     break;
9068 
9069   case OO_Percent:
9070   case OO_Caret:
9071   case OO_Pipe:
9072   case OO_LessLess:
9073   case OO_GreaterGreater:
9074     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9075     break;
9076 
9077   case OO_Amp: // '&' is either unary or binary
9078     if (Args.size() == 1)
9079       // C++ [over.match.oper]p3:
9080       //   -- For the operator ',', the unary operator '&', or the
9081       //      operator '->', the built-in candidates set is empty.
9082       break;
9083 
9084     OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9085     break;
9086 
9087   case OO_Tilde:
9088     OpBuilder.addUnaryTildePromotedIntegralOverloads();
9089     break;
9090 
9091   case OO_Equal:
9092     OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9093     LLVM_FALLTHROUGH;
9094 
9095   case OO_PlusEqual:
9096   case OO_MinusEqual:
9097     OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9098     LLVM_FALLTHROUGH;
9099 
9100   case OO_StarEqual:
9101   case OO_SlashEqual:
9102     OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9103     break;
9104 
9105   case OO_PercentEqual:
9106   case OO_LessLessEqual:
9107   case OO_GreaterGreaterEqual:
9108   case OO_AmpEqual:
9109   case OO_CaretEqual:
9110   case OO_PipeEqual:
9111     OpBuilder.addAssignmentIntegralOverloads();
9112     break;
9113 
9114   case OO_Exclaim:
9115     OpBuilder.addExclaimOverload();
9116     break;
9117 
9118   case OO_AmpAmp:
9119   case OO_PipePipe:
9120     OpBuilder.addAmpAmpOrPipePipeOverload();
9121     break;
9122 
9123   case OO_Subscript:
9124     OpBuilder.addSubscriptOverloads();
9125     break;
9126 
9127   case OO_ArrowStar:
9128     OpBuilder.addArrowStarOverloads();
9129     break;
9130 
9131   case OO_Conditional:
9132     OpBuilder.addConditionalOperatorOverloads();
9133     OpBuilder.addGenericBinaryArithmeticOverloads();
9134     break;
9135   }
9136 }
9137 
9138 /// Add function candidates found via argument-dependent lookup
9139 /// to the set of overloading candidates.
9140 ///
9141 /// This routine performs argument-dependent name lookup based on the
9142 /// given function name (which may also be an operator name) and adds
9143 /// all of the overload candidates found by ADL to the overload
9144 /// candidate set (C++ [basic.lookup.argdep]).
9145 void
9146 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9147                                            SourceLocation Loc,
9148                                            ArrayRef<Expr *> Args,
9149                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
9150                                            OverloadCandidateSet& CandidateSet,
9151                                            bool PartialOverloading) {
9152   ADLResult Fns;
9153 
9154   // FIXME: This approach for uniquing ADL results (and removing
9155   // redundant candidates from the set) relies on pointer-equality,
9156   // which means we need to key off the canonical decl.  However,
9157   // always going back to the canonical decl might not get us the
9158   // right set of default arguments.  What default arguments are
9159   // we supposed to consider on ADL candidates, anyway?
9160 
9161   // FIXME: Pass in the explicit template arguments?
9162   ArgumentDependentLookup(Name, Loc, Args, Fns);
9163 
9164   // Erase all of the candidates we already knew about.
9165   for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9166                                    CandEnd = CandidateSet.end();
9167        Cand != CandEnd; ++Cand)
9168     if (Cand->Function) {
9169       Fns.erase(Cand->Function);
9170       if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9171         Fns.erase(FunTmpl);
9172     }
9173 
9174   // For each of the ADL candidates we found, add it to the overload
9175   // set.
9176   for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9177     DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9178 
9179     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9180       if (ExplicitTemplateArgs)
9181         continue;
9182 
9183       AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9184                            /*SuppressUserConversions=*/false, PartialOverloading,
9185                            /*AllowExplicit*/ true,
9186                            /*AllowExplicitConversions*/ false,
9187                            ADLCallKind::UsesADL);
9188     } else {
9189       AddTemplateOverloadCandidate(
9190           cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9191           CandidateSet,
9192           /*SuppressUserConversions=*/false, PartialOverloading,
9193           /*AllowExplicit*/true, ADLCallKind::UsesADL);
9194     }
9195   }
9196 }
9197 
9198 namespace {
9199 enum class Comparison { Equal, Better, Worse };
9200 }
9201 
9202 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9203 /// overload resolution.
9204 ///
9205 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9206 /// Cand1's first N enable_if attributes have precisely the same conditions as
9207 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9208 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9209 ///
9210 /// Note that you can have a pair of candidates such that Cand1's enable_if
9211 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9212 /// worse than Cand1's.
9213 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9214                                        const FunctionDecl *Cand2) {
9215   // Common case: One (or both) decls don't have enable_if attrs.
9216   bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9217   bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9218   if (!Cand1Attr || !Cand2Attr) {
9219     if (Cand1Attr == Cand2Attr)
9220       return Comparison::Equal;
9221     return Cand1Attr ? Comparison::Better : Comparison::Worse;
9222   }
9223 
9224   auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9225   auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9226 
9227   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9228   for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9229     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9230     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9231 
9232     // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9233     // has fewer enable_if attributes than Cand2, and vice versa.
9234     if (!Cand1A)
9235       return Comparison::Worse;
9236     if (!Cand2A)
9237       return Comparison::Better;
9238 
9239     Cand1ID.clear();
9240     Cand2ID.clear();
9241 
9242     (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9243     (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9244     if (Cand1ID != Cand2ID)
9245       return Comparison::Worse;
9246   }
9247 
9248   return Comparison::Equal;
9249 }
9250 
9251 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9252                                           const OverloadCandidate &Cand2) {
9253   if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9254       !Cand2.Function->isMultiVersion())
9255     return false;
9256 
9257   // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9258   // is obviously better.
9259   if (Cand1.Function->isInvalidDecl()) return false;
9260   if (Cand2.Function->isInvalidDecl()) return true;
9261 
9262   // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9263   // cpu_dispatch, else arbitrarily based on the identifiers.
9264   bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9265   bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9266   const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9267   const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9268 
9269   if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9270     return false;
9271 
9272   if (Cand1CPUDisp && !Cand2CPUDisp)
9273     return true;
9274   if (Cand2CPUDisp && !Cand1CPUDisp)
9275     return false;
9276 
9277   if (Cand1CPUSpec && Cand2CPUSpec) {
9278     if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9279       return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9280 
9281     std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9282         FirstDiff = std::mismatch(
9283             Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9284             Cand2CPUSpec->cpus_begin(),
9285             [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9286               return LHS->getName() == RHS->getName();
9287             });
9288 
9289     assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9290            "Two different cpu-specific versions should not have the same "
9291            "identifier list, otherwise they'd be the same decl!");
9292     return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9293   }
9294   llvm_unreachable("No way to get here unless both had cpu_dispatch");
9295 }
9296 
9297 /// isBetterOverloadCandidate - Determines whether the first overload
9298 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9299 bool clang::isBetterOverloadCandidate(
9300     Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9301     SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9302   // Define viable functions to be better candidates than non-viable
9303   // functions.
9304   if (!Cand2.Viable)
9305     return Cand1.Viable;
9306   else if (!Cand1.Viable)
9307     return false;
9308 
9309   // C++ [over.match.best]p1:
9310   //
9311   //   -- if F is a static member function, ICS1(F) is defined such
9312   //      that ICS1(F) is neither better nor worse than ICS1(G) for
9313   //      any function G, and, symmetrically, ICS1(G) is neither
9314   //      better nor worse than ICS1(F).
9315   unsigned StartArg = 0;
9316   if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9317     StartArg = 1;
9318 
9319   auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9320     // We don't allow incompatible pointer conversions in C++.
9321     if (!S.getLangOpts().CPlusPlus)
9322       return ICS.isStandard() &&
9323              ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9324 
9325     // The only ill-formed conversion we allow in C++ is the string literal to
9326     // char* conversion, which is only considered ill-formed after C++11.
9327     return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9328            hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9329   };
9330 
9331   // Define functions that don't require ill-formed conversions for a given
9332   // argument to be better candidates than functions that do.
9333   unsigned NumArgs = Cand1.Conversions.size();
9334   assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9335   bool HasBetterConversion = false;
9336   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9337     bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9338     bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9339     if (Cand1Bad != Cand2Bad) {
9340       if (Cand1Bad)
9341         return false;
9342       HasBetterConversion = true;
9343     }
9344   }
9345 
9346   if (HasBetterConversion)
9347     return true;
9348 
9349   // C++ [over.match.best]p1:
9350   //   A viable function F1 is defined to be a better function than another
9351   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
9352   //   conversion sequence than ICSi(F2), and then...
9353   bool HasWorseConversion = false;
9354   for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9355     switch (CompareImplicitConversionSequences(S, Loc,
9356                                                Cand1.Conversions[ArgIdx],
9357                                                Cand2.Conversions[ArgIdx])) {
9358     case ImplicitConversionSequence::Better:
9359       // Cand1 has a better conversion sequence.
9360       HasBetterConversion = true;
9361       break;
9362 
9363     case ImplicitConversionSequence::Worse:
9364       if (Cand1.Function && Cand1.Function == Cand2.Function &&
9365           (Cand2.RewriteKind & CRK_Reversed) != 0) {
9366         // Work around large-scale breakage caused by considering reversed
9367         // forms of operator== in C++20:
9368         //
9369         // When comparing a function against its reversed form, if we have a
9370         // better conversion for one argument and a worse conversion for the
9371         // other, we prefer the non-reversed form.
9372         //
9373         // This prevents a conversion function from being considered ambiguous
9374         // with its own reversed form in various where it's only incidentally
9375         // heterogeneous.
9376         //
9377         // We diagnose this as an extension from CreateOverloadedBinOp.
9378         HasWorseConversion = true;
9379         break;
9380       }
9381 
9382       // Cand1 can't be better than Cand2.
9383       return false;
9384 
9385     case ImplicitConversionSequence::Indistinguishable:
9386       // Do nothing.
9387       break;
9388     }
9389   }
9390 
9391   //    -- for some argument j, ICSj(F1) is a better conversion sequence than
9392   //       ICSj(F2), or, if not that,
9393   if (HasBetterConversion)
9394     return true;
9395   if (HasWorseConversion)
9396     return false;
9397 
9398   //   -- the context is an initialization by user-defined conversion
9399   //      (see 8.5, 13.3.1.5) and the standard conversion sequence
9400   //      from the return type of F1 to the destination type (i.e.,
9401   //      the type of the entity being initialized) is a better
9402   //      conversion sequence than the standard conversion sequence
9403   //      from the return type of F2 to the destination type.
9404   if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9405       Cand1.Function && Cand2.Function &&
9406       isa<CXXConversionDecl>(Cand1.Function) &&
9407       isa<CXXConversionDecl>(Cand2.Function)) {
9408     // First check whether we prefer one of the conversion functions over the
9409     // other. This only distinguishes the results in non-standard, extension
9410     // cases such as the conversion from a lambda closure type to a function
9411     // pointer or block.
9412     ImplicitConversionSequence::CompareKind Result =
9413         compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9414     if (Result == ImplicitConversionSequence::Indistinguishable)
9415       Result = CompareStandardConversionSequences(S, Loc,
9416                                                   Cand1.FinalConversion,
9417                                                   Cand2.FinalConversion);
9418 
9419     if (Result != ImplicitConversionSequence::Indistinguishable)
9420       return Result == ImplicitConversionSequence::Better;
9421 
9422     // FIXME: Compare kind of reference binding if conversion functions
9423     // convert to a reference type used in direct reference binding, per
9424     // C++14 [over.match.best]p1 section 2 bullet 3.
9425   }
9426 
9427   // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9428   // as combined with the resolution to CWG issue 243.
9429   //
9430   // When the context is initialization by constructor ([over.match.ctor] or
9431   // either phase of [over.match.list]), a constructor is preferred over
9432   // a conversion function.
9433   if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9434       Cand1.Function && Cand2.Function &&
9435       isa<CXXConstructorDecl>(Cand1.Function) !=
9436           isa<CXXConstructorDecl>(Cand2.Function))
9437     return isa<CXXConstructorDecl>(Cand1.Function);
9438 
9439   //    -- F1 is a non-template function and F2 is a function template
9440   //       specialization, or, if not that,
9441   bool Cand1IsSpecialization = Cand1.Function &&
9442                                Cand1.Function->getPrimaryTemplate();
9443   bool Cand2IsSpecialization = Cand2.Function &&
9444                                Cand2.Function->getPrimaryTemplate();
9445   if (Cand1IsSpecialization != Cand2IsSpecialization)
9446     return Cand2IsSpecialization;
9447 
9448   //   -- F1 and F2 are function template specializations, and the function
9449   //      template for F1 is more specialized than the template for F2
9450   //      according to the partial ordering rules described in 14.5.5.2, or,
9451   //      if not that,
9452   if (Cand1IsSpecialization && Cand2IsSpecialization) {
9453     if (FunctionTemplateDecl *BetterTemplate
9454           = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9455                                          Cand2.Function->getPrimaryTemplate(),
9456                                          Loc,
9457                        isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9458                                                              : TPOC_Call,
9459                                          Cand1.ExplicitCallArguments,
9460                                          Cand2.ExplicitCallArguments))
9461       return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9462   }
9463 
9464   //   -- F1 is a constructor for a class D, F2 is a constructor for a base
9465   //      class B of D, and for all arguments the corresponding parameters of
9466   //      F1 and F2 have the same type.
9467   // FIXME: Implement the "all parameters have the same type" check.
9468   bool Cand1IsInherited =
9469       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9470   bool Cand2IsInherited =
9471       dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9472   if (Cand1IsInherited != Cand2IsInherited)
9473     return Cand2IsInherited;
9474   else if (Cand1IsInherited) {
9475     assert(Cand2IsInherited);
9476     auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9477     auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9478     if (Cand1Class->isDerivedFrom(Cand2Class))
9479       return true;
9480     if (Cand2Class->isDerivedFrom(Cand1Class))
9481       return false;
9482     // Inherited from sibling base classes: still ambiguous.
9483   }
9484 
9485   //   -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9486   //   -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9487   //      with reversed order of parameters and F1 is not
9488   //
9489   // We rank reversed + different operator as worse than just reversed, but
9490   // that comparison can never happen, because we only consider reversing for
9491   // the maximally-rewritten operator (== or <=>).
9492   if (Cand1.RewriteKind != Cand2.RewriteKind)
9493     return Cand1.RewriteKind < Cand2.RewriteKind;
9494 
9495   // Check C++17 tie-breakers for deduction guides.
9496   {
9497     auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9498     auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9499     if (Guide1 && Guide2) {
9500       //  -- F1 is generated from a deduction-guide and F2 is not
9501       if (Guide1->isImplicit() != Guide2->isImplicit())
9502         return Guide2->isImplicit();
9503 
9504       //  -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9505       if (Guide1->isCopyDeductionCandidate())
9506         return true;
9507     }
9508   }
9509 
9510   // Check for enable_if value-based overload resolution.
9511   if (Cand1.Function && Cand2.Function) {
9512     Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9513     if (Cmp != Comparison::Equal)
9514       return Cmp == Comparison::Better;
9515   }
9516 
9517   if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9518     FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9519     return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9520            S.IdentifyCUDAPreference(Caller, Cand2.Function);
9521   }
9522 
9523   bool HasPS1 = Cand1.Function != nullptr &&
9524                 functionHasPassObjectSizeParams(Cand1.Function);
9525   bool HasPS2 = Cand2.Function != nullptr &&
9526                 functionHasPassObjectSizeParams(Cand2.Function);
9527   if (HasPS1 != HasPS2 && HasPS1)
9528     return true;
9529 
9530   return isBetterMultiversionCandidate(Cand1, Cand2);
9531 }
9532 
9533 /// Determine whether two declarations are "equivalent" for the purposes of
9534 /// name lookup and overload resolution. This applies when the same internal/no
9535 /// linkage entity is defined by two modules (probably by textually including
9536 /// the same header). In such a case, we don't consider the declarations to
9537 /// declare the same entity, but we also don't want lookups with both
9538 /// declarations visible to be ambiguous in some cases (this happens when using
9539 /// a modularized libstdc++).
9540 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9541                                                   const NamedDecl *B) {
9542   auto *VA = dyn_cast_or_null<ValueDecl>(A);
9543   auto *VB = dyn_cast_or_null<ValueDecl>(B);
9544   if (!VA || !VB)
9545     return false;
9546 
9547   // The declarations must be declaring the same name as an internal linkage
9548   // entity in different modules.
9549   if (!VA->getDeclContext()->getRedeclContext()->Equals(
9550           VB->getDeclContext()->getRedeclContext()) ||
9551       getOwningModule(const_cast<ValueDecl *>(VA)) ==
9552           getOwningModule(const_cast<ValueDecl *>(VB)) ||
9553       VA->isExternallyVisible() || VB->isExternallyVisible())
9554     return false;
9555 
9556   // Check that the declarations appear to be equivalent.
9557   //
9558   // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9559   // For constants and functions, we should check the initializer or body is
9560   // the same. For non-constant variables, we shouldn't allow it at all.
9561   if (Context.hasSameType(VA->getType(), VB->getType()))
9562     return true;
9563 
9564   // Enum constants within unnamed enumerations will have different types, but
9565   // may still be similar enough to be interchangeable for our purposes.
9566   if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9567     if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9568       // Only handle anonymous enums. If the enumerations were named and
9569       // equivalent, they would have been merged to the same type.
9570       auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9571       auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9572       if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9573           !Context.hasSameType(EnumA->getIntegerType(),
9574                                EnumB->getIntegerType()))
9575         return false;
9576       // Allow this only if the value is the same for both enumerators.
9577       return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9578     }
9579   }
9580 
9581   // Nothing else is sufficiently similar.
9582   return false;
9583 }
9584 
9585 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9586     SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9587   Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9588 
9589   Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9590   Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9591       << !M << (M ? M->getFullModuleName() : "");
9592 
9593   for (auto *E : Equiv) {
9594     Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9595     Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9596         << !M << (M ? M->getFullModuleName() : "");
9597   }
9598 }
9599 
9600 /// Computes the best viable function (C++ 13.3.3)
9601 /// within an overload candidate set.
9602 ///
9603 /// \param Loc The location of the function name (or operator symbol) for
9604 /// which overload resolution occurs.
9605 ///
9606 /// \param Best If overload resolution was successful or found a deleted
9607 /// function, \p Best points to the candidate function found.
9608 ///
9609 /// \returns The result of overload resolution.
9610 OverloadingResult
9611 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9612                                          iterator &Best) {
9613   llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9614   std::transform(begin(), end(), std::back_inserter(Candidates),
9615                  [](OverloadCandidate &Cand) { return &Cand; });
9616 
9617   // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9618   // are accepted by both clang and NVCC. However, during a particular
9619   // compilation mode only one call variant is viable. We need to
9620   // exclude non-viable overload candidates from consideration based
9621   // only on their host/device attributes. Specifically, if one
9622   // candidate call is WrongSide and the other is SameSide, we ignore
9623   // the WrongSide candidate.
9624   if (S.getLangOpts().CUDA) {
9625     const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9626     bool ContainsSameSideCandidate =
9627         llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9628           // Check viable function only.
9629           return Cand->Viable && Cand->Function &&
9630                  S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9631                      Sema::CFP_SameSide;
9632         });
9633     if (ContainsSameSideCandidate) {
9634       auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9635         // Check viable function only to avoid unnecessary data copying/moving.
9636         return Cand->Viable && Cand->Function &&
9637                S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9638                    Sema::CFP_WrongSide;
9639       };
9640       llvm::erase_if(Candidates, IsWrongSideCandidate);
9641     }
9642   }
9643 
9644   // Find the best viable function.
9645   Best = end();
9646   for (auto *Cand : Candidates) {
9647     Cand->Best = false;
9648     if (Cand->Viable)
9649       if (Best == end() ||
9650           isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9651         Best = Cand;
9652   }
9653 
9654   // If we didn't find any viable functions, abort.
9655   if (Best == end())
9656     return OR_No_Viable_Function;
9657 
9658   llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9659 
9660   llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9661   PendingBest.push_back(&*Best);
9662   Best->Best = true;
9663 
9664   // Make sure that this function is better than every other viable
9665   // function. If not, we have an ambiguity.
9666   while (!PendingBest.empty()) {
9667     auto *Curr = PendingBest.pop_back_val();
9668     for (auto *Cand : Candidates) {
9669       if (Cand->Viable && !Cand->Best &&
9670           !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9671         PendingBest.push_back(Cand);
9672         Cand->Best = true;
9673 
9674         if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9675                                                      Curr->Function))
9676           EquivalentCands.push_back(Cand->Function);
9677         else
9678           Best = end();
9679       }
9680     }
9681   }
9682 
9683   // If we found more than one best candidate, this is ambiguous.
9684   if (Best == end())
9685     return OR_Ambiguous;
9686 
9687   // Best is the best viable function.
9688   if (Best->Function && Best->Function->isDeleted())
9689     return OR_Deleted;
9690 
9691   if (!EquivalentCands.empty())
9692     S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9693                                                     EquivalentCands);
9694 
9695   return OR_Success;
9696 }
9697 
9698 namespace {
9699 
9700 enum OverloadCandidateKind {
9701   oc_function,
9702   oc_method,
9703   oc_reversed_binary_operator,
9704   oc_constructor,
9705   oc_implicit_default_constructor,
9706   oc_implicit_copy_constructor,
9707   oc_implicit_move_constructor,
9708   oc_implicit_copy_assignment,
9709   oc_implicit_move_assignment,
9710   oc_implicit_equality_comparison,
9711   oc_inherited_constructor
9712 };
9713 
9714 enum OverloadCandidateSelect {
9715   ocs_non_template,
9716   ocs_template,
9717   ocs_described_template,
9718 };
9719 
9720 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9721 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9722                           OverloadCandidateRewriteKind CRK,
9723                           std::string &Description) {
9724 
9725   bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9726   if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9727     isTemplate = true;
9728     Description = S.getTemplateArgumentBindingsText(
9729         FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9730   }
9731 
9732   OverloadCandidateSelect Select = [&]() {
9733     if (!Description.empty())
9734       return ocs_described_template;
9735     return isTemplate ? ocs_template : ocs_non_template;
9736   }();
9737 
9738   OverloadCandidateKind Kind = [&]() {
9739     if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9740       return oc_implicit_equality_comparison;
9741 
9742     if (CRK & CRK_Reversed)
9743       return oc_reversed_binary_operator;
9744 
9745     if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9746       if (!Ctor->isImplicit()) {
9747         if (isa<ConstructorUsingShadowDecl>(Found))
9748           return oc_inherited_constructor;
9749         else
9750           return oc_constructor;
9751       }
9752 
9753       if (Ctor->isDefaultConstructor())
9754         return oc_implicit_default_constructor;
9755 
9756       if (Ctor->isMoveConstructor())
9757         return oc_implicit_move_constructor;
9758 
9759       assert(Ctor->isCopyConstructor() &&
9760              "unexpected sort of implicit constructor");
9761       return oc_implicit_copy_constructor;
9762     }
9763 
9764     if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9765       // This actually gets spelled 'candidate function' for now, but
9766       // it doesn't hurt to split it out.
9767       if (!Meth->isImplicit())
9768         return oc_method;
9769 
9770       if (Meth->isMoveAssignmentOperator())
9771         return oc_implicit_move_assignment;
9772 
9773       if (Meth->isCopyAssignmentOperator())
9774         return oc_implicit_copy_assignment;
9775 
9776       assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9777       return oc_method;
9778     }
9779 
9780     return oc_function;
9781   }();
9782 
9783   return std::make_pair(Kind, Select);
9784 }
9785 
9786 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9787   // FIXME: It'd be nice to only emit a note once per using-decl per overload
9788   // set.
9789   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9790     S.Diag(FoundDecl->getLocation(),
9791            diag::note_ovl_candidate_inherited_constructor)
9792       << Shadow->getNominatedBaseClass();
9793 }
9794 
9795 } // end anonymous namespace
9796 
9797 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9798                                     const FunctionDecl *FD) {
9799   for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9800     bool AlwaysTrue;
9801     if (EnableIf->getCond()->isValueDependent() ||
9802         !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9803       return false;
9804     if (!AlwaysTrue)
9805       return false;
9806   }
9807   return true;
9808 }
9809 
9810 /// Returns true if we can take the address of the function.
9811 ///
9812 /// \param Complain - If true, we'll emit a diagnostic
9813 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9814 ///   we in overload resolution?
9815 /// \param Loc - The location of the statement we're complaining about. Ignored
9816 ///   if we're not complaining, or if we're in overload resolution.
9817 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9818                                               bool Complain,
9819                                               bool InOverloadResolution,
9820                                               SourceLocation Loc) {
9821   if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9822     if (Complain) {
9823       if (InOverloadResolution)
9824         S.Diag(FD->getBeginLoc(),
9825                diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9826       else
9827         S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9828     }
9829     return false;
9830   }
9831 
9832   auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9833     return P->hasAttr<PassObjectSizeAttr>();
9834   });
9835   if (I == FD->param_end())
9836     return true;
9837 
9838   if (Complain) {
9839     // Add one to ParamNo because it's user-facing
9840     unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9841     if (InOverloadResolution)
9842       S.Diag(FD->getLocation(),
9843              diag::note_ovl_candidate_has_pass_object_size_params)
9844           << ParamNo;
9845     else
9846       S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9847           << FD << ParamNo;
9848   }
9849   return false;
9850 }
9851 
9852 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9853                                                const FunctionDecl *FD) {
9854   return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9855                                            /*InOverloadResolution=*/true,
9856                                            /*Loc=*/SourceLocation());
9857 }
9858 
9859 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9860                                              bool Complain,
9861                                              SourceLocation Loc) {
9862   return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9863                                              /*InOverloadResolution=*/false,
9864                                              Loc);
9865 }
9866 
9867 // Notes the location of an overload candidate.
9868 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9869                                  OverloadCandidateRewriteKind RewriteKind,
9870                                  QualType DestType, bool TakingAddress) {
9871   if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9872     return;
9873   if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9874       !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9875     return;
9876 
9877   std::string FnDesc;
9878   std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9879       ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
9880   PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9881                          << (unsigned)KSPair.first << (unsigned)KSPair.second
9882                          << Fn << FnDesc;
9883 
9884   HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9885   Diag(Fn->getLocation(), PD);
9886   MaybeEmitInheritedConstructorNote(*this, Found);
9887 }
9888 
9889 // Notes the location of all overload candidates designated through
9890 // OverloadedExpr
9891 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9892                                      bool TakingAddress) {
9893   assert(OverloadedExpr->getType() == Context.OverloadTy);
9894 
9895   OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9896   OverloadExpr *OvlExpr = Ovl.Expression;
9897 
9898   for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9899                             IEnd = OvlExpr->decls_end();
9900        I != IEnd; ++I) {
9901     if (FunctionTemplateDecl *FunTmpl =
9902                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9903       NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
9904                             TakingAddress);
9905     } else if (FunctionDecl *Fun
9906                       = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9907       NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
9908     }
9909   }
9910 }
9911 
9912 /// Diagnoses an ambiguous conversion.  The partial diagnostic is the
9913 /// "lead" diagnostic; it will be given two arguments, the source and
9914 /// target types of the conversion.
9915 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9916                                  Sema &S,
9917                                  SourceLocation CaretLoc,
9918                                  const PartialDiagnostic &PDiag) const {
9919   S.Diag(CaretLoc, PDiag)
9920     << Ambiguous.getFromType() << Ambiguous.getToType();
9921   // FIXME: The note limiting machinery is borrowed from
9922   // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9923   // refactoring here.
9924   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9925   unsigned CandsShown = 0;
9926   AmbiguousConversionSequence::const_iterator I, E;
9927   for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9928     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9929       break;
9930     ++CandsShown;
9931     S.NoteOverloadCandidate(I->first, I->second);
9932   }
9933   if (I != E)
9934     S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9935 }
9936 
9937 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9938                                   unsigned I, bool TakingCandidateAddress) {
9939   const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9940   assert(Conv.isBad());
9941   assert(Cand->Function && "for now, candidate must be a function");
9942   FunctionDecl *Fn = Cand->Function;
9943 
9944   // There's a conversion slot for the object argument if this is a
9945   // non-constructor method.  Note that 'I' corresponds the
9946   // conversion-slot index.
9947   bool isObjectArgument = false;
9948   if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9949     if (I == 0)
9950       isObjectArgument = true;
9951     else
9952       I--;
9953   }
9954 
9955   std::string FnDesc;
9956   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9957       ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
9958                                 FnDesc);
9959 
9960   Expr *FromExpr = Conv.Bad.FromExpr;
9961   QualType FromTy = Conv.Bad.getFromType();
9962   QualType ToTy = Conv.Bad.getToType();
9963 
9964   if (FromTy == S.Context.OverloadTy) {
9965     assert(FromExpr && "overload set argument came from implicit argument?");
9966     Expr *E = FromExpr->IgnoreParens();
9967     if (isa<UnaryOperator>(E))
9968       E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9969     DeclarationName Name = cast<OverloadExpr>(E)->getName();
9970 
9971     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9972         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9973         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9974         << Name << I + 1;
9975     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9976     return;
9977   }
9978 
9979   // Do some hand-waving analysis to see if the non-viability is due
9980   // to a qualifier mismatch.
9981   CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9982   CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9983   if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9984     CToTy = RT->getPointeeType();
9985   else {
9986     // TODO: detect and diagnose the full richness of const mismatches.
9987     if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9988       if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9989         CFromTy = FromPT->getPointeeType();
9990         CToTy = ToPT->getPointeeType();
9991       }
9992   }
9993 
9994   if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9995       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9996     Qualifiers FromQs = CFromTy.getQualifiers();
9997     Qualifiers ToQs = CToTy.getQualifiers();
9998 
9999     if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10000       if (isObjectArgument)
10001         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10002             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10003             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10004             << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10005       else
10006         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10007             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10008             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10009             << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10010             << ToTy->isReferenceType() << I + 1;
10011       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10012       return;
10013     }
10014 
10015     if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10016       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10017           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10018           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10019           << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10020           << (unsigned)isObjectArgument << I + 1;
10021       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10022       return;
10023     }
10024 
10025     if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10026       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10027           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10028           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10029           << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10030           << (unsigned)isObjectArgument << I + 1;
10031       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10032       return;
10033     }
10034 
10035     if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10036       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10037           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10038           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10039           << FromQs.hasUnaligned() << I + 1;
10040       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10041       return;
10042     }
10043 
10044     unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10045     assert(CVR && "unexpected qualifiers mismatch");
10046 
10047     if (isObjectArgument) {
10048       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10049           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10050           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10051           << (CVR - 1);
10052     } else {
10053       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10054           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10055           << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10056           << (CVR - 1) << I + 1;
10057     }
10058     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10059     return;
10060   }
10061 
10062   // Special diagnostic for failure to convert an initializer list, since
10063   // telling the user that it has type void is not useful.
10064   if (FromExpr && isa<InitListExpr>(FromExpr)) {
10065     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10066         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10067         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10068         << ToTy << (unsigned)isObjectArgument << I + 1;
10069     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10070     return;
10071   }
10072 
10073   // Diagnose references or pointers to incomplete types differently,
10074   // since it's far from impossible that the incompleteness triggered
10075   // the failure.
10076   QualType TempFromTy = FromTy.getNonReferenceType();
10077   if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10078     TempFromTy = PTy->getPointeeType();
10079   if (TempFromTy->isIncompleteType()) {
10080     // Emit the generic diagnostic and, optionally, add the hints to it.
10081     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10082         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10083         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10084         << ToTy << (unsigned)isObjectArgument << I + 1
10085         << (unsigned)(Cand->Fix.Kind);
10086 
10087     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10088     return;
10089   }
10090 
10091   // Diagnose base -> derived pointer conversions.
10092   unsigned BaseToDerivedConversion = 0;
10093   if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10094     if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10095       if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10096                                                FromPtrTy->getPointeeType()) &&
10097           !FromPtrTy->getPointeeType()->isIncompleteType() &&
10098           !ToPtrTy->getPointeeType()->isIncompleteType() &&
10099           S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10100                           FromPtrTy->getPointeeType()))
10101         BaseToDerivedConversion = 1;
10102     }
10103   } else if (const ObjCObjectPointerType *FromPtrTy
10104                                     = FromTy->getAs<ObjCObjectPointerType>()) {
10105     if (const ObjCObjectPointerType *ToPtrTy
10106                                         = ToTy->getAs<ObjCObjectPointerType>())
10107       if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10108         if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10109           if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10110                                                 FromPtrTy->getPointeeType()) &&
10111               FromIface->isSuperClassOf(ToIface))
10112             BaseToDerivedConversion = 2;
10113   } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10114     if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10115         !FromTy->isIncompleteType() &&
10116         !ToRefTy->getPointeeType()->isIncompleteType() &&
10117         S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10118       BaseToDerivedConversion = 3;
10119     } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10120                ToTy.getNonReferenceType().getCanonicalType() ==
10121                FromTy.getNonReferenceType().getCanonicalType()) {
10122       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10123           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10124           << (unsigned)isObjectArgument << I + 1
10125           << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10126       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10127       return;
10128     }
10129   }
10130 
10131   if (BaseToDerivedConversion) {
10132     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10133         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10134         << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10135         << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10136     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10137     return;
10138   }
10139 
10140   if (isa<ObjCObjectPointerType>(CFromTy) &&
10141       isa<PointerType>(CToTy)) {
10142       Qualifiers FromQs = CFromTy.getQualifiers();
10143       Qualifiers ToQs = CToTy.getQualifiers();
10144       if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10145         S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10146             << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10147             << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10148             << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10149         MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10150         return;
10151       }
10152   }
10153 
10154   if (TakingCandidateAddress &&
10155       !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10156     return;
10157 
10158   // Emit the generic diagnostic and, optionally, add the hints to it.
10159   PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10160   FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10161         << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10162         << ToTy << (unsigned)isObjectArgument << I + 1
10163         << (unsigned)(Cand->Fix.Kind);
10164 
10165   // If we can fix the conversion, suggest the FixIts.
10166   for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10167        HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10168     FDiag << *HI;
10169   S.Diag(Fn->getLocation(), FDiag);
10170 
10171   MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10172 }
10173 
10174 /// Additional arity mismatch diagnosis specific to a function overload
10175 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10176 /// over a candidate in any candidate set.
10177 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10178                                unsigned NumArgs) {
10179   FunctionDecl *Fn = Cand->Function;
10180   unsigned MinParams = Fn->getMinRequiredArguments();
10181 
10182   // With invalid overloaded operators, it's possible that we think we
10183   // have an arity mismatch when in fact it looks like we have the
10184   // right number of arguments, because only overloaded operators have
10185   // the weird behavior of overloading member and non-member functions.
10186   // Just don't report anything.
10187   if (Fn->isInvalidDecl() &&
10188       Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10189     return true;
10190 
10191   if (NumArgs < MinParams) {
10192     assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10193            (Cand->FailureKind == ovl_fail_bad_deduction &&
10194             Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10195   } else {
10196     assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10197            (Cand->FailureKind == ovl_fail_bad_deduction &&
10198             Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10199   }
10200 
10201   return false;
10202 }
10203 
10204 /// General arity mismatch diagnosis over a candidate in a candidate set.
10205 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10206                                   unsigned NumFormalArgs) {
10207   assert(isa<FunctionDecl>(D) &&
10208       "The templated declaration should at least be a function"
10209       " when diagnosing bad template argument deduction due to too many"
10210       " or too few arguments");
10211 
10212   FunctionDecl *Fn = cast<FunctionDecl>(D);
10213 
10214   // TODO: treat calls to a missing default constructor as a special case
10215   const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10216   unsigned MinParams = Fn->getMinRequiredArguments();
10217 
10218   // at least / at most / exactly
10219   unsigned mode, modeCount;
10220   if (NumFormalArgs < MinParams) {
10221     if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10222         FnTy->isTemplateVariadic())
10223       mode = 0; // "at least"
10224     else
10225       mode = 2; // "exactly"
10226     modeCount = MinParams;
10227   } else {
10228     if (MinParams != FnTy->getNumParams())
10229       mode = 1; // "at most"
10230     else
10231       mode = 2; // "exactly"
10232     modeCount = FnTy->getNumParams();
10233   }
10234 
10235   std::string Description;
10236   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10237       ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10238 
10239   if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10240     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10241         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10242         << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10243   else
10244     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10245         << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10246         << Description << mode << modeCount << NumFormalArgs;
10247 
10248   MaybeEmitInheritedConstructorNote(S, Found);
10249 }
10250 
10251 /// Arity mismatch diagnosis specific to a function overload candidate.
10252 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10253                                   unsigned NumFormalArgs) {
10254   if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10255     DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10256 }
10257 
10258 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10259   if (TemplateDecl *TD = Templated->getDescribedTemplate())
10260     return TD;
10261   llvm_unreachable("Unsupported: Getting the described template declaration"
10262                    " for bad deduction diagnosis");
10263 }
10264 
10265 /// Diagnose a failed template-argument deduction.
10266 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10267                                  DeductionFailureInfo &DeductionFailure,
10268                                  unsigned NumArgs,
10269                                  bool TakingCandidateAddress) {
10270   TemplateParameter Param = DeductionFailure.getTemplateParameter();
10271   NamedDecl *ParamD;
10272   (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10273   (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10274   (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10275   switch (DeductionFailure.Result) {
10276   case Sema::TDK_Success:
10277     llvm_unreachable("TDK_success while diagnosing bad deduction");
10278 
10279   case Sema::TDK_Incomplete: {
10280     assert(ParamD && "no parameter found for incomplete deduction result");
10281     S.Diag(Templated->getLocation(),
10282            diag::note_ovl_candidate_incomplete_deduction)
10283         << ParamD->getDeclName();
10284     MaybeEmitInheritedConstructorNote(S, Found);
10285     return;
10286   }
10287 
10288   case Sema::TDK_IncompletePack: {
10289     assert(ParamD && "no parameter found for incomplete deduction result");
10290     S.Diag(Templated->getLocation(),
10291            diag::note_ovl_candidate_incomplete_deduction_pack)
10292         << ParamD->getDeclName()
10293         << (DeductionFailure.getFirstArg()->pack_size() + 1)
10294         << *DeductionFailure.getFirstArg();
10295     MaybeEmitInheritedConstructorNote(S, Found);
10296     return;
10297   }
10298 
10299   case Sema::TDK_Underqualified: {
10300     assert(ParamD && "no parameter found for bad qualifiers deduction result");
10301     TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10302 
10303     QualType Param = DeductionFailure.getFirstArg()->getAsType();
10304 
10305     // Param will have been canonicalized, but it should just be a
10306     // qualified version of ParamD, so move the qualifiers to that.
10307     QualifierCollector Qs;
10308     Qs.strip(Param);
10309     QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10310     assert(S.Context.hasSameType(Param, NonCanonParam));
10311 
10312     // Arg has also been canonicalized, but there's nothing we can do
10313     // about that.  It also doesn't matter as much, because it won't
10314     // have any template parameters in it (because deduction isn't
10315     // done on dependent types).
10316     QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10317 
10318     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10319         << ParamD->getDeclName() << Arg << NonCanonParam;
10320     MaybeEmitInheritedConstructorNote(S, Found);
10321     return;
10322   }
10323 
10324   case Sema::TDK_Inconsistent: {
10325     assert(ParamD && "no parameter found for inconsistent deduction result");
10326     int which = 0;
10327     if (isa<TemplateTypeParmDecl>(ParamD))
10328       which = 0;
10329     else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10330       // Deduction might have failed because we deduced arguments of two
10331       // different types for a non-type template parameter.
10332       // FIXME: Use a different TDK value for this.
10333       QualType T1 =
10334           DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10335       QualType T2 =
10336           DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10337       if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10338         S.Diag(Templated->getLocation(),
10339                diag::note_ovl_candidate_inconsistent_deduction_types)
10340           << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10341           << *DeductionFailure.getSecondArg() << T2;
10342         MaybeEmitInheritedConstructorNote(S, Found);
10343         return;
10344       }
10345 
10346       which = 1;
10347     } else {
10348       which = 2;
10349     }
10350 
10351     // Tweak the diagnostic if the problem is that we deduced packs of
10352     // different arities. We'll print the actual packs anyway in case that
10353     // includes additional useful information.
10354     if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10355         DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10356         DeductionFailure.getFirstArg()->pack_size() !=
10357             DeductionFailure.getSecondArg()->pack_size()) {
10358       which = 3;
10359     }
10360 
10361     S.Diag(Templated->getLocation(),
10362            diag::note_ovl_candidate_inconsistent_deduction)
10363         << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10364         << *DeductionFailure.getSecondArg();
10365     MaybeEmitInheritedConstructorNote(S, Found);
10366     return;
10367   }
10368 
10369   case Sema::TDK_InvalidExplicitArguments:
10370     assert(ParamD && "no parameter found for invalid explicit arguments");
10371     if (ParamD->getDeclName())
10372       S.Diag(Templated->getLocation(),
10373              diag::note_ovl_candidate_explicit_arg_mismatch_named)
10374           << ParamD->getDeclName();
10375     else {
10376       int index = 0;
10377       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10378         index = TTP->getIndex();
10379       else if (NonTypeTemplateParmDecl *NTTP
10380                                   = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10381         index = NTTP->getIndex();
10382       else
10383         index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10384       S.Diag(Templated->getLocation(),
10385              diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10386           << (index + 1);
10387     }
10388     MaybeEmitInheritedConstructorNote(S, Found);
10389     return;
10390 
10391   case Sema::TDK_ConstraintsNotSatisfied: {
10392     // Format the template argument list into the argument string.
10393     SmallString<128> TemplateArgString;
10394     TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10395     TemplateArgString = " ";
10396     TemplateArgString += S.getTemplateArgumentBindingsText(
10397         getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10398     if (TemplateArgString.size() == 1)
10399       TemplateArgString.clear();
10400     S.Diag(Templated->getLocation(),
10401            diag::note_ovl_candidate_unsatisfied_constraints)
10402         << TemplateArgString;
10403 
10404     S.DiagnoseUnsatisfiedConstraint(
10405         static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10406     return;
10407   }
10408   case Sema::TDK_TooManyArguments:
10409   case Sema::TDK_TooFewArguments:
10410     DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10411     return;
10412 
10413   case Sema::TDK_InstantiationDepth:
10414     S.Diag(Templated->getLocation(),
10415            diag::note_ovl_candidate_instantiation_depth);
10416     MaybeEmitInheritedConstructorNote(S, Found);
10417     return;
10418 
10419   case Sema::TDK_SubstitutionFailure: {
10420     // Format the template argument list into the argument string.
10421     SmallString<128> TemplateArgString;
10422     if (TemplateArgumentList *Args =
10423             DeductionFailure.getTemplateArgumentList()) {
10424       TemplateArgString = " ";
10425       TemplateArgString += S.getTemplateArgumentBindingsText(
10426           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10427       if (TemplateArgString.size() == 1)
10428         TemplateArgString.clear();
10429     }
10430 
10431     // If this candidate was disabled by enable_if, say so.
10432     PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10433     if (PDiag && PDiag->second.getDiagID() ==
10434           diag::err_typename_nested_not_found_enable_if) {
10435       // FIXME: Use the source range of the condition, and the fully-qualified
10436       //        name of the enable_if template. These are both present in PDiag.
10437       S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10438         << "'enable_if'" << TemplateArgString;
10439       return;
10440     }
10441 
10442     // We found a specific requirement that disabled the enable_if.
10443     if (PDiag && PDiag->second.getDiagID() ==
10444         diag::err_typename_nested_not_found_requirement) {
10445       S.Diag(Templated->getLocation(),
10446              diag::note_ovl_candidate_disabled_by_requirement)
10447         << PDiag->second.getStringArg(0) << TemplateArgString;
10448       return;
10449     }
10450 
10451     // Format the SFINAE diagnostic into the argument string.
10452     // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10453     //        formatted message in another diagnostic.
10454     SmallString<128> SFINAEArgString;
10455     SourceRange R;
10456     if (PDiag) {
10457       SFINAEArgString = ": ";
10458       R = SourceRange(PDiag->first, PDiag->first);
10459       PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10460     }
10461 
10462     S.Diag(Templated->getLocation(),
10463            diag::note_ovl_candidate_substitution_failure)
10464         << TemplateArgString << SFINAEArgString << R;
10465     MaybeEmitInheritedConstructorNote(S, Found);
10466     return;
10467   }
10468 
10469   case Sema::TDK_DeducedMismatch:
10470   case Sema::TDK_DeducedMismatchNested: {
10471     // Format the template argument list into the argument string.
10472     SmallString<128> TemplateArgString;
10473     if (TemplateArgumentList *Args =
10474             DeductionFailure.getTemplateArgumentList()) {
10475       TemplateArgString = " ";
10476       TemplateArgString += S.getTemplateArgumentBindingsText(
10477           getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10478       if (TemplateArgString.size() == 1)
10479         TemplateArgString.clear();
10480     }
10481 
10482     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10483         << (*DeductionFailure.getCallArgIndex() + 1)
10484         << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10485         << TemplateArgString
10486         << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10487     break;
10488   }
10489 
10490   case Sema::TDK_NonDeducedMismatch: {
10491     // FIXME: Provide a source location to indicate what we couldn't match.
10492     TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10493     TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10494     if (FirstTA.getKind() == TemplateArgument::Template &&
10495         SecondTA.getKind() == TemplateArgument::Template) {
10496       TemplateName FirstTN = FirstTA.getAsTemplate();
10497       TemplateName SecondTN = SecondTA.getAsTemplate();
10498       if (FirstTN.getKind() == TemplateName::Template &&
10499           SecondTN.getKind() == TemplateName::Template) {
10500         if (FirstTN.getAsTemplateDecl()->getName() ==
10501             SecondTN.getAsTemplateDecl()->getName()) {
10502           // FIXME: This fixes a bad diagnostic where both templates are named
10503           // the same.  This particular case is a bit difficult since:
10504           // 1) It is passed as a string to the diagnostic printer.
10505           // 2) The diagnostic printer only attempts to find a better
10506           //    name for types, not decls.
10507           // Ideally, this should folded into the diagnostic printer.
10508           S.Diag(Templated->getLocation(),
10509                  diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10510               << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10511           return;
10512         }
10513       }
10514     }
10515 
10516     if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10517         !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10518       return;
10519 
10520     // FIXME: For generic lambda parameters, check if the function is a lambda
10521     // call operator, and if so, emit a prettier and more informative
10522     // diagnostic that mentions 'auto' and lambda in addition to
10523     // (or instead of?) the canonical template type parameters.
10524     S.Diag(Templated->getLocation(),
10525            diag::note_ovl_candidate_non_deduced_mismatch)
10526         << FirstTA << SecondTA;
10527     return;
10528   }
10529   // TODO: diagnose these individually, then kill off
10530   // note_ovl_candidate_bad_deduction, which is uselessly vague.
10531   case Sema::TDK_MiscellaneousDeductionFailure:
10532     S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10533     MaybeEmitInheritedConstructorNote(S, Found);
10534     return;
10535   case Sema::TDK_CUDATargetMismatch:
10536     S.Diag(Templated->getLocation(),
10537            diag::note_cuda_ovl_candidate_target_mismatch);
10538     return;
10539   }
10540 }
10541 
10542 /// Diagnose a failed template-argument deduction, for function calls.
10543 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10544                                  unsigned NumArgs,
10545                                  bool TakingCandidateAddress) {
10546   unsigned TDK = Cand->DeductionFailure.Result;
10547   if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10548     if (CheckArityMismatch(S, Cand, NumArgs))
10549       return;
10550   }
10551   DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10552                        Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10553 }
10554 
10555 /// CUDA: diagnose an invalid call across targets.
10556 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10557   FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10558   FunctionDecl *Callee = Cand->Function;
10559 
10560   Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10561                            CalleeTarget = S.IdentifyCUDATarget(Callee);
10562 
10563   std::string FnDesc;
10564   std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10565       ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10566                                 Cand->getRewriteKind(), FnDesc);
10567 
10568   S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10569       << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10570       << FnDesc /* Ignored */
10571       << CalleeTarget << CallerTarget;
10572 
10573   // This could be an implicit constructor for which we could not infer the
10574   // target due to a collsion. Diagnose that case.
10575   CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10576   if (Meth != nullptr && Meth->isImplicit()) {
10577     CXXRecordDecl *ParentClass = Meth->getParent();
10578     Sema::CXXSpecialMember CSM;
10579 
10580     switch (FnKindPair.first) {
10581     default:
10582       return;
10583     case oc_implicit_default_constructor:
10584       CSM = Sema::CXXDefaultConstructor;
10585       break;
10586     case oc_implicit_copy_constructor:
10587       CSM = Sema::CXXCopyConstructor;
10588       break;
10589     case oc_implicit_move_constructor:
10590       CSM = Sema::CXXMoveConstructor;
10591       break;
10592     case oc_implicit_copy_assignment:
10593       CSM = Sema::CXXCopyAssignment;
10594       break;
10595     case oc_implicit_move_assignment:
10596       CSM = Sema::CXXMoveAssignment;
10597       break;
10598     };
10599 
10600     bool ConstRHS = false;
10601     if (Meth->getNumParams()) {
10602       if (const ReferenceType *RT =
10603               Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10604         ConstRHS = RT->getPointeeType().isConstQualified();
10605       }
10606     }
10607 
10608     S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10609                                               /* ConstRHS */ ConstRHS,
10610                                               /* Diagnose */ true);
10611   }
10612 }
10613 
10614 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10615   FunctionDecl *Callee = Cand->Function;
10616   EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10617 
10618   S.Diag(Callee->getLocation(),
10619          diag::note_ovl_candidate_disabled_by_function_cond_attr)
10620       << Attr->getCond()->getSourceRange() << Attr->getMessage();
10621 }
10622 
10623 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10624   ExplicitSpecifier ES;
10625   const char *DeclName;
10626   switch (Cand->Function->getDeclKind()) {
10627   case Decl::Kind::CXXConstructor:
10628     ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10629     DeclName = "constructor";
10630     break;
10631   case Decl::Kind::CXXConversion:
10632     ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10633     DeclName = "conversion operator";
10634     break;
10635   case Decl::Kind::CXXDeductionGuide:
10636     ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10637     DeclName = "deductiong guide";
10638     break;
10639   default:
10640     llvm_unreachable("invalid Decl");
10641   }
10642   assert(ES.getExpr() && "null expression should be handled before");
10643   S.Diag(Cand->Function->getLocation(),
10644          diag::note_ovl_candidate_explicit_forbidden)
10645       << DeclName;
10646   S.Diag(ES.getExpr()->getBeginLoc(),
10647          diag::note_explicit_bool_resolved_to_true);
10648 }
10649 
10650 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10651   FunctionDecl *Callee = Cand->Function;
10652 
10653   S.Diag(Callee->getLocation(),
10654          diag::note_ovl_candidate_disabled_by_extension)
10655     << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10656 }
10657 
10658 /// Generates a 'note' diagnostic for an overload candidate.  We've
10659 /// already generated a primary error at the call site.
10660 ///
10661 /// It really does need to be a single diagnostic with its caret
10662 /// pointed at the candidate declaration.  Yes, this creates some
10663 /// major challenges of technical writing.  Yes, this makes pointing
10664 /// out problems with specific arguments quite awkward.  It's still
10665 /// better than generating twenty screens of text for every failed
10666 /// overload.
10667 ///
10668 /// It would be great to be able to express per-candidate problems
10669 /// more richly for those diagnostic clients that cared, but we'd
10670 /// still have to be just as careful with the default diagnostics.
10671 /// \param CtorDestAS Addr space of object being constructed (for ctor
10672 /// candidates only).
10673 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10674                                   unsigned NumArgs,
10675                                   bool TakingCandidateAddress,
10676                                   LangAS CtorDestAS = LangAS::Default) {
10677   FunctionDecl *Fn = Cand->Function;
10678 
10679   // Note deleted candidates, but only if they're viable.
10680   if (Cand->Viable) {
10681     if (Fn->isDeleted()) {
10682       std::string FnDesc;
10683       std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10684           ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10685                                     Cand->getRewriteKind(), FnDesc);
10686 
10687       S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10688           << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10689           << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10690       MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10691       return;
10692     }
10693 
10694     // We don't really have anything else to say about viable candidates.
10695     S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10696     return;
10697   }
10698 
10699   switch (Cand->FailureKind) {
10700   case ovl_fail_too_many_arguments:
10701   case ovl_fail_too_few_arguments:
10702     return DiagnoseArityMismatch(S, Cand, NumArgs);
10703 
10704   case ovl_fail_bad_deduction:
10705     return DiagnoseBadDeduction(S, Cand, NumArgs,
10706                                 TakingCandidateAddress);
10707 
10708   case ovl_fail_illegal_constructor: {
10709     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10710       << (Fn->getPrimaryTemplate() ? 1 : 0);
10711     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10712     return;
10713   }
10714 
10715   case ovl_fail_object_addrspace_mismatch: {
10716     Qualifiers QualsForPrinting;
10717     QualsForPrinting.setAddressSpace(CtorDestAS);
10718     S.Diag(Fn->getLocation(),
10719            diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10720         << QualsForPrinting;
10721     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10722     return;
10723   }
10724 
10725   case ovl_fail_trivial_conversion:
10726   case ovl_fail_bad_final_conversion:
10727   case ovl_fail_final_conversion_not_exact:
10728     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10729 
10730   case ovl_fail_bad_conversion: {
10731     unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10732     for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10733       if (Cand->Conversions[I].isBad())
10734         return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10735 
10736     // FIXME: this currently happens when we're called from SemaInit
10737     // when user-conversion overload fails.  Figure out how to handle
10738     // those conditions and diagnose them well.
10739     return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10740   }
10741 
10742   case ovl_fail_bad_target:
10743     return DiagnoseBadTarget(S, Cand);
10744 
10745   case ovl_fail_enable_if:
10746     return DiagnoseFailedEnableIfAttr(S, Cand);
10747 
10748   case ovl_fail_explicit_resolved:
10749     return DiagnoseFailedExplicitSpec(S, Cand);
10750 
10751   case ovl_fail_ext_disabled:
10752     return DiagnoseOpenCLExtensionDisabled(S, Cand);
10753 
10754   case ovl_fail_inhctor_slice:
10755     // It's generally not interesting to note copy/move constructors here.
10756     if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10757       return;
10758     S.Diag(Fn->getLocation(),
10759            diag::note_ovl_candidate_inherited_constructor_slice)
10760       << (Fn->getPrimaryTemplate() ? 1 : 0)
10761       << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10762     MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10763     return;
10764 
10765   case ovl_fail_addr_not_available: {
10766     bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10767     (void)Available;
10768     assert(!Available);
10769     break;
10770   }
10771   case ovl_non_default_multiversion_function:
10772     // Do nothing, these should simply be ignored.
10773     break;
10774   }
10775 }
10776 
10777 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10778   // Desugar the type of the surrogate down to a function type,
10779   // retaining as many typedefs as possible while still showing
10780   // the function type (and, therefore, its parameter types).
10781   QualType FnType = Cand->Surrogate->getConversionType();
10782   bool isLValueReference = false;
10783   bool isRValueReference = false;
10784   bool isPointer = false;
10785   if (const LValueReferenceType *FnTypeRef =
10786         FnType->getAs<LValueReferenceType>()) {
10787     FnType = FnTypeRef->getPointeeType();
10788     isLValueReference = true;
10789   } else if (const RValueReferenceType *FnTypeRef =
10790                FnType->getAs<RValueReferenceType>()) {
10791     FnType = FnTypeRef->getPointeeType();
10792     isRValueReference = true;
10793   }
10794   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10795     FnType = FnTypePtr->getPointeeType();
10796     isPointer = true;
10797   }
10798   // Desugar down to a function type.
10799   FnType = QualType(FnType->getAs<FunctionType>(), 0);
10800   // Reconstruct the pointer/reference as appropriate.
10801   if (isPointer) FnType = S.Context.getPointerType(FnType);
10802   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10803   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10804 
10805   S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10806     << FnType;
10807 }
10808 
10809 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10810                                          SourceLocation OpLoc,
10811                                          OverloadCandidate *Cand) {
10812   assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10813   std::string TypeStr("operator");
10814   TypeStr += Opc;
10815   TypeStr += "(";
10816   TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10817   if (Cand->Conversions.size() == 1) {
10818     TypeStr += ")";
10819     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10820   } else {
10821     TypeStr += ", ";
10822     TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10823     TypeStr += ")";
10824     S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
10825   }
10826 }
10827 
10828 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10829                                          OverloadCandidate *Cand) {
10830   for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10831     if (ICS.isBad()) break; // all meaningless after first invalid
10832     if (!ICS.isAmbiguous()) continue;
10833 
10834     ICS.DiagnoseAmbiguousConversion(
10835         S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10836   }
10837 }
10838 
10839 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10840   if (Cand->Function)
10841     return Cand->Function->getLocation();
10842   if (Cand->IsSurrogate)
10843     return Cand->Surrogate->getLocation();
10844   return SourceLocation();
10845 }
10846 
10847 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10848   switch ((Sema::TemplateDeductionResult)DFI.Result) {
10849   case Sema::TDK_Success:
10850   case Sema::TDK_NonDependentConversionFailure:
10851     llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10852 
10853   case Sema::TDK_Invalid:
10854   case Sema::TDK_Incomplete:
10855   case Sema::TDK_IncompletePack:
10856     return 1;
10857 
10858   case Sema::TDK_Underqualified:
10859   case Sema::TDK_Inconsistent:
10860     return 2;
10861 
10862   case Sema::TDK_SubstitutionFailure:
10863   case Sema::TDK_DeducedMismatch:
10864   case Sema::TDK_ConstraintsNotSatisfied:
10865   case Sema::TDK_DeducedMismatchNested:
10866   case Sema::TDK_NonDeducedMismatch:
10867   case Sema::TDK_MiscellaneousDeductionFailure:
10868   case Sema::TDK_CUDATargetMismatch:
10869     return 3;
10870 
10871   case Sema::TDK_InstantiationDepth:
10872     return 4;
10873 
10874   case Sema::TDK_InvalidExplicitArguments:
10875     return 5;
10876 
10877   case Sema::TDK_TooManyArguments:
10878   case Sema::TDK_TooFewArguments:
10879     return 6;
10880   }
10881   llvm_unreachable("Unhandled deduction result");
10882 }
10883 
10884 namespace {
10885 struct CompareOverloadCandidatesForDisplay {
10886   Sema &S;
10887   SourceLocation Loc;
10888   size_t NumArgs;
10889   OverloadCandidateSet::CandidateSetKind CSK;
10890 
10891   CompareOverloadCandidatesForDisplay(
10892       Sema &S, SourceLocation Loc, size_t NArgs,
10893       OverloadCandidateSet::CandidateSetKind CSK)
10894       : S(S), NumArgs(NArgs), CSK(CSK) {}
10895 
10896   bool operator()(const OverloadCandidate *L,
10897                   const OverloadCandidate *R) {
10898     // Fast-path this check.
10899     if (L == R) return false;
10900 
10901     // Order first by viability.
10902     if (L->Viable) {
10903       if (!R->Viable) return true;
10904 
10905       // TODO: introduce a tri-valued comparison for overload
10906       // candidates.  Would be more worthwhile if we had a sort
10907       // that could exploit it.
10908       if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10909         return true;
10910       if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10911         return false;
10912     } else if (R->Viable)
10913       return false;
10914 
10915     assert(L->Viable == R->Viable);
10916 
10917     // Criteria by which we can sort non-viable candidates:
10918     if (!L->Viable) {
10919       // 1. Arity mismatches come after other candidates.
10920       if (L->FailureKind == ovl_fail_too_many_arguments ||
10921           L->FailureKind == ovl_fail_too_few_arguments) {
10922         if (R->FailureKind == ovl_fail_too_many_arguments ||
10923             R->FailureKind == ovl_fail_too_few_arguments) {
10924           int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10925           int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10926           if (LDist == RDist) {
10927             if (L->FailureKind == R->FailureKind)
10928               // Sort non-surrogates before surrogates.
10929               return !L->IsSurrogate && R->IsSurrogate;
10930             // Sort candidates requiring fewer parameters than there were
10931             // arguments given after candidates requiring more parameters
10932             // than there were arguments given.
10933             return L->FailureKind == ovl_fail_too_many_arguments;
10934           }
10935           return LDist < RDist;
10936         }
10937         return false;
10938       }
10939       if (R->FailureKind == ovl_fail_too_many_arguments ||
10940           R->FailureKind == ovl_fail_too_few_arguments)
10941         return true;
10942 
10943       // 2. Bad conversions come first and are ordered by the number
10944       // of bad conversions and quality of good conversions.
10945       if (L->FailureKind == ovl_fail_bad_conversion) {
10946         if (R->FailureKind != ovl_fail_bad_conversion)
10947           return true;
10948 
10949         // The conversion that can be fixed with a smaller number of changes,
10950         // comes first.
10951         unsigned numLFixes = L->Fix.NumConversionsFixed;
10952         unsigned numRFixes = R->Fix.NumConversionsFixed;
10953         numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10954         numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10955         if (numLFixes != numRFixes) {
10956           return numLFixes < numRFixes;
10957         }
10958 
10959         // If there's any ordering between the defined conversions...
10960         // FIXME: this might not be transitive.
10961         assert(L->Conversions.size() == R->Conversions.size());
10962 
10963         int leftBetter = 0;
10964         unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10965         for (unsigned E = L->Conversions.size(); I != E; ++I) {
10966           switch (CompareImplicitConversionSequences(S, Loc,
10967                                                      L->Conversions[I],
10968                                                      R->Conversions[I])) {
10969           case ImplicitConversionSequence::Better:
10970             leftBetter++;
10971             break;
10972 
10973           case ImplicitConversionSequence::Worse:
10974             leftBetter--;
10975             break;
10976 
10977           case ImplicitConversionSequence::Indistinguishable:
10978             break;
10979           }
10980         }
10981         if (leftBetter > 0) return true;
10982         if (leftBetter < 0) return false;
10983 
10984       } else if (R->FailureKind == ovl_fail_bad_conversion)
10985         return false;
10986 
10987       if (L->FailureKind == ovl_fail_bad_deduction) {
10988         if (R->FailureKind != ovl_fail_bad_deduction)
10989           return true;
10990 
10991         if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10992           return RankDeductionFailure(L->DeductionFailure)
10993                < RankDeductionFailure(R->DeductionFailure);
10994       } else if (R->FailureKind == ovl_fail_bad_deduction)
10995         return false;
10996 
10997       // TODO: others?
10998     }
10999 
11000     // Sort everything else by location.
11001     SourceLocation LLoc = GetLocationForCandidate(L);
11002     SourceLocation RLoc = GetLocationForCandidate(R);
11003 
11004     // Put candidates without locations (e.g. builtins) at the end.
11005     if (LLoc.isInvalid()) return false;
11006     if (RLoc.isInvalid()) return true;
11007 
11008     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11009   }
11010 };
11011 }
11012 
11013 /// CompleteNonViableCandidate - Normally, overload resolution only
11014 /// computes up to the first bad conversion. Produces the FixIt set if
11015 /// possible.
11016 static void
11017 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11018                            ArrayRef<Expr *> Args,
11019                            OverloadCandidateSet::CandidateSetKind CSK) {
11020   assert(!Cand->Viable);
11021 
11022   // Don't do anything on failures other than bad conversion.
11023   if (Cand->FailureKind != ovl_fail_bad_conversion) return;
11024 
11025   // We only want the FixIts if all the arguments can be corrected.
11026   bool Unfixable = false;
11027   // Use a implicit copy initialization to check conversion fixes.
11028   Cand->Fix.setConversionChecker(TryCopyInitialization);
11029 
11030   // Attempt to fix the bad conversion.
11031   unsigned ConvCount = Cand->Conversions.size();
11032   for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11033        ++ConvIdx) {
11034     assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11035     if (Cand->Conversions[ConvIdx].isInitialized() &&
11036         Cand->Conversions[ConvIdx].isBad()) {
11037       Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11038       break;
11039     }
11040   }
11041 
11042   // FIXME: this should probably be preserved from the overload
11043   // operation somehow.
11044   bool SuppressUserConversions = false;
11045 
11046   unsigned ConvIdx = 0;
11047   unsigned ArgIdx = 0;
11048   ArrayRef<QualType> ParamTypes;
11049   bool Reversed = Cand->RewriteKind & CRK_Reversed;
11050 
11051   if (Cand->IsSurrogate) {
11052     QualType ConvType
11053       = Cand->Surrogate->getConversionType().getNonReferenceType();
11054     if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11055       ConvType = ConvPtrType->getPointeeType();
11056     ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11057     // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11058     ConvIdx = 1;
11059   } else if (Cand->Function) {
11060     ParamTypes =
11061         Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11062     if (isa<CXXMethodDecl>(Cand->Function) &&
11063         !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11064       // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11065       ConvIdx = 1;
11066       if (CSK == OverloadCandidateSet::CSK_Operator &&
11067           Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11068         // Argument 0 is 'this', which doesn't have a corresponding parameter.
11069         ArgIdx = 1;
11070     }
11071   } else {
11072     // Builtin operator.
11073     assert(ConvCount <= 3);
11074     ParamTypes = Cand->BuiltinParamTypes;
11075   }
11076 
11077   // Fill in the rest of the conversions.
11078   for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11079        ConvIdx != ConvCount;
11080        ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11081     assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11082     if (Cand->Conversions[ConvIdx].isInitialized()) {
11083       // We've already checked this conversion.
11084     } else if (ParamIdx < ParamTypes.size()) {
11085       if (ParamTypes[ParamIdx]->isDependentType())
11086         Cand->Conversions[ConvIdx].setAsIdentityConversion(
11087             Args[ArgIdx]->getType());
11088       else {
11089         Cand->Conversions[ConvIdx] =
11090             TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11091                                   SuppressUserConversions,
11092                                   /*InOverloadResolution=*/true,
11093                                   /*AllowObjCWritebackConversion=*/
11094                                   S.getLangOpts().ObjCAutoRefCount);
11095         // Store the FixIt in the candidate if it exists.
11096         if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11097           Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11098       }
11099     } else
11100       Cand->Conversions[ConvIdx].setEllipsis();
11101   }
11102 }
11103 
11104 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11105     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11106     SourceLocation OpLoc,
11107     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11108   // Sort the candidates by viability and position.  Sorting directly would
11109   // be prohibitive, so we make a set of pointers and sort those.
11110   SmallVector<OverloadCandidate*, 32> Cands;
11111   if (OCD == OCD_AllCandidates) Cands.reserve(size());
11112   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11113     if (!Filter(*Cand))
11114       continue;
11115     switch (OCD) {
11116     case OCD_AllCandidates:
11117       if (!Cand->Viable) {
11118         if (!Cand->Function && !Cand->IsSurrogate) {
11119           // This a non-viable builtin candidate.  We do not, in general,
11120           // want to list every possible builtin candidate.
11121           continue;
11122         }
11123         CompleteNonViableCandidate(S, Cand, Args, Kind);
11124       }
11125       break;
11126 
11127     case OCD_ViableCandidates:
11128       if (!Cand->Viable)
11129         continue;
11130       break;
11131 
11132     case OCD_AmbiguousCandidates:
11133       if (!Cand->Best)
11134         continue;
11135       break;
11136     }
11137 
11138     Cands.push_back(Cand);
11139   }
11140 
11141   llvm::stable_sort(
11142       Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11143 
11144   return Cands;
11145 }
11146 
11147 /// When overload resolution fails, prints diagnostic messages containing the
11148 /// candidates in the candidate set.
11149 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11150     Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11151     StringRef Opc, SourceLocation OpLoc,
11152     llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11153 
11154   auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11155 
11156   S.Diag(PD.first, PD.second);
11157 
11158   NoteCandidates(S, Args, Cands, Opc, OpLoc);
11159 }
11160 
11161 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11162                                           ArrayRef<OverloadCandidate *> Cands,
11163                                           StringRef Opc, SourceLocation OpLoc) {
11164   bool ReportedAmbiguousConversions = false;
11165 
11166   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11167   unsigned CandsShown = 0;
11168   auto I = Cands.begin(), E = Cands.end();
11169   for (; I != E; ++I) {
11170     OverloadCandidate *Cand = *I;
11171 
11172     // Set an arbitrary limit on the number of candidate functions we'll spam
11173     // the user with.  FIXME: This limit should depend on details of the
11174     // candidate list.
11175     if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11176       break;
11177     }
11178     ++CandsShown;
11179 
11180     if (Cand->Function)
11181       NoteFunctionCandidate(S, Cand, Args.size(),
11182                             /*TakingCandidateAddress=*/false, DestAS);
11183     else if (Cand->IsSurrogate)
11184       NoteSurrogateCandidate(S, Cand);
11185     else {
11186       assert(Cand->Viable &&
11187              "Non-viable built-in candidates are not added to Cands.");
11188       // Generally we only see ambiguities including viable builtin
11189       // operators if overload resolution got screwed up by an
11190       // ambiguous user-defined conversion.
11191       //
11192       // FIXME: It's quite possible for different conversions to see
11193       // different ambiguities, though.
11194       if (!ReportedAmbiguousConversions) {
11195         NoteAmbiguousUserConversions(S, OpLoc, Cand);
11196         ReportedAmbiguousConversions = true;
11197       }
11198 
11199       // If this is a viable builtin, print it.
11200       NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11201     }
11202   }
11203 
11204   if (I != E)
11205     S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11206 }
11207 
11208 static SourceLocation
11209 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11210   return Cand->Specialization ? Cand->Specialization->getLocation()
11211                               : SourceLocation();
11212 }
11213 
11214 namespace {
11215 struct CompareTemplateSpecCandidatesForDisplay {
11216   Sema &S;
11217   CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11218 
11219   bool operator()(const TemplateSpecCandidate *L,
11220                   const TemplateSpecCandidate *R) {
11221     // Fast-path this check.
11222     if (L == R)
11223       return false;
11224 
11225     // Assuming that both candidates are not matches...
11226 
11227     // Sort by the ranking of deduction failures.
11228     if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11229       return RankDeductionFailure(L->DeductionFailure) <
11230              RankDeductionFailure(R->DeductionFailure);
11231 
11232     // Sort everything else by location.
11233     SourceLocation LLoc = GetLocationForCandidate(L);
11234     SourceLocation RLoc = GetLocationForCandidate(R);
11235 
11236     // Put candidates without locations (e.g. builtins) at the end.
11237     if (LLoc.isInvalid())
11238       return false;
11239     if (RLoc.isInvalid())
11240       return true;
11241 
11242     return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11243   }
11244 };
11245 }
11246 
11247 /// Diagnose a template argument deduction failure.
11248 /// We are treating these failures as overload failures due to bad
11249 /// deductions.
11250 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11251                                                  bool ForTakingAddress) {
11252   DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11253                        DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11254 }
11255 
11256 void TemplateSpecCandidateSet::destroyCandidates() {
11257   for (iterator i = begin(), e = end(); i != e; ++i) {
11258     i->DeductionFailure.Destroy();
11259   }
11260 }
11261 
11262 void TemplateSpecCandidateSet::clear() {
11263   destroyCandidates();
11264   Candidates.clear();
11265 }
11266 
11267 /// NoteCandidates - When no template specialization match is found, prints
11268 /// diagnostic messages containing the non-matching specializations that form
11269 /// the candidate set.
11270 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11271 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11272 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11273   // Sort the candidates by position (assuming no candidate is a match).
11274   // Sorting directly would be prohibitive, so we make a set of pointers
11275   // and sort those.
11276   SmallVector<TemplateSpecCandidate *, 32> Cands;
11277   Cands.reserve(size());
11278   for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11279     if (Cand->Specialization)
11280       Cands.push_back(Cand);
11281     // Otherwise, this is a non-matching builtin candidate.  We do not,
11282     // in general, want to list every possible builtin candidate.
11283   }
11284 
11285   llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11286 
11287   // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11288   // for generalization purposes (?).
11289   const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11290 
11291   SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11292   unsigned CandsShown = 0;
11293   for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11294     TemplateSpecCandidate *Cand = *I;
11295 
11296     // Set an arbitrary limit on the number of candidates we'll spam
11297     // the user with.  FIXME: This limit should depend on details of the
11298     // candidate list.
11299     if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11300       break;
11301     ++CandsShown;
11302 
11303     assert(Cand->Specialization &&
11304            "Non-matching built-in candidates are not added to Cands.");
11305     Cand->NoteDeductionFailure(S, ForTakingAddress);
11306   }
11307 
11308   if (I != E)
11309     S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11310 }
11311 
11312 // [PossiblyAFunctionType]  -->   [Return]
11313 // NonFunctionType --> NonFunctionType
11314 // R (A) --> R(A)
11315 // R (*)(A) --> R (A)
11316 // R (&)(A) --> R (A)
11317 // R (S::*)(A) --> R (A)
11318 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11319   QualType Ret = PossiblyAFunctionType;
11320   if (const PointerType *ToTypePtr =
11321     PossiblyAFunctionType->getAs<PointerType>())
11322     Ret = ToTypePtr->getPointeeType();
11323   else if (const ReferenceType *ToTypeRef =
11324     PossiblyAFunctionType->getAs<ReferenceType>())
11325     Ret = ToTypeRef->getPointeeType();
11326   else if (const MemberPointerType *MemTypePtr =
11327     PossiblyAFunctionType->getAs<MemberPointerType>())
11328     Ret = MemTypePtr->getPointeeType();
11329   Ret =
11330     Context.getCanonicalType(Ret).getUnqualifiedType();
11331   return Ret;
11332 }
11333 
11334 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11335                                  bool Complain = true) {
11336   if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11337       S.DeduceReturnType(FD, Loc, Complain))
11338     return true;
11339 
11340   auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11341   if (S.getLangOpts().CPlusPlus17 &&
11342       isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11343       !S.ResolveExceptionSpec(Loc, FPT))
11344     return true;
11345 
11346   return false;
11347 }
11348 
11349 namespace {
11350 // A helper class to help with address of function resolution
11351 // - allows us to avoid passing around all those ugly parameters
11352 class AddressOfFunctionResolver {
11353   Sema& S;
11354   Expr* SourceExpr;
11355   const QualType& TargetType;
11356   QualType TargetFunctionType; // Extracted function type from target type
11357 
11358   bool Complain;
11359   //DeclAccessPair& ResultFunctionAccessPair;
11360   ASTContext& Context;
11361 
11362   bool TargetTypeIsNonStaticMemberFunction;
11363   bool FoundNonTemplateFunction;
11364   bool StaticMemberFunctionFromBoundPointer;
11365   bool HasComplained;
11366 
11367   OverloadExpr::FindResult OvlExprInfo;
11368   OverloadExpr *OvlExpr;
11369   TemplateArgumentListInfo OvlExplicitTemplateArgs;
11370   SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11371   TemplateSpecCandidateSet FailedCandidates;
11372 
11373 public:
11374   AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11375                             const QualType &TargetType, bool Complain)
11376       : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11377         Complain(Complain), Context(S.getASTContext()),
11378         TargetTypeIsNonStaticMemberFunction(
11379             !!TargetType->getAs<MemberPointerType>()),
11380         FoundNonTemplateFunction(false),
11381         StaticMemberFunctionFromBoundPointer(false),
11382         HasComplained(false),
11383         OvlExprInfo(OverloadExpr::find(SourceExpr)),
11384         OvlExpr(OvlExprInfo.Expression),
11385         FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11386     ExtractUnqualifiedFunctionTypeFromTargetType();
11387 
11388     if (TargetFunctionType->isFunctionType()) {
11389       if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11390         if (!UME->isImplicitAccess() &&
11391             !S.ResolveSingleFunctionTemplateSpecialization(UME))
11392           StaticMemberFunctionFromBoundPointer = true;
11393     } else if (OvlExpr->hasExplicitTemplateArgs()) {
11394       DeclAccessPair dap;
11395       if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11396               OvlExpr, false, &dap)) {
11397         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11398           if (!Method->isStatic()) {
11399             // If the target type is a non-function type and the function found
11400             // is a non-static member function, pretend as if that was the
11401             // target, it's the only possible type to end up with.
11402             TargetTypeIsNonStaticMemberFunction = true;
11403 
11404             // And skip adding the function if its not in the proper form.
11405             // We'll diagnose this due to an empty set of functions.
11406             if (!OvlExprInfo.HasFormOfMemberPointer)
11407               return;
11408           }
11409 
11410         Matches.push_back(std::make_pair(dap, Fn));
11411       }
11412       return;
11413     }
11414 
11415     if (OvlExpr->hasExplicitTemplateArgs())
11416       OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11417 
11418     if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11419       // C++ [over.over]p4:
11420       //   If more than one function is selected, [...]
11421       if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11422         if (FoundNonTemplateFunction)
11423           EliminateAllTemplateMatches();
11424         else
11425           EliminateAllExceptMostSpecializedTemplate();
11426       }
11427     }
11428 
11429     if (S.getLangOpts().CUDA && Matches.size() > 1)
11430       EliminateSuboptimalCudaMatches();
11431   }
11432 
11433   bool hasComplained() const { return HasComplained; }
11434 
11435 private:
11436   bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11437     QualType Discard;
11438     return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11439            S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11440   }
11441 
11442   /// \return true if A is considered a better overload candidate for the
11443   /// desired type than B.
11444   bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11445     // If A doesn't have exactly the correct type, we don't want to classify it
11446     // as "better" than anything else. This way, the user is required to
11447     // disambiguate for us if there are multiple candidates and no exact match.
11448     return candidateHasExactlyCorrectType(A) &&
11449            (!candidateHasExactlyCorrectType(B) ||
11450             compareEnableIfAttrs(S, A, B) == Comparison::Better);
11451   }
11452 
11453   /// \return true if we were able to eliminate all but one overload candidate,
11454   /// false otherwise.
11455   bool eliminiateSuboptimalOverloadCandidates() {
11456     // Same algorithm as overload resolution -- one pass to pick the "best",
11457     // another pass to be sure that nothing is better than the best.
11458     auto Best = Matches.begin();
11459     for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11460       if (isBetterCandidate(I->second, Best->second))
11461         Best = I;
11462 
11463     const FunctionDecl *BestFn = Best->second;
11464     auto IsBestOrInferiorToBest = [this, BestFn](
11465         const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11466       return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11467     };
11468 
11469     // Note: We explicitly leave Matches unmodified if there isn't a clear best
11470     // option, so we can potentially give the user a better error
11471     if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11472       return false;
11473     Matches[0] = *Best;
11474     Matches.resize(1);
11475     return true;
11476   }
11477 
11478   bool isTargetTypeAFunction() const {
11479     return TargetFunctionType->isFunctionType();
11480   }
11481 
11482   // [ToType]     [Return]
11483 
11484   // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11485   // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11486   // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11487   void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11488     TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11489   }
11490 
11491   // return true if any matching specializations were found
11492   bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11493                                    const DeclAccessPair& CurAccessFunPair) {
11494     if (CXXMethodDecl *Method
11495               = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11496       // Skip non-static function templates when converting to pointer, and
11497       // static when converting to member pointer.
11498       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11499         return false;
11500     }
11501     else if (TargetTypeIsNonStaticMemberFunction)
11502       return false;
11503 
11504     // C++ [over.over]p2:
11505     //   If the name is a function template, template argument deduction is
11506     //   done (14.8.2.2), and if the argument deduction succeeds, the
11507     //   resulting template argument list is used to generate a single
11508     //   function template specialization, which is added to the set of
11509     //   overloaded functions considered.
11510     FunctionDecl *Specialization = nullptr;
11511     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11512     if (Sema::TemplateDeductionResult Result
11513           = S.DeduceTemplateArguments(FunctionTemplate,
11514                                       &OvlExplicitTemplateArgs,
11515                                       TargetFunctionType, Specialization,
11516                                       Info, /*IsAddressOfFunction*/true)) {
11517       // Make a note of the failed deduction for diagnostics.
11518       FailedCandidates.addCandidate()
11519           .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11520                MakeDeductionFailureInfo(Context, Result, Info));
11521       return false;
11522     }
11523 
11524     // Template argument deduction ensures that we have an exact match or
11525     // compatible pointer-to-function arguments that would be adjusted by ICS.
11526     // This function template specicalization works.
11527     assert(S.isSameOrCompatibleFunctionType(
11528               Context.getCanonicalType(Specialization->getType()),
11529               Context.getCanonicalType(TargetFunctionType)));
11530 
11531     if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11532       return false;
11533 
11534     Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11535     return true;
11536   }
11537 
11538   bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11539                                       const DeclAccessPair& CurAccessFunPair) {
11540     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11541       // Skip non-static functions when converting to pointer, and static
11542       // when converting to member pointer.
11543       if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11544         return false;
11545     }
11546     else if (TargetTypeIsNonStaticMemberFunction)
11547       return false;
11548 
11549     if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11550       if (S.getLangOpts().CUDA)
11551         if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11552           if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11553             return false;
11554       if (FunDecl->isMultiVersion()) {
11555         const auto *TA = FunDecl->getAttr<TargetAttr>();
11556         if (TA && !TA->isDefaultVersion())
11557           return false;
11558       }
11559 
11560       // If any candidate has a placeholder return type, trigger its deduction
11561       // now.
11562       if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11563                                Complain)) {
11564         HasComplained |= Complain;
11565         return false;
11566       }
11567 
11568       if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11569         return false;
11570 
11571       // If we're in C, we need to support types that aren't exactly identical.
11572       if (!S.getLangOpts().CPlusPlus ||
11573           candidateHasExactlyCorrectType(FunDecl)) {
11574         Matches.push_back(std::make_pair(
11575             CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11576         FoundNonTemplateFunction = true;
11577         return true;
11578       }
11579     }
11580 
11581     return false;
11582   }
11583 
11584   bool FindAllFunctionsThatMatchTargetTypeExactly() {
11585     bool Ret = false;
11586 
11587     // If the overload expression doesn't have the form of a pointer to
11588     // member, don't try to convert it to a pointer-to-member type.
11589     if (IsInvalidFormOfPointerToMemberFunction())
11590       return false;
11591 
11592     for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11593                                E = OvlExpr->decls_end();
11594          I != E; ++I) {
11595       // Look through any using declarations to find the underlying function.
11596       NamedDecl *Fn = (*I)->getUnderlyingDecl();
11597 
11598       // C++ [over.over]p3:
11599       //   Non-member functions and static member functions match
11600       //   targets of type "pointer-to-function" or "reference-to-function."
11601       //   Nonstatic member functions match targets of
11602       //   type "pointer-to-member-function."
11603       // Note that according to DR 247, the containing class does not matter.
11604       if (FunctionTemplateDecl *FunctionTemplate
11605                                         = dyn_cast<FunctionTemplateDecl>(Fn)) {
11606         if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11607           Ret = true;
11608       }
11609       // If we have explicit template arguments supplied, skip non-templates.
11610       else if (!OvlExpr->hasExplicitTemplateArgs() &&
11611                AddMatchingNonTemplateFunction(Fn, I.getPair()))
11612         Ret = true;
11613     }
11614     assert(Ret || Matches.empty());
11615     return Ret;
11616   }
11617 
11618   void EliminateAllExceptMostSpecializedTemplate() {
11619     //   [...] and any given function template specialization F1 is
11620     //   eliminated if the set contains a second function template
11621     //   specialization whose function template is more specialized
11622     //   than the function template of F1 according to the partial
11623     //   ordering rules of 14.5.5.2.
11624 
11625     // The algorithm specified above is quadratic. We instead use a
11626     // two-pass algorithm (similar to the one used to identify the
11627     // best viable function in an overload set) that identifies the
11628     // best function template (if it exists).
11629 
11630     UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11631     for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11632       MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11633 
11634     // TODO: It looks like FailedCandidates does not serve much purpose
11635     // here, since the no_viable diagnostic has index 0.
11636     UnresolvedSetIterator Result = S.getMostSpecialized(
11637         MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11638         SourceExpr->getBeginLoc(), S.PDiag(),
11639         S.PDiag(diag::err_addr_ovl_ambiguous)
11640             << Matches[0].second->getDeclName(),
11641         S.PDiag(diag::note_ovl_candidate)
11642             << (unsigned)oc_function << (unsigned)ocs_described_template,
11643         Complain, TargetFunctionType);
11644 
11645     if (Result != MatchesCopy.end()) {
11646       // Make it the first and only element
11647       Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11648       Matches[0].second = cast<FunctionDecl>(*Result);
11649       Matches.resize(1);
11650     } else
11651       HasComplained |= Complain;
11652   }
11653 
11654   void EliminateAllTemplateMatches() {
11655     //   [...] any function template specializations in the set are
11656     //   eliminated if the set also contains a non-template function, [...]
11657     for (unsigned I = 0, N = Matches.size(); I != N; ) {
11658       if (Matches[I].second->getPrimaryTemplate() == nullptr)
11659         ++I;
11660       else {
11661         Matches[I] = Matches[--N];
11662         Matches.resize(N);
11663       }
11664     }
11665   }
11666 
11667   void EliminateSuboptimalCudaMatches() {
11668     S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11669   }
11670 
11671 public:
11672   void ComplainNoMatchesFound() const {
11673     assert(Matches.empty());
11674     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11675         << OvlExpr->getName() << TargetFunctionType
11676         << OvlExpr->getSourceRange();
11677     if (FailedCandidates.empty())
11678       S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11679                                   /*TakingAddress=*/true);
11680     else {
11681       // We have some deduction failure messages. Use them to diagnose
11682       // the function templates, and diagnose the non-template candidates
11683       // normally.
11684       for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11685                                  IEnd = OvlExpr->decls_end();
11686            I != IEnd; ++I)
11687         if (FunctionDecl *Fun =
11688                 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11689           if (!functionHasPassObjectSizeParams(Fun))
11690             S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11691                                     /*TakingAddress=*/true);
11692       FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11693     }
11694   }
11695 
11696   bool IsInvalidFormOfPointerToMemberFunction() const {
11697     return TargetTypeIsNonStaticMemberFunction &&
11698       !OvlExprInfo.HasFormOfMemberPointer;
11699   }
11700 
11701   void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11702       // TODO: Should we condition this on whether any functions might
11703       // have matched, or is it more appropriate to do that in callers?
11704       // TODO: a fixit wouldn't hurt.
11705       S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11706         << TargetType << OvlExpr->getSourceRange();
11707   }
11708 
11709   bool IsStaticMemberFunctionFromBoundPointer() const {
11710     return StaticMemberFunctionFromBoundPointer;
11711   }
11712 
11713   void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11714     S.Diag(OvlExpr->getBeginLoc(),
11715            diag::err_invalid_form_pointer_member_function)
11716         << OvlExpr->getSourceRange();
11717   }
11718 
11719   void ComplainOfInvalidConversion() const {
11720     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11721         << OvlExpr->getName() << TargetType;
11722   }
11723 
11724   void ComplainMultipleMatchesFound() const {
11725     assert(Matches.size() > 1);
11726     S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11727         << OvlExpr->getName() << OvlExpr->getSourceRange();
11728     S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11729                                 /*TakingAddress=*/true);
11730   }
11731 
11732   bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11733 
11734   int getNumMatches() const { return Matches.size(); }
11735 
11736   FunctionDecl* getMatchingFunctionDecl() const {
11737     if (Matches.size() != 1) return nullptr;
11738     return Matches[0].second;
11739   }
11740 
11741   const DeclAccessPair* getMatchingFunctionAccessPair() const {
11742     if (Matches.size() != 1) return nullptr;
11743     return &Matches[0].first;
11744   }
11745 };
11746 }
11747 
11748 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11749 /// an overloaded function (C++ [over.over]), where @p From is an
11750 /// expression with overloaded function type and @p ToType is the type
11751 /// we're trying to resolve to. For example:
11752 ///
11753 /// @code
11754 /// int f(double);
11755 /// int f(int);
11756 ///
11757 /// int (*pfd)(double) = f; // selects f(double)
11758 /// @endcode
11759 ///
11760 /// This routine returns the resulting FunctionDecl if it could be
11761 /// resolved, and NULL otherwise. When @p Complain is true, this
11762 /// routine will emit diagnostics if there is an error.
11763 FunctionDecl *
11764 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11765                                          QualType TargetType,
11766                                          bool Complain,
11767                                          DeclAccessPair &FoundResult,
11768                                          bool *pHadMultipleCandidates) {
11769   assert(AddressOfExpr->getType() == Context.OverloadTy);
11770 
11771   AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11772                                      Complain);
11773   int NumMatches = Resolver.getNumMatches();
11774   FunctionDecl *Fn = nullptr;
11775   bool ShouldComplain = Complain && !Resolver.hasComplained();
11776   if (NumMatches == 0 && ShouldComplain) {
11777     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11778       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11779     else
11780       Resolver.ComplainNoMatchesFound();
11781   }
11782   else if (NumMatches > 1 && ShouldComplain)
11783     Resolver.ComplainMultipleMatchesFound();
11784   else if (NumMatches == 1) {
11785     Fn = Resolver.getMatchingFunctionDecl();
11786     assert(Fn);
11787     if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11788       ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11789     FoundResult = *Resolver.getMatchingFunctionAccessPair();
11790     if (Complain) {
11791       if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11792         Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11793       else
11794         CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11795     }
11796   }
11797 
11798   if (pHadMultipleCandidates)
11799     *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11800   return Fn;
11801 }
11802 
11803 /// Given an expression that refers to an overloaded function, try to
11804 /// resolve that function to a single function that can have its address taken.
11805 /// This will modify `Pair` iff it returns non-null.
11806 ///
11807 /// This routine can only realistically succeed if all but one candidates in the
11808 /// overload set for SrcExpr cannot have their addresses taken.
11809 FunctionDecl *
11810 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11811                                                   DeclAccessPair &Pair) {
11812   OverloadExpr::FindResult R = OverloadExpr::find(E);
11813   OverloadExpr *Ovl = R.Expression;
11814   FunctionDecl *Result = nullptr;
11815   DeclAccessPair DAP;
11816   // Don't use the AddressOfResolver because we're specifically looking for
11817   // cases where we have one overload candidate that lacks
11818   // enable_if/pass_object_size/...
11819   for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11820     auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11821     if (!FD)
11822       return nullptr;
11823 
11824     if (!checkAddressOfFunctionIsAvailable(FD))
11825       continue;
11826 
11827     // We have more than one result; quit.
11828     if (Result)
11829       return nullptr;
11830     DAP = I.getPair();
11831     Result = FD;
11832   }
11833 
11834   if (Result)
11835     Pair = DAP;
11836   return Result;
11837 }
11838 
11839 /// Given an overloaded function, tries to turn it into a non-overloaded
11840 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11841 /// will perform access checks, diagnose the use of the resultant decl, and, if
11842 /// requested, potentially perform a function-to-pointer decay.
11843 ///
11844 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11845 /// Otherwise, returns true. This may emit diagnostics and return true.
11846 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11847     ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11848   Expr *E = SrcExpr.get();
11849   assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11850 
11851   DeclAccessPair DAP;
11852   FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11853   if (!Found || Found->isCPUDispatchMultiVersion() ||
11854       Found->isCPUSpecificMultiVersion())
11855     return false;
11856 
11857   // Emitting multiple diagnostics for a function that is both inaccessible and
11858   // unavailable is consistent with our behavior elsewhere. So, always check
11859   // for both.
11860   DiagnoseUseOfDecl(Found, E->getExprLoc());
11861   CheckAddressOfMemberAccess(E, DAP);
11862   Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11863   if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11864     SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11865   else
11866     SrcExpr = Fixed;
11867   return true;
11868 }
11869 
11870 /// Given an expression that refers to an overloaded function, try to
11871 /// resolve that overloaded function expression down to a single function.
11872 ///
11873 /// This routine can only resolve template-ids that refer to a single function
11874 /// template, where that template-id refers to a single template whose template
11875 /// arguments are either provided by the template-id or have defaults,
11876 /// as described in C++0x [temp.arg.explicit]p3.
11877 ///
11878 /// If no template-ids are found, no diagnostics are emitted and NULL is
11879 /// returned.
11880 FunctionDecl *
11881 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11882                                                   bool Complain,
11883                                                   DeclAccessPair *FoundResult) {
11884   // C++ [over.over]p1:
11885   //   [...] [Note: any redundant set of parentheses surrounding the
11886   //   overloaded function name is ignored (5.1). ]
11887   // C++ [over.over]p1:
11888   //   [...] The overloaded function name can be preceded by the &
11889   //   operator.
11890 
11891   // If we didn't actually find any template-ids, we're done.
11892   if (!ovl->hasExplicitTemplateArgs())
11893     return nullptr;
11894 
11895   TemplateArgumentListInfo ExplicitTemplateArgs;
11896   ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11897   TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11898 
11899   // Look through all of the overloaded functions, searching for one
11900   // whose type matches exactly.
11901   FunctionDecl *Matched = nullptr;
11902   for (UnresolvedSetIterator I = ovl->decls_begin(),
11903          E = ovl->decls_end(); I != E; ++I) {
11904     // C++0x [temp.arg.explicit]p3:
11905     //   [...] In contexts where deduction is done and fails, or in contexts
11906     //   where deduction is not done, if a template argument list is
11907     //   specified and it, along with any default template arguments,
11908     //   identifies a single function template specialization, then the
11909     //   template-id is an lvalue for the function template specialization.
11910     FunctionTemplateDecl *FunctionTemplate
11911       = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11912 
11913     // C++ [over.over]p2:
11914     //   If the name is a function template, template argument deduction is
11915     //   done (14.8.2.2), and if the argument deduction succeeds, the
11916     //   resulting template argument list is used to generate a single
11917     //   function template specialization, which is added to the set of
11918     //   overloaded functions considered.
11919     FunctionDecl *Specialization = nullptr;
11920     TemplateDeductionInfo Info(FailedCandidates.getLocation());
11921     if (TemplateDeductionResult Result
11922           = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11923                                     Specialization, Info,
11924                                     /*IsAddressOfFunction*/true)) {
11925       // Make a note of the failed deduction for diagnostics.
11926       // TODO: Actually use the failed-deduction info?
11927       FailedCandidates.addCandidate()
11928           .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11929                MakeDeductionFailureInfo(Context, Result, Info));
11930       continue;
11931     }
11932 
11933     assert(Specialization && "no specialization and no error?");
11934 
11935     // Multiple matches; we can't resolve to a single declaration.
11936     if (Matched) {
11937       if (Complain) {
11938         Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11939           << ovl->getName();
11940         NoteAllOverloadCandidates(ovl);
11941       }
11942       return nullptr;
11943     }
11944 
11945     Matched = Specialization;
11946     if (FoundResult) *FoundResult = I.getPair();
11947   }
11948 
11949   if (Matched &&
11950       completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11951     return nullptr;
11952 
11953   return Matched;
11954 }
11955 
11956 // Resolve and fix an overloaded expression that can be resolved
11957 // because it identifies a single function template specialization.
11958 //
11959 // Last three arguments should only be supplied if Complain = true
11960 //
11961 // Return true if it was logically possible to so resolve the
11962 // expression, regardless of whether or not it succeeded.  Always
11963 // returns true if 'complain' is set.
11964 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11965                       ExprResult &SrcExpr, bool doFunctionPointerConverion,
11966                       bool complain, SourceRange OpRangeForComplaining,
11967                                            QualType DestTypeForComplaining,
11968                                             unsigned DiagIDForComplaining) {
11969   assert(SrcExpr.get()->getType() == Context.OverloadTy);
11970 
11971   OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11972 
11973   DeclAccessPair found;
11974   ExprResult SingleFunctionExpression;
11975   if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11976                            ovl.Expression, /*complain*/ false, &found)) {
11977     if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11978       SrcExpr = ExprError();
11979       return true;
11980     }
11981 
11982     // It is only correct to resolve to an instance method if we're
11983     // resolving a form that's permitted to be a pointer to member.
11984     // Otherwise we'll end up making a bound member expression, which
11985     // is illegal in all the contexts we resolve like this.
11986     if (!ovl.HasFormOfMemberPointer &&
11987         isa<CXXMethodDecl>(fn) &&
11988         cast<CXXMethodDecl>(fn)->isInstance()) {
11989       if (!complain) return false;
11990 
11991       Diag(ovl.Expression->getExprLoc(),
11992            diag::err_bound_member_function)
11993         << 0 << ovl.Expression->getSourceRange();
11994 
11995       // TODO: I believe we only end up here if there's a mix of
11996       // static and non-static candidates (otherwise the expression
11997       // would have 'bound member' type, not 'overload' type).
11998       // Ideally we would note which candidate was chosen and why
11999       // the static candidates were rejected.
12000       SrcExpr = ExprError();
12001       return true;
12002     }
12003 
12004     // Fix the expression to refer to 'fn'.
12005     SingleFunctionExpression =
12006         FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12007 
12008     // If desired, do function-to-pointer decay.
12009     if (doFunctionPointerConverion) {
12010       SingleFunctionExpression =
12011         DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12012       if (SingleFunctionExpression.isInvalid()) {
12013         SrcExpr = ExprError();
12014         return true;
12015       }
12016     }
12017   }
12018 
12019   if (!SingleFunctionExpression.isUsable()) {
12020     if (complain) {
12021       Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12022         << ovl.Expression->getName()
12023         << DestTypeForComplaining
12024         << OpRangeForComplaining
12025         << ovl.Expression->getQualifierLoc().getSourceRange();
12026       NoteAllOverloadCandidates(SrcExpr.get());
12027 
12028       SrcExpr = ExprError();
12029       return true;
12030     }
12031 
12032     return false;
12033   }
12034 
12035   SrcExpr = SingleFunctionExpression;
12036   return true;
12037 }
12038 
12039 /// Add a single candidate to the overload set.
12040 static void AddOverloadedCallCandidate(Sema &S,
12041                                        DeclAccessPair FoundDecl,
12042                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
12043                                        ArrayRef<Expr *> Args,
12044                                        OverloadCandidateSet &CandidateSet,
12045                                        bool PartialOverloading,
12046                                        bool KnownValid) {
12047   NamedDecl *Callee = FoundDecl.getDecl();
12048   if (isa<UsingShadowDecl>(Callee))
12049     Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12050 
12051   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12052     if (ExplicitTemplateArgs) {
12053       assert(!KnownValid && "Explicit template arguments?");
12054       return;
12055     }
12056     // Prevent ill-formed function decls to be added as overload candidates.
12057     if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12058       return;
12059 
12060     S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12061                            /*SuppressUserConversions=*/false,
12062                            PartialOverloading);
12063     return;
12064   }
12065 
12066   if (FunctionTemplateDecl *FuncTemplate
12067       = dyn_cast<FunctionTemplateDecl>(Callee)) {
12068     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12069                                    ExplicitTemplateArgs, Args, CandidateSet,
12070                                    /*SuppressUserConversions=*/false,
12071                                    PartialOverloading);
12072     return;
12073   }
12074 
12075   assert(!KnownValid && "unhandled case in overloaded call candidate");
12076 }
12077 
12078 /// Add the overload candidates named by callee and/or found by argument
12079 /// dependent lookup to the given overload set.
12080 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12081                                        ArrayRef<Expr *> Args,
12082                                        OverloadCandidateSet &CandidateSet,
12083                                        bool PartialOverloading) {
12084 
12085 #ifndef NDEBUG
12086   // Verify that ArgumentDependentLookup is consistent with the rules
12087   // in C++0x [basic.lookup.argdep]p3:
12088   //
12089   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
12090   //   and let Y be the lookup set produced by argument dependent
12091   //   lookup (defined as follows). If X contains
12092   //
12093   //     -- a declaration of a class member, or
12094   //
12095   //     -- a block-scope function declaration that is not a
12096   //        using-declaration, or
12097   //
12098   //     -- a declaration that is neither a function or a function
12099   //        template
12100   //
12101   //   then Y is empty.
12102 
12103   if (ULE->requiresADL()) {
12104     for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12105            E = ULE->decls_end(); I != E; ++I) {
12106       assert(!(*I)->getDeclContext()->isRecord());
12107       assert(isa<UsingShadowDecl>(*I) ||
12108              !(*I)->getDeclContext()->isFunctionOrMethod());
12109       assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12110     }
12111   }
12112 #endif
12113 
12114   // It would be nice to avoid this copy.
12115   TemplateArgumentListInfo TABuffer;
12116   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12117   if (ULE->hasExplicitTemplateArgs()) {
12118     ULE->copyTemplateArgumentsInto(TABuffer);
12119     ExplicitTemplateArgs = &TABuffer;
12120   }
12121 
12122   for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12123          E = ULE->decls_end(); I != E; ++I)
12124     AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12125                                CandidateSet, PartialOverloading,
12126                                /*KnownValid*/ true);
12127 
12128   if (ULE->requiresADL())
12129     AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12130                                          Args, ExplicitTemplateArgs,
12131                                          CandidateSet, PartialOverloading);
12132 }
12133 
12134 /// Determine whether a declaration with the specified name could be moved into
12135 /// a different namespace.
12136 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12137   switch (Name.getCXXOverloadedOperator()) {
12138   case OO_New: case OO_Array_New:
12139   case OO_Delete: case OO_Array_Delete:
12140     return false;
12141 
12142   default:
12143     return true;
12144   }
12145 }
12146 
12147 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12148 /// template, where the non-dependent name was declared after the template
12149 /// was defined. This is common in code written for a compilers which do not
12150 /// correctly implement two-stage name lookup.
12151 ///
12152 /// Returns true if a viable candidate was found and a diagnostic was issued.
12153 static bool
12154 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12155                        const CXXScopeSpec &SS, LookupResult &R,
12156                        OverloadCandidateSet::CandidateSetKind CSK,
12157                        TemplateArgumentListInfo *ExplicitTemplateArgs,
12158                        ArrayRef<Expr *> Args,
12159                        bool *DoDiagnoseEmptyLookup = nullptr) {
12160   if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12161     return false;
12162 
12163   for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12164     if (DC->isTransparentContext())
12165       continue;
12166 
12167     SemaRef.LookupQualifiedName(R, DC);
12168 
12169     if (!R.empty()) {
12170       R.suppressDiagnostics();
12171 
12172       if (isa<CXXRecordDecl>(DC)) {
12173         // Don't diagnose names we find in classes; we get much better
12174         // diagnostics for these from DiagnoseEmptyLookup.
12175         R.clear();
12176         if (DoDiagnoseEmptyLookup)
12177           *DoDiagnoseEmptyLookup = true;
12178         return false;
12179       }
12180 
12181       OverloadCandidateSet Candidates(FnLoc, CSK);
12182       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12183         AddOverloadedCallCandidate(SemaRef, I.getPair(),
12184                                    ExplicitTemplateArgs, Args,
12185                                    Candidates, false, /*KnownValid*/ false);
12186 
12187       OverloadCandidateSet::iterator Best;
12188       if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12189         // No viable functions. Don't bother the user with notes for functions
12190         // which don't work and shouldn't be found anyway.
12191         R.clear();
12192         return false;
12193       }
12194 
12195       // Find the namespaces where ADL would have looked, and suggest
12196       // declaring the function there instead.
12197       Sema::AssociatedNamespaceSet AssociatedNamespaces;
12198       Sema::AssociatedClassSet AssociatedClasses;
12199       SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12200                                                  AssociatedNamespaces,
12201                                                  AssociatedClasses);
12202       Sema::AssociatedNamespaceSet SuggestedNamespaces;
12203       if (canBeDeclaredInNamespace(R.getLookupName())) {
12204         DeclContext *Std = SemaRef.getStdNamespace();
12205         for (Sema::AssociatedNamespaceSet::iterator
12206                it = AssociatedNamespaces.begin(),
12207                end = AssociatedNamespaces.end(); it != end; ++it) {
12208           // Never suggest declaring a function within namespace 'std'.
12209           if (Std && Std->Encloses(*it))
12210             continue;
12211 
12212           // Never suggest declaring a function within a namespace with a
12213           // reserved name, like __gnu_cxx.
12214           NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12215           if (NS &&
12216               NS->getQualifiedNameAsString().find("__") != std::string::npos)
12217             continue;
12218 
12219           SuggestedNamespaces.insert(*it);
12220         }
12221       }
12222 
12223       SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12224         << R.getLookupName();
12225       if (SuggestedNamespaces.empty()) {
12226         SemaRef.Diag(Best->Function->getLocation(),
12227                      diag::note_not_found_by_two_phase_lookup)
12228           << R.getLookupName() << 0;
12229       } else if (SuggestedNamespaces.size() == 1) {
12230         SemaRef.Diag(Best->Function->getLocation(),
12231                      diag::note_not_found_by_two_phase_lookup)
12232           << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12233       } else {
12234         // FIXME: It would be useful to list the associated namespaces here,
12235         // but the diagnostics infrastructure doesn't provide a way to produce
12236         // a localized representation of a list of items.
12237         SemaRef.Diag(Best->Function->getLocation(),
12238                      diag::note_not_found_by_two_phase_lookup)
12239           << R.getLookupName() << 2;
12240       }
12241 
12242       // Try to recover by calling this function.
12243       return true;
12244     }
12245 
12246     R.clear();
12247   }
12248 
12249   return false;
12250 }
12251 
12252 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12253 /// template, where the non-dependent operator was declared after the template
12254 /// was defined.
12255 ///
12256 /// Returns true if a viable candidate was found and a diagnostic was issued.
12257 static bool
12258 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12259                                SourceLocation OpLoc,
12260                                ArrayRef<Expr *> Args) {
12261   DeclarationName OpName =
12262     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12263   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12264   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12265                                 OverloadCandidateSet::CSK_Operator,
12266                                 /*ExplicitTemplateArgs=*/nullptr, Args);
12267 }
12268 
12269 namespace {
12270 class BuildRecoveryCallExprRAII {
12271   Sema &SemaRef;
12272 public:
12273   BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12274     assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12275     SemaRef.IsBuildingRecoveryCallExpr = true;
12276   }
12277 
12278   ~BuildRecoveryCallExprRAII() {
12279     SemaRef.IsBuildingRecoveryCallExpr = false;
12280   }
12281 };
12282 
12283 }
12284 
12285 /// Attempts to recover from a call where no functions were found.
12286 ///
12287 /// Returns true if new candidates were found.
12288 static ExprResult
12289 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12290                       UnresolvedLookupExpr *ULE,
12291                       SourceLocation LParenLoc,
12292                       MutableArrayRef<Expr *> Args,
12293                       SourceLocation RParenLoc,
12294                       bool EmptyLookup, bool AllowTypoCorrection) {
12295   // Do not try to recover if it is already building a recovery call.
12296   // This stops infinite loops for template instantiations like
12297   //
12298   // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12299   // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12300   //
12301   if (SemaRef.IsBuildingRecoveryCallExpr)
12302     return ExprError();
12303   BuildRecoveryCallExprRAII RCE(SemaRef);
12304 
12305   CXXScopeSpec SS;
12306   SS.Adopt(ULE->getQualifierLoc());
12307   SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12308 
12309   TemplateArgumentListInfo TABuffer;
12310   TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12311   if (ULE->hasExplicitTemplateArgs()) {
12312     ULE->copyTemplateArgumentsInto(TABuffer);
12313     ExplicitTemplateArgs = &TABuffer;
12314   }
12315 
12316   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12317                  Sema::LookupOrdinaryName);
12318   bool DoDiagnoseEmptyLookup = EmptyLookup;
12319   if (!DiagnoseTwoPhaseLookup(
12320           SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12321           ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12322     NoTypoCorrectionCCC NoTypoValidator{};
12323     FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12324                                                 ExplicitTemplateArgs != nullptr,
12325                                                 dyn_cast<MemberExpr>(Fn));
12326     CorrectionCandidateCallback &Validator =
12327         AllowTypoCorrection
12328             ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12329             : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12330     if (!DoDiagnoseEmptyLookup ||
12331         SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12332                                     Args))
12333       return ExprError();
12334   }
12335 
12336   assert(!R.empty() && "lookup results empty despite recovery");
12337 
12338   // If recovery created an ambiguity, just bail out.
12339   if (R.isAmbiguous()) {
12340     R.suppressDiagnostics();
12341     return ExprError();
12342   }
12343 
12344   // Build an implicit member call if appropriate.  Just drop the
12345   // casts and such from the call, we don't really care.
12346   ExprResult NewFn = ExprError();
12347   if ((*R.begin())->isCXXClassMember())
12348     NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12349                                                     ExplicitTemplateArgs, S);
12350   else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12351     NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12352                                         ExplicitTemplateArgs);
12353   else
12354     NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12355 
12356   if (NewFn.isInvalid())
12357     return ExprError();
12358 
12359   // This shouldn't cause an infinite loop because we're giving it
12360   // an expression with viable lookup results, which should never
12361   // end up here.
12362   return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12363                                MultiExprArg(Args.data(), Args.size()),
12364                                RParenLoc);
12365 }
12366 
12367 /// Constructs and populates an OverloadedCandidateSet from
12368 /// the given function.
12369 /// \returns true when an the ExprResult output parameter has been set.
12370 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12371                                   UnresolvedLookupExpr *ULE,
12372                                   MultiExprArg Args,
12373                                   SourceLocation RParenLoc,
12374                                   OverloadCandidateSet *CandidateSet,
12375                                   ExprResult *Result) {
12376 #ifndef NDEBUG
12377   if (ULE->requiresADL()) {
12378     // To do ADL, we must have found an unqualified name.
12379     assert(!ULE->getQualifier() && "qualified name with ADL");
12380 
12381     // We don't perform ADL for implicit declarations of builtins.
12382     // Verify that this was correctly set up.
12383     FunctionDecl *F;
12384     if (ULE->decls_begin() != ULE->decls_end() &&
12385         ULE->decls_begin() + 1 == ULE->decls_end() &&
12386         (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12387         F->getBuiltinID() && F->isImplicit())
12388       llvm_unreachable("performing ADL for builtin");
12389 
12390     // We don't perform ADL in C.
12391     assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12392   }
12393 #endif
12394 
12395   UnbridgedCastsSet UnbridgedCasts;
12396   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12397     *Result = ExprError();
12398     return true;
12399   }
12400 
12401   // Add the functions denoted by the callee to the set of candidate
12402   // functions, including those from argument-dependent lookup.
12403   AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12404 
12405   if (getLangOpts().MSVCCompat &&
12406       CurContext->isDependentContext() && !isSFINAEContext() &&
12407       (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12408 
12409     OverloadCandidateSet::iterator Best;
12410     if (CandidateSet->empty() ||
12411         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12412             OR_No_Viable_Function) {
12413       // In Microsoft mode, if we are inside a template class member function
12414       // then create a type dependent CallExpr. The goal is to postpone name
12415       // lookup to instantiation time to be able to search into type dependent
12416       // base classes.
12417       CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12418                                       VK_RValue, RParenLoc);
12419       CE->setTypeDependent(true);
12420       CE->setValueDependent(true);
12421       CE->setInstantiationDependent(true);
12422       *Result = CE;
12423       return true;
12424     }
12425   }
12426 
12427   if (CandidateSet->empty())
12428     return false;
12429 
12430   UnbridgedCasts.restore();
12431   return false;
12432 }
12433 
12434 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12435 /// the completed call expression. If overload resolution fails, emits
12436 /// diagnostics and returns ExprError()
12437 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12438                                            UnresolvedLookupExpr *ULE,
12439                                            SourceLocation LParenLoc,
12440                                            MultiExprArg Args,
12441                                            SourceLocation RParenLoc,
12442                                            Expr *ExecConfig,
12443                                            OverloadCandidateSet *CandidateSet,
12444                                            OverloadCandidateSet::iterator *Best,
12445                                            OverloadingResult OverloadResult,
12446                                            bool AllowTypoCorrection) {
12447   if (CandidateSet->empty())
12448     return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12449                                  RParenLoc, /*EmptyLookup=*/true,
12450                                  AllowTypoCorrection);
12451 
12452   switch (OverloadResult) {
12453   case OR_Success: {
12454     FunctionDecl *FDecl = (*Best)->Function;
12455     SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12456     if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12457       return ExprError();
12458     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12459     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12460                                          ExecConfig, /*IsExecConfig=*/false,
12461                                          (*Best)->IsADLCandidate);
12462   }
12463 
12464   case OR_No_Viable_Function: {
12465     // Try to recover by looking for viable functions which the user might
12466     // have meant to call.
12467     ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12468                                                 Args, RParenLoc,
12469                                                 /*EmptyLookup=*/false,
12470                                                 AllowTypoCorrection);
12471     if (!Recovery.isInvalid())
12472       return Recovery;
12473 
12474     // If the user passes in a function that we can't take the address of, we
12475     // generally end up emitting really bad error messages. Here, we attempt to
12476     // emit better ones.
12477     for (const Expr *Arg : Args) {
12478       if (!Arg->getType()->isFunctionType())
12479         continue;
12480       if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12481         auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12482         if (FD &&
12483             !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12484                                                        Arg->getExprLoc()))
12485           return ExprError();
12486       }
12487     }
12488 
12489     CandidateSet->NoteCandidates(
12490         PartialDiagnosticAt(
12491             Fn->getBeginLoc(),
12492             SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12493                 << ULE->getName() << Fn->getSourceRange()),
12494         SemaRef, OCD_AllCandidates, Args);
12495     break;
12496   }
12497 
12498   case OR_Ambiguous:
12499     CandidateSet->NoteCandidates(
12500         PartialDiagnosticAt(Fn->getBeginLoc(),
12501                             SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12502                                 << ULE->getName() << Fn->getSourceRange()),
12503         SemaRef, OCD_AmbiguousCandidates, Args);
12504     break;
12505 
12506   case OR_Deleted: {
12507     CandidateSet->NoteCandidates(
12508         PartialDiagnosticAt(Fn->getBeginLoc(),
12509                             SemaRef.PDiag(diag::err_ovl_deleted_call)
12510                                 << ULE->getName() << Fn->getSourceRange()),
12511         SemaRef, OCD_AllCandidates, Args);
12512 
12513     // We emitted an error for the unavailable/deleted function call but keep
12514     // the call in the AST.
12515     FunctionDecl *FDecl = (*Best)->Function;
12516     Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12517     return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12518                                          ExecConfig, /*IsExecConfig=*/false,
12519                                          (*Best)->IsADLCandidate);
12520   }
12521   }
12522 
12523   // Overload resolution failed.
12524   return ExprError();
12525 }
12526 
12527 static void markUnaddressableCandidatesUnviable(Sema &S,
12528                                                 OverloadCandidateSet &CS) {
12529   for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12530     if (I->Viable &&
12531         !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12532       I->Viable = false;
12533       I->FailureKind = ovl_fail_addr_not_available;
12534     }
12535   }
12536 }
12537 
12538 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12539 /// (which eventually refers to the declaration Func) and the call
12540 /// arguments Args/NumArgs, attempt to resolve the function call down
12541 /// to a specific function. If overload resolution succeeds, returns
12542 /// the call expression produced by overload resolution.
12543 /// Otherwise, emits diagnostics and returns ExprError.
12544 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12545                                          UnresolvedLookupExpr *ULE,
12546                                          SourceLocation LParenLoc,
12547                                          MultiExprArg Args,
12548                                          SourceLocation RParenLoc,
12549                                          Expr *ExecConfig,
12550                                          bool AllowTypoCorrection,
12551                                          bool CalleesAddressIsTaken) {
12552   OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12553                                     OverloadCandidateSet::CSK_Normal);
12554   ExprResult result;
12555 
12556   if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12557                              &result))
12558     return result;
12559 
12560   // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12561   // functions that aren't addressible are considered unviable.
12562   if (CalleesAddressIsTaken)
12563     markUnaddressableCandidatesUnviable(*this, CandidateSet);
12564 
12565   OverloadCandidateSet::iterator Best;
12566   OverloadingResult OverloadResult =
12567       CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12568 
12569   return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12570                                   ExecConfig, &CandidateSet, &Best,
12571                                   OverloadResult, AllowTypoCorrection);
12572 }
12573 
12574 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12575   return Functions.size() > 1 ||
12576     (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12577 }
12578 
12579 /// Create a unary operation that may resolve to an overloaded
12580 /// operator.
12581 ///
12582 /// \param OpLoc The location of the operator itself (e.g., '*').
12583 ///
12584 /// \param Opc The UnaryOperatorKind that describes this operator.
12585 ///
12586 /// \param Fns The set of non-member functions that will be
12587 /// considered by overload resolution. The caller needs to build this
12588 /// set based on the context using, e.g.,
12589 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12590 /// set should not contain any member functions; those will be added
12591 /// by CreateOverloadedUnaryOp().
12592 ///
12593 /// \param Input The input argument.
12594 ExprResult
12595 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12596                               const UnresolvedSetImpl &Fns,
12597                               Expr *Input, bool PerformADL) {
12598   OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12599   assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12600   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12601   // TODO: provide better source location info.
12602   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12603 
12604   if (checkPlaceholderForOverload(*this, Input))
12605     return ExprError();
12606 
12607   Expr *Args[2] = { Input, nullptr };
12608   unsigned NumArgs = 1;
12609 
12610   // For post-increment and post-decrement, add the implicit '0' as
12611   // the second argument, so that we know this is a post-increment or
12612   // post-decrement.
12613   if (Opc == UO_PostInc || Opc == UO_PostDec) {
12614     llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12615     Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12616                                      SourceLocation());
12617     NumArgs = 2;
12618   }
12619 
12620   ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12621 
12622   if (Input->isTypeDependent()) {
12623     if (Fns.empty())
12624       return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12625                                          VK_RValue, OK_Ordinary, OpLoc, false);
12626 
12627     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12628     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12629         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12630         /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12631     return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12632                                        Context.DependentTy, VK_RValue, OpLoc,
12633                                        FPOptions());
12634   }
12635 
12636   // Build an empty overload set.
12637   OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12638 
12639   // Add the candidates from the given function set.
12640   AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12641 
12642   // Add operator candidates that are member functions.
12643   AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12644 
12645   // Add candidates from ADL.
12646   if (PerformADL) {
12647     AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12648                                          /*ExplicitTemplateArgs*/nullptr,
12649                                          CandidateSet);
12650   }
12651 
12652   // Add builtin operator candidates.
12653   AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12654 
12655   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12656 
12657   // Perform overload resolution.
12658   OverloadCandidateSet::iterator Best;
12659   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12660   case OR_Success: {
12661     // We found a built-in operator or an overloaded operator.
12662     FunctionDecl *FnDecl = Best->Function;
12663 
12664     if (FnDecl) {
12665       Expr *Base = nullptr;
12666       // We matched an overloaded operator. Build a call to that
12667       // operator.
12668 
12669       // Convert the arguments.
12670       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12671         CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12672 
12673         ExprResult InputRes =
12674           PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12675                                               Best->FoundDecl, Method);
12676         if (InputRes.isInvalid())
12677           return ExprError();
12678         Base = Input = InputRes.get();
12679       } else {
12680         // Convert the arguments.
12681         ExprResult InputInit
12682           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12683                                                       Context,
12684                                                       FnDecl->getParamDecl(0)),
12685                                       SourceLocation(),
12686                                       Input);
12687         if (InputInit.isInvalid())
12688           return ExprError();
12689         Input = InputInit.get();
12690       }
12691 
12692       // Build the actual expression node.
12693       ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12694                                                 Base, HadMultipleCandidates,
12695                                                 OpLoc);
12696       if (FnExpr.isInvalid())
12697         return ExprError();
12698 
12699       // Determine the result type.
12700       QualType ResultTy = FnDecl->getReturnType();
12701       ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12702       ResultTy = ResultTy.getNonLValueExprType(Context);
12703 
12704       Args[0] = Input;
12705       CallExpr *TheCall = CXXOperatorCallExpr::Create(
12706           Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12707           FPOptions(), Best->IsADLCandidate);
12708 
12709       if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12710         return ExprError();
12711 
12712       if (CheckFunctionCall(FnDecl, TheCall,
12713                             FnDecl->getType()->castAs<FunctionProtoType>()))
12714         return ExprError();
12715 
12716       return MaybeBindToTemporary(TheCall);
12717     } else {
12718       // We matched a built-in operator. Convert the arguments, then
12719       // break out so that we will build the appropriate built-in
12720       // operator node.
12721       ExprResult InputRes = PerformImplicitConversion(
12722           Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12723           CCK_ForBuiltinOverloadedOp);
12724       if (InputRes.isInvalid())
12725         return ExprError();
12726       Input = InputRes.get();
12727       break;
12728     }
12729   }
12730 
12731   case OR_No_Viable_Function:
12732     // This is an erroneous use of an operator which can be overloaded by
12733     // a non-member function. Check for non-member operators which were
12734     // defined too late to be candidates.
12735     if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12736       // FIXME: Recover by calling the found function.
12737       return ExprError();
12738 
12739     // No viable function; fall through to handling this as a
12740     // built-in operator, which will produce an error message for us.
12741     break;
12742 
12743   case OR_Ambiguous:
12744     CandidateSet.NoteCandidates(
12745         PartialDiagnosticAt(OpLoc,
12746                             PDiag(diag::err_ovl_ambiguous_oper_unary)
12747                                 << UnaryOperator::getOpcodeStr(Opc)
12748                                 << Input->getType() << Input->getSourceRange()),
12749         *this, OCD_AmbiguousCandidates, ArgsArray,
12750         UnaryOperator::getOpcodeStr(Opc), OpLoc);
12751     return ExprError();
12752 
12753   case OR_Deleted:
12754     CandidateSet.NoteCandidates(
12755         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12756                                        << UnaryOperator::getOpcodeStr(Opc)
12757                                        << Input->getSourceRange()),
12758         *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12759         OpLoc);
12760     return ExprError();
12761   }
12762 
12763   // Either we found no viable overloaded operator or we matched a
12764   // built-in operator. In either case, fall through to trying to
12765   // build a built-in operation.
12766   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12767 }
12768 
12769 /// Perform lookup for an overloaded binary operator.
12770 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
12771                                  OverloadedOperatorKind Op,
12772                                  const UnresolvedSetImpl &Fns,
12773                                  ArrayRef<Expr *> Args, bool PerformADL) {
12774   SourceLocation OpLoc = CandidateSet.getLocation();
12775 
12776   OverloadedOperatorKind ExtraOp =
12777       CandidateSet.getRewriteInfo().AllowRewrittenCandidates
12778           ? getRewrittenOverloadedOperator(Op)
12779           : OO_None;
12780 
12781   // Add the candidates from the given function set. This also adds the
12782   // rewritten candidates using these functions if necessary.
12783   AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
12784 
12785   // Add operator candidates that are member functions.
12786   AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12787   if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
12788     AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
12789                                 OverloadCandidateParamOrder::Reversed);
12790 
12791   // In C++20, also add any rewritten member candidates.
12792   if (ExtraOp) {
12793     AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
12794     if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
12795       AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
12796                                   CandidateSet,
12797                                   OverloadCandidateParamOrder::Reversed);
12798   }
12799 
12800   // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12801   // performed for an assignment operator (nor for operator[] nor operator->,
12802   // which don't get here).
12803   if (Op != OO_Equal && PerformADL) {
12804     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12805     AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12806                                          /*ExplicitTemplateArgs*/ nullptr,
12807                                          CandidateSet);
12808     if (ExtraOp) {
12809       DeclarationName ExtraOpName =
12810           Context.DeclarationNames.getCXXOperatorName(ExtraOp);
12811       AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
12812                                            /*ExplicitTemplateArgs*/ nullptr,
12813                                            CandidateSet);
12814     }
12815   }
12816 
12817   // Add builtin operator candidates.
12818   //
12819   // FIXME: We don't add any rewritten candidates here. This is strictly
12820   // incorrect; a builtin candidate could be hidden by a non-viable candidate,
12821   // resulting in our selecting a rewritten builtin candidate. For example:
12822   //
12823   //   enum class E { e };
12824   //   bool operator!=(E, E) requires false;
12825   //   bool k = E::e != E::e;
12826   //
12827   // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
12828   // it seems unreasonable to consider rewritten builtin candidates. A core
12829   // issue has been filed proposing to removed this requirement.
12830   AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12831 }
12832 
12833 /// Create a binary operation that may resolve to an overloaded
12834 /// operator.
12835 ///
12836 /// \param OpLoc The location of the operator itself (e.g., '+').
12837 ///
12838 /// \param Opc The BinaryOperatorKind that describes this operator.
12839 ///
12840 /// \param Fns The set of non-member functions that will be
12841 /// considered by overload resolution. The caller needs to build this
12842 /// set based on the context using, e.g.,
12843 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12844 /// set should not contain any member functions; those will be added
12845 /// by CreateOverloadedBinOp().
12846 ///
12847 /// \param LHS Left-hand argument.
12848 /// \param RHS Right-hand argument.
12849 /// \param PerformADL Whether to consider operator candidates found by ADL.
12850 /// \param AllowRewrittenCandidates Whether to consider candidates found by
12851 ///        C++20 operator rewrites.
12852 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
12853 ///        the function in question. Such a function is never a candidate in
12854 ///        our overload resolution. This also enables synthesizing a three-way
12855 ///        comparison from < and == as described in C++20 [class.spaceship]p1.
12856 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12857                                        BinaryOperatorKind Opc,
12858                                        const UnresolvedSetImpl &Fns, Expr *LHS,
12859                                        Expr *RHS, bool PerformADL,
12860                                        bool AllowRewrittenCandidates,
12861                                        FunctionDecl *DefaultedFn) {
12862   Expr *Args[2] = { LHS, RHS };
12863   LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12864 
12865   if (!getLangOpts().CPlusPlus2a)
12866     AllowRewrittenCandidates = false;
12867 
12868   OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12869 
12870   // If either side is type-dependent, create an appropriate dependent
12871   // expression.
12872   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12873     if (Fns.empty()) {
12874       // If there are no functions to store, just build a dependent
12875       // BinaryOperator or CompoundAssignment.
12876       if (Opc <= BO_Assign || Opc > BO_OrAssign)
12877         return new (Context) BinaryOperator(
12878             Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12879             OpLoc, FPFeatures);
12880 
12881       return new (Context) CompoundAssignOperator(
12882           Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12883           Context.DependentTy, Context.DependentTy, OpLoc,
12884           FPFeatures);
12885     }
12886 
12887     // FIXME: save results of ADL from here?
12888     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12889     // TODO: provide better source location info in DNLoc component.
12890     DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12891     DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12892     UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12893         Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12894         /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12895     return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12896                                        Context.DependentTy, VK_RValue, OpLoc,
12897                                        FPFeatures);
12898   }
12899 
12900   // Always do placeholder-like conversions on the RHS.
12901   if (checkPlaceholderForOverload(*this, Args[1]))
12902     return ExprError();
12903 
12904   // Do placeholder-like conversion on the LHS; note that we should
12905   // not get here with a PseudoObject LHS.
12906   assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12907   if (checkPlaceholderForOverload(*this, Args[0]))
12908     return ExprError();
12909 
12910   // If this is the assignment operator, we only perform overload resolution
12911   // if the left-hand side is a class or enumeration type. This is actually
12912   // a hack. The standard requires that we do overload resolution between the
12913   // various built-in candidates, but as DR507 points out, this can lead to
12914   // problems. So we do it this way, which pretty much follows what GCC does.
12915   // Note that we go the traditional code path for compound assignment forms.
12916   if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12917     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12918 
12919   // If this is the .* operator, which is not overloadable, just
12920   // create a built-in binary operator.
12921   if (Opc == BO_PtrMemD)
12922     return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12923 
12924   // Build the overload set.
12925   OverloadCandidateSet CandidateSet(
12926       OpLoc, OverloadCandidateSet::CSK_Operator,
12927       OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
12928   if (DefaultedFn)
12929     CandidateSet.exclude(DefaultedFn);
12930   LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
12931 
12932   bool HadMultipleCandidates = (CandidateSet.size() > 1);
12933 
12934   // Perform overload resolution.
12935   OverloadCandidateSet::iterator Best;
12936   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12937     case OR_Success: {
12938       // We found a built-in operator or an overloaded operator.
12939       FunctionDecl *FnDecl = Best->Function;
12940 
12941       bool IsReversed = (Best->RewriteKind & CRK_Reversed);
12942       if (IsReversed)
12943         std::swap(Args[0], Args[1]);
12944 
12945       if (FnDecl) {
12946         Expr *Base = nullptr;
12947         // We matched an overloaded operator. Build a call to that
12948         // operator.
12949 
12950         OverloadedOperatorKind ChosenOp =
12951             FnDecl->getDeclName().getCXXOverloadedOperator();
12952 
12953         // C++2a [over.match.oper]p9:
12954         //   If a rewritten operator== candidate is selected by overload
12955         //   resolution for an operator@, its return type shall be cv bool
12956         if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
12957             !FnDecl->getReturnType()->isBooleanType()) {
12958           Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
12959               << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
12960               << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12961           Diag(FnDecl->getLocation(), diag::note_declared_at);
12962           return ExprError();
12963         }
12964 
12965         if (AllowRewrittenCandidates && !IsReversed &&
12966             CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
12967           // We could have reversed this operator, but didn't. Check if the
12968           // reversed form was a viable candidate, and if so, if it had a
12969           // better conversion for either parameter. If so, this call is
12970           // formally ambiguous, and allowing it is an extension.
12971           for (OverloadCandidate &Cand : CandidateSet) {
12972             if (Cand.Viable && Cand.Function == FnDecl &&
12973                 Cand.RewriteKind & CRK_Reversed) {
12974               for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
12975                 if (CompareImplicitConversionSequences(
12976                         *this, OpLoc, Cand.Conversions[ArgIdx],
12977                         Best->Conversions[ArgIdx]) ==
12978                     ImplicitConversionSequence::Better) {
12979                   Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
12980                       << BinaryOperator::getOpcodeStr(Opc)
12981                       << Args[0]->getType() << Args[1]->getType()
12982                       << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12983                   Diag(FnDecl->getLocation(),
12984                        diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
12985                 }
12986               }
12987               break;
12988             }
12989           }
12990         }
12991 
12992         // Convert the arguments.
12993         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12994           // Best->Access is only meaningful for class members.
12995           CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12996 
12997           ExprResult Arg1 =
12998             PerformCopyInitialization(
12999               InitializedEntity::InitializeParameter(Context,
13000                                                      FnDecl->getParamDecl(0)),
13001               SourceLocation(), Args[1]);
13002           if (Arg1.isInvalid())
13003             return ExprError();
13004 
13005           ExprResult Arg0 =
13006             PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13007                                                 Best->FoundDecl, Method);
13008           if (Arg0.isInvalid())
13009             return ExprError();
13010           Base = Args[0] = Arg0.getAs<Expr>();
13011           Args[1] = RHS = Arg1.getAs<Expr>();
13012         } else {
13013           // Convert the arguments.
13014           ExprResult Arg0 = PerformCopyInitialization(
13015             InitializedEntity::InitializeParameter(Context,
13016                                                    FnDecl->getParamDecl(0)),
13017             SourceLocation(), Args[0]);
13018           if (Arg0.isInvalid())
13019             return ExprError();
13020 
13021           ExprResult Arg1 =
13022             PerformCopyInitialization(
13023               InitializedEntity::InitializeParameter(Context,
13024                                                      FnDecl->getParamDecl(1)),
13025               SourceLocation(), Args[1]);
13026           if (Arg1.isInvalid())
13027             return ExprError();
13028           Args[0] = LHS = Arg0.getAs<Expr>();
13029           Args[1] = RHS = Arg1.getAs<Expr>();
13030         }
13031 
13032         // Build the actual expression node.
13033         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13034                                                   Best->FoundDecl, Base,
13035                                                   HadMultipleCandidates, OpLoc);
13036         if (FnExpr.isInvalid())
13037           return ExprError();
13038 
13039         // Determine the result type.
13040         QualType ResultTy = FnDecl->getReturnType();
13041         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13042         ResultTy = ResultTy.getNonLValueExprType(Context);
13043 
13044         CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13045             Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13046             FPFeatures, Best->IsADLCandidate);
13047 
13048         if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13049                                 FnDecl))
13050           return ExprError();
13051 
13052         ArrayRef<const Expr *> ArgsArray(Args, 2);
13053         const Expr *ImplicitThis = nullptr;
13054         // Cut off the implicit 'this'.
13055         if (isa<CXXMethodDecl>(FnDecl)) {
13056           ImplicitThis = ArgsArray[0];
13057           ArgsArray = ArgsArray.slice(1);
13058         }
13059 
13060         // Check for a self move.
13061         if (Op == OO_Equal)
13062           DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13063 
13064         checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13065                   isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13066                   VariadicDoesNotApply);
13067 
13068         ExprResult R = MaybeBindToTemporary(TheCall);
13069         if (R.isInvalid())
13070           return ExprError();
13071 
13072         // For a rewritten candidate, we've already reversed the arguments
13073         // if needed. Perform the rest of the rewrite now.
13074         if ((Best->RewriteKind & CRK_DifferentOperator) ||
13075             (Op == OO_Spaceship && IsReversed)) {
13076           if (Op == OO_ExclaimEqual) {
13077             assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13078             R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13079           } else {
13080             assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13081             llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13082             Expr *ZeroLiteral =
13083                 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13084 
13085             Sema::CodeSynthesisContext Ctx;
13086             Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13087             Ctx.Entity = FnDecl;
13088             pushCodeSynthesisContext(Ctx);
13089 
13090             R = CreateOverloadedBinOp(
13091                 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13092                 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13093                 /*AllowRewrittenCandidates=*/false);
13094 
13095             popCodeSynthesisContext();
13096           }
13097           if (R.isInvalid())
13098             return ExprError();
13099         } else {
13100           assert(ChosenOp == Op && "unexpected operator name");
13101         }
13102 
13103         // Make a note in the AST if we did any rewriting.
13104         if (Best->RewriteKind != CRK_None)
13105           R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13106 
13107         return R;
13108       } else {
13109         // We matched a built-in operator. Convert the arguments, then
13110         // break out so that we will build the appropriate built-in
13111         // operator node.
13112         ExprResult ArgsRes0 = PerformImplicitConversion(
13113             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13114             AA_Passing, CCK_ForBuiltinOverloadedOp);
13115         if (ArgsRes0.isInvalid())
13116           return ExprError();
13117         Args[0] = ArgsRes0.get();
13118 
13119         ExprResult ArgsRes1 = PerformImplicitConversion(
13120             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13121             AA_Passing, CCK_ForBuiltinOverloadedOp);
13122         if (ArgsRes1.isInvalid())
13123           return ExprError();
13124         Args[1] = ArgsRes1.get();
13125         break;
13126       }
13127     }
13128 
13129     case OR_No_Viable_Function: {
13130       // C++ [over.match.oper]p9:
13131       //   If the operator is the operator , [...] and there are no
13132       //   viable functions, then the operator is assumed to be the
13133       //   built-in operator and interpreted according to clause 5.
13134       if (Opc == BO_Comma)
13135         break;
13136 
13137       // When defaulting an 'operator<=>', we can try to synthesize a three-way
13138       // compare result using '==' and '<'.
13139       if (DefaultedFn && Opc == BO_Cmp) {
13140         ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13141                                                           Args[1], DefaultedFn);
13142         if (E.isInvalid() || E.isUsable())
13143           return E;
13144       }
13145 
13146       // For class as left operand for assignment or compound assignment
13147       // operator do not fall through to handling in built-in, but report that
13148       // no overloaded assignment operator found
13149       ExprResult Result = ExprError();
13150       StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13151       auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13152                                                    Args, OpLoc);
13153       if (Args[0]->getType()->isRecordType() &&
13154           Opc >= BO_Assign && Opc <= BO_OrAssign) {
13155         Diag(OpLoc,  diag::err_ovl_no_viable_oper)
13156              << BinaryOperator::getOpcodeStr(Opc)
13157              << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13158         if (Args[0]->getType()->isIncompleteType()) {
13159           Diag(OpLoc, diag::note_assign_lhs_incomplete)
13160             << Args[0]->getType()
13161             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13162         }
13163       } else {
13164         // This is an erroneous use of an operator which can be overloaded by
13165         // a non-member function. Check for non-member operators which were
13166         // defined too late to be candidates.
13167         if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13168           // FIXME: Recover by calling the found function.
13169           return ExprError();
13170 
13171         // No viable function; try to create a built-in operation, which will
13172         // produce an error. Then, show the non-viable candidates.
13173         Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13174       }
13175       assert(Result.isInvalid() &&
13176              "C++ binary operator overloading is missing candidates!");
13177       CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13178       return Result;
13179     }
13180 
13181     case OR_Ambiguous:
13182       CandidateSet.NoteCandidates(
13183           PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13184                                          << BinaryOperator::getOpcodeStr(Opc)
13185                                          << Args[0]->getType()
13186                                          << Args[1]->getType()
13187                                          << Args[0]->getSourceRange()
13188                                          << Args[1]->getSourceRange()),
13189           *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13190           OpLoc);
13191       return ExprError();
13192 
13193     case OR_Deleted:
13194       if (isImplicitlyDeleted(Best->Function)) {
13195         FunctionDecl *DeletedFD = Best->Function;
13196         DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13197         if (DFK.isSpecialMember()) {
13198           Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13199             << Args[0]->getType() << DFK.asSpecialMember();
13200         } else {
13201           assert(DFK.isComparison());
13202           Diag(OpLoc, diag::err_ovl_deleted_comparison)
13203             << Args[0]->getType() << DeletedFD;
13204         }
13205 
13206         // The user probably meant to call this special member. Just
13207         // explain why it's deleted.
13208         NoteDeletedFunction(DeletedFD);
13209         return ExprError();
13210       }
13211       CandidateSet.NoteCandidates(
13212           PartialDiagnosticAt(
13213               OpLoc, PDiag(diag::err_ovl_deleted_oper)
13214                          << getOperatorSpelling(Best->Function->getDeclName()
13215                                                     .getCXXOverloadedOperator())
13216                          << Args[0]->getSourceRange()
13217                          << Args[1]->getSourceRange()),
13218           *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13219           OpLoc);
13220       return ExprError();
13221   }
13222 
13223   // We matched a built-in operator; build it.
13224   return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13225 }
13226 
13227 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13228     SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13229     FunctionDecl *DefaultedFn) {
13230   const ComparisonCategoryInfo *Info =
13231       Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13232   // If we're not producing a known comparison category type, we can't
13233   // synthesize a three-way comparison. Let the caller diagnose this.
13234   if (!Info)
13235     return ExprResult((Expr*)nullptr);
13236 
13237   // If we ever want to perform this synthesis more generally, we will need to
13238   // apply the temporary materialization conversion to the operands.
13239   assert(LHS->isGLValue() && RHS->isGLValue() &&
13240          "cannot use prvalue expressions more than once");
13241   Expr *OrigLHS = LHS;
13242   Expr *OrigRHS = RHS;
13243 
13244   // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13245   // each of them multiple times below.
13246   LHS = new (Context)
13247       OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13248                       LHS->getObjectKind(), LHS);
13249   RHS = new (Context)
13250       OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13251                       RHS->getObjectKind(), RHS);
13252 
13253   ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13254                                         DefaultedFn);
13255   if (Eq.isInvalid())
13256     return ExprError();
13257 
13258   ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13259                                           true, DefaultedFn);
13260   if (Less.isInvalid())
13261     return ExprError();
13262 
13263   ExprResult Greater;
13264   if (Info->isPartial()) {
13265     Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13266                                     DefaultedFn);
13267     if (Greater.isInvalid())
13268       return ExprError();
13269   }
13270 
13271   // Form the list of comparisons we're going to perform.
13272   struct Comparison {
13273     ExprResult Cmp;
13274     ComparisonCategoryResult Result;
13275   } Comparisons[4] =
13276   { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13277                           : ComparisonCategoryResult::Equivalent},
13278     {Less, ComparisonCategoryResult::Less},
13279     {Greater, ComparisonCategoryResult::Greater},
13280     {ExprResult(), ComparisonCategoryResult::Unordered},
13281   };
13282 
13283   int I = Info->isPartial() ? 3 : 2;
13284 
13285   // Combine the comparisons with suitable conditional expressions.
13286   ExprResult Result;
13287   for (; I >= 0; --I) {
13288     // Build a reference to the comparison category constant.
13289     auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13290     // FIXME: Missing a constant for a comparison category. Diagnose this?
13291     if (!VI)
13292       return ExprResult((Expr*)nullptr);
13293     ExprResult ThisResult =
13294         BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13295     if (ThisResult.isInvalid())
13296       return ExprError();
13297 
13298     // Build a conditional unless this is the final case.
13299     if (Result.get()) {
13300       Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13301                                   ThisResult.get(), Result.get());
13302       if (Result.isInvalid())
13303         return ExprError();
13304     } else {
13305       Result = ThisResult;
13306     }
13307   }
13308 
13309   // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13310   // bind the OpaqueValueExprs before they're (repeatedly) used.
13311   Expr *SyntacticForm = new (Context)
13312       BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13313                      Result.get()->getValueKind(),
13314                      Result.get()->getObjectKind(), OpLoc, FPFeatures);
13315   Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13316   return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13317 }
13318 
13319 ExprResult
13320 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13321                                          SourceLocation RLoc,
13322                                          Expr *Base, Expr *Idx) {
13323   Expr *Args[2] = { Base, Idx };
13324   DeclarationName OpName =
13325       Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13326 
13327   // If either side is type-dependent, create an appropriate dependent
13328   // expression.
13329   if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13330 
13331     CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13332     // CHECKME: no 'operator' keyword?
13333     DeclarationNameInfo OpNameInfo(OpName, LLoc);
13334     OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13335     UnresolvedLookupExpr *Fn
13336       = UnresolvedLookupExpr::Create(Context, NamingClass,
13337                                      NestedNameSpecifierLoc(), OpNameInfo,
13338                                      /*ADL*/ true, /*Overloaded*/ false,
13339                                      UnresolvedSetIterator(),
13340                                      UnresolvedSetIterator());
13341     // Can't add any actual overloads yet
13342 
13343     return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13344                                        Context.DependentTy, VK_RValue, RLoc,
13345                                        FPOptions());
13346   }
13347 
13348   // Handle placeholders on both operands.
13349   if (checkPlaceholderForOverload(*this, Args[0]))
13350     return ExprError();
13351   if (checkPlaceholderForOverload(*this, Args[1]))
13352     return ExprError();
13353 
13354   // Build an empty overload set.
13355   OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13356 
13357   // Subscript can only be overloaded as a member function.
13358 
13359   // Add operator candidates that are member functions.
13360   AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13361 
13362   // Add builtin operator candidates.
13363   AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13364 
13365   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13366 
13367   // Perform overload resolution.
13368   OverloadCandidateSet::iterator Best;
13369   switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13370     case OR_Success: {
13371       // We found a built-in operator or an overloaded operator.
13372       FunctionDecl *FnDecl = Best->Function;
13373 
13374       if (FnDecl) {
13375         // We matched an overloaded operator. Build a call to that
13376         // operator.
13377 
13378         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13379 
13380         // Convert the arguments.
13381         CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13382         ExprResult Arg0 =
13383           PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13384                                               Best->FoundDecl, Method);
13385         if (Arg0.isInvalid())
13386           return ExprError();
13387         Args[0] = Arg0.get();
13388 
13389         // Convert the arguments.
13390         ExprResult InputInit
13391           = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13392                                                       Context,
13393                                                       FnDecl->getParamDecl(0)),
13394                                       SourceLocation(),
13395                                       Args[1]);
13396         if (InputInit.isInvalid())
13397           return ExprError();
13398 
13399         Args[1] = InputInit.getAs<Expr>();
13400 
13401         // Build the actual expression node.
13402         DeclarationNameInfo OpLocInfo(OpName, LLoc);
13403         OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13404         ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13405                                                   Best->FoundDecl,
13406                                                   Base,
13407                                                   HadMultipleCandidates,
13408                                                   OpLocInfo.getLoc(),
13409                                                   OpLocInfo.getInfo());
13410         if (FnExpr.isInvalid())
13411           return ExprError();
13412 
13413         // Determine the result type
13414         QualType ResultTy = FnDecl->getReturnType();
13415         ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13416         ResultTy = ResultTy.getNonLValueExprType(Context);
13417 
13418         CXXOperatorCallExpr *TheCall =
13419             CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13420                                         Args, ResultTy, VK, RLoc, FPOptions());
13421 
13422         if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13423           return ExprError();
13424 
13425         if (CheckFunctionCall(Method, TheCall,
13426                               Method->getType()->castAs<FunctionProtoType>()))
13427           return ExprError();
13428 
13429         return MaybeBindToTemporary(TheCall);
13430       } else {
13431         // We matched a built-in operator. Convert the arguments, then
13432         // break out so that we will build the appropriate built-in
13433         // operator node.
13434         ExprResult ArgsRes0 = PerformImplicitConversion(
13435             Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13436             AA_Passing, CCK_ForBuiltinOverloadedOp);
13437         if (ArgsRes0.isInvalid())
13438           return ExprError();
13439         Args[0] = ArgsRes0.get();
13440 
13441         ExprResult ArgsRes1 = PerformImplicitConversion(
13442             Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13443             AA_Passing, CCK_ForBuiltinOverloadedOp);
13444         if (ArgsRes1.isInvalid())
13445           return ExprError();
13446         Args[1] = ArgsRes1.get();
13447 
13448         break;
13449       }
13450     }
13451 
13452     case OR_No_Viable_Function: {
13453       PartialDiagnostic PD = CandidateSet.empty()
13454           ? (PDiag(diag::err_ovl_no_oper)
13455              << Args[0]->getType() << /*subscript*/ 0
13456              << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13457           : (PDiag(diag::err_ovl_no_viable_subscript)
13458              << Args[0]->getType() << Args[0]->getSourceRange()
13459              << Args[1]->getSourceRange());
13460       CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13461                                   OCD_AllCandidates, Args, "[]", LLoc);
13462       return ExprError();
13463     }
13464 
13465     case OR_Ambiguous:
13466       CandidateSet.NoteCandidates(
13467           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13468                                         << "[]" << Args[0]->getType()
13469                                         << Args[1]->getType()
13470                                         << Args[0]->getSourceRange()
13471                                         << Args[1]->getSourceRange()),
13472           *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13473       return ExprError();
13474 
13475     case OR_Deleted:
13476       CandidateSet.NoteCandidates(
13477           PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13478                                         << "[]" << Args[0]->getSourceRange()
13479                                         << Args[1]->getSourceRange()),
13480           *this, OCD_AllCandidates, Args, "[]", LLoc);
13481       return ExprError();
13482     }
13483 
13484   // We matched a built-in operator; build it.
13485   return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13486 }
13487 
13488 /// BuildCallToMemberFunction - Build a call to a member
13489 /// function. MemExpr is the expression that refers to the member
13490 /// function (and includes the object parameter), Args/NumArgs are the
13491 /// arguments to the function call (not including the object
13492 /// parameter). The caller needs to validate that the member
13493 /// expression refers to a non-static member function or an overloaded
13494 /// member function.
13495 ExprResult
13496 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13497                                 SourceLocation LParenLoc,
13498                                 MultiExprArg Args,
13499                                 SourceLocation RParenLoc) {
13500   assert(MemExprE->getType() == Context.BoundMemberTy ||
13501          MemExprE->getType() == Context.OverloadTy);
13502 
13503   // Dig out the member expression. This holds both the object
13504   // argument and the member function we're referring to.
13505   Expr *NakedMemExpr = MemExprE->IgnoreParens();
13506 
13507   // Determine whether this is a call to a pointer-to-member function.
13508   if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13509     assert(op->getType() == Context.BoundMemberTy);
13510     assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13511 
13512     QualType fnType =
13513       op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13514 
13515     const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13516     QualType resultType = proto->getCallResultType(Context);
13517     ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13518 
13519     // Check that the object type isn't more qualified than the
13520     // member function we're calling.
13521     Qualifiers funcQuals = proto->getMethodQuals();
13522 
13523     QualType objectType = op->getLHS()->getType();
13524     if (op->getOpcode() == BO_PtrMemI)
13525       objectType = objectType->castAs<PointerType>()->getPointeeType();
13526     Qualifiers objectQuals = objectType.getQualifiers();
13527 
13528     Qualifiers difference = objectQuals - funcQuals;
13529     difference.removeObjCGCAttr();
13530     difference.removeAddressSpace();
13531     if (difference) {
13532       std::string qualsString = difference.getAsString();
13533       Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13534         << fnType.getUnqualifiedType()
13535         << qualsString
13536         << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13537     }
13538 
13539     CXXMemberCallExpr *call =
13540         CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13541                                   valueKind, RParenLoc, proto->getNumParams());
13542 
13543     if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13544                             call, nullptr))
13545       return ExprError();
13546 
13547     if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13548       return ExprError();
13549 
13550     if (CheckOtherCall(call, proto))
13551       return ExprError();
13552 
13553     return MaybeBindToTemporary(call);
13554   }
13555 
13556   if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13557     return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13558                             RParenLoc);
13559 
13560   UnbridgedCastsSet UnbridgedCasts;
13561   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13562     return ExprError();
13563 
13564   MemberExpr *MemExpr;
13565   CXXMethodDecl *Method = nullptr;
13566   DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13567   NestedNameSpecifier *Qualifier = nullptr;
13568   if (isa<MemberExpr>(NakedMemExpr)) {
13569     MemExpr = cast<MemberExpr>(NakedMemExpr);
13570     Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13571     FoundDecl = MemExpr->getFoundDecl();
13572     Qualifier = MemExpr->getQualifier();
13573     UnbridgedCasts.restore();
13574   } else {
13575     UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13576     Qualifier = UnresExpr->getQualifier();
13577 
13578     QualType ObjectType = UnresExpr->getBaseType();
13579     Expr::Classification ObjectClassification
13580       = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13581                             : UnresExpr->getBase()->Classify(Context);
13582 
13583     // Add overload candidates
13584     OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13585                                       OverloadCandidateSet::CSK_Normal);
13586 
13587     // FIXME: avoid copy.
13588     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13589     if (UnresExpr->hasExplicitTemplateArgs()) {
13590       UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13591       TemplateArgs = &TemplateArgsBuffer;
13592     }
13593 
13594     for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13595            E = UnresExpr->decls_end(); I != E; ++I) {
13596 
13597       NamedDecl *Func = *I;
13598       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13599       if (isa<UsingShadowDecl>(Func))
13600         Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13601 
13602 
13603       // Microsoft supports direct constructor calls.
13604       if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13605         AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13606                              CandidateSet,
13607                              /*SuppressUserConversions*/ false);
13608       } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13609         // If explicit template arguments were provided, we can't call a
13610         // non-template member function.
13611         if (TemplateArgs)
13612           continue;
13613 
13614         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13615                            ObjectClassification, Args, CandidateSet,
13616                            /*SuppressUserConversions=*/false);
13617       } else {
13618         AddMethodTemplateCandidate(
13619             cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13620             TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13621             /*SuppressUserConversions=*/false);
13622       }
13623     }
13624 
13625     DeclarationName DeclName = UnresExpr->getMemberName();
13626 
13627     UnbridgedCasts.restore();
13628 
13629     OverloadCandidateSet::iterator Best;
13630     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13631                                             Best)) {
13632     case OR_Success:
13633       Method = cast<CXXMethodDecl>(Best->Function);
13634       FoundDecl = Best->FoundDecl;
13635       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13636       if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13637         return ExprError();
13638       // If FoundDecl is different from Method (such as if one is a template
13639       // and the other a specialization), make sure DiagnoseUseOfDecl is
13640       // called on both.
13641       // FIXME: This would be more comprehensively addressed by modifying
13642       // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13643       // being used.
13644       if (Method != FoundDecl.getDecl() &&
13645                       DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13646         return ExprError();
13647       break;
13648 
13649     case OR_No_Viable_Function:
13650       CandidateSet.NoteCandidates(
13651           PartialDiagnosticAt(
13652               UnresExpr->getMemberLoc(),
13653               PDiag(diag::err_ovl_no_viable_member_function_in_call)
13654                   << DeclName << MemExprE->getSourceRange()),
13655           *this, OCD_AllCandidates, Args);
13656       // FIXME: Leaking incoming expressions!
13657       return ExprError();
13658 
13659     case OR_Ambiguous:
13660       CandidateSet.NoteCandidates(
13661           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13662                               PDiag(diag::err_ovl_ambiguous_member_call)
13663                                   << DeclName << MemExprE->getSourceRange()),
13664           *this, OCD_AmbiguousCandidates, Args);
13665       // FIXME: Leaking incoming expressions!
13666       return ExprError();
13667 
13668     case OR_Deleted:
13669       CandidateSet.NoteCandidates(
13670           PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13671                               PDiag(diag::err_ovl_deleted_member_call)
13672                                   << DeclName << MemExprE->getSourceRange()),
13673           *this, OCD_AllCandidates, Args);
13674       // FIXME: Leaking incoming expressions!
13675       return ExprError();
13676     }
13677 
13678     MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13679 
13680     // If overload resolution picked a static member, build a
13681     // non-member call based on that function.
13682     if (Method->isStatic()) {
13683       return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13684                                    RParenLoc);
13685     }
13686 
13687     MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13688   }
13689 
13690   QualType ResultType = Method->getReturnType();
13691   ExprValueKind VK = Expr::getValueKindForType(ResultType);
13692   ResultType = ResultType.getNonLValueExprType(Context);
13693 
13694   assert(Method && "Member call to something that isn't a method?");
13695   const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13696   CXXMemberCallExpr *TheCall =
13697       CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13698                                 RParenLoc, Proto->getNumParams());
13699 
13700   // Check for a valid return type.
13701   if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13702                           TheCall, Method))
13703     return ExprError();
13704 
13705   // Convert the object argument (for a non-static member function call).
13706   // We only need to do this if there was actually an overload; otherwise
13707   // it was done at lookup.
13708   if (!Method->isStatic()) {
13709     ExprResult ObjectArg =
13710       PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13711                                           FoundDecl, Method);
13712     if (ObjectArg.isInvalid())
13713       return ExprError();
13714     MemExpr->setBase(ObjectArg.get());
13715   }
13716 
13717   // Convert the rest of the arguments
13718   if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13719                               RParenLoc))
13720     return ExprError();
13721 
13722   DiagnoseSentinelCalls(Method, LParenLoc, Args);
13723 
13724   if (CheckFunctionCall(Method, TheCall, Proto))
13725     return ExprError();
13726 
13727   // In the case the method to call was not selected by the overloading
13728   // resolution process, we still need to handle the enable_if attribute. Do
13729   // that here, so it will not hide previous -- and more relevant -- errors.
13730   if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13731     if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13732       Diag(MemE->getMemberLoc(),
13733            diag::err_ovl_no_viable_member_function_in_call)
13734           << Method << Method->getSourceRange();
13735       Diag(Method->getLocation(),
13736            diag::note_ovl_candidate_disabled_by_function_cond_attr)
13737           << Attr->getCond()->getSourceRange() << Attr->getMessage();
13738       return ExprError();
13739     }
13740   }
13741 
13742   if ((isa<CXXConstructorDecl>(CurContext) ||
13743        isa<CXXDestructorDecl>(CurContext)) &&
13744       TheCall->getMethodDecl()->isPure()) {
13745     const CXXMethodDecl *MD = TheCall->getMethodDecl();
13746 
13747     if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13748         MemExpr->performsVirtualDispatch(getLangOpts())) {
13749       Diag(MemExpr->getBeginLoc(),
13750            diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13751           << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13752           << MD->getParent()->getDeclName();
13753 
13754       Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13755       if (getLangOpts().AppleKext)
13756         Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13757             << MD->getParent()->getDeclName() << MD->getDeclName();
13758     }
13759   }
13760 
13761   if (CXXDestructorDecl *DD =
13762           dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13763     // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13764     bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13765     CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13766                          CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13767                          MemExpr->getMemberLoc());
13768   }
13769 
13770   return MaybeBindToTemporary(TheCall);
13771 }
13772 
13773 /// BuildCallToObjectOfClassType - Build a call to an object of class
13774 /// type (C++ [over.call.object]), which can end up invoking an
13775 /// overloaded function call operator (@c operator()) or performing a
13776 /// user-defined conversion on the object argument.
13777 ExprResult
13778 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13779                                    SourceLocation LParenLoc,
13780                                    MultiExprArg Args,
13781                                    SourceLocation RParenLoc) {
13782   if (checkPlaceholderForOverload(*this, Obj))
13783     return ExprError();
13784   ExprResult Object = Obj;
13785 
13786   UnbridgedCastsSet UnbridgedCasts;
13787   if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13788     return ExprError();
13789 
13790   assert(Object.get()->getType()->isRecordType() &&
13791          "Requires object type argument");
13792   const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13793 
13794   // C++ [over.call.object]p1:
13795   //  If the primary-expression E in the function call syntax
13796   //  evaluates to a class object of type "cv T", then the set of
13797   //  candidate functions includes at least the function call
13798   //  operators of T. The function call operators of T are obtained by
13799   //  ordinary lookup of the name operator() in the context of
13800   //  (E).operator().
13801   OverloadCandidateSet CandidateSet(LParenLoc,
13802                                     OverloadCandidateSet::CSK_Operator);
13803   DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13804 
13805   if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13806                           diag::err_incomplete_object_call, Object.get()))
13807     return true;
13808 
13809   LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13810   LookupQualifiedName(R, Record->getDecl());
13811   R.suppressDiagnostics();
13812 
13813   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13814        Oper != OperEnd; ++Oper) {
13815     AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13816                        Object.get()->Classify(Context), Args, CandidateSet,
13817                        /*SuppressUserConversion=*/false);
13818   }
13819 
13820   // C++ [over.call.object]p2:
13821   //   In addition, for each (non-explicit in C++0x) conversion function
13822   //   declared in T of the form
13823   //
13824   //        operator conversion-type-id () cv-qualifier;
13825   //
13826   //   where cv-qualifier is the same cv-qualification as, or a
13827   //   greater cv-qualification than, cv, and where conversion-type-id
13828   //   denotes the type "pointer to function of (P1,...,Pn) returning
13829   //   R", or the type "reference to pointer to function of
13830   //   (P1,...,Pn) returning R", or the type "reference to function
13831   //   of (P1,...,Pn) returning R", a surrogate call function [...]
13832   //   is also considered as a candidate function. Similarly,
13833   //   surrogate call functions are added to the set of candidate
13834   //   functions for each conversion function declared in an
13835   //   accessible base class provided the function is not hidden
13836   //   within T by another intervening declaration.
13837   const auto &Conversions =
13838       cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13839   for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13840     NamedDecl *D = *I;
13841     CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13842     if (isa<UsingShadowDecl>(D))
13843       D = cast<UsingShadowDecl>(D)->getTargetDecl();
13844 
13845     // Skip over templated conversion functions; they aren't
13846     // surrogates.
13847     if (isa<FunctionTemplateDecl>(D))
13848       continue;
13849 
13850     CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13851     if (!Conv->isExplicit()) {
13852       // Strip the reference type (if any) and then the pointer type (if
13853       // any) to get down to what might be a function type.
13854       QualType ConvType = Conv->getConversionType().getNonReferenceType();
13855       if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13856         ConvType = ConvPtrType->getPointeeType();
13857 
13858       if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13859       {
13860         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13861                               Object.get(), Args, CandidateSet);
13862       }
13863     }
13864   }
13865 
13866   bool HadMultipleCandidates = (CandidateSet.size() > 1);
13867 
13868   // Perform overload resolution.
13869   OverloadCandidateSet::iterator Best;
13870   switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13871                                           Best)) {
13872   case OR_Success:
13873     // Overload resolution succeeded; we'll build the appropriate call
13874     // below.
13875     break;
13876 
13877   case OR_No_Viable_Function: {
13878     PartialDiagnostic PD =
13879         CandidateSet.empty()
13880             ? (PDiag(diag::err_ovl_no_oper)
13881                << Object.get()->getType() << /*call*/ 1
13882                << Object.get()->getSourceRange())
13883             : (PDiag(diag::err_ovl_no_viable_object_call)
13884                << Object.get()->getType() << Object.get()->getSourceRange());
13885     CandidateSet.NoteCandidates(
13886         PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13887         OCD_AllCandidates, Args);
13888     break;
13889   }
13890   case OR_Ambiguous:
13891     CandidateSet.NoteCandidates(
13892         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13893                             PDiag(diag::err_ovl_ambiguous_object_call)
13894                                 << Object.get()->getType()
13895                                 << Object.get()->getSourceRange()),
13896         *this, OCD_AmbiguousCandidates, Args);
13897     break;
13898 
13899   case OR_Deleted:
13900     CandidateSet.NoteCandidates(
13901         PartialDiagnosticAt(Object.get()->getBeginLoc(),
13902                             PDiag(diag::err_ovl_deleted_object_call)
13903                                 << Object.get()->getType()
13904                                 << Object.get()->getSourceRange()),
13905         *this, OCD_AllCandidates, Args);
13906     break;
13907   }
13908 
13909   if (Best == CandidateSet.end())
13910     return true;
13911 
13912   UnbridgedCasts.restore();
13913 
13914   if (Best->Function == nullptr) {
13915     // Since there is no function declaration, this is one of the
13916     // surrogate candidates. Dig out the conversion function.
13917     CXXConversionDecl *Conv
13918       = cast<CXXConversionDecl>(
13919                          Best->Conversions[0].UserDefined.ConversionFunction);
13920 
13921     CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13922                               Best->FoundDecl);
13923     if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13924       return ExprError();
13925     assert(Conv == Best->FoundDecl.getDecl() &&
13926              "Found Decl & conversion-to-functionptr should be same, right?!");
13927     // We selected one of the surrogate functions that converts the
13928     // object parameter to a function pointer. Perform the conversion
13929     // on the object argument, then let BuildCallExpr finish the job.
13930 
13931     // Create an implicit member expr to refer to the conversion operator.
13932     // and then call it.
13933     ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13934                                              Conv, HadMultipleCandidates);
13935     if (Call.isInvalid())
13936       return ExprError();
13937     // Record usage of conversion in an implicit cast.
13938     Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13939                                     CK_UserDefinedConversion, Call.get(),
13940                                     nullptr, VK_RValue);
13941 
13942     return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13943   }
13944 
13945   CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13946 
13947   // We found an overloaded operator(). Build a CXXOperatorCallExpr
13948   // that calls this method, using Object for the implicit object
13949   // parameter and passing along the remaining arguments.
13950   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13951 
13952   // An error diagnostic has already been printed when parsing the declaration.
13953   if (Method->isInvalidDecl())
13954     return ExprError();
13955 
13956   const FunctionProtoType *Proto =
13957     Method->getType()->getAs<FunctionProtoType>();
13958 
13959   unsigned NumParams = Proto->getNumParams();
13960 
13961   DeclarationNameInfo OpLocInfo(
13962                Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13963   OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13964   ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13965                                            Obj, HadMultipleCandidates,
13966                                            OpLocInfo.getLoc(),
13967                                            OpLocInfo.getInfo());
13968   if (NewFn.isInvalid())
13969     return true;
13970 
13971   // The number of argument slots to allocate in the call. If we have default
13972   // arguments we need to allocate space for them as well. We additionally
13973   // need one more slot for the object parameter.
13974   unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13975 
13976   // Build the full argument list for the method call (the implicit object
13977   // parameter is placed at the beginning of the list).
13978   SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13979 
13980   bool IsError = false;
13981 
13982   // Initialize the implicit object parameter.
13983   ExprResult ObjRes =
13984     PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13985                                         Best->FoundDecl, Method);
13986   if (ObjRes.isInvalid())
13987     IsError = true;
13988   else
13989     Object = ObjRes;
13990   MethodArgs[0] = Object.get();
13991 
13992   // Check the argument types.
13993   for (unsigned i = 0; i != NumParams; i++) {
13994     Expr *Arg;
13995     if (i < Args.size()) {
13996       Arg = Args[i];
13997 
13998       // Pass the argument.
13999 
14000       ExprResult InputInit
14001         = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14002                                                     Context,
14003                                                     Method->getParamDecl(i)),
14004                                     SourceLocation(), Arg);
14005 
14006       IsError |= InputInit.isInvalid();
14007       Arg = InputInit.getAs<Expr>();
14008     } else {
14009       ExprResult DefArg
14010         = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14011       if (DefArg.isInvalid()) {
14012         IsError = true;
14013         break;
14014       }
14015 
14016       Arg = DefArg.getAs<Expr>();
14017     }
14018 
14019     MethodArgs[i + 1] = Arg;
14020   }
14021 
14022   // If this is a variadic call, handle args passed through "...".
14023   if (Proto->isVariadic()) {
14024     // Promote the arguments (C99 6.5.2.2p7).
14025     for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14026       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14027                                                         nullptr);
14028       IsError |= Arg.isInvalid();
14029       MethodArgs[i + 1] = Arg.get();
14030     }
14031   }
14032 
14033   if (IsError)
14034     return true;
14035 
14036   DiagnoseSentinelCalls(Method, LParenLoc, Args);
14037 
14038   // Once we've built TheCall, all of the expressions are properly owned.
14039   QualType ResultTy = Method->getReturnType();
14040   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14041   ResultTy = ResultTy.getNonLValueExprType(Context);
14042 
14043   CXXOperatorCallExpr *TheCall =
14044       CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14045                                   ResultTy, VK, RParenLoc, FPOptions());
14046 
14047   if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14048     return true;
14049 
14050   if (CheckFunctionCall(Method, TheCall, Proto))
14051     return true;
14052 
14053   return MaybeBindToTemporary(TheCall);
14054 }
14055 
14056 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14057 ///  (if one exists), where @c Base is an expression of class type and
14058 /// @c Member is the name of the member we're trying to find.
14059 ExprResult
14060 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14061                                bool *NoArrowOperatorFound) {
14062   assert(Base->getType()->isRecordType() &&
14063          "left-hand side must have class type");
14064 
14065   if (checkPlaceholderForOverload(*this, Base))
14066     return ExprError();
14067 
14068   SourceLocation Loc = Base->getExprLoc();
14069 
14070   // C++ [over.ref]p1:
14071   //
14072   //   [...] An expression x->m is interpreted as (x.operator->())->m
14073   //   for a class object x of type T if T::operator->() exists and if
14074   //   the operator is selected as the best match function by the
14075   //   overload resolution mechanism (13.3).
14076   DeclarationName OpName =
14077     Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14078   OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14079   const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
14080 
14081   if (RequireCompleteType(Loc, Base->getType(),
14082                           diag::err_typecheck_incomplete_tag, Base))
14083     return ExprError();
14084 
14085   LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14086   LookupQualifiedName(R, BaseRecord->getDecl());
14087   R.suppressDiagnostics();
14088 
14089   for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14090        Oper != OperEnd; ++Oper) {
14091     AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14092                        None, CandidateSet, /*SuppressUserConversion=*/false);
14093   }
14094 
14095   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14096 
14097   // Perform overload resolution.
14098   OverloadCandidateSet::iterator Best;
14099   switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14100   case OR_Success:
14101     // Overload resolution succeeded; we'll build the call below.
14102     break;
14103 
14104   case OR_No_Viable_Function: {
14105     auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14106     if (CandidateSet.empty()) {
14107       QualType BaseType = Base->getType();
14108       if (NoArrowOperatorFound) {
14109         // Report this specific error to the caller instead of emitting a
14110         // diagnostic, as requested.
14111         *NoArrowOperatorFound = true;
14112         return ExprError();
14113       }
14114       Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14115         << BaseType << Base->getSourceRange();
14116       if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14117         Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14118           << FixItHint::CreateReplacement(OpLoc, ".");
14119       }
14120     } else
14121       Diag(OpLoc, diag::err_ovl_no_viable_oper)
14122         << "operator->" << Base->getSourceRange();
14123     CandidateSet.NoteCandidates(*this, Base, Cands);
14124     return ExprError();
14125   }
14126   case OR_Ambiguous:
14127     CandidateSet.NoteCandidates(
14128         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14129                                        << "->" << Base->getType()
14130                                        << Base->getSourceRange()),
14131         *this, OCD_AmbiguousCandidates, Base);
14132     return ExprError();
14133 
14134   case OR_Deleted:
14135     CandidateSet.NoteCandidates(
14136         PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14137                                        << "->" << Base->getSourceRange()),
14138         *this, OCD_AllCandidates, Base);
14139     return ExprError();
14140   }
14141 
14142   CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14143 
14144   // Convert the object parameter.
14145   CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14146   ExprResult BaseResult =
14147     PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14148                                         Best->FoundDecl, Method);
14149   if (BaseResult.isInvalid())
14150     return ExprError();
14151   Base = BaseResult.get();
14152 
14153   // Build the operator call.
14154   ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14155                                             Base, HadMultipleCandidates, OpLoc);
14156   if (FnExpr.isInvalid())
14157     return ExprError();
14158 
14159   QualType ResultTy = Method->getReturnType();
14160   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14161   ResultTy = ResultTy.getNonLValueExprType(Context);
14162   CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14163       Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14164 
14165   if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14166     return ExprError();
14167 
14168   if (CheckFunctionCall(Method, TheCall,
14169                         Method->getType()->castAs<FunctionProtoType>()))
14170     return ExprError();
14171 
14172   return MaybeBindToTemporary(TheCall);
14173 }
14174 
14175 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14176 /// a literal operator described by the provided lookup results.
14177 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14178                                           DeclarationNameInfo &SuffixInfo,
14179                                           ArrayRef<Expr*> Args,
14180                                           SourceLocation LitEndLoc,
14181                                        TemplateArgumentListInfo *TemplateArgs) {
14182   SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14183 
14184   OverloadCandidateSet CandidateSet(UDSuffixLoc,
14185                                     OverloadCandidateSet::CSK_Normal);
14186   AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14187                                  TemplateArgs);
14188 
14189   bool HadMultipleCandidates = (CandidateSet.size() > 1);
14190 
14191   // Perform overload resolution. This will usually be trivial, but might need
14192   // to perform substitutions for a literal operator template.
14193   OverloadCandidateSet::iterator Best;
14194   switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14195   case OR_Success:
14196   case OR_Deleted:
14197     break;
14198 
14199   case OR_No_Viable_Function:
14200     CandidateSet.NoteCandidates(
14201         PartialDiagnosticAt(UDSuffixLoc,
14202                             PDiag(diag::err_ovl_no_viable_function_in_call)
14203                                 << R.getLookupName()),
14204         *this, OCD_AllCandidates, Args);
14205     return ExprError();
14206 
14207   case OR_Ambiguous:
14208     CandidateSet.NoteCandidates(
14209         PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14210                                                 << R.getLookupName()),
14211         *this, OCD_AmbiguousCandidates, Args);
14212     return ExprError();
14213   }
14214 
14215   FunctionDecl *FD = Best->Function;
14216   ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14217                                         nullptr, HadMultipleCandidates,
14218                                         SuffixInfo.getLoc(),
14219                                         SuffixInfo.getInfo());
14220   if (Fn.isInvalid())
14221     return true;
14222 
14223   // Check the argument types. This should almost always be a no-op, except
14224   // that array-to-pointer decay is applied to string literals.
14225   Expr *ConvArgs[2];
14226   for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14227     ExprResult InputInit = PerformCopyInitialization(
14228       InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14229       SourceLocation(), Args[ArgIdx]);
14230     if (InputInit.isInvalid())
14231       return true;
14232     ConvArgs[ArgIdx] = InputInit.get();
14233   }
14234 
14235   QualType ResultTy = FD->getReturnType();
14236   ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14237   ResultTy = ResultTy.getNonLValueExprType(Context);
14238 
14239   UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14240       Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14241       VK, LitEndLoc, UDSuffixLoc);
14242 
14243   if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14244     return ExprError();
14245 
14246   if (CheckFunctionCall(FD, UDL, nullptr))
14247     return ExprError();
14248 
14249   return MaybeBindToTemporary(UDL);
14250 }
14251 
14252 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14253 /// given LookupResult is non-empty, it is assumed to describe a member which
14254 /// will be invoked. Otherwise, the function will be found via argument
14255 /// dependent lookup.
14256 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14257 /// otherwise CallExpr is set to ExprError() and some non-success value
14258 /// is returned.
14259 Sema::ForRangeStatus
14260 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14261                                 SourceLocation RangeLoc,
14262                                 const DeclarationNameInfo &NameInfo,
14263                                 LookupResult &MemberLookup,
14264                                 OverloadCandidateSet *CandidateSet,
14265                                 Expr *Range, ExprResult *CallExpr) {
14266   Scope *S = nullptr;
14267 
14268   CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14269   if (!MemberLookup.empty()) {
14270     ExprResult MemberRef =
14271         BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14272                                  /*IsPtr=*/false, CXXScopeSpec(),
14273                                  /*TemplateKWLoc=*/SourceLocation(),
14274                                  /*FirstQualifierInScope=*/nullptr,
14275                                  MemberLookup,
14276                                  /*TemplateArgs=*/nullptr, S);
14277     if (MemberRef.isInvalid()) {
14278       *CallExpr = ExprError();
14279       return FRS_DiagnosticIssued;
14280     }
14281     *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14282     if (CallExpr->isInvalid()) {
14283       *CallExpr = ExprError();
14284       return FRS_DiagnosticIssued;
14285     }
14286   } else {
14287     UnresolvedSet<0> FoundNames;
14288     UnresolvedLookupExpr *Fn =
14289       UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14290                                    NestedNameSpecifierLoc(), NameInfo,
14291                                    /*NeedsADL=*/true, /*Overloaded=*/false,
14292                                    FoundNames.begin(), FoundNames.end());
14293 
14294     bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14295                                                     CandidateSet, CallExpr);
14296     if (CandidateSet->empty() || CandidateSetError) {
14297       *CallExpr = ExprError();
14298       return FRS_NoViableFunction;
14299     }
14300     OverloadCandidateSet::iterator Best;
14301     OverloadingResult OverloadResult =
14302         CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14303 
14304     if (OverloadResult == OR_No_Viable_Function) {
14305       *CallExpr = ExprError();
14306       return FRS_NoViableFunction;
14307     }
14308     *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14309                                          Loc, nullptr, CandidateSet, &Best,
14310                                          OverloadResult,
14311                                          /*AllowTypoCorrection=*/false);
14312     if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14313       *CallExpr = ExprError();
14314       return FRS_DiagnosticIssued;
14315     }
14316   }
14317   return FRS_Success;
14318 }
14319 
14320 
14321 /// FixOverloadedFunctionReference - E is an expression that refers to
14322 /// a C++ overloaded function (possibly with some parentheses and
14323 /// perhaps a '&' around it). We have resolved the overloaded function
14324 /// to the function declaration Fn, so patch up the expression E to
14325 /// refer (possibly indirectly) to Fn. Returns the new expr.
14326 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14327                                            FunctionDecl *Fn) {
14328   if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14329     Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14330                                                    Found, Fn);
14331     if (SubExpr == PE->getSubExpr())
14332       return PE;
14333 
14334     return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14335   }
14336 
14337   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14338     Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14339                                                    Found, Fn);
14340     assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14341                                SubExpr->getType()) &&
14342            "Implicit cast type cannot be determined from overload");
14343     assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14344     if (SubExpr == ICE->getSubExpr())
14345       return ICE;
14346 
14347     return ImplicitCastExpr::Create(Context, ICE->getType(),
14348                                     ICE->getCastKind(),
14349                                     SubExpr, nullptr,
14350                                     ICE->getValueKind());
14351   }
14352 
14353   if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14354     if (!GSE->isResultDependent()) {
14355       Expr *SubExpr =
14356           FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14357       if (SubExpr == GSE->getResultExpr())
14358         return GSE;
14359 
14360       // Replace the resulting type information before rebuilding the generic
14361       // selection expression.
14362       ArrayRef<Expr *> A = GSE->getAssocExprs();
14363       SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14364       unsigned ResultIdx = GSE->getResultIndex();
14365       AssocExprs[ResultIdx] = SubExpr;
14366 
14367       return GenericSelectionExpr::Create(
14368           Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14369           GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14370           GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14371           ResultIdx);
14372     }
14373     // Rather than fall through to the unreachable, return the original generic
14374     // selection expression.
14375     return GSE;
14376   }
14377 
14378   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14379     assert(UnOp->getOpcode() == UO_AddrOf &&
14380            "Can only take the address of an overloaded function");
14381     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14382       if (Method->isStatic()) {
14383         // Do nothing: static member functions aren't any different
14384         // from non-member functions.
14385       } else {
14386         // Fix the subexpression, which really has to be an
14387         // UnresolvedLookupExpr holding an overloaded member function
14388         // or template.
14389         Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14390                                                        Found, Fn);
14391         if (SubExpr == UnOp->getSubExpr())
14392           return UnOp;
14393 
14394         assert(isa<DeclRefExpr>(SubExpr)
14395                && "fixed to something other than a decl ref");
14396         assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14397                && "fixed to a member ref with no nested name qualifier");
14398 
14399         // We have taken the address of a pointer to member
14400         // function. Perform the computation here so that we get the
14401         // appropriate pointer to member type.
14402         QualType ClassType
14403           = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14404         QualType MemPtrType
14405           = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14406         // Under the MS ABI, lock down the inheritance model now.
14407         if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14408           (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14409 
14410         return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14411                                            VK_RValue, OK_Ordinary,
14412                                            UnOp->getOperatorLoc(), false);
14413       }
14414     }
14415     Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14416                                                    Found, Fn);
14417     if (SubExpr == UnOp->getSubExpr())
14418       return UnOp;
14419 
14420     return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14421                                      Context.getPointerType(SubExpr->getType()),
14422                                        VK_RValue, OK_Ordinary,
14423                                        UnOp->getOperatorLoc(), false);
14424   }
14425 
14426   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14427     // FIXME: avoid copy.
14428     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14429     if (ULE->hasExplicitTemplateArgs()) {
14430       ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14431       TemplateArgs = &TemplateArgsBuffer;
14432     }
14433 
14434     DeclRefExpr *DRE =
14435         BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14436                          ULE->getQualifierLoc(), Found.getDecl(),
14437                          ULE->getTemplateKeywordLoc(), TemplateArgs);
14438     DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14439     return DRE;
14440   }
14441 
14442   if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14443     // FIXME: avoid copy.
14444     TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14445     if (MemExpr->hasExplicitTemplateArgs()) {
14446       MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14447       TemplateArgs = &TemplateArgsBuffer;
14448     }
14449 
14450     Expr *Base;
14451 
14452     // If we're filling in a static method where we used to have an
14453     // implicit member access, rewrite to a simple decl ref.
14454     if (MemExpr->isImplicitAccess()) {
14455       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14456         DeclRefExpr *DRE = BuildDeclRefExpr(
14457             Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14458             MemExpr->getQualifierLoc(), Found.getDecl(),
14459             MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14460         DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14461         return DRE;
14462       } else {
14463         SourceLocation Loc = MemExpr->getMemberLoc();
14464         if (MemExpr->getQualifier())
14465           Loc = MemExpr->getQualifierLoc().getBeginLoc();
14466         Base =
14467             BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14468       }
14469     } else
14470       Base = MemExpr->getBase();
14471 
14472     ExprValueKind valueKind;
14473     QualType type;
14474     if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14475       valueKind = VK_LValue;
14476       type = Fn->getType();
14477     } else {
14478       valueKind = VK_RValue;
14479       type = Context.BoundMemberTy;
14480     }
14481 
14482     return BuildMemberExpr(
14483         Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14484         MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14485         /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14486         type, valueKind, OK_Ordinary, TemplateArgs);
14487   }
14488 
14489   llvm_unreachable("Invalid reference to overloaded function");
14490 }
14491 
14492 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14493                                                 DeclAccessPair Found,
14494                                                 FunctionDecl *Fn) {
14495   return FixOverloadedFunctionReference(E.get(), Found, Fn);
14496 }
14497